arkgate 4.8.2 → 4.8.4
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 +257 -3
- package/README.md +47 -9
- package/bin/ark-check-runtime.mjs +340 -5
- package/bin/ark-layer-match.mjs +170 -13
- package/bin/ark-mcp-runtime.mjs +9 -2
- package/bin/lib/analysis-completeness.mjs +86 -0
- package/bin/lib/analysis-engine.mjs +6 -6
- package/bin/lib/architecture-scan.mjs +2 -0
- package/bin/lib/ark-order-facts.mjs +59 -0
- package/bin/lib/ark-order-sensors.mjs +31 -2
- package/bin/lib/arkrule-file-hints.mjs +6 -2
- package/bin/lib/arkrules-contract.mjs +9 -1
- package/bin/lib/arkrules-sensors.mjs +22 -2
- package/bin/lib/check-args.mjs +66 -0
- package/bin/lib/config-contract.mjs +26 -0
- package/bin/lib/config-extras.mjs +2 -0
- package/bin/lib/design-smells.mjs +85 -0
- package/bin/lib/diagnostic-catalog.mjs +8 -2
- package/bin/lib/first-run-help.mjs +12 -0
- package/bin/lib/invariant-coverage-io.mjs +175 -19
- package/bin/lib/invariant-coverage.mjs +110 -7
- package/bin/lib/literal-path-drift-io.mjs +569 -0
- package/bin/lib/literal-path-drift.mjs +761 -0
- package/bin/lib/policy-delta-io.mjs +5 -0
- package/bin/lib/remediation.mjs +24 -1
- package/bin/lib/resolved-candidate-facts.mjs +31 -0
- package/bin/lib/rules-under-contract.mjs +5 -0
- package/bin/lib/scan-files.mjs +54 -0
- package/bin/lib/sensor-promote-cli.mjs +372 -0
- package/bin/lib/sensor-promote-io.mjs +246 -0
- package/bin/lib/sensor-promotion.mjs +363 -0
- package/dist/{configTypes-BdCe_gvv.d.ts → configTypes-dy5PfTqS.d.ts} +36 -0
- package/dist/{diagnosticCatalog-CPzH-MLN.d.ts → diagnosticCatalog-DgTs0abp.d.ts} +169 -11
- package/dist/eslint/index.cjs +5 -5
- package/dist/eslint/index.d.ts +34 -1
- package/dist/eslint/index.js +5 -5
- package/dist/index.cjs +31 -31
- package/dist/index.d.ts +85 -7
- package/dist/index.js +31 -31
- package/dist/nestjs/index.cjs +5 -5
- package/dist/nestjs/index.d.ts +3 -3
- package/dist/nestjs/index.js +5 -5
- package/dist/runtime/index.cjs +13 -13
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.js +13 -13
- package/dist/{types-DCSlrRnV.d.ts → types-BuM8WNqe.d.ts} +1 -1
- package/dist/{types-C9KApBzX.d.ts → types-D95drJ3_.d.ts} +1 -1
- package/docs/README.md +4 -4
- package/docs/agent-guide.md +182 -0
- package/docs/configuration.md +89 -9
- package/docs/develop.md +24 -2
- package/docs/diagnostics.md +79 -1
- package/docs/enthusiast/README.md +6 -4
- package/docs/package-surface.md +36 -4
- package/docs/product-voice.md +15 -5
- package/docs/use.md +8 -5
- package/package.json +2 -2
- package/schemas/ark.arkrules.schema.json +1 -0
- package/schemas/ark.config.schema.json +72 -0
- package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
- package/server.json +3 -3
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +13 -3
- package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
- package/templates/agent-skills/ark-contract/SKILL.md +4 -0
- package/templates/agent-skills/ark-coverage/SKILL.md +1 -0
- package/templates/agent-skills/ark-place/SKILL.md +6 -2
- package/templates/arkrules/ApplicationOrchestration.json +6 -0
- package/templates/skills/ark-adopt.md +13 -3
- package/templates/skills/ark-autopilot.md +1 -1
- package/templates/skills/ark-contract.md +4 -0
- package/templates/skills/ark-coverage.md +1 -0
- package/templates/skills/ark-place.md +6 -2
package/dist/runtime/index.cjs
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}function
|
|
1
|
+
"use strict";var Li=Object.create;var vt=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var $i=Object.getOwnPropertyNames;var Mi=Object.getPrototypeOf,Hi=Object.prototype.hasOwnProperty;var i=(e,t)=>vt(e,"name",{value:t,configurable:!0});var bt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var xo=(e,t)=>{for(var n in t)vt(e,n,{get:t[n],enumerable:!0})},Oo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $i(t))!Hi.call(e,o)&&o!==n&&vt(e,o,{get:()=>t[o],enumerable:!(r=Fi(t,o))||r.enumerable});return e};var Ki=(e,t,n)=>(n=e!=null?Li(Mi(e)):{},Oo(t||!e||!e.__esModule?vt(n,"default",{value:e,enumerable:!0}):n,e)),Gi=e=>Oo(vt({},"__esModule",{value:!0}),e);function mo(e,t){return e<t?-1:e>t?1:0}function rc(e){return[...new Set(e)].sort(mo)}function ln(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return rc(t)}function oc(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function sc(e){return typeof e=="string"&&nc.has(e)?e:"singleton"}function ic(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(mo)){if(n.length===0)continue;let r=oc(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function ac(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=ln(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=ic(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function yo(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:sc(t.lifetime),uses:ln(t.uses),reactsTo:ln(t.reactsTo),raises:ln(t.raises),sends:ln(t.sends)},o=ac(t.extendedInfo);return o&&(r.extendedInfo=o),r}function ce(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let s of n){let a=yo(s);!a||r.has(a.id)||(r.add(a.id),o.push(a))}return o.sort((s,a)=>mo(s.id,a.id)),{schemaVersion:"1.0",kernelInstanceId:t,components:o}}var cn,rr,nc,ft=bt(()=>{"use strict";cn="1.0",rr=["singleton","transient"],nc=new Set(rr);i(mo,"compare");i(rc,"uniqueSorted");i(ln,"nameList");i(oc,"jsonPrimitive");i(sc,"closedLifetime");i(ic,"sanitizeMetadata");i(ac,"sanitizeArkRunExtendedInfo");i(yo,"sanitizeArkRunComponent");i(ce,"buildDependencyInformationPackage")});function un(e,t){return e<t?-1:e>t?1:0}function ho(e){return[...new Set(e)].sort(un)}function Ii(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Ro(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function de(e,t){if(e==null||e==="")return[];if(typeof e=="string")return ho(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new X(t);let n=[];for(let r of e){if(typeof r!="string")throw new X(t);let o=r.trim();o.length>0&&n.push(o)}return ho(n)}function Si(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 dn(e,t){return e?t.some(n=>Si(e,n)):!1}function Ci(e){if(e==null||e==="")return ar;if(typeof e=="string"&&lc.has(e))return e;throw new X("slice")}function wi(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 X("degreesOfSeparation")}function vi(e,t){if(e==null||e==="")return Ii();if(typeof e=="string"||Array.isArray(e))return{...Ii(),tokens:de(e,t)};if(typeof e!="object")throw new X(t);let n=e;for(let r of Object.keys(n))if(!dc.has(r))throw new X(t);return{tokens:[],ids:de(n.ids,t),labels:de(n.labels,t),tags:de(n.tags,t),groups:de(n.groups,t),architectureKinds:de(n.architectureKinds,t)}}function gn(e={}){if(e==null||e==="")return gn({});if(typeof e!="object"||Array.isArray(e))throw new X("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!cc.has(n))throw new X("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Ci(t.slice),nodeIds:de(t.nodeIds,"nodeIds"),degreesOfSeparation:wi(t.degreesOfSeparation),include:vi(t.include,"include"),exclude:vi(t.exclude,"exclude")}}function mn(e){let t={};e.slice&&(t.slice=Ci(e.slice));let n=de(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=wi(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=de(e.include??void 0,"include");o.length>0&&(t.include=o);let s=de(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function pc(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 bi(e,t){if(!Ro(t))return!0;let n=pc(e);return t.tokens.some(r=>n.some(o=>Si(o,r)))||dn(e.id,t.ids)||dn(e.label,t.labels)||e.tags?.some(r=>dn(r,t.tags))||dn(e.group,t.groups)?!0:dn(e.architectureKind,t.architectureKinds)}function uc(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return ce({kernelInstanceId:t.kernelInstanceId,components:t.components})}return ce({})}function fc(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 or(e){return{id:e,kind:"interaction"}}function pn(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function sr(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 gc(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(pn(n,fc(s)),t==="technical"){for(let a of s.uses)pn(n,n.get(a)??or(a)),sr(r,o,s.id,a,"uses");continue}for(let a of s.raises)pn(n,n.get(a)??or(a)),sr(r,o,s.id,a,"raises");for(let a of s.reactsTo)pn(n,n.get(a)??or(a)),sr(r,o,a,s.id,"reactsTo");for(let a of s.sends)pn(n,n.get(a)??or(a)),sr(r,o,s.id,a,"sends")}return{nodes:n,edges:r}}function mc(e){let t=new Map,n=i((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 yc(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let s=new Set,a=o.map(l=>({id:l,depth:0}));for(;a.length>0;){let l=a.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)&&a.push({id:c,depth:l.depth+1})}return s}function fn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function Ei(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function hc(e){let t=new Set,n=new Map;for(let r of e){let o=fn(r),s=o,a=2;for(;t.has(s);)s=`${o}_${a}`,a+=1;t.add(s),n.set(r,s)}return n}function cr(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=hc(n),o=ho(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],a=i((l,c)=>{let g=r.get(l.id)??fn(l.id),m=Ei(l.label??l.id);s.push(`${c}${g}["${m}"]`)},"emitNode");for(let l of o){let c=fn(`group_${l}`);s.push(` subgraph ${c}["${Ei(l)}"]`);for(let g of e.nodes)g.group===l&&a(g," ");s.push(" end")}for(let l of e.nodes)l.group||a(l," ");for(let l of e.edges){let c=r.get(l.from)??fn(l.from),g=r.get(l.to)??fn(l.to);s.push(` ${c} -->|${l.kind}| ${g}`)}return s.join(`
|
|
2
|
+
`)}function Rc(e,t,n){let r=new Set(e.keys());if(Ro(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&bi(c,n.include)}))),Ro(n.exclude))for(let l of[...r]){let c=e.get(l);c&&bi(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=yc(r,n.nodeIds,n.degreesOfSeparation,mc(o)));let s=[...r].sort(un).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>un(l.from,c.from)||un(l.kind,c.kind)||un(l.to,c.to));return{nodes:s,edges:a}}function yn(e={},t={}){let n=uc(e),r=gn(t),o=gc(n.components,r.slice),s=Rc(o.nodes,o.edges,r),a={schemaVersion:ir,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=cr(a),a}var ir,ar,lr,Ao,ko,Io,X,lc,cc,dc,dr=bt(()=>{"use strict";ft();ir="1.0",ar="process",lr=["process","technical"],Ao=["component","interaction"],ko=["raises","reactsTo","sends"],Io=["uses"],X=class extends Error{static{i(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}},lc=new Set(lr),cc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),dc=new Set(["ids","labels","tags","groups","architectureKinds"]);i(un,"compare");i(ho,"uniqueSorted");i(Ii,"emptyMatch");i(Ro,"matchHasCriteria");i(de,"nameList");i(Si,"globMatch");i(dn,"anyGlob");i(Ci,"closedSlice");i(wi,"closedDegrees");i(vi,"closedMatch");i(gn,"closeArkRunGraphQuery");i(mn,"arkRunGraphQueryFromSearchParams");i(pc,"nodeFields");i(bi,"nodeMatches");i(uc,"asPackage");i(fc,"componentNode");i(or,"interactionNode");i(pn,"addNode");i(sr,"addEdge");i(gc,"buildSlice");i(mc,"adjacency");i(yc,"neighborhood");i(fn,"mermaidSafeId");i(Ei,"mermaidLabel");i(hc,"uniqueMermaidIds");i(cr,"formatArkRunGraphMermaid");i(Rc,"filterGraph");i(yn,"requestArkRunGraph")});function pr(e){if(e===void 0)return"local";if(typeof e=="string"&&Ac.has(e))return e;throw new je("transport")}function ur(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new je("ephemeral")}function hn(e){let t=pr(e.transport),n=ur(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 gt,Be,Ac,je,Rn=bt(()=>{"use strict";gt=["local","localBlocking","broker"],Be=!0,Ac=new Set(gt),je=class extends Error{static{i(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}};i(pr,"closedArkRunTransportKind");i(ur,"closedArkRunEphemeral");i(hn,"resolveArkRunSendPlan")});function kn(e){return e==="production"}function Ic(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 xi(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function qe(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=xi(t);if(n)return qe(n);let r=Ic(t);return r!==void 0&&r[0]===127}function Oi(e){if(e===void 0)return An;if(typeof e!="string")throw new te(String(e));let t=e.trim();if(kc.has(t.toLowerCase())||!qe(t))throw new te(t);let n=t.toLowerCase();if(n==="localhost")return An;if(n==="[::1]")return"::1";let r=xi(n);return r?Oi(r):n}function vc(e){if(e===void 0)return gr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new te(`port:${String(e)}`);return e}function Rt(e={}){if(kn(e.nodeEnv)||kn(e.processNodeEnv))throw new We;return{host:Oi(e.host),port:vc(e.port)}}function we(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function bc(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function Ec(e){return{kinds:[...gt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:yr}}function In(e={}){let t=Rt({host:e.host,port:e.port}),n=ce({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]});return{schemaVersion:fr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Ec(e),observability:bc(e.observability)??{}}}function At(e){return`event: ${mr}
|
|
3
3
|
data: ${JSON.stringify(e)}
|
|
4
4
|
|
|
5
|
-
`}var fr,bn,mr,yt,gt,ht,yr,gr,Be,Q,rl,wn=St(()=>{"use strict";ft();vn();fr="1.0",bn="127.0.0.1",mr=0,yt="/snapshot",gt="/events",ht="/graph",yr="snapshot",gr="in-process-local",Be=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},Q=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},rl=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Sn,"isArkRunInspectorProductionEnv");i(ol,"ipv4Octets");i(ha,"unwrapIpv4Mapped");i(qe,"isArkRunInspectorLoopbackHost");i(Ra,"closedHost");i(sl,"closedPort");i(Rt,"resolveArkRunInspectorBind");i(Se,"arkRunInspectorUrl");i(al,"jsonClone");i(il,"closedTransportFacts");i(Cn,"buildArkRunInspectorSnapshot");i(At,"formatArkRunInspectorSseEvent")});var Aa={};So(Aa,{listenArkRunInspector:()=>ul});function cl(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function ll(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function dl(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function hr(e,t,n){e.writeHead(t,cl()),e.end(JSON.stringify(n))}function pl(e,t){let n=e.address();if(n===null||typeof n=="string")throw new Q(t.host);if(!qe(n.address))throw new Q(n.address);return{host:t.host,port:n.port}}async function ul(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,c=i(()=>e.getInspectorSnapshot(a),"snapshot"),l=n.createServer((m,y)=>{let h=dl(m.url),d=h.pathname;if(m.method==="GET"&&(d==="/"||d===yt)){hr(y,200,c());return}if(m.method==="GET"&&d===ht){try{hr(y,200,e.requestGraph(kn({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(p){if(p instanceof z){hr(y,400,{error:p.message,option:p.option});return}throw p}return}if(m.method==="GET"&&d===gt){y.writeHead(200,ll()),y.flushHeaders(),y.write(At(c())),r.add(y);let p=s>0?setInterval(()=>{y.write(At(c()))},s):void 0;p&&o.add(p);let u=i(()=>{r.delete(y),p&&(clearInterval(p),o.delete(p))},"drop");m.on("close",u),y.on("close",u);return}hr(y,404,{error:"not found"})});try{await new Promise((m,y)=>{let h=i(d=>y(d),"onError");l.once("error",h),l.listen({host:t.bind.host,port:t.bind.port},()=>{l.off("error",h);try{a=pl(l,t.bind),m()}catch(d){y(d instanceof Error?d:new Q(t.bind.host))}})})}catch(m){throw await new Promise(y=>{l.close(()=>y())}),m}return{host:a.host,port:a.port,url:Se(a.host,a.port,"/"),snapshotUrl:Se(a.host,a.port,yt),eventsUrl:Se(a.host,a.port,gt),graphUrl:Se(a.host,a.port,ht),close(){for(let m of o)clearInterval(m);o.clear();for(let m of r)m.end();return r.clear(),new Promise((m,y)=>{l.close(h=>{h?y(h):m()})})}}}var ka=St(()=>{"use strict";dr();wn();i(cl,"jsonHeaders");i(ll,"sseHeaders");i(dl,"requestUrl");i(hr,"writeJson");i(pl,"boundAddress");i(ul,"listenArkRunInspector")});var Rl={};So(Rl,{ANALYSIS_IR_SCHEMA_VERSION:()=>qn,ARK_ANALYSIS_RESULT_SCHEMA:()=>_o,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>_n,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ia,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>aa,ARK_RUN_COMPONENT_LIFETIMES:()=>rr,ARK_RUN_EPHEMERAL_DEFAULT:()=>je,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>ir,ARK_RUN_GRAPH_NODE_KINDS:()=>ho,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>Ro,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>ar,ARK_RUN_GRAPH_SLICES:()=>cr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>Ao,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>mn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>bn,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>mr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>gt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>ht,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>fr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>yt,ARK_RUN_INSPECTOR_SSE_EVENT:()=>yr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>gr,ARK_RUN_TRANSPORT_KINDS:()=>mt,ArkRunInspectorBindError:()=>Q,ArkRunInspectorProductionError:()=>Be,DEFAULT_MAX_HISTORY_SIZE:()=>Rr,DIAGNOSTIC_CATALOG:()=>cn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Qs,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>Xs,EventContractRegistryImpl:()=>Xe,EventContractViolationError:()=>Te,InMemoryAuditStore:()=>et,InMemoryEventBuffer:()=>Ee,InMemoryOutboxStore:()=>_r,InMemoryReadModelStore:()=>dt,InMemoryWorkflowStore:()=>pt,IntentRegistry:()=>xe,InvalidArkRunGraphQueryError:()=>z,InvalidArkRunSendOptionError:()=>Ve,InvalidIntentNameError:()=>_e,LayerPolicyContextError:()=>Ne,MANIFEST_SCHEMA_VERSION:()=>pn,ObservedLayerFlowViolationError:()=>De,POLICY_DELTA_SCHEMA_VERSION:()=>Wn,PolicyEngine:()=>ke,PolicyViolationError:()=>pe,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Bn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>be,SourceMetadataOverrideError:()=>ue,UnknownEventSourceError:()=>Ie,UnregisteredIntentError:()=>Oe,analyzeArchitectureConvergence:()=>Ke,analyzeChange:()=>rn,analyzePolicyDelta:()=>eo,analyzeProject:()=>it,analyzeResolvedProject:()=>lt,architecturalPolicies:()=>Nn,arkRunGraphQueryFromSearchParams:()=>kn,arkRunInspectorUrl:()=>Se,buildArkRunInspectorSnapshot:()=>Cn,buildDependencyInformationPackage:()=>le,buildPublishPolicyContext:()=>_t,catalogFixForRuleId:()=>oa,catalogWhyForRuleId:()=>sa,checkAdapterGovernance:()=>Gn,checkContract:()=>Hr,classifyArkPolicyDelta:()=>Yn,closeArkRunGraphQuery:()=>An,closedArkRunEphemeral:()=>ur,closedArkRunTransportKind:()=>pr,collectAnalysisConfigWarnings:()=>an,collectForbiddenCapabilityUses:()=>Me,createAICodeGate:()=>Jr,createAdapter:()=>Mr,createAdapterResult:()=>Oo,createArchitectureProfile:()=>Vt,createArchitectureProfileFromArkConfig:()=>jt,createArkKernel:()=>kt,createArkKernelFromConfig:()=>Eo,createArkManifest:()=>un,createArkTestHarness:()=>Tr,createAuditTrail:()=>$t,createDependencyGraph:()=>Mt,createElevenLayerArkConfig:()=>Fr,createEventBus:()=>Or,createEventContractRegistry:()=>Lt,createIntentRegistry:()=>Ct,createLenientArkKernel:()=>kr,createLenientArkKernelFromConfig:()=>bo,createMetadataRegistry:()=>Bt,createObservabilityReporter:()=>Ft,createProjectionRegistry:()=>dn,createResolvedCandidateFacts:()=>jn,createSaga:()=>uo,createStrictArkKernel:()=>Ar,createStrictArkKernelFromConfig:()=>vo,createWorkflowEngine:()=>ut,defaultIntentRegistry:()=>br,defineArchitectureProfilePolicy:()=>Ot,defineIntent:()=>vr,defineLayerPolicy:()=>xt,definePolicy:()=>Pe,definePort:()=>$r,definePublishPolicy:()=>Sr,detectArchitectureCycles:()=>Qn,deterministicHash:()=>M,diagnosticDocsFragment:()=>io,diagnosticDocsPath:()=>na,elevenLayerProfile:()=>Fe,evaluateArchitectureGraph:()=>Ue,explainViolation:()=>to,extractSemanticDependencies:()=>$e,formatArkRunGraphMermaid:()=>lr,formatArkRunInspectorSseEvent:()=>At,getDiagnosticCatalogEntry:()=>ln,isArkRunInspectorLoopbackHost:()=>qe,isArkRunInspectorProductionEnv:()=>Sn,isCataloguedOrArkRuleFamily:()=>ta,isKnownDiagnosticCode:()=>ea,isLayerPolicy:()=>Pt,loadContract:()=>nn,loadResolvedCandidateFacts:()=>he,policyDeltaAcknowledgementMatches:()=>Zn,preflightChange:()=>oo,preflightResolvedChange:()=>so,requestArkRunGraph:()=>In,resolveArkRunInspectorBind:()=>Rt,resolveArkRunSendPlan:()=>En,resolvedFactsEvidenceRequirementsHash:()=>at,serializeDiagnosticCatalog:()=>ra,stableSerialize:()=>D,startArkRunInspector:()=>xn,syncRegistryToGraph:()=>Ht,toAdapterDiagnostic:()=>On,validateIntentName:()=>wt,version:()=>Pn});module.exports=Oa(Rl);var Pn="4.8.2";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"}i(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."}i(La,"layerImportNextAction");function Fa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(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.`}}i($a,"arkRunNextAction");function ce(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, 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() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. 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 only. Change \u03BE with proposeRelease + release. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ce,"deterministicNextAction");var _n="1.5",Ma="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function wo(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(wo,"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("|")}i(Po,"adapterFindingTargetKey");function xo(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}`})}i(xo,"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")}`}i(Ha,"adapterFindingRefFromTargetKey");function Ka(e){return`${Ma}#${e}`}i(Ka,"adapterDocsCodePath");function Ga(e,t,n){return ce({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})}i(Ga,"nextActionForDiagnostic");function On(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)}:{}},a=n??Po(e),c=Ha(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:wo(e.line,1),column:wo(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ga(r,s,e),findingRef:c,targetKey:a,docsCodePath:Ka(r)}}i(On,"toAdapterDiagnostic");function Oo(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??[],a=e.warnings??[],c=xo(s),l=xo(a),m=[...s.map((h,d)=>On(h,"error",c[d])),...a.map((h,d)=>On(h,"warning",l[d]))],y={schemaVersion:_n,completenessReasons:r,diagnostics:m};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...y,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...h}:{...y,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...o}:{...y,mode:n,valid:!1,completeness:t,...o}}i(Oo,"createAdapterResult");var _o={$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:_n},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 xe=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var No=new xe;function vr(e,t){return No.define(e,t)}i(vr,"defineIntent");function Ct(){return new xe}i(Ct,"createIntentRegistry");var br=No;var To=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function wt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!To.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${To.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(wt,"validateIntentName");var pe=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
5
|
+
`}var fr,An,gr,mt,yt,ht,mr,yr,We,te,kc,vn=bt(()=>{"use strict";ft();Rn();fr="1.0",An="127.0.0.1",gr=0,mt="/snapshot",yt="/events",ht="/graph",mr="snapshot",yr="in-process-local",We=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},te=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},kc=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(kn,"isArkRunInspectorProductionEnv");i(Ic,"ipv4Octets");i(xi,"unwrapIpv4Mapped");i(qe,"isArkRunInspectorLoopbackHost");i(Oi,"closedHost");i(vc,"closedPort");i(Rt,"resolveArkRunInspectorBind");i(we,"arkRunInspectorUrl");i(bc,"jsonClone");i(Ec,"closedTransportFacts");i(In,"buildArkRunInspectorSnapshot");i(At,"formatArkRunInspectorSseEvent")});var Pi={};xo(Pi,{listenArkRunInspector:()=>Oc});function Sc(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Cc(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function wc(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function hr(e,t,n){e.writeHead(t,Sc()),e.end(JSON.stringify(n))}function xc(e,t){let n=e.address();if(n===null||typeof n=="string")throw new te(t.host);if(!qe(n.address))throw new te(n.address);return{host:t.host,port:n.port}}async function Oc(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((g,m)=>{let h=wc(g.url),p=h.pathname;if(g.method==="GET"&&(p==="/"||p===mt)){hr(m,200,l());return}if(g.method==="GET"&&p===ht){try{hr(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 X){hr(m,400,{error:f.message,option:f.option});return}throw f}return}if(g.method==="GET"&&p===yt){m.writeHead(200,Cc()),m.flushHeaders(),m.write(At(l())),r.add(m);let f=s>0?setInterval(()=>{m.write(At(l()))},s):void 0;f&&o.add(f);let u=i(()=>{r.delete(m),f&&(clearInterval(f),o.delete(f))},"drop");g.on("close",u),m.on("close",u);return}hr(m,404,{error:"not found"})});try{await new Promise((g,m)=>{let h=i(p=>m(p),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{a=xc(c,t.bind),g()}catch(p){m(p instanceof Error?p:new te(t.bind.host))}})})}catch(g){throw await new Promise(m=>{c.close(()=>m())}),g}return{host:a.host,port:a.port,url:we(a.host,a.port,"/"),snapshotUrl:we(a.host,a.port,mt),eventsUrl:we(a.host,a.port,yt),graphUrl:we(a.host,a.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 _i=bt(()=>{"use strict";dr();vn();i(Sc,"jsonHeaders");i(Cc,"sseHeaders");i(wc,"requestUrl");i(hr,"writeJson");i(xc,"boundAddress");i(Oc,"listenArkRunInspector")});var Lc={};xo(Lc,{ANALYSIS_IR_SCHEMA_VERSION:()=>Bn,ARK_ANALYSIS_RESULT_SCHEMA:()=>Do,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Pn,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Ri,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>hi,ARK_RUN_COMPONENT_LIFETIMES:()=>rr,ARK_RUN_EPHEMERAL_DEFAULT:()=>Be,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>ar,ARK_RUN_GRAPH_NODE_KINDS:()=>Ao,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>ko,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>ir,ARK_RUN_GRAPH_SLICES:()=>lr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>Io,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>cn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>An,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>gr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>yt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>ht,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>fr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>mt,ARK_RUN_INSPECTOR_SSE_EVENT:()=>mr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>yr,ARK_RUN_TRANSPORT_KINDS:()=>gt,ArkRunInspectorBindError:()=>te,ArkRunInspectorProductionError:()=>We,DEFAULT_MAX_HISTORY_SIZE:()=>Rr,DIAGNOSTIC_CATALOG:()=>nn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ci,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>di,EventContractRegistryImpl:()=>Je,EventContractViolationError:()=>De,InMemoryAuditStore:()=>Qe,InMemoryEventBuffer:()=>Ee,InMemoryOutboxStore:()=>Dr,InMemoryReadModelStore:()=>dt,InMemoryWorkflowStore:()=>pt,IntentRegistry:()=>Oe,InvalidArkRunGraphQueryError:()=>X,InvalidArkRunSendOptionError:()=>je,InvalidIntentNameError:()=>Ne,LayerPolicyContextError:()=>Te,MANIFEST_SCHEMA_VERSION:()=>sn,ObservedLayerFlowViolationError:()=>Le,POLICY_DELTA_SCHEMA_VERSION:()=>qn,PolicyEngine:()=>ve,PolicyViolationError:()=>ue,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>jn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Ce,SourceMetadataOverrideError:()=>fe,UnknownEventSourceError:()=>be,UnregisteredIntentError:()=>_e,analyzeArchitectureConvergence:()=>Ke,analyzeChange:()=>en,analyzePolicyDelta:()=>ro,analyzeProject:()=>at,analyzeResolvedProject:()=>ct,architecturalPolicies:()=>_n,arkRunGraphQueryFromSearchParams:()=>mn,arkRunInspectorUrl:()=>we,buildArkRunInspectorSnapshot:()=>In,buildDependencyInformationPackage:()=>ce,buildPublishPolicyContext:()=>Ot,catalogFixForRuleId:()=>mi,catalogWhyForRuleId:()=>yi,checkAdapterGovernance:()=>Kn,checkContract:()=>Ur,classifyArkPolicyDelta:()=>zn,closeArkRunGraphQuery:()=>gn,closedArkRunEphemeral:()=>ur,closedArkRunTransportKind:()=>pr,collectAnalysisConfigWarnings:()=>tn,collectForbiddenCapabilityUses:()=>Me,createAICodeGate:()=>eo,createAdapter:()=>Gr,createAdapterResult:()=>To,createArchitectureProfile:()=>Kt,createArchitectureProfileFromArkConfig:()=>Gt,createArkKernel:()=>kt,createArkKernelFromConfig:()=>Eo,createArkManifest:()=>an,createArkTestHarness:()=>Fr,createAuditTrail:()=>Lt,createDependencyGraph:()=>Ft,createElevenLayerArkConfig:()=>Hr,createEventBus:()=>Tr,createEventContractRegistry:()=>Tt,createIntentRegistry:()=>Et,createLenientArkKernel:()=>kr,createLenientArkKernelFromConfig:()=>Co,createMetadataRegistry:()=>Ut,createObservabilityReporter:()=>Dt,createProjectionRegistry:()=>on,createResolvedCandidateFacts:()=>Vn,createSaga:()=>go,createStrictArkKernel:()=>Ar,createStrictArkKernelFromConfig:()=>So,createWorkflowEngine:()=>ut,defaultIntentRegistry:()=>Cr,defineArchitectureProfilePolicy:()=>xt,defineIntent:()=>Sr,defineLayerPolicy:()=>Ct,definePolicy:()=>Pe,definePort:()=>Kr,definePublishPolicy:()=>wr,detectArchitectureCycles:()=>Zn,deterministicHash:()=>B,diagnosticDocsFragment:()=>co,diagnosticDocsPath:()=>fi,elevenLayerProfile:()=>Fe,evaluateArchitectureGraph:()=>Ue,explainViolation:()=>oo,extractSemanticDependencies:()=>$e,formatArkRunGraphMermaid:()=>cr,formatArkRunInspectorSseEvent:()=>At,getDiagnosticCatalogEntry:()=>rn,isArkRunInspectorLoopbackHost:()=>qe,isArkRunInspectorProductionEnv:()=>kn,isCataloguedOrArkRuleFamily:()=>ui,isKnownDiagnosticCode:()=>pi,isLayerPolicy:()=>wt,loadContract:()=>Qt,loadResolvedCandidateFacts:()=>Ae,policyDeltaAcknowledgementMatches:()=>Yn,preflightChange:()=>io,preflightResolvedChange:()=>ao,requestArkRunGraph:()=>yn,resolveArkRunInspectorBind:()=>Rt,resolveArkRunSendPlan:()=>hn,resolvedFactsEvidenceRequirementsHash:()=>it,serializeDiagnosticCatalog:()=>gi,stableSerialize:()=>D,startArkRunInspector:()=>bn,syncRegistryToGraph:()=>$t,toAdapterDiagnostic:()=>On,validateIntentName:()=>St,version:()=>xn});module.exports=Gi(Lc);var xn="4.8.4";var Ui=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Vi=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,ji=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Bi(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ui.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Vi.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":ji.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Bi,"classifyLayerImportKind");function Wi(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=Bi(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Wi,"layerImportNextAction");function qi(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(qi,"arkRunCallSiteName");function zi(e){let t=qi(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(zi,"arkRunNextAction");function le(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Wi(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 zi(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() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. 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 only. Change \u03BE with proposeRelease + release. 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 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 preflight again. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(le,"deterministicNextAction");var Pn="1.5",Yi="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function Po(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Po,"positiveInteger");function No(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(No,"adapterFindingTargetKey");function _o(e){let t=new Map;return e.map(n=>{let r=No(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(_o,"adapterFindingOccurrenceTargetKeys");function Xi(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Xi,"adapterFindingRefFromTargetKey");function Zi(e){return`${Yi}#${e}`}i(Zi,"adapterDocsCodePath");function Ji(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})}i(Ji,"nextActionForDiagnostic");function On(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)}:{}},a=n??No(e),l=Xi(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:Po(e.line,1),column:Po(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ji(r,s,e),findingRef:l,targetKey:a,docsCodePath:Zi(r)}}i(On,"toAdapterDiagnostic");function To(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??[],a=e.warnings??[],l=_o(s),c=_o(a),g=[...s.map((h,p)=>On(h,"error",l[p])),...a.map((h,p)=>On(h,"warning",c[p]))],m={schemaVersion:Pn,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}}i(To,"createAdapterResult");var Do={$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:Pn},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 Oe=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Lo=new Oe;function Sr(e,t){return Lo.define(e,t)}i(Sr,"defineIntent");function Et(){return new Oe}i(Et,"createIntentRegistry");var Cr=Lo;var Fo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function St(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Fo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Fo.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(St,"validateIntentName");var ue=class extends Error{static{i(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 ke=class{static{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let c of a)n.push({policyName:s.name,severity:s.severity,message:c.message,details:c.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new pe(n.hardViolations);return n}clear(){this.policies.length=0}};function Pe(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}i(Pe,"definePolicy");function Ua(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Ua,"defaultLayerOf");function Do(e,t){return t.resolveLayer?.(e)??Ua(e)}i(Do,"resolveLayer");function Va(e,t,n){return e===n.from&&t===n.to}i(Va,"matchesRule");function xt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Pe({name:t,severity:n,tags:["layer"],check:i(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],s=[];for(let a of o){let c=Do(a.from,e),l=Do(a.to,e);for(let m of e.rules)!m.allowed&&Va(c,l,m)&&s.push({policyName:t,severity:n,message:m.message??`Layer violation: ${a.from} (${c}) must not relate to ${a.to} (${l})`})}return s.length>0?s:!0},"check")})}i(xt,"defineLayerPolicy");function Pt(e){return e.tags?.includes("layer")??!1}i(Pt,"isLayerPolicy");var Nn={layerIsolation(){return Nn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return xt({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 Ot(e,t={}){return xt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(Ot,"defineArchitectureProfilePolicy");function _t(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(_t,"buildPublishPolicyContext");function Sr(e){return Pe(e)}i(Sr,"definePublishPolicy");var Oe=class extends Error{static{i(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},_e=class extends Error{static{i(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Ne=class extends Error{static{i(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},Te=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Ie=class extends Error{static{i(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},ue=class extends Error{static{i(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},De=class extends Error{static{i(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function Nt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=wt(e);if(!n.valid)throw new _e(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Oe(e)}}i(Nt,"assertIntentAllowed");function Lo(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Ie(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Ie(e.intent,e.metadata.source)}}i(Lo,"assertSourceAllowed");function Tt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Te(e.intent,n.issues)}i(Tt,"assertContractAllowed");function Ze(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Ze,"isPlainRecord");function Je(e){return Array.isArray(e)?e.map(Je):Ze(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Je(n)])):e}i(Je,"clonePatchValue");function Cr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=Je(s);continue}if(Ze(r[o])&&Ze(s)){r[o]=Cr(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=wr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Cr,"mergeRecordPatch");function wr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let a=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=Je(o);return}if(Ze(r[s])&&Ze(o)){r[s]=Cr(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=wr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(wr,"mergeArrayPatch");function Fo(e,t){if(Array.isArray(t)){if(e===void 0)return Je(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return wr(e,t)}if(e===void 0)return Je(t);if(!Ze(e))throw new Error("Object interceptor patch requires an object payload.");return Cr(e,t)}i(Fo,"applyPayloadPatch");async function $o(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:i(l=>{s.push(l)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let l of s)c={...c,payload:Fo(c.payload,l),metadata:{...c.metadata}};Tt(c,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=c,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await ja(o,r,a,t)}}return r}i($o,"applyInterceptors");async function ja(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}i(ja,"recordInterceptorError");var Mo=new Map;function Ho(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ho,"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}i(Tn,"normalizeGlobSeparators");function Ba(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(Ba,"bracesBalanced");function Le(e){let t=Mo.get(e);if(t)return t;let n=Tn(e),r=Ba(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=Ho(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=Ho(l)}let a=new RegExp(`^${o}$`);return Mo.set(e,a),a}i(Le,"globToRegExp");function qa(e){return Tn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(qa,"concreteGlobSegments");function xr(e,t){let n=Tn(String(e)),r=qa(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let m of r){let y=-1;for(let h=c;h<a.length;h+=1)if(a[h]===m){y=h;break}if(y<0)return s;l=y,c=y+1}return(l+1)*1e6+r.length*1e4+o}i(xr,"patternSpecificity");function ne(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Le(a).test(n))){for(let a of s.patterns??[])if(Le(a).test(n)){let c=xr(a,n);c>o&&(o=c,r=s.name)}}return r}i(ne,"layerForRelativePath");function Ko(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(Ko,"sliceIdForPath");function za(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 a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(za,"inferSliceFoldersFromPatterns");function Wa(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 za(r?.patterns)}i(Wa,"resolveSliceFolders");function Ya(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(Ya,"peerIsolationMustDeny");function re(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=Wa(o,t,r?.layers),l=s&&a?Ko(s,c):void 0,m=s&&a?Ko(a,c):void 0;if(Ya({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:m}))return o;continue}if(t!==n)return o}}i(re,"findDeniedEdgeRule");async function Go(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=re(r.rules,o,s);if(!a)return;let c=t.mode,l=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,m={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:c,message:l,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:m}),await t.recordAudit("layer.observedViolation",e,m),c==="hard")throw new De(n,e.intent,o,s,l)}i(Go,"assertObservedLayerFlowAllowed");async function Uo(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof pe&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}i(Uo,"enforcePublishPolicy");function Za(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}i(Za,"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{}}i(Dt,"appendTrace");async function Dn(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)}})}}i(Dn,"recordAudit");async function Vo(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 Dn(e,"event.rawPublish",t,n)}i(Vo,"recordRawPublishDiagnostic");async function jo(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Za(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 Dn(e,"event.published",t,{subscribersNotified:n}),o}i(jo,"recordSuccessfulPublish");function Pr(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}i(Pr,"enrichMetadata");var Bo=0;function Ja(){return Bo+=1,`interceptor-${Date.now()}-${Bo}`}i(Ja,"nextInterceptorRegistrationId");var Qe=class{static{i(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new ke(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Pt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Ne;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=_t({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,l,m=typeof t!="function";if(m){let d=t,p=r??n??{};l={...d,metadata:Pr(d.metadata,p,this.recording.instanceId)}}else{let d=t,p=n,u=r??{},f=d(p);l={...f,metadata:Pr(f.metadata,u,this.recording.instanceId)}}m&&this.strictRegistry&&await Vo(this.recording,l),Nt(l.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Lo(l,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Tt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),l=await $o(l,{interceptorsForIntent:i(d=>this.interceptorsByIntent.get(d)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),Tt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Go(l,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(l.metadata.source,l.intent);let y=[...this.subscriptionsByIntent.get(l.intent)??[]];this.policyEngine&&await Uo(l,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((d,p,u)=>this.safeHook(d,p,u),"safeHook")}),await jo(this.recording,l,s?y.length:0,o.tx);let h=(async()=>{s&&await Promise.all(y.map(d=>this.invokeHandler(d,l))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(l),"onPublish",l)})();return a?await h:h.then(void 0,()=>{}),l}createPublisher(t){let n=typeof t=="string"?t:t.name;return Nt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:i(async(r,o,s={},a)=>{if(s.source&&s.source!==n)throw new ue(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Nt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let c=this.subscriptionsByIntent.get(r);if(!c)return;let l=c.indexOf(o);l>=0&&c.splice(l,1),c.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Nt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Ja(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){Dt(this.recording,t)}async recordAudit(t,n,r){await Dn(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 Or(e){return new Qe(e)}i(Or,"createEventBus");function Qa(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}i(Qa,"formatStandardSchemaPath");function Xa(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}i(Xa,"actualType");function ei(e,t){return e?`${e}.${t}`:t}i(ei,"formatPath");function qo(e,t,n,r,o){let s=Xa(e);if(t.type!=="unknown"&&s!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${s}.`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}zo(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,c)=>{qo(a,t.items,`${n}[${c}]`,r,o)})}i(qo,"validateSchemaField");function zo(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let c=ei(o,s),l=e[s];if(l===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}qo(l,a,c,n,r)}}i(zo,"validateObjectSchema");var Xe=class{static{i(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(zo(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(s))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let c of a.issues)o.push({intent:t.intent,version:r.version,field:Qa(c.path),message:c.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function Lt(){return new Xe}i(Lt,"createEventContractRegistry");var Wo=0;function ti(){return Wo+=1,`outbox-${Date.now()}-${Wo}`}i(ti,"nextOutboxId");function Yo(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Yo,"cloneRecord");var Ee=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:ti(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Yo(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(Yo)}async clear(){this.records.clear()}},_r=Ee;function Nr(e){return`${e.from}->${e.to}`}i(Nr,"flowKey");function Zo(e){let t=new Set,n=[];for(let r of e){let o=Nr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(Zo,"uniqueFlows");function Jo(e,t){let n=new Set(t.map(Nr));return e.filter(r=>!n.has(Nr(r)))}i(Jo,"difference");function Ft(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})),a=n?.getHistory().map(f=>({from:f.event.metadata.source,to:f.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="observed").map(f=>({from:f.from,to:f.to})),l=Zo([...o,...s]),m=Zo([...a,...c]),y=m.filter(f=>!f.from||f.from==="unknown"),h=t?Array.from(new Set(m.map(f=>f.from).filter(f=>f&&f!=="unknown"&&!t.has(f)))):[],d=t?Array.from(new Set(m.map(f=>f.to).filter(f=>!t.has(f)))):[],p=new Set(m.flatMap(f=>[f.from,f.to])),u=t?t.list().map(f=>f.name).filter(f=>!p.has(f)):[];return{generatedAt:new Date().toISOString(),declaredProductions:l,observedProductions:m,declaredButUnobserved:Jo(l,m),observedButUndeclared:Jo(m.filter(f=>f.from!=="unknown"),l),unknownSources:y,unregisteredObservedSources:h,unregisteredObservedIntents:d,registeredButNeverObserved:u}}}}i(Ft,"createObservabilityReporter");function Tr(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}i(Tr,"createArkTestHarness");var Qo=0;function ni(){return Qo+=1,`audit-${Date.now()}-${Qo}`}i(ni,"createAuditId");function ri(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}i(ri,"matchesQuery");var et=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>ri(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Ln=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:ni(),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 $t(e={}){return new Ln(e.store??new et(e.maxRecords))}i($t,"createAuditTrail");var Fn=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
|
|
7
|
+
${n}`),this.name="PolicyViolationError",this.violations=t}};var ve=class{static{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let l of a)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new ue(n.hardViolations);return n}clear(){this.policies.length=0}};function Pe(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}i(Pe,"definePolicy");function Qi(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Qi,"defaultLayerOf");function $o(e,t){return t.resolveLayer?.(e)??Qi(e)}i($o,"resolveLayer");function ea(e,t,n){return e===n.from&&t===n.to}i(ea,"matchesRule");function Ct(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Pe({name:t,severity:n,tags:["layer"],check:i(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],s=[];for(let a of o){let l=$o(a.from,e),c=$o(a.to,e);for(let g of e.rules)!g.allowed&&ea(l,c,g)&&s.push({policyName:t,severity:n,message:g.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(Ct,"defineLayerPolicy");function wt(e){return e.tags?.includes("layer")??!1}i(wt,"isLayerPolicy");var _n={layerIsolation(){return _n.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return Ct({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 xt(e,t={}){return Ct({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(xt,"defineArchitectureProfilePolicy");function Ot(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(Ot,"buildPublishPolicyContext");function wr(e){return Pe(e)}i(wr,"definePublishPolicy");var _e=class extends Error{static{i(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},Ne=class extends Error{static{i(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Te=class extends Error{static{i(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},De=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},be=class extends Error{static{i(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},fe=class extends Error{static{i(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},Le=class extends Error{static{i(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function Pt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=St(e);if(!n.valid)throw new Ne(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new _e(e)}}i(Pt,"assertIntentAllowed");function Mo(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new be(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new be(e.intent,e.metadata.source)}}i(Mo,"assertSourceAllowed");function _t(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new De(e.intent,n.issues)}i(_t,"assertContractAllowed");function Ye(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Ye,"isPlainRecord");function Xe(e){return Array.isArray(e)?e.map(Xe):Ye(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Xe(n)])):e}i(Xe,"clonePatchValue");function xr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=Xe(s);continue}if(Ye(r[o])&&Ye(s)){r[o]=xr(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=Or(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(xr,"mergeRecordPatch");function Or(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let a=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=Xe(o);return}if(Ye(r[s])&&Ye(o)){r[s]=xr(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=Or(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(Or,"mergeArrayPatch");function Ho(e,t){if(Array.isArray(t)){if(e===void 0)return Xe(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return Or(e,t)}if(e===void 0)return Xe(t);if(!Ye(e))throw new Error("Object interceptor patch requires an object payload.");return xr(e,t)}i(Ho,"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:i(c=>{s.push(c)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let c of s)l={...l,payload:Ho(l.payload,c),metadata:{...l.metadata}};_t(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await ta(o,r,a,t)}}return r}i(Ko,"applyInterceptors");async function ta(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}i(ta,"recordInterceptorError");var Go=new Map;function Uo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Uo,"escapeLiteral");function Nn(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(Nn,"normalizeGlobSeparators");function na(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(na,"bracesBalanced");function ge(e){let t=Go.get(e);if(t)return t;let n=Nn(e),r=na(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Uo(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+=Uo(c)}let a=new RegExp(`^${o}$`);return Go.set(e,a),a}i(ge,"globToRegExp");function ra(e){return Nn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(ra,"concreteGlobSegments");function Pr(e,t){let n=Nn(String(e)),r=ra(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let g of r){let m=-1;for(let h=l;h<a.length;h+=1)if(a[h]===g){m=h;break}if(m<0)return s;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+o}i(Pr,"patternSpecificity");function ie(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ge(a).test(n))){for(let a of s.patterns??[])if(ge(a).test(n)){let l=Pr(a,n);l>o&&(o=l,r=s.name)}}return r}i(ie,"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()}`}i(Vo,"sliceIdForPath");function oa(e){let t=new Set;for(let n of e??[]){let o=Nn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(oa,"inferSliceFoldersFromPatterns");function sa(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 oa(r?.patterns)}i(sa,"resolveSliceFolders");function jo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(jo,"normalizeSegments");function qo(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(qo,"trimTrailingSlashes");var ia=["src","app"];function aa(e){let t=qo(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(aa,"isBlanketRoot");function Bo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=jo(n);for(let s of t){if(typeof s!="string"||s.length===0||aa(s))continue;if(s.includes("*")){let c=qo(s.toLowerCase());if(ge(c).test(r)||ge(`${c}/**`).test(r))return!0;continue}let a=jo(s);if(a.length===0)continue;let l=ia.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let g=!0;for(let m=0;m<a.length;m+=1)if(o[c+m]!==a[m]){g=!1;break}if(g)return!0}}return!1}i(Bo,"pathUnderSharedRoot");function Wo(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(Wo,"sliceMatchesDeclaration");function la(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Wo(r.from,t)&&Wo(r.to,n))}i(la,"crossSliceEdgeAllowed");function ca(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"}}i(ca,"peerIsolationDecision");function zo(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(zo,"peerIsolationDenyExplanation");function me(e,t,n,r){return _r(e,t,n,r)?.rule}i(me,"findDeniedEdgeRule");function _r(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,l=sa(o,t,r?.layers),c=s&&a?Vo(s,l):void 0,g=s&&a?Vo(a,l):void 0,m=ca({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:g,fromShared:!c&&Bo(s,o.sharedRoots),toShared:!g&&Bo(a,o.sharedRoots),crossSliceAllowed:la(o.allowedCrossSlice,c,g)});if(m.denied)return{rule:o,peerIsolationReason:m.reason,fromSlice:c,toSlice:g};continue}if(t!==n)return{rule:o}}}i(_r,"findDeniedEdgeDecision");async function Yo(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=me(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,g={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:g}),await t.recordAudit("layer.observedViolation",e,g),l==="hard")throw new Le(n,e.intent,o,s,c)}i(Yo,"assertObservedLayerFlowAllowed");async function Xo(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof ue&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}i(Xo,"enforcePublishPolicy");function da(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}i(da,"appendHistory");function Nt(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}i(Nt,"appendTrace");async function Tn(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){Nt(e,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}i(Tn,"recordAudit");async function Zo(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."};Nt(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 Tn(e,"event.rawPublish",t,n)}i(Zo,"recordRawPublishDiagnostic");async function Jo(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return da(e,o),await e.eventBuffer?.enqueue(t,r),Nt(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 Tn(e,"event.published",t,{subscribersNotified:n}),o}i(Jo,"recordSuccessfulPublish");function Nr(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}i(Nr,"enrichMetadata");var Qo=0;function pa(){return Qo+=1,`interceptor-${Date.now()}-${Qo}`}i(pa,"nextInterceptorRegistrationId");var Ze=class{static{i(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new ve(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(wt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Te;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=Ot({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,g=typeof t!="function";if(g){let p=t,f=r??n??{};c={...p,metadata:Nr(p.metadata,f,this.recording.instanceId)}}else{let p=t,f=n,u=r??{},y=p(f);c={...y,metadata:Nr(y.metadata,u,this.recording.instanceId)}}g&&this.strictRegistry&&await Zo(this.recording,c),Pt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Mo(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),_t(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Ko(c,{interceptorsForIntent:i(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),_t(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Yo(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((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 Xo(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,f,u)=>this.recordAudit(p,f,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((p,f,u)=>this.safeHook(p,f,u),"safeHook")}),await Jo(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 a?await h:h.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return Pt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:i(async(r,o,s={},a)=>{if(s.source&&s.source!==n)throw new fe(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Pt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Pt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:pa(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){Nt(this.recording,t)}async recordAudit(t,n,r){await Tn(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 Tr(e){return new Ze(e)}i(Tr,"createEventBus");function ua(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}i(ua,"formatStandardSchemaPath");function fa(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}i(fa,"actualType");function ga(e,t){return e?`${e}.${t}`:t}i(ga,"formatPath");function es(e,t,n,r,o){let s=fa(e);if(t.type!=="unknown"&&s!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${s}.`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}ts(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{es(a,t.items,`${n}[${l}]`,r,o)})}i(es,"validateSchemaField");function ts(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=ga(o,s),c=e[s];if(c===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}es(c,a,l,n,r)}}i(ts,"validateObjectSchema");var Je=class{static{i(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(ts(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(s))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let l of a.issues)o.push({intent:t.intent,version:r.version,field:ua(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 Tt(){return new Je}i(Tt,"createEventContractRegistry");var ns=0;function ma(){return ns+=1,`outbox-${Date.now()}-${ns}`}i(ma,"nextOutboxId");function rs(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(rs,"cloneRecord");var Ee=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:ma(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),rs(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(rs)}async clear(){this.records.clear()}},Dr=Ee;function Lr(e){return`${e.from}->${e.to}`}i(Lr,"flowKey");function os(e){let t=new Set,n=[];for(let r of e){let o=Lr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(os,"uniqueFlows");function ss(e,t){let n=new Set(t.map(Lr));return e.filter(r=>!n.has(Lr(r)))}i(ss,"difference");function Dt(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})),a=n?.getHistory().map(y=>({from:y.event.metadata.source,to:y.event.intent}))??[],l=a.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="observed").map(y=>({from:y.from,to:y.to})),c=os([...o,...s]),g=os([...a,...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:ss(c,g),observedButUndeclared:ss(g.filter(y=>y.from!=="unknown"),c),unknownSources:m,unregisteredObservedSources:h,unregisteredObservedIntents:p,registeredButNeverObserved:u}}}}i(Dt,"createObservabilityReporter");function Fr(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}i(Fr,"createArkTestHarness");var is=0;function ya(){return is+=1,`audit-${Date.now()}-${is}`}i(ya,"createAuditId");function ha(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}i(ha,"matchesQuery");var Qe=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>ha(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Dn=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:ya(),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 Lt(e={}){return new Dn(e.store??new Qe(e.maxRecords))}i(Lt,"createAuditTrail");var Ln=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
|
|
8
8
|
`;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";t+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
|
|
9
9
|
`}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(t+=` ${this.safeId(r)}
|
|
10
|
-
`);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let a=t.resolveLayer(s)??"Unclassified",
|
|
10
|
+
`);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let a=t.resolveLayer(s)??"Unclassified",l=n.get(a)??[];l.push(s),n.set(a,l)}let r=`flowchart TD
|
|
11
11
|
`;for(let s of t.layers){let a=n.get(s.name)??[];if(a.length!==0){r+=` subgraph ${this.safeId(s.name)}[${s.name}]
|
|
12
|
-
`;for(let
|
|
12
|
+
`;for(let l of a)r+=` ${this.safeId(l)}[${l}]
|
|
13
13
|
`;r+=` end
|
|
14
14
|
`}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
|
|
15
15
|
`;for(let s of o)r+=` ${this.safeId(s)}[${s}]
|
|
16
16
|
`;r+=` end
|
|
17
17
|
`}for(let s of this.edges){let a=s.kind?`|${s.kind}|`:"";r+=` ${this.safeId(s.from)} -->${a} ${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
|
|
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=i(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 a=new Set(n.map(l=>l.join("->")));return Array.from(a).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function Ft(){return new Ln}i(Ft,"createDependencyGraph");function $t(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"))}i($t,"syncRegistryToGraph");var et={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},as={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...et,default:[]},kernelRoots:{...et},managedLayers:{...et,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},ls={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...et,default:[]},managedLayers:{...et,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...et,default:[]}}};function Mt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Mt,"isObject");function cs(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Mt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(cs,"declaredLayerNames");function ds(e){if(!Mt(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}}i(ds,"defaultedArkRun");function ps(e){if(!Mt(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}}i(ps,"defaultedArkOrder");function us(e,t){let n=e.arkRun;if(n===void 0||!Mt(n))return;let r=cs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,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"})}}i(us,"validateArkRunExtra");function fs(e,t){let n=e.arkOrder;if(n===void 0||!Mt(n))return;let r=cs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,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"})}}i(fs,"validateArkOrderExtra");var oe="1.3",$n="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",gs=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ra=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Aa(){let e=[];for(let t of gs)for(let n of gs)t===n||Ra.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Aa,"createDefaultRules");var Mn=Aa(),$r=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],re={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ms={$schema:"https://json-schema.org/draft/2020-12/schema",$id:$n,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:$n,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:oe,default:oe},name:{type:"string",minLength:1},include:{...re,minItems:1,default:["src"]},exclude:{...re,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Mn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...re,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:{...re,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...re,minItems:1},exclude:re,intentPrefixes:re,description:{type:"string",minLength:1},forbiddenGlobals:re,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:{...re,minItems:1},sharedRoots:{...re,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:{...re,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...re,minItems:1}}},arkRun:as,arkOrder:ls}},ye=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
19
19
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
20
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function
|
|
21
|
-
`));return a}i(Mr,"createAdapter");function Hr(e,t=[]){let n=t.filter(r=>!ps(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(Hr,"checkContract");function Gn(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}i(Gn,"checkAdapterGovernance");function ps(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(ps,"hasMember");var Gr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Vr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),jr=Object.freeze(Object.keys(Vr).sort()),Kr=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 qt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Kr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Kr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Kr[e.slice(0,s)]??null}i(qt,"capabilityForModuleSpecifier");function ve(e,t){for(let n of t)if(Ur[n]?.includes(e))return n;return null}i(ve,"forbiddenGlobalForModuleSpecifier");function Un(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Vr[r];if(o)return o}return null}i(Un,"capabilityForAmbientName");function nt(e){if(e?.pure===!0)return[...Gr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Gr.includes(r));return[...new Set(n)].sort()}i(nt,"effectiveCapabilityDeny");function zt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(zt,"ambientCoveredByForbiddenGlobals");function Vn(e){let t=new Set,n=new Set,r=Object.keys(Vr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Ur[o]??[])t.add(`import-exact:${a}`)}for(let o of nt(e)){if(t.add(`import:${o}`),o==="process")for(let s of Ur.process)t.add(`import-exact:${s}`);for(let s of r)Un(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Vn,"loweredLayerCoverage");function rt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(rt,"literalText");function ms(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(ms,"lineOf");function us(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(us,"isTypeOnlyReference");function ys(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(ys,"singleFileChecker");function Br(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Br,"symbolAt");function qr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Br(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(qr,"localDeclaration");function $e(e,t){let n,r=[],o=i((a,c,l,m=!1)=>r.push({specifier:l,kind:c,line:ms(t,a),typeOnly:m,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",rt(e,a.moduleSpecifier),us(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",rt(e,a.moduleSpecifier),us(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",rt(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,m=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!qr(e,n??(n=ys(e,t)),t,a.expression);(c||m)&&o(a,m?"require":"dynamic-import",rt(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i($e,"extractSemanticDependencies");function yi(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=rt(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(yi,"staticAccessPath");function gi(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(gi,"runtimeIdentifierReference");function fs(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(fs,"bestForbiddenMatch");function Me(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ys(e,t),s=new Map,a=new Set;for(let d of t.statements)if(e.isVariableStatement(d))for(let p of d.declarationList.declarations)e.isIdentifier(p.name)&&a.add(p.name.text);let c=i(d=>{let p=yi(e,d);if(!p)return;let u=Br(o,p.root),f=u?s.get(u):void 0;return f?[...f,...p.segments.slice(1)]:qr(e,o,t,p.root)||a.has(p.root.text)?void 0:p.segments},"resolvePath");for(let d of t.statements)if(e.isVariableStatement(d))for(let p of d.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let u=c(p.initializer),f=Br(o,p.name);!u||!f||s.set(f,u)}let l=[],m=new Set,y=i((d,p)=>{let u=ms(t,p),f=`${d}:${p.getStart(t)}`;m.has(f)||(m.add(f),l.push({name:d,line:u,node:p}))},"flag"),h=i(d=>{let p=d.parent&&(e.isPropertyAccessExpression(d.parent)||e.isElementAccessExpression(d.parent))&&d.parent.expression===d;if((e.isPropertyAccessExpression(d)||e.isElementAccessExpression(d))&&!p){let u=c(d),f=u?fs(r,u):void 0;f&&y(f,d)}else e.isIdentifier(d)&&r.has(d.text)&&gi(e,d)&&!qr(e,o,t,d)&&y(d.text,d);if(e.isVariableDeclaration(d)&&e.isObjectBindingPattern(d.name)&&d.initializer){let u=c(d.initializer);if(u)for(let f of d.name.elements){if(!e.isIdentifier(f.name))continue;let v=f.propertyName?rt(e,f.propertyName)??f.propertyName.text:f.name.text,b=fs(r,[...u,v]);b&&y(b,d.initializer)}}e.forEachChild(d,h)},"visit");return h(t),l}i(Me,"collectForbiddenCapabilityUses");function zr(e,t,n){let r=[];for(let o of n?.dependencies??$e(e,t)){if(o.typeOnly||!o.specifier)continue;let s=qt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Me(e,t,jr)){let s=Un(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(zr,"collectCapabilityUses");var Wr={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."},Yr=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 Zr(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Zr,"resolveIntentLayer");function He(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(He,"looksLikeArkIntent");function Wt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&He(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Wr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Wr.PUBLISH_MISSING_SOURCE}),t}i(Wt,"classifyPublishFacts");function F(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(F,"violation");function ot(e,t){return e.slice(0,t).split(`
|
|
22
|
-
`).length}i(ot,"lineOf");function hi(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}i(hi,"extractQuotedStrings");function Ri(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:c})}}return t.sort((r,o)=>r.index-o.index)}i(Ri,"extractModuleSpecifiers");function Ai(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(Ai,"extractQuotedStringsAst");function ki(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}i(ki,"hasInfrastructureToken");function Ii(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(Ii,"isKnownInfrastructurePackage");function Ei(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Ei,"layerHasInfrastructureRole");function Zt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Zt,"tsStringLiteralText");function vi(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(vi,"tsPropertyName");function gs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:vi(e,r.name)===n)}i(gs,"tsObjectProperty");function Jt(e,t,n){return gs(e,t,n)!==void 0}i(Jt,"tsObjectHasProperty");function Yt(e,t,n){let r=gs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Yt,"tsObjectPropertyValue");function bi(e,t){let n=Yt(e,t,"metadata");return Jt(e,n,"source")}i(bi,"tsObjectHasMetadataSource");function hs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?hs(e,t.name):!1:!1}i(hs,"tsLooksLikeIntentCreatorExpression");function Si(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}i(Si,"tsIsPublishCall");function Ci(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Zt(e,n);return r!==void 0&&He(r)||Jt(e,n,"intent")||hs(e,n)}i(Ci,"tsIsArkPublishCandidate");function wi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return bi(e,n)||Jt(e,r,"source")||Jt(e,o,"source")}i(wi,"tsPublishHasSource");function xi(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Yt(e,n,"metadata");return Zt(e,Yt(e,s,"source"))??Zt(e,Yt(e,r,"source"))??Zt(e,Yt(e,o,"source"))}i(xi,"tsPublishSourceLiteral");function Pi(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,l=[],m=i(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),y=i(h=>{if(Si(e,h)){let d=h.arguments[0],p=Zt(e,d);for(let f of Wt({publishCall:!0,rawIntentName:p,objectHasIntent:Jt(e,d,"intent"),arkPublishCandidate:Ci(e,h),hasSource:wi(e,h)}))l.push(F(f.ruleId,f.message,{line:m(h),filePath:a}));let u=xi(e,h);if(r&&c&&u&&He(u)){let f=r.resolveLayer(u);f&&f!==c&&l.push(F("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${f}, but the target file is classified as ${c}.`,{line:m(h),filePath:a,target:u,fromLayer:c,toLayer:f}))}}e.forEachChild(h,y)},"visit");return y(o),l}i(Pi,"analyzePublishAst");function Jr(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],l=a,m=l?.filePath,y=l?.layer,h=e.typescript,d=h?h.createSourceFile(m??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,p=d?$e(e.typescript,d):void 0,u=p?p.filter(I=>I.specifier!==void 0).map(I=>({value:I.specifier,index:I.node.getStart(d),kind:I.kind,typeOnly:I.typeOnly})):Ri(s),f=e.typescript?Ai(e.typescript,s):hi(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(m))for(let I of p?.filter(({unresolved:k})=>k)??[]){let k=I.kind==="require";c.push(F(k?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${k?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:I.line,filePath:m}))}let v=y!==void 0&&(r.has(y)||Ei(y)),b=y!==void 0?` If "${y}" 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 I of n)if(I instanceof RegExp){I.lastIndex=0;let k=I.exec(s);I.lastIndex=0,k&&c.push(F("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${I}`,{line:k.index===void 0?void 0:ot(s,k.index),filePath:m,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else s.includes(I)&&c.push(F("FORBIDDEN_SUBSTRING",`Forbidden substring: ${I}`,{line:ot(s,s.indexOf(I)),filePath:m}));for(let I of u){let k=e.resolveImportTarget?.(I.value,m)??(e.resolveImportLayer?{layer:e.resolveImportLayer(I.value,m)}:void 0),C=typeof m=="string"?e.resolveImportTarget?.(m)??(e.resolveImportLayer?{layer:y,relPath:void 0}:void 0):void 0,Y=k?.layer;if(Y&&y){let _=re(e.architectureProfile?.rules,y,Y,{fromPath:C?.relPath,toPath:k?.relPath,layers:e.architectureLayers});if(_){if(I.typeOnly&&!_.peerIsolation)continue;let j=!!_.peerIsolation;c.push(F("LAYER_IMPORT_VIOLATION",_.message??(j?`Layer "${y}" must not import across slices into "${Y}".`:`Layer "${y}" must not import "${Y}".`),{line:ot(s,I.index),source:I.value,target:I.value,filePath:m,fromLayer:y,toLayer:Y,suggestion:j?"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:I.kind,peerIsolation:j,...I.typeOnly?{typeOnly:!0}:{}}}));continue}continue}v||I.typeOnly||!ki(I.value)&&!Ii(I.value)||c.push(F("FORBIDDEN_IMPORT",`Forbidden ${I.kind} target: "${I.value}".`,{line:ot(s,I.index),source:I.value,target:I.value,filePath:m,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:I.kind}}))}if(e.policies)for(let I of e.policies){let k=I.check({source:s,context:a});if(k!==!0)if(Array.isArray(k))for(let C of k)c.push(F("POLICY_VIOLATION",C.message,{filePath:m,suggestion:`Fix violation of policy "${I.name}".`}));else k===!1?c.push(F("POLICY_VIOLATION",`Policy ${I.name} failed on generated code`)):c.push(F("POLICY_VIOLATION",k.message))}if(o&&t.size>0)for(let I of f)He(I.value)&&!t.has(I.value)&&c.push(F("UNKNOWN_INTENT",`Unknown intent reference: "${I.value}"`,{line:ot(s,I.index),filePath:m,target:I.value,suggestion:`Register intent "${I.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&y)for(let I of f){if(!He(I.value))continue;let k=e.architectureProfile.resolveLayer(I.value);if(!k)continue;let C=re(e.architectureProfile.rules,y,k);C&&c.push(F("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${y}" must not reference "${k}" through "${I.value}".`,{line:ot(s,I.index),filePath:m,target:I.value,fromLayer:y,toLayer:k,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let I of e.extensions)try{let k=I.analyze(s,a);c.push(...k)}catch(k){c.push(F("EXTENSION_ERROR",`Extension "${I.name}" failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&d&&y&&e.forbiddenGlobals?.[y]?.length)try{let I=e.forbiddenGlobals[y];c.push(...Me(e.typescript,d,I).map(k=>F("FORBIDDEN_GLOBAL",`${y} must not use the ambient global "${k.name}".`,{line:k.line,filePath:m,target:k.name,fromLayer:y,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let k of p??[]){if(k.typeOnly||!k.specifier)continue;let C=ve(k.specifier,I);C&&c.push(F("FORBIDDEN_GLOBAL",`${y} must not use module "${k.specifier}" because it is the import form of forbidden global "${C}".`,{line:k.line,filePath:m,source:k.specifier,target:k.specifier,fromLayer:y,details:{importKind:k.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(I){c.push(F("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&d&&y&&e.capabilityWalls?.[y]?.length)try{let I=new Set(e.capabilityWalls[y]),k=e.forbiddenGlobals?.[y]??[];for(let C of zr(e.typescript,d))I.has(C.capability)&&(C.source==="ambient-global"&&zt(C.symbol,k)||C.source==="import-based"&&ve(C.symbol,k)||c.push(F("CAPABILITY_VIOLATION",C.source==="import-based"?`${y} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${y} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:m,target:C.symbol,capability:C.capability,fromLayer:y,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(I){c.push(F("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript)try{c.push(...Pi(e.typescript,s,a,e.architectureProfile))}catch(I){c.push(F("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${I instanceof Error?I.message:String(I)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}i(Jr,"createAICodeGate");function M(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(M,"deterministicHash");function D(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(D).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${D(t[n])}`).join(",")}}`}i(D,"stableSerialize");var be="1.2";var Rs=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=D(e),r=D(t);return n<r?-1:n>r?1:0}i(B,"compareCanonical");function q(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(q,"sortedUnique");function at(e){let t={schemaVersion:"1.2",include:q(e.include??[]),exclude:q(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:q(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:q(n.patterns??[]),exclude:q(n.exclude??[]),forbiddenGlobals:q(n.forbiddenGlobals??[]),intentPrefixes:q(n.intentPrefixes??[]),capabilityDeny:q(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(B),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:q(e.arkRun.compositionRoots),managedLayers:q(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return M(D(t))}i(at,"resolvedFactsEvidenceRequirementsHash");function Oi(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(B),n=e.files.map(k=>({...k,typeOnlyExportNames:q(k.typeOnlyExportNames)})).sort((k,C)=>k.path<C.path?-1:k.path>C.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:q(k.namedBindings)}:{}})).sort(B),o=e.capabilityUses.map(k=>({...k})).sort(B),s=e.ambientUses.map(k=>({...k})).sort(B),a=e.publishCalls.map(k=>({...k})).sort(B),c=e.intentReferences.map(k=>({...k})).sort(B),l=e.safetyUses.map(k=>({...k})).sort(B),m=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(C=>({...C}))})).sort(B),y=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(B),h=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(B),d=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(B),p=(e.arkRunDeclarations??[]).map(k=>({...k,uses:q(k.uses),reactsTo:q(k.reactsTo),raises:q(k.raises),sends:q(k.sends)})).sort(B),u=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(B),f=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(B),v=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(B),b=e.files.map(({path:k,contentHash:C})=>({path:k,contentHash:C})).sort((k,C)=>k.path<C.path?-1:k.path>C.path?1:0),I=M(D(b));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:I,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:l,classShapes:m,arkRunKernelCalls:y,arkRunManagedNews:h,arkRunCompositionRootHits:d,arkRunDeclarations:p,arkOrderPlaneCalls:u,arkOrderGenericUpdates:f,arkOrderRootHits:v}}i(Oi,"canonicalResolvedFactsInput");function As(e){let t=Oi(e);return{...t,factsHash:M(D(t))}}i(As,"createCanonicalResolvedCandidateFacts");function jn(e){return As(Is($(e,"$"),!1))}i(jn,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i($,"asRecord");function H(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(H,"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}i(T,"requiredText");function ye(e,t,n){if(e[t]!==void 0)return T(e,t,n)}i(ye,"optionalText");function G(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 c of o.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(G,"requiredProjectPath");function L(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(L,"requiredBoolean");function ks(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(ks,"requiredInteger");function oe(e,t,n){let r=ks(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(oe,"requiredPositiveInteger");function U(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(U,"requiredArray");function ge(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(ge,"enumValue");function st(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(st,"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)}}i(_i,"assertUnique");function Is(e,t){H(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",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ge(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ge(e,"completeness",["complete","partial","unavailable"],"$"),o=U(e,"completenessReasons","$").map((S,P)=>{let R=`$.completenessReasons[${P}]`,A=$(S,R);H(A,["code","message","file"],R);let N=A.file===void 0?void 0:G(A,"file",R);return{code:T(A,"code",R),message:T(A,"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=U(e,"files","$").map((S,P)=>{let R=`$.files[${P}]`,A=$(S,R);return H(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:G(A,"path",R),contentHash:T(A,"contentHash",R),parseStatus:ge(A,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:ks(A,"parseDiagnosticCount",R),exportsOnlyTypes:L(A,"exportsOnlyTypes",R),typeOnlyExportNames:st(A.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:L(A,"hasTopLevelSideEffects",R)}}),a=U(e,"dependencies","$").map((S,P)=>{let R=`$.dependencies[${P}]`,A=$(S,R);H(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let N=ye(A,"specifier",R),K=ye(A,"target",R),Ae=ge(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(Ae==="resolved-project"&&!K)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(Ae!=="resolved-project"&&K)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(Ae!=="dynamic"&&!N)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:G(A,"from",R),...N?{specifier:N}:{},kind:ge(A,"kind",["import","export","dynamic-import","require"],R),typeOnly:L(A,"typeOnly",R),line:oe(A,"line",R),resolution:Ae,...K?{target:G(A,"target",R)}:{},...A.namedBindings!==void 0?{namedBindings:st(A.namedBindings,`${R}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:L(A,"targetTypeOnlyExports",R)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:L(A,"sourcePureTypeModule",R)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:L(A,"namedBindingsTypeOnly",R)}:{},...A.portProofEligible!==void 0?{portProofEligible:L(A,"portProofEligible",R)}:{}}}),c=U(e,"capabilityUses","$").map((S,P)=>{let R=`$.capabilityUses[${P}]`,A=$(S,R);return H(A,["file","line","symbol","capability","source"],R),{file:G(A,"file",R),line:oe(A,"line",R),symbol:T(A,"symbol",R),capability:ge(A,"capability",Rs,R),source:ge(A,"source",["ambient-global","import-based"],R)}}),l=U(e,"ambientUses","$").map((S,P)=>{let R=`$.ambientUses[${P}]`,A=$(S,R);return H(A,["file","line","symbol"],R),{file:G(A,"file",R),line:oe(A,"line",R),symbol:T(A,"symbol",R)}}),m=U(e,"publishCalls","$").map((S,P)=>{let R=`$.publishCalls[${P}]`,A=$(S,R);H(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let N=ye(A,"rawIntentName",R),K=ye(A,"sourceIntent",R);return{file:G(A,"file",R),line:oe(A,"line",R),...N?{rawIntentName:N}:{},objectHasIntent:L(A,"objectHasIntent",R),arkPublishCandidate:L(A,"arkPublishCandidate",R),hasSource:L(A,"hasSource",R),...K?{sourceIntent:K}:{}}}),y=U(e,"intentReferences","$").map((S,P)=>{let R=`$.intentReferences[${P}]`,A=$(S,R);return H(A,["file","line","intent"],R),{file:G(A,"file",R),line:oe(A,"line",R),intent:T(A,"intent",R)}}),h=U(e,"safetyUses","$").map((S,P)=>{let R=`$.safetyUses[${P}]`,A=$(S,R);H(A,["file","line","kind","symbol"],R);let N=ye(A,"symbol",R),K=ge(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if(K==="in-memory-store"&&!N)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if(K!=="in-memory-store"&&N)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:G(A,"file",R),line:oe(A,"line",R),kind:K,...N?{symbol:N}:{}}});_i(s,S=>S.path,"$.files");let d=new Set(s.map(S=>S.path));for(let S of s){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!d.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:U(e,"arkRunKernelCalls","$")).map((S,P)=>{let R=`$.arkRunKernelCalls[${P}]`,A=$(S,R);H(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let N=ye(A,"receiver",R),K=ye(A,"nameLiteral",R);return{file:G(A,"file",R),line:oe(A,"line",R),kind:ge(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:T(A,"callee",R),viaImport:L(A,"viaImport",R),...N?{receiver:N}:{},...K?{nameLiteral:K}:{}}}),v=(e.arkRunManagedNews===void 0?[]:U(e,"arkRunManagedNews","$")).map((S,P)=>{let R=`$.arkRunManagedNews[${P}]`,A=$(S,R);H(A,["file","line","typeName","importedFrom"],R);let N=ye(A,"importedFrom",R);return{file:G(A,"file",R),line:oe(A,"line",R),typeName:T(A,"typeName",R),...N?{importedFrom:N}:{}}}),I=(e.arkRunCompositionRootHits===void 0?[]:U(e,"arkRunCompositionRootHits","$")).map((S,P)=>{let R=`$.arkRunCompositionRootHits[${P}]`,A=$(S,R);return H(A,["file","matchedRoot","hasKernelFactory"],R),{file:G(A,"file",R),matchedRoot:T(A,"matchedRoot",R),hasKernelFactory:L(A,"hasKernelFactory",R)}}),k=e.arkRunDeclarations===void 0?[]:U(e,"arkRunDeclarations","$"),Y=(e.arkOrderPlaneCalls===void 0?[]:U(e,"arkOrderPlaneCalls","$")).map((S,P)=>{let R=`$.arkOrderPlaneCalls[${P}]`,A=$(S,R);return H(A,["file","line","callee"],R),{file:G(A,"file",R),line:oe(A,"line",R),callee:T(A,"callee",R)}}),j=(e.arkOrderGenericUpdates===void 0?[]:U(e,"arkOrderGenericUpdates","$")).map((S,P)=>{let R=`$.arkOrderGenericUpdates[${P}]`,A=$(S,R);return H(A,["file","line","method"],R),{file:G(A,"file",R),line:oe(A,"line",R),method:T(A,"method",R)}}),ze=(e.arkOrderRootHits===void 0?[]:U(e,"arkOrderRootHits","$")).map((S,P)=>{let R=`$.arkOrderRootHits[${P}]`,A=$(S,R);return H(A,["file","matchedRoot","hasPlaneFactory"],R),{file:G(A,"file",R),matchedRoot:T(A,"matchedRoot",R),hasPlaneFactory:L(A,"hasPlaneFactory",R)}}),We=k.map((S,P)=>{let R=`$.arkRunDeclarations[${P}]`,A=$(S,R);return H(A,["file","line","uses","reactsTo","raises","sends"],R),{file:G(A,"file",R),line:oe(A,"line",R),uses:st(A.uses,`${R}.uses`),reactsTo:st(A.reactsTo,`${R}.reactsTo`),raises:st(A.raises,`${R}.raises`),sends:st(A.sends,`${R}.sends`)}});for(let[S,P]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",m],["$.intentReferences",y],["$.safetyUses",h],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",I],["$.arkRunDeclarations",We],["$.arkOrderPlaneCalls",Y],["$.arkOrderGenericUpdates",j],["$.arkOrderRootHits",ze]])for(let R of P)if(!d.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let Ye=ye(e,"projectPackageName","$"),Er=(e.classShapes===void 0?[]:U(e,"classShapes","$")).map((S,P)=>{let R=`$.classShapes[${P}]`,A=$(S,R);H(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let N=U(A,"mutatingMethods",R).map((K,Ae)=>{let we=`${R}.mutatingMethods[${Ae}]`,It=$(K,we);return H(It,["name","referencesGuardOrPublish"],we),{name:T(It,"name",we),referencesGuardOrPublish:L(It,"referencesGuardOrPublish",we)}});return{file:G(A,"file",R),className:T(A,"className",R),exported:L(A,"exported",R),hasPublicMutableFields:L(A,"hasPublicMutableFields",R),hasPublicSetters:L(A,"hasPublicSetters",R),hasPublicConstructor:L(A,"hasPublicConstructor",R),hasStaticFactory:L(A,"hasStaticFactory",R),mutatingMethods:N,...A.dataOnly===void 0?{}:{dataOnly:L(A,"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","$"),...Ye?{projectPackageName:Ye}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:l,publishCalls:m,intentReferences:y,safetyUses:h,classShapes:Er,arkRunKernelCalls:u,arkRunManagedNews:v,arkRunCompositionRootHits:I,arkRunDeclarations:We,arkOrderPlaneCalls:Y,arkOrderGenericUpdates:j,arkOrderRootHits:ze}}i(Is,"parseResolvedFactsInput");function he(e){let t=$(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=As(Is(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(he,"loadResolvedCandidateFacts");var Ni=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},se={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Bn={$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:V}}},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:V,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:V,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:se,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,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:V,line:se,symbol:x,capability:{enum:Ni},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:se,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:se,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:V,line:se,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:se,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:V,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:V,line:se,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:V,line:se,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:se,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:V,line:se,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:se,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},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 qn="1.0";function Z(e){return`${e.from}->${e.to}`}i(Z,"dependencyKey");function Qt(e,t,n,r="dependency"){return{id:`${e}:${r}:${Z(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Z(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Z(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Z(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Z(t)} from the candidate, then preflight again.`}:{}}}i(Qt,"dependencyFinding");function Ke(e){let t=[],n=new Map(e.changeMap.map.files.map(d=>[d.path,d])),r=new Map(e.changes.map(d=>[d.path,d])),o=new Map(e.changeMap.map.dependencies.map(d=>[Z(d),d])),s=new Map(e.baseDependencies.map(d=>[Z(d),d])),a=new Map(e.candidateDependencies.map(d=>[Z(d),d]));for(let d of[...n.values()].sort((p,u)=>p.path.localeCompare(u.path))){let p=r.get(d.path);p?p.operation!==d.operation?t.push({id:`contradictory:file:${d.path}`,classification:"contradictory",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:p.operation,message:`${d.path} was planned as ${d.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${d.path} to the planned ${d.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${d.path}`,classification:"satisfied",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:p.operation,message:`${d.path} matches the planned ${d.operation} operation.`}):t.push({id:`missing:file:${d.path}`,classification:"missing",subject:"file",path:d.path,expectedOperation:d.operation,message:`${d.path} was planned as ${d.operation} but is absent from the actual change.`,nextAction:`${d.operation[0].toUpperCase()}${d.operation.slice(1)} ${d.path} in the complete change set, then preflight again.`})}for(let d of[...r.values()].sort((p,u)=>p.path.localeCompare(u.path)))n.has(d.path)||t.push({id:`unplanned:file:${d.path}`,classification:"unplanned",subject:"file",path:d.path,actualOperation:d.operation,message:`${d.path} has an unplanned ${d.operation} operation.`,nextAction:`Remove ${d.path} from the change set, then preflight again.`});let c=new Set;for(let d of[...o.values()].sort((p,u)=>Z(p).localeCompare(Z(u)))){if(a.has(Z(d))){t.push(Qt("satisfied",d,`${d.from} -> ${d.to} exists in the candidate architecture.`));continue}let p={from:d.to,to:d.from};a.has(Z(p))?(c.add(Z(p)),t.push(Qt("contradictory",d,`${d.from} -> ${d.to} was planned, but the candidate contains the reverse edge.`))):t.push(Qt("missing",d,`${d.from} -> ${d.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[d,p]of[...a].sort(([u],[f])=>u.localeCompare(f)))s.has(d)||o.has(d)||c.has(d)||!l.has(p.from)&&!l.has(p.to)||t.push({...Qt("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let m=new Set(e.changeMap.map.files.filter(d=>d.operation==="delete").map(d=>d.path));for(let[d,p]of[...s].sort(([u],[f])=>u.localeCompare(f)))a.has(d)||m.has(p.from)||m.has(p.to)||!l.has(p.from)&&!l.has(p.to)||t.push({...Qt("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let y={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((d,p)=>y[d.classification]-y[p.classification]||(d.subject===p.subject?0:d.subject==="file"?-1:1)||d.id.localeCompare(p.id));let h={satisfied:t.filter(d=>d.classification==="satisfied").length,missing:t.filter(d=>d.classification==="missing").length,contradictory:t.filter(d=>d.classification==="contradictory").length,unplanned:t.filter(d=>d.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}i(Ke,"analyzeArchitectureConvergence");var Es="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ti=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"];var vs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Su={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Es,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:Es},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:[...Ti]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:vs,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:vs}}}};function Xt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Xt,"emptyEffectiveArkRules");function bs(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}))}}}i(bs,"effectiveContractPolicyPayload");function Di(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Di,"titleMatchesInvariant");function Li(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(Li,"symbolPresent");function Ss(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=[],a=[];for(let c of t){let l=[],m=c.coverage?.test!==!1,y=c.coverage?.symbol;if(!r&&m)for(let u of n){let f=e.fileContents[u];if(f&&Di(f,c.id)){l.push("test-title");break}}y&&Li(e.fileContents,y)&&l.push("symbol");let d=(c.coverage?.test===!0||!!y||c.coverage===void 0)&&l.length>0||c.coverage?.test===!1&&!y?!0:l.length>0,p=r&&m&&l.length===0;if(s.push({invariantId:c.id,layer:c.provenance.layer,sourceFile:c.provenance.sourceFile,mode:c.mode,covered:d&&!p,evidence:l,partial:p,description:c.description}),!d||p){let u=c.mode==="enforced"&&!p,f=r||n.length===0?"never-had-tests":"tests-disappeared";a.push({ruleId:"INVARIANT_UNCOVERED",message:p?o?`Invariant ${c.id} coverage cannot be proven (coverage file budget exhausted); reporting partial, not covered.`:`Invariant ${c.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:f==="tests-disappeared"?`Invariant ${c.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${c.id} is not covered by a test title or declared symbol (never-had-tests).`,file:c.provenance.sourceFile,line:1,arkruleId:c.id,arkruleSource:c.provenance.sourceFile,fromLayer:c.provenance.layer,severity:u?"error":"warning",failsStrict:u,kind:f})}}return{coverage:s,violations:a,partial:s.some(c=>c.partial)}}i(Ss,"evaluateInvariantCoverage");function Cs(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(Cs,"canPromoteInvariant");var Wn="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}})}i(O,"addFinding");function ee(e){return[...new Set(e??[])].sort()}i(ee,"sortedUnique");function ae(e,t,n,r,o){let s=ee(n),a=ee(r),c=new Set(s),l=new Set(a),m=a.filter(h=>!c.has(h)),y=s.filter(h=>!l.has(h));m.length===0&&y.length===0||(m.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),y.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(ae,"compareStringSets");function en(e,t,n,r,o,s,a){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(en,"compareBoolean");function zn(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(zn,"keyed");function Fi(e,t,n){let r=zn(t,s=>s.name),o=zn(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 a=r.values.get(s),c=o.values.get(s),l=`$.layers[${s}]`;if(!a&&c){O(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){O(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;ae(e,`${l}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ae(e,`${l}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let m=Vn(a),y=Vn(c);ae(e,`${l}.forbiddenGlobals`,m.rawGlobals,y.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ae(e,`${l}.capabilities`,m.atoms,y.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)."}),ee(a.intentPrefixes).join("\0")!==ee(c.intentPrefixes).join("\0")&&O(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:ee(a.intentPrefixes),after:ee(c.intentPrefixes)}),en(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),en(e,`${l}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Fi,"compareLayers");function $i(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=zn(t,r),s=zn(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 a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let c=o.values.get(a),l=s.values.get(a),m=`$.rules[${a}]`;if(!c&&l){l.allowed===!1&&O(e,{kind:"deny-added",path:m,classification:"strengthening",message:"A denied dependency edge was added.",after:l});continue}if(c&&!l){c.allowed===!1&&O(e,{kind:"deny-removed",path:m,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!l)continue;c.allowed!==l.allowed&&O(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${m}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:l.allowed});let y=c.peerIsolation===!0,h=l.peerIsolation===!0;if(y!==h){let d=c.from===c.to&&l.from===l.to;O(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${m}.peerIsolation`,classification:d?h?"strengthening":"weakening":"judgment-required",message:d?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:y,after:h})}ee(c.sliceFolders).join("\0")!==ee(l.sliceFolders).join("\0")&&O(e,{kind:"slice-folders-changed",path:`${m}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:ee(c.sliceFolders),after:ee(l.sliceFolders)})}}i($i,"compareRules");function Mi(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,c=o[s]??0;a!==c&&O(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])en(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Mi,"compareSafety");function Qr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Qr,"arkRunMode");function Xr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Xr,"arkOrderMode");function Hi(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 (${Xr(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 a=Xr(r),c=Xr(o);if(a!==c){let l=a==="advisory"&&c==="enforced";O(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:c})}ae(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."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Hi,"compareArkOrder");function Ki(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 (${Qr(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 a=Qr(r),c=Qr(o);if(a!==c){let l=a==="advisory"&&c==="enforced";O(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:c})}ae(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."}),ae(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."}),en(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Ki,"compareArkRun");function Gi(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(Gi,"overallClassification");function ws(e,t){return`${e}::${t}`}i(ws,"ruleKey");function xs(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(ws(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(ws(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(xs,"indexEffectiveRules");function Ui(e,t,n,r,o,s){let a=new Map((s??[]).map(d=>[d.invariantId,d])),c=t.arkRules??{},l=n.arkRules??{},m=[...new Set([...Object.keys(c),...Object.keys(l)])].sort();for(let d of m){let p=c[d],u=l[d],f=`$.arkRules[${d}]`;if(p===void 0&&u!==void 0){O(e,{kind:"arkrules-ref-added",path:f,classification:"strengthening",message:`ArkRules reference for layer ${d} was added.`,after:u});continue}if(p!==void 0&&u===void 0){O(e,{kind:"arkrules-ref-removed",path:f,classification:"weakening",message:`ArkRules reference for layer ${d} was removed.`,before:p});continue}p!==u&&O(e,{kind:"arkrules-ref-path-changed",path:f,classification:"judgment-required",message:`ArkRules file path for layer ${d} changed; verify the effective rules still match intent.`,before:p,after:u})}let y=xs(r),h=xs(o);for(let d of[...new Set([...y.structure.keys(),...h.structure.keys()])].sort()){let p=y.structure.get(d),u=h.structure.get(d),f=`$.arkRules.structure[${d}]`;if(!p&&u){O(e,{kind:"arkrule-structure-added",path:f,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(p&&!u){O(e,{kind:"arkrule-structure-removed",path:f,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!u)){if(p.mode!==u.mode){let v=p.mode==="advisory"&&u.mode==="enforced";O(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${f}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:p.mode,after:u.mode})}p.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${f}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:p.sensor,after:u.sensor})}}for(let d of[...new Set([...y.invariants.keys(),...h.invariants.keys()])].sort()){let p=y.invariants.get(d),u=h.invariants.get(d),f=`$.arkRules.invariants[${d}]`;if(!p&&u){O(e,{kind:"arkrule-invariant-added",path:f,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(p&&!u){O(e,{kind:"arkrule-invariant-removed",path:f,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!u)&&p.mode!==u.mode)if(p.mode==="advisory"&&u.mode==="enforced"){let b=a?.get(u.id),I=Cs(b);I.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${f}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${f}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${I.reason}`,before:p.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${f}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:p.mode,after:u.mode})}}i(Ui,"compareArkRules");function Yn(e,t,n){let r=[];ae(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ae(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."}),ae(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."}),en(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let c=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:s,after:a})}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}),Fi(r,e.layers,t.layers),$i(r,e.rules,t.rules),Mi(r,e,t),Ui(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Ki(r,e,t),Hi(r,e,t),r.sort((c,l)=>c.path.localeCompare(l.path)||c.id.localeCompare(l.id)),{schemaVersion:Wn,classification:Gi(r),findings:r}}i(Yn,"classifyArkPolicyDelta");function Zn(e,t){if(!e||e.schemaVersion!==Wn||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=ee(e.findingIds),r=ee(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(Zn,"policyDeltaAcknowledgementMatches");function Ge(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Ge,"normalizePath");function Ps(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Ps,"isIdentifierStart");function Jn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Jn,"isIdentifierCharacter");function J(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(J,"skipWhitespace");function tn(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(tn,"readString");function te(e,t,n){return e.startsWith(t,n)&&!Jn(e[n-1])&&!Jn(e[n+t.length])}i(te,"isWordAt");function Os(e,t){let n=J(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=J(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!te(e,"type",n))return!1;let o=J(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||te(e,"as",o)||!Ps(e[o]))return!1;for(n=o;n<e.length&&Jn(e[n]);)n+=1;if(n=J(e,n),te(e,"as",n)){if(n=J(e,n+2),!Ps(e[n]))return!1;for(;n<e.length&&Jn(e[n]);)n+=1}r=!0}return!1}i(Os,"bracedNamedBindingsAreTypeOnly");function Vi(e,t){if(t=J(e,t+6),e[t]==="(")return tn(e,J(e,t+1));let n=!1;if(te(e,"type",t)){let o=J(e,t+4);e[o]!==","&&!te(e,"from",o)&&(n=!0)}else Os(e,t)&&(n=!0);let r=_s(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Vi,"specifierAfterImport");function ji(e,t){t=t+6;let n=J(e,t),r=!1;if(te(e,"type",n)){let s=J(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Os(e,n)&&(r=!0);let o=_s(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(ji,"specifierAfterExport");function _s(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(te(e,"from",t))return tn(e,J(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return tn(e,t);if(t>0&&(te(e,"import",t)||te(e,"export",t)))return}}i(_s,"specifierInStaticStatement");function Bi(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i(Bi,"skipTemplateLiteral");function qi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=J(e,t+7);if(e[r]!=="(")return;r=J(e,r+1);let o=tn(e,r);return o?{...o,requireCall:!0}:void 0}i(qi,"specifierAfterRequire");function zi(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=
|
|
24
|
-
`).length;r.push({file:e.path,symbol:s,capability:
|
|
25
|
-
`).length,c={kind:"import",file:e.path,line:a,excerpt:o.excerpt},l=Wi(e.path,s,t);n.push({from:e.path,specifier:s,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}i(Ns,"moduleFactsFor");function Wi(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(Wi,"resolveSpecifier");function Ts(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=re(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(Ts,"violationsFor");var Yi={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 Zi(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Zi,"hasActiveArkRules");function Ji(e,t){return Zi(e,t)?M(D(bs({config:e,arkRules:t,warnings:[]}))):M(D(e))}i(Ji,"policyHashFor");function nn(e,t,n){let r=typeof e=="string"?ls(e,t):Lr(e,t),o=n?.arkRules??Xt();return{...r,arkRules:o,policyHash:Ji(r.config,o)}}i(nn,"loadContract");function eo(e){let t=nn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=nn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Yn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=o.length>0,a=s&&Zn(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(eo,"analyzePolicyDelta");function it(e){let t=e.files.map(h=>{let d=Ge(h.path);return{path:d,content:h.content,contentHash:M(h.content),layer:ne(d,e.contract.config.layers)??null}}).sort((h,d)=>h.path.localeCompare(d.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let d=Ns(h,n);r.push(...d.edges),o.push(...d.capabilityUses)}let s=Ts(r,e.contract.config),a=new Map(e.contract.config.layers.map(h=>[h.name,h])),c=new Map(e.contract.config.layers.map(h=>[h.name,new Set(nt(h))]));for(let h of o){let d=n.get(h.file)?.layer;if(!d)continue;let p=a.get(d),u=ve(h.symbol,p?.forbiddenGlobals??[]);if(u){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${d} must not use module "${h.symbol}" because it is the import form of forbidden global "${u}".`,symbol:h.symbol,evidence:h.evidence});continue}c.get(d)?.has(h.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${d} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let l=t.length===0?"complete":"partial",m=l==="complete"?[]:[{...Yi}],y={schemaVersion:qn,policyHash:e.contract.policyHash,compilerOptionsHash:M(D(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:l,completenessReasons:m,valid:l==="complete"&&s.length===0,ir:y}}i(it,"analyzeProject");function rn(e){let t=new Map(e.files.map(n=>[Ge(n.path),n]));for(let n of e.changes){let r=Ge(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return it({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(rn,"analyzeChange");function to(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(to,"explainViolation");function Qn(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],c=i(l=>{n.set(l,t),r.set(l,t),t+=1,s.push(l),o.add(l);for(let h of[...e.get(l)??[]].sort())e.has(h)&&(n.has(h)?o.has(h)&&r.set(l,Math.min(r.get(l)??0,n.get(h)??0)):(c(h),r.set(l,Math.min(r.get(l)??0,r.get(h)??0))));if(r.get(l)!==n.get(l))return;let m=[],y;do{if(y=s.pop(),y===void 0)break;o.delete(y),m.push(y)}while(y!==l);m.length>1&&a.push(m.sort())},"connect");for(let l of[...e.keys()].sort())n.has(l)||c(l);return a.sort((l,m)=>l[0]<m[0]?-1:l[0]>m[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(Qn,"detectArchitectureCycles");function Ue(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=re(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation,l=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=a.message??(c?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}). Extract shared code or use events/ports across slices.`:`${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:l?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...l?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Qn(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(Ue,"evaluateArchitectureGraph");var Qi=["no-anemic-model"];function Ds(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ds,"escapeGlobLiteral");function Xi(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}$`)}i(Xi,"globToRegExp");function on(e,t){return!t||t.length===0?!0:t.some(n=>Xi(n).test(e))}i(on,"matchesAppliesTo");function ec(e){return Qi.includes(e)}i(ec,"isTier2");function Ls(e){return e.mode==="enforced"&&!ec(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Ls,"severityFor");function ct(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}}i(ct,"baseViolation");function no(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(no,"isInRuleLayer");function Xn(e,t,n){return t.filter(r=>!(!r.exported||!on(r.file,e.appliesTo)||!no(r.file,e,n)))}i(Xn,"shapesForRule");function tc(e,t,n){let r=[];for(let o of Xn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(ct(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(tc,"evaluateAggregatePrivateState");function nc(e,t,n){let r=[];for(let o of Xn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(ct(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(nc,"evaluateAlwaysValidFactory");function rc(e,t,n){let r=[];for(let o of Xn(e,t,n))for(let s of o.mutatingMethods)s.referencesGuardOrPublish||r.push(ct(e,o.file,`Mutating method ${o.className}.${s.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(rc,"evaluateDomainEventOnMutation");function oc(e,t){let n=[];for(let r of t.files)on(r,e.appliesTo)&&no(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(ct(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(oc,"evaluateOrchestrationOnly");function sc(e,t){let n=[];for(let r of t.files)on(r,e.appliesTo)&&no(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(ct(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(sc,"evaluateThinAdapter");function ac(e,t,n){let r=[];for(let o of Xn(e,t,n))if(o.dataOnly===!0){let s=ct(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(ac,"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(...tc(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...nc(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...rc(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...oc(n,e));break;case"thin-adapter":t.push(...sc(n,e));break;case"no-anemic-model":t.push(...ac(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(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(l=>on(l,o.appliesTo)))continue;let{severity:a,failsStrict:c}=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:a,sensor:o.sensor,failsStrict:c})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>on(c,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i($s,"collectEmptyAppliesToFindings");var ic=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,cc=/\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*=)/,lc=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,dc=/\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*=/,pc=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function uc(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(dc.source,"g"))??[],r=t.match(new RegExp(pc.source,"g"))??[],o=(t.match(/\bif\s*\(/g)??[]).length,s=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&o+s>=6,c=ic.test(t),l=cc.test(t)||lc.test(t),m=n.length>=1||r.length>=2,y=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=c&&m||l&&m||c&&y&&(o>=4||n.length>=1)||l&&c;return!a&&!h?null:{...a?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{}}}i(uc,"deriveArkRuleFileHints");function Ms(e){let t={};for(let[n,r]of Object.entries(e)){let o=uc(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}i(Ms,"buildArkRuleFileHints");function fc(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(fc,"normalizeExtraMergeTeethClassification");function er(e){let t=fc(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(er,"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}}i(Hs,"classifyResolvedLayerCoverage");var mc=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var cf=new Set(mc);function Ks(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Ks,"isArkRunKernelModuleSpecifier");var yc=["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"],ro=new Set(yc);function Gs(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(ro.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(ro.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:ro.has(e.slice(0,r))}i(Gs,"isArkRunTransportBypassSpecifier");var gc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Rf=new Set(gc);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"},hc="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.")})}i(Bs,"isDomainRoleLayer");function Rc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Rc,"compareFindings");function Re(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Us[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ce({ruleId:Us[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Re,"finding");function Ac(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(Ac,"bagForFile");function Vs(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Vs,"emitKinds");function js(e){return e==="subscribe"||e==="register-handler"}i(js,"handleKinds");function kc(e){return e==="resolve"||e==="resolve-singleton"}i(kc,"dependKinds");function Ic(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Re(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let c=s.get(a.matchedRoot)??[];c.push(a),s.set(a.matchedRoot,c)}for(let a of o){let c=[...s.get(a)??[]].sort((m,y)=>m.file.localeCompare(y.file));if(c.length===0){r.push(Re(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(c.some(m=>m.hasKernelFactory))continue;let l=c[0];r.push(Re(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Ic,"evaluateMissingRoot");function Ec(e,t,n,r,o){let s=new Map(t.map(c=>[c.name,c.intentPrefixes??[]])),a=[];for(let c of n){let l=c.specifier;if(!l||!Ks(l))continue;let m=r(c.from);m&&Bs(m,s.get(m)??[])&&a.push(Re(e,"arkrun-kernel-in-domain",c.from,c.line,`${m} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:m,target:l},o))}return a}i(Ec,"evaluateKernelInDomain");function vc(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let c=new Map(t.map(y=>[y.name,y.intentPrefixes??[]])),l=new Set(r.filter(y=>y.hasKernelFactory).map(y=>y.file)),m=[];for(let y of n){if(l.has(y.file))continue;let h=y.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let d=o(y.file);!d||!a.has(d)||Bs(d,c.get(d)??[])||m.push(Re(e,"arkrun-direct-new",y.file,y.line,`${d} must not construct ${y.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:d,target:y.typeName},s))}return m}i(vc,"evaluateDirectNew");function bc(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let c=new Set(e.managedLayers);if(c.size===0)return{findings:s,completenessReasons:a};for(let l of t){if(!Vs(l.kind)&&!js(l.kind)&&!kc(l.kind))continue;let m=r(l.file);if(!m||!c.has(m))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:hc,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let y=Ac(n,l.file);if(Vs(l.kind)){if(y.raises.has(l.nameLiteral)||y.sends.has(l.nameLiteral))continue;s.push(Re(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:m,target:l.nameLiteral},o));continue}if(js(l.kind)){if(y.reactsTo.has(l.nameLiteral))continue;s.push(Re(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:m,target:l.nameLiteral},o));continue}y.uses.has(l.nameLiteral)||s.push(Re(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:m,target:l.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(bc,"evaluateUndeclared");function Sc(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let c=a.specifier;if(!c||!Gs(c))continue;let l=n(a.from);!l||!o.has(l)||s.push(Re(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(c)}; use the ArkRun kernel transport.`,{fromLayer:l,target:c},r))}return s}i(Sc,"evaluateTransportBypass");function qs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=er(e.classification),r=bc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Ic(t,e.compositionRootHits,n),...Ec(t,e.layers,e.dependencies,e.layerForFile,n),...vc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Sc(t,e.dependencies,e.layerForFile,n)].sort(Rc),s=[...r.completenessReasons].sort((a,c)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,m=`${c.code}\0${c.file??""}\0${c.message}`;return l<m?-1:l>m?1:0});return{findings:o,completenessReasons:s}}i(qs,"evaluateArkRunSensors");function zs(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(zs,"isArkOrderModuleSpecifier");var Ws={"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"};function Cc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Cc,"isDomainRoleLayer");function sn(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Ws[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ce({ruleId:Ws[t],fromLayer:s?.fromLayer,target:s?.target})}}i(sn,"finding");function Ys(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=er(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(sn(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let a=new Map;for(let c of e.planeRootHits){let l=a.get(c.matchedRoot)??[];l.push(c),a.set(c.matchedRoot,l)}for(let c of o){let l=a.get(c)??[];if(l.length===0){r.push(sn(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(c)} matched no governed files and has no createOrderPlane factory.`,{target:c},n));continue}l.some(m=>m.hasPlaneFactory)||r.push(sn(t,"arkorder-missing-plane",l[0].file,1,`ArkOrder plane root ${JSON.stringify(c)} has no createOrderPlane factory.`,{target:c},n))}}let s=new Map(e.layers.map(a=>[a.name,a.intentPrefixes??[]]));for(let a of e.dependencies){let c=a.specifier;if(!c||!zs(c))continue;let l=e.layerForFile(a.from);l&&Cc(l,s.get(l)??[])&&r.push(sn(t,"arkorder-kernel-in-domain",a.from,a.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:l,target:c},n))}for(let a of e.genericUpdates)r.push(sn(t,"arkorder-generic-update",a.file,a.line,`Generic ${a.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:a.method},n));return r.sort((a,c)=>a.file.localeCompare(c.file)||a.ruleId.localeCompare(c.ruleId)||a.line-c.line),{findings:r,completenessReasons:[]}}i(Ys,"evaluateArkOrderSensors");function W(e,t,n={}){return{ruleId:e,message:t,...n}}i(W,"configWarning");function an(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(p=>typeof p!="string"))&&s.push(W("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(W("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let p of["maxTsSuppressions","maxAnyCasts"]){let u=t.safety[p];u!==void 0&&(!Number.isInteger(u)||u<0)&&s.push(W("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${p} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],l=new Set([...a.map(p=>p.name).filter(Boolean),...c.map(p=>p.name).filter(p=>!!p)]);a.length===0&&s.push(W("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let m=new Set,y=new Set;for(let p of a){if(!p.name){s.push(W("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}m.has(p.name)&&y.add(p.name),m.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(f=>typeof f!="string"))&&s.push(W("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${p.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:p.name}));let u=Array.isArray(p.patterns)?p.patterns:[];if(u.length===0){s.push(W("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let f of u){let v;try{v=Le(f)}catch(I){s.push(W("CONFIG_INVALID_LAYER_PATTERN",`Layer "${p.name}" has an invalid pattern "${f}": ${I instanceof Error?I.message:String(I)}`,{layer:p.name,pattern:f}));continue}let b=p.optional===!0||p.reserved===!0||p.allowEmpty===!0;!r.some(I=>v.test(I))&&!b&&s.push(W("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${p.name}" pattern "${f}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:p.name,pattern:f,failsStrict:!1,reserved:!1}))}}for(let p of y)s.push(W("CONFIG_DUPLICATE_LAYER",`Layer "${p}" is configured more than once.`,{layer:p}));if(l.size>0)for(let p of n??[])p.from&&!l.has(p.from)&&s.push(W("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${p.from}".`,{fromLayer:p.from,toLayer:p.to})),p.to&&!l.has(p.to)&&s.push(W("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${p.to}".`,{fromLayer:p.from,toLayer:p.to}));let h=new Set;if(a.length>1)for(let p of r){let u=-1,f=[];for(let v of a)for(let b of v.patterns??[]){if(!Le(b).test(p))continue;let I=xr(b,p);I>u?(u=I,f=[v.name]):I===u&&!f.includes(v.name)&&f.push(v.name)}f.length>1&&h.add([...f].sort().join(" + "))}h.size>0&&s.push(W("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 d=r.filter(p=>!ne(p,a));return d.length>0&&s.push(W("CONFIG_UNCLASSIFIED_FILES",`${d.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:d.length,samples:d.slice(0,5)})),s}i(an,"collectAnalysisConfigWarnings");function wc(e,t){return t.some(n=>{try{return Le(n).test(e)}catch{return!1}})}i(wc,"matchesAny");function xc(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(f=>f.kind==="ts-suppression").map(({file:f,line:v})=>({file:f,line:v})),c=t.safetyUses.filter(f=>f.kind==="any-cast").map(({file:f,line:v})=>({file:f,line:v})),l=t.safetyUses.filter(f=>(f.kind==="dynamic-import"||f.kind==="dynamic-require")&&!wc(f.file,s)).map(f=>({file:f.file,line:f.line,kind:f.kind==="dynamic-require"?"require":"import"})),m=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(f=>f.kind==="in-memory-store").map(f=>({file:f.file,line:f.line,store:f.symbol??"in-memory store"})),y=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(f=>f.peerIsolation===!1||f.allowed===!1&&!!f.from&&f.from===f.to&&f.peerIsolation!==!0).map(f=>({from:f.from,to:f.to})),h={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:l,inMemoryProductionStores:m,disabledPeerIsolationRules:y,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},d=[],p=l.filter(f=>f.kind==="import");if(p.length>0){let f=p[0];d.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let u=l.filter(f=>f.kind==="require");if(u.length>0){let f=u[0];d.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let f=a[0];d.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(c.length>o){let f=c[0];d.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(m.length>0){let f=m[0];d.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:f.file,line:f.line,message:`${m.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 y.length>0&&d.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${y.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:d}}i(xc,"evaluateSafety");function Pc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(Pc,"ambientForbiddenGlobal");function Zs(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Zr(e,n.length>0?n:Yr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Zs,"intentLayer");function Oc(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!Pc(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let c=o.get(a),l=c?.forbiddenGlobals??[],m=s.source==="import-based"?t.dependencies.find(y=>y.from===s.file&&y.line===s.line&&y.specifier===s.symbol&&!y.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&zt(s.symbol,l))){if(s.source==="import-based"){let y=ve(s.symbol,l);if(y){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...m?{edgeKind:m}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${y}".`});continue}}nt(c).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...m?{edgeKind:m}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let l of Wt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:l.ruleId,file:s.file,line:s.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!s.sourceIntent)continue;let c=Zs(s.sourceIntent,e.contract);!c||c===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let c=Zs(s.intent,e.contract);if(!c)continue;let l=re(e.contract.config.rules,a,c);l&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,message:l.message??`${a} must not reference ${c} intent ${s.intent}.`})}return r}i(Oc,"contentViolations");function _c(e){let{facts:t}=e,n=at(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((g,ie)=>{let Et=`${g.code}\0${g.file??""}\0${g.message}`,vt=`${ie.code}\0${ie.file??""}\0${ie.message}`;return Et<vt?-1:Et>vt?1:0}),a=t.files.map(g=>({...g,layer:ne(g.path,e.contract.config.layers)??null})),c=new Map(a.map(g=>[g.path,g.layer])),l=t.dependencies.map(g=>{let ie=g.target?c.get(g.target)??ne(g.target,e.contract.config.layers):void 0;return{from:g.from,fromLayer:c.get(g.from)??null,...g.resolution==="resolved-project"&&g.target?{to:g.target,...ie?{toLayer:ie}:{}}:{},line:g.line,kind:g.kind,typeOnly:g.typeOnly,...g.targetTypeOnlyExports?{targetTypeOnlyExports:g.targetTypeOnlyExports}:{},...g.sourcePureTypeModule?{sourcePureTypeModule:g.sourcePureTypeModule}:{},...g.namedBindingsTypeOnly?{namedBindingsTypeOnly:g.namedBindingsTypeOnly}:{},...g.portProofEligible?{portProofEligible:g.portProofEligible}:{}}}),m=an({config:e.contract.config,rules:e.contract.config.rules,files:a.map(g=>g.path)}),y=xc(e,t),h=e.contract.arkRules??Xt(),d=a.map(g=>g.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Ms(e.coverageInputs.fileContents):{},...e.fileHints??{}},f=[...Fs({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:d,layerForFile:i(g=>c.get(g)??ne(g,e.contract.config.layers),"layerForFile"),fileHints:u}),...$s(h,d)],v=f.filter(g=>g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,nextAction:g.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${g.arkruleId} in ${g.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${g.arkruleId} (declared in ${g.arkruleSource}), then preflight again.`})),b=f.filter(g=>!g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,failsStrict:!1,nextAction:g.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${g.arkruleId} in ${g.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${g.arkruleId} in ${g.arkruleSource} (advisory).`})),k=(h.invariants?.length??0)>0?Ss({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}):{coverage:[],violations:[],partial:!1},C=k.violations.filter(g=>g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,nextAction:`Add a test title or declared symbol covering ${g.arkruleId} (declared in ${g.arkruleSource}), then preflight again.`})),Y=k.violations.filter(g=>!g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${g.arkruleId} in ${g.arkruleSource} (advisory / partial).`})),_=Hs(a),j=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:i(g=>c.get(g)??ne(g,e.contract.config.layers),"layerForFile"),classification:_}),Ce=e.contract.config.arkRun?.mode,ze=j.findings.filter(()=>Ce==="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:g.failsStrict,...g.severity?{severity:g.severity}:{}})),We=j.findings.filter(()=>Ce!=="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:!1})),Ye=Ys({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,dependencies:t.dependencies,layerForFile:i(g=>c.get(g)??ne(g,e.contract.config.layers),"layerForFile"),classification:_}),Ir=e.contract.config.arkOrder?.mode,Er=Ye.findings.filter(()=>Ir==="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:g.failsStrict,...g.severity?{severity:g.severity}:{}})),S=Ye.findings.filter(()=>Ir!=="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:!1})),R=[...k.partial&&k.coverage.some(g=>g.mode==="enforced"&&g.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."}]:[],...j.completenessReasons,...Ye.completenessReasons],A=Ue({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(g=>g.layer).map(g=>g.path),contentViolations:[...Oc(e,t,c),...v,...C,...ze,...Er],edges:l,warnings:[...m,...y.warnings,...b,...Y,...We,...S],safety:y.report}),N=o==="complete"&&R.length>0?"partial":o,K=N==="complete"?s:[...s,...R].sort((g,ie)=>{let Et=`${g.code}\0${g.file??""}\0${g.message}`,vt=`${ie.code}\0${ie.file??""}\0${ie.message}`;return Et<vt?-1:Et>vt?1:0}),Ae=A.violations.filter(g=>g.failsStrict!==!1),we=N==="complete"&&Ae.length===0,It=we&&A.warnings.every(g=>g.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:N,completenessReasons:K,valid:we,strictValid:It,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:y.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(g=>g.name),edges:l,capabilityUses:t.capabilityUses,violations:A.violations,warnings:A.warnings}}}i(_c,"analyzeCanonicalResolvedProject");function lt(e){return _c({contract:e.contract,facts:he(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(lt,"analyzeResolvedProject");function Js(e){return M(D(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Js,"analysisTreeHash");function oo(e){let t=it(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],o=new Set,s=[];for(let u of e.changes){let f=u.path.replace(/\\/g,"/"),v=Ge(u.path);if(!v||v===".."||v.startsWith("../")||f.startsWith("/")||/^[A-Za-z]:\//.test(f)||f.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(v)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}o.add(v),"delete"in u&&u.delete&&!n.has(v)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:v,delete:!0}:{path:v,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 a=rn({...e,changes:r}),c=new Map(a.ir.files.map(u=>[u.path,u])),l=a.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let f=c.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}:{},...f?{fromLayer:f}:{},edgeKind:"import",message:u.message}}),m=Ue({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(u=>u.path),contentViolations:l,edges:a.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}:{}}))}),y=r.map(u=>{let f=Ge(u.path),v=n.get(f),b=c.get(f);return{path:f,operation:"delete"in u&&u.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},...b?{candidateContentHash:b.contentHash}:{}}}).sort((u,f)=>u.path.localeCompare(f.path)),h=[...s,...m.violations].map(u=>({...u,nextAction:ce(u)})),d=h.filter(u=>u.failsStrict!==!1),p=e.changeMap?Ke({changeMap:e.changeMap,changes:y,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:a.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"&&a.valid&&d.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Js(t.ir.files),candidateTreeHash:Js(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:y,violations:h,warnings:m.warnings}}i(oo,"preflightChange");function Nc(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(Nc,"canonicalChangePath");function Tc(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(Tc,"identityViolations");function Dc(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(Dc,"preparedChange");function so(e){let t=he(e.baseFacts),n=he(e.candidateFacts),r=lt({contract:e.contract,facts:t}),o=lt({contract:e.contract,facts:n}),s=new Map(t.files.map(p=>[p.path,p])),a=new Map(n.files.map(p=>[p.path,p])),c=Tc(t,n),l=new Map,m=[];for(let p of e.changes){let u=Nc(p.path);if(!u){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(u)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:u,line:1,message:`The atomic change set contains more than one operation for ${u}.`});continue}l.set(u,p);let f=s.get(u),v=a.get(u);if("delete"in p&&p.delete)f||c.push({ruleId:"DELETE_TARGET_MISSING",file:u,line:1,message:`Cannot delete ${u} because it is not present in the supplied base facts.`}),v&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:u,line:1,message:`Candidate facts still contain deleted file ${u}.`});else{let b="content"in p?p.content:"",I=M(b);v?v.contentHash!==I&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:u,line:1,expectedContentHash:I,candidateContentHash:v.contentHash,message:`Candidate facts for ${u} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:u,line:1,message:`Candidate facts do not contain changed file ${u}.`})}m.push(Dc(p,u,s,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...s.keys(),...a.keys()])){if(l.has(p))continue;let u=s.get(p),f=a.get(p);u&&f&&D(u)===D(f)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let y=e.changeMap?Ke({changeMap:e.changeMap,changes:m,baseDependencies:r.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:o.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,h=[...c,...o.ir.violations].map(p=>({...p,nextAction:ce(p)})),d=h.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&d.length===0&&(y?.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}:{},...y?{convergence:y}:{},changes:m.sort((p,u)=>p.path<u.path?-1:p.path>u.path?1:0),violations:h,warnings:o.ir.warnings}}i(so,"preflightResolvedChange");var tr="docs/diagnostics.md",Qs="1.0";function E(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var cn=Object.freeze([E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \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."),E("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."),E("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}),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe."),E("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."),E("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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.")]),ao=new Map(cn.map(e=>[e.ruleId,e])),Xs=Object.freeze(cn.map(e=>e.ruleId));function ea(e){return typeof e=="string"&&e.length>0&&ao.has(e)}i(ea,"isKnownDiagnosticCode");function ta(e){return typeof e!="string"||e.length===0?!1:ao.has(e)?!0:e.startsWith("ARKRULE_")}i(ta,"isCataloguedOrArkRuleFamily");function ln(e){if(!(typeof e!="string"||e.length===0))return ao.get(e)}i(ln,"getDiagnosticCatalogEntry");function io(e){return`#${ln(e)?.docsAnchor??e}`}i(io,"diagnosticDocsFragment");function na(e){return`${tr}${io(e)}`}i(na,"diagnosticDocsPath");function ra(){return{schemaVersion:"1.0",docsPath:tr,codes:cn}}i(ra,"serializeDiagnosticCatalog");function oa(e){return ln(e)?.fix}i(oa,"catalogFixForRuleId");function sa(e){return ln(e)?.why}i(sa,"catalogWhyForRuleId");var aa="1.1";var ia="1.0";var dt=class{static{i(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function Lc(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(Lc,"initialState");var nr=class{static{i(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new dt,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)??Lc(r),s=await r.project(t,o);await this.store.save(r.name,s);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function dn(e){return new nr(e)}i(dn,"createProjectionRegistry");var pn="1.0";function Fc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(Fc,"policyId");var co=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function un(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,a=e.projections,c=e.eventContracts,l=e.observability,m=t?t.list().map(b=>({name:b.name,dependencies:t.getDependencies(b.name),productions:t.getProductions(b.name)})):[],y=t?t.getAllRelationships():[],h=n?n.getPolicies().map(b=>({id:Fc(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})):[],d=r?r.toJSON():[],p=o?o.toJSON():{nodes:[],edges:[]},u=d.filter(b=>(b.emits?.length??0)>0||(b.consumes?.length??0)>0).map(b=>({entity:b.name,emits:b.emits,consumes:b.consumes})),f=a?a.list().map(b=>({name:b.name,sourceIntents:b.sourceIntents,checkpoint:a.getCheckpoint(b.name)})):[],v={schemaVersion:"1.0",version:Pn,exportedAt:new Date().toISOString(),intents:m,relationships:y,policies:h,entities:d,graph:p,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:f,eventContracts:c?.list()??[],observability:l?.report(),links:{entityIntents:u}};return new co(v)}i(un,"createArkManifest");var ca=0;function la(e){return ca+=1,`${e}-${Date.now()}-${ca}`}i(la,"createWorkflowId");function lo(e){return e instanceof Error?e.message:String(e)}i(lo,"errorMessage");function $c(e){return new Promise(t=>{setTimeout(t,e)})}i($c,"sleep");async function Mc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((a,c)=>{o=setTimeout(()=>{let l=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(l),c(l)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}i(Mc,"withTimeout");var pt=class{static{i(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let a=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||a){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let c=(s.version??0)+1;return s.version=c,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},po=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new pt}bus;options;static{i(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),a={id:r.id??la(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:t}),this.executeSnapshot(a,o,r.tx)}async resume(t,n={}){let r=await this.get(t,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(t,n,r){try{let o=n.steps.filter(s=>!t.completedSteps.includes(s.name));for(let s of o)await this.runStep(t,s,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=lo(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=s;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let c;try{c=await Mc(l=>Promise.resolve(n.execute(t.context,this.bus,l)),n.timeoutMs,n.name)}catch(l){if(a<s){o.delayMs&&await $c(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:a,error:lo(l)}),l}c&&Object.assign(t.context,c),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(a=>t.completedSteps.includes(a.name));for(let a=s.length-1;a>=0;a-=1){let c=s[a];if(c.compensate)try{await Promise.resolve(c.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:c.name})}catch(l){await this.audit("workflow.step.failed",t,{step:c.name,compensation:!0,error:lo(l)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function ut(e,t){return new po(e,t)}i(ut,"createWorkflowEngine");function uo(e,t,n={}){let r=ut(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??la(e.name),a="idle",c=[];return{id:s,definition:e,get status(){return a},get completedSteps(){return[...c]},async run(l){a="running",c=[];try{let m=await r.start(e.name,l,{id:s});a=m.status==="waiting"?"idle":m.status,c=[...m.completedSteps]}catch(m){let y=await r.get(s);throw a=y?.status==="waiting"?"idle":y?.status??"failed",c=y?.completedSteps??[],m}}}}i(uo,"createSaga");ft();dr();vn();wn();wn();async function xn(e,t={}){let n=Rt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(ka(),Aa));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(xn,"startArkRunInspector");dr();wn();ft();vn();ft();var fl=new Set(["singleton","transient"]);function Ia(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return t}i(Ia,"cloneComponent");function ml(e){if(e===void 0)return"singleton";if(typeof e=="string"&&fl.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(ml,"closedLifetime");function Ea(){let e=new Map,t=new Map,n=new Set;function r(a){let c=e.get(a);if(!c)throw new Error(`ArkRun component "${a}" is not registered.`);return c}i(r,"mustRecord");function o(a,c){if(!c.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return c.factory()}finally{n.delete(a)}}i(o,"instantiate");function s(a,c){if(t.has(a))return t.get(a);let l=o(a,c);return t.set(a,l),l}return i(s,"singleton"),{register(a){let c=typeof a?.id=="string"?a.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let l=ml(a.lifetime),m=mo({id:c,lifetime:l,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!m)throw new Error("ArkRun component id must be a non-empty string.");let y=typeof a.factory=="function"?a.factory:void 0;return e.set(c,{component:m,factory:y}),Ia(m)},resolve(a){let c=r(a);return c.component.lifetime==="transient"?o(a,c):s(a,c)},resolveSingleton(a){let c=r(a);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return s(a,c)},snapshotComponents(){return[...e.values()].map(a=>Ia(a.component))}}}i(Ea,"createComponentRegistry");vn();function yl(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new ue(e.source,t.source);return t.source=e.source,t}i(yl,"stampMetadata");function gl(){}i(gl,"ignoreDetachedFailure");async function ko(e,t,n,r={}){let o=En({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=yl(r),a=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let c=Promise.resolve(e.broker.send(a));o.awaitHandoff?await c:c.then(void 0,gl)}return o}i(ko,"sendOnArkRunTransport");var Rr=1e3,va=0;function hl(){return va+=1,`ark-kernel-${Date.now()}-${va}`}i(hl,"nextKernelInstanceId");function kt(e={}){let t=e.strict??!0,n=e.instanceId??hl(),r=e.profile??Fe,o=e.maxHistorySize??Rr,s=Ct(),a=Mt(),c=e.metadata??Bt(),l=e.auditTrail??$t({maxRecords:o}),m=e.eventContracts??Lt(),y=e.eventBuffer??e.outbox??new Ee,h=e.projections??dn({auditTrail:l}),d=new ke([Ot(r),...e.policies??[]]),p=i(()=>{Ht(s,a,{requireRegisteredTargets:!0})},"syncGraph"),u=e.ephemeral??!0,f=e.broker,v=new Qe({intentRegistry:s,dependencyGraph:a,policyEngine:d,strictRegistry:!0,validateIntentNaming:!0,auditTrail:l,eventContracts:m,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:y,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async _=>{await h.apply(_)}}),b=ut(v,{auditTrail:l}),I=Ft({registry:s,eventBus:v,graph:a}),k=Ea(),C=typeof f?.send=="function",Y={instanceId:n,profile:r,registry:s,graph:a,metadata:c,auditTrail:l,eventContracts:m,eventBuffer:y,outbox:y,projections:h,policyEngine:d,eventBus:v,workflowEngine:b,observability:I,publisher(_){let j=v.createPublisher(_);return{source:j.source,publish:j.publish,send(Ce,ze,We={}){return ko({eventBus:v,broker:f,defaultEphemeral:u},Ce,ze,{...We,source:j.source})}}},send(_,j,Ce={}){return ko({eventBus:v,broker:f,defaultEphemeral:u},_,j,Ce)},register(_){return k.register(_)},resolve(_){return k.resolve(_)},resolveSingleton(_){return k.resolveSingleton(_)},getDependencyInformationPackage(){return le({kernelInstanceId:n,components:k.snapshotComponents()})},requestGraph(_){return In({kernelInstanceId:n,components:k.snapshotComponents()},_)},getInspectorSnapshot(_){return Cn({kernelInstanceId:n,host:_?.host,port:_?.port,package:{kernelInstanceId:n,components:k.snapshotComponents()},observability:I.report(),ephemeralDefault:u,brokerBound:C})},startInspector(_){return xn(Y,_)},syncGraph:p,manifest(){return p(),un({registry:s,policyEngine:d,metadata:c,graph:a,profile:r,projections:h,eventContracts:m,observability:I})}};return Y}i(kt,"createArkKernel");function Ar(e={}){return kt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Ar,"createStrictArkKernel");function Io(e,t={}){let{profileName:n,...r}=t;return{...r,profile:jt(e,{name:n})}}i(Io,"createOptionsFromConfig");function Eo(e,t={}){return kt(Io(e,t))}i(Eo,"createArkKernelFromConfig");function vo(e,t={}){return Ar(Io(e,t))}i(vo,"createStrictArkKernelFromConfig");function bo(e,t={}){return kr(Io(e,t))}i(bo,"createLenientArkKernelFromConfig");function kr(e={}){return kt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(kr,"createLenientArkKernel");0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_RUN_COMPONENT_LIFETIMES,ARK_RUN_EPHEMERAL_DEFAULT,ARK_RUN_GRAPH_DEFAULT_SLICE,ARK_RUN_GRAPH_NODE_KINDS,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,ARK_RUN_GRAPH_SCHEMA_VERSION,ARK_RUN_GRAPH_SLICES,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,ARK_RUN_INSPECTOR_DEFAULT_HOST,ARK_RUN_INSPECTOR_DEFAULT_PORT,ARK_RUN_INSPECTOR_EVENTS_PATH,ARK_RUN_INSPECTOR_GRAPH_PATH,ARK_RUN_INSPECTOR_SCHEMA_VERSION,ARK_RUN_INSPECTOR_SNAPSHOT_PATH,ARK_RUN_INSPECTOR_SSE_EVENT,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,ARK_RUN_TRANSPORT_KINDS,ArkRunInspectorBindError,ArkRunInspectorProductionError,DEFAULT_MAX_HISTORY_SIZE,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EventContractRegistryImpl,EventContractViolationError,InMemoryAuditStore,InMemoryEventBuffer,InMemoryOutboxStore,InMemoryReadModelStore,InMemoryWorkflowStore,IntentRegistry,InvalidArkRunGraphQueryError,InvalidArkRunSendOptionError,InvalidIntentNameError,LayerPolicyContextError,MANIFEST_SCHEMA_VERSION,ObservedLayerFlowViolationError,POLICY_DELTA_SCHEMA_VERSION,PolicyEngine,PolicyViolationError,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,SourceMetadataOverrideError,UnknownEventSourceError,UnregisteredIntentError,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,architecturalPolicies,arkRunGraphQueryFromSearchParams,arkRunInspectorUrl,buildArkRunInspectorSnapshot,buildDependencyInformationPackage,buildPublishPolicyContext,catalogFixForRuleId,catalogWhyForRuleId,checkAdapterGovernance,checkContract,classifyArkPolicyDelta,closeArkRunGraphQuery,closedArkRunEphemeral,closedArkRunTransportKind,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapter,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createArkKernel,createArkKernelFromConfig,createArkManifest,createArkTestHarness,createAuditTrail,createDependencyGraph,createElevenLayerArkConfig,createEventBus,createEventContractRegistry,createIntentRegistry,createLenientArkKernel,createLenientArkKernelFromConfig,createMetadataRegistry,createObservabilityReporter,createProjectionRegistry,createResolvedCandidateFacts,createSaga,createStrictArkKernel,createStrictArkKernelFromConfig,createWorkflowEngine,defaultIntentRegistry,defineArchitectureProfilePolicy,defineIntent,defineLayerPolicy,definePolicy,definePort,definePublishPolicy,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,formatArkRunGraphMermaid,formatArkRunInspectorSseEvent,getDiagnosticCatalogEntry,isArkRunInspectorLoopbackHost,isArkRunInspectorProductionEnv,isCataloguedOrArkRuleFamily,isKnownDiagnosticCode,isLayerPolicy,loadContract,loadResolvedCandidateFacts,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,requestArkRunGraph,resolveArkRunInspectorBind,resolveArkRunSendPlan,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,stableSerialize,startArkRunInspector,syncRegistryToGraph,toAdapterDiagnostic,validateIntentName,version});
|
|
20
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ys(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ys,"isObject");function Fn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Fn,"propertyPath");function tt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(tt,"valueType");function ka(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(ka,"resolveSchemaRef");function Ht(e,t,n,r,o){if(t.$ref){let s=ka(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ht(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(!ys(e)){o.push({path:n,message:`must be an object; received ${tt(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Fn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Fn(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in s||Ht(e[l],a,Fn(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&Ht(e[a],l,Fn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${tt(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(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>Ht(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${tt(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 ${tt(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${tt(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(Ht,"validateNode");function Ia(e){let t={...e,$schema:e.$schema===void 0?$n:e.$schema,schemaVersion:e.schemaVersion===void 0?oe:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Mn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=ds(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=ps(e.arkOrder)),t}i(Ia,"defaultedConfig");function va(e){return e===oe?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(va,"migratedFromOf");function ba(){let e=new Set([oe]);for(let t of $r)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(ba,"knownInputVersions");function Ea(e,t="ark.config.json"){if(!ys(e))throw new ye(t,[{path:"$",message:`must be an object; received ${tt(e)}`}]);let n=ba(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${oe}`}]);if(r!=="unversioned"&&!n.has(r))throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${oe}`}]);let o=r,s={...e},a=0;for(;o!==oe&&a<$r.length+1;){a+=1;let l=$r.find(c=>c.from===o);if(!l)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${oe}`}]);o=l.to,s.schemaVersion=o}if(o!==oe)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${oe}`}]);return{candidate:Ia(s),migratedFrom:va(r)}}i(Ea,"migrateArkConfig");function Mr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ea(e,t),o=[];if(Ht(n,ms,"$",ms,o),us(n,o),fs(n,o),o.length>0)throw new ye(t,o);return{config:n,migratedFrom:r}}i(Mr,"loadArkConfigContract");function hs(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ye(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Mr(n,t)}i(hs,"parseArkConfigJson");function Rs(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:$n,schemaVersion:oe};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Rs,"withArkConfigMetadata");function Sa(e){return e.endsWith(".")?e:`${e}.`}i(Sa,"normalizePrefix");function Ca(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}i(Ca,"byLongestPrefix");function Kt(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Sa)})),n=[...t].sort(Ca),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(a=>o.startsWith(a)))?.name}}}i(Kt,"createArchitectureProfile");function Gt(e,t={}){return Kt({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??[]})}i(Gt,"createArchitectureProfileFromArkConfig");var wa=[{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}],Fe=Kt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:wa,rules:Mn.map(e=>({...e}))}),xa={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 Hr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Rs({include:e.include??[t],layers:Fe.layers.map(o=>({name:o.name,patterns:(xa[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Fe.rules]})}i(Hr,"createElevenLayerArkConfig");var Hn=class{static{i(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 Ut(){return new Hn}i(Ut,"createMetadataRegistry");function Kr(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}i(Kr,"definePort");function Gr(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 a={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=Kn(a);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
|
|
21
|
+
`));return a}i(Gr,"createAdapter");function Ur(e,t=[]){let n=t.filter(r=>!As(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(Ur,"checkContract");function Kn(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}i(Kn,"checkAdapterGovernance");function As(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(As,"hasMember");var jr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Wr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),qr=Object.freeze(Object.keys(Wr).sort()),Vr=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"}),Br=Object.freeze({process:Object.freeze(["process","node:process"])});function Vt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Vr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Vr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Vr[e.slice(0,s)]??null}i(Vt,"capabilityForModuleSpecifier");function Se(e,t){for(let n of t)if(Br[n]?.includes(e))return n;return null}i(Se,"forbiddenGlobalForModuleSpecifier");function Gn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Wr[r];if(o)return o}return null}i(Gn,"capabilityForAmbientName");function nt(e){if(e?.pure===!0)return[...jr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>jr.includes(r));return[...new Set(n)].sort()}i(nt,"effectiveCapabilityDeny");function jt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(jt,"ambientCoveredByForbiddenGlobals");function Un(e){let t=new Set,n=new Set,r=Object.keys(Wr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Br[o]??[])t.add(`import-exact:${a}`)}for(let o of nt(e)){if(t.add(`import:${o}`),o==="process")for(let s of Br.process)t.add(`import-exact:${s}`);for(let s of r)Gn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Un,"loweredLayerCoverage");function rt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(rt,"literalText");function vs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(vs,"lineOf");function ks(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(ks,"isTypeOnlyReference");function bs(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(bs,"singleFileChecker");function zr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(zr,"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):zr(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Yr,"localDeclaration");function $e(e,t){let n,r=[],o=i((a,l,c,g=!1)=>r.push({specifier:c,kind:l,line:vs(t,a),typeOnly:g,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",rt(e,a.moduleSpecifier),ks(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",rt(e,a.moduleSpecifier),ks(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",rt(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Yr(e,n??(n=bs(e,t)),t,a.expression);(l||g)&&o(a,g?"require":"dynamic-import",rt(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i($e,"extractSemanticDependencies");function Oa(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=rt(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(Oa,"staticAccessPath");function Pa(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(Pa,"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}}i(Is,"bestForbiddenMatch");function Me(e,t,n){if(n.length===0)return[];let r=new Set(n),o=bs(e,t),s=new Map,a=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations)e.isIdentifier(f.name)&&a.add(f.name.text);let l=i(p=>{let f=Oa(e,p);if(!f)return;let u=zr(o,f.root),y=u?s.get(u):void 0;return y?[...y,...f.segments.slice(1)]:Yr(e,o,t,f.root)||a.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=zr(o,f.name);!u||!y||s.set(y,u)}let c=[],g=new Set,m=i((p,f)=>{let u=vs(t,f),y=`${p}:${f.getStart(t)}`;g.has(y)||(g.add(y),c.push({name:p,line:u,node:f}))},"flag"),h=i(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)&&Pa(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 b=y.propertyName?rt(e,y.propertyName)??y.propertyName.text:y.name.text,E=Is(r,[...u,b]);E&&m(E,p.initializer)}}e.forEachChild(p,h)},"visit");return h(t),c}i(Me,"collectForbiddenCapabilityUses");function Xr(e,t,n){let r=[];for(let o of n?.dependencies??$e(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Vt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Me(e,t,qr)){let s=Gn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(Xr,"collectCapabilityUses");var Zr={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."},Jr=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 Qr(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Qr,"resolveIntentLayer");function He(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(He,"looksLikeArkIntent");function Bt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&He(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Zr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Zr.PUBLISH_MISSING_SOURCE}),t}i(Bt,"classifyPublishFacts");function U(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(U,"violation");function ot(e,t){return e.slice(0,t).split(`
|
|
22
|
+
`).length}i(ot,"lineOf");function _a(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}i(_a,"extractQuotedStrings");function Na(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}i(Na,"extractModuleSpecifiers");function Ta(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(Ta,"extractQuotedStringsAst");function Da(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}i(Da,"hasInfrastructureToken");function La(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(La,"isKnownInfrastructurePackage");function Fa(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Fa,"layerHasInfrastructureRole");function qt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(qt,"tsStringLiteralText");function $a(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i($a,"tsPropertyName");function Es(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:$a(e,r.name)===n)}i(Es,"tsObjectProperty");function zt(e,t,n){return Es(e,t,n)!==void 0}i(zt,"tsObjectHasProperty");function Wt(e,t,n){let r=Es(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Wt,"tsObjectPropertyValue");function Ma(e,t){let n=Wt(e,t,"metadata");return zt(e,n,"source")}i(Ma,"tsObjectHasMetadataSource");function Ss(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ss(e,t.name):!1:!1}i(Ss,"tsLooksLikeIntentCreatorExpression");function Ha(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}i(Ha,"tsIsPublishCall");function Ka(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=qt(e,n);return r!==void 0&&He(r)||zt(e,n,"intent")||Ss(e,n)}i(Ka,"tsIsArkPublishCandidate");function Ga(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Ma(e,n)||zt(e,r,"source")||zt(e,o,"source")}i(Ga,"tsPublishHasSource");function Ua(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Wt(e,n,"metadata");return qt(e,Wt(e,s,"source"))??qt(e,Wt(e,r,"source"))??qt(e,Wt(e,o,"source"))}i(Ua,"tsPublishSourceLiteral");function Va(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],g=i(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),m=i(h=>{if(Ha(e,h)){let p=h.arguments[0],f=qt(e,p);for(let y of Bt({publishCall:!0,rawIntentName:f,objectHasIntent:zt(e,p,"intent"),arkPublishCandidate:Ka(e,h),hasSource:Ga(e,h)}))c.push(U(y.ruleId,y.message,{line:g(h),filePath:a}));let u=Ua(e,h);if(r&&l&&u&&He(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:a,target:u,fromLayer:l,toLayer:y}))}}e.forEachChild(h,m)},"visit");return m(o),c}i(Va,"analyzePublishAst");function eo(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let l=[],c=a,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?$e(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})):Na(s),y=e.typescript?Ta(e.typescript,s):_a(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 b=m!==void 0&&(r.has(m)||Fa(m)),E=m!==void 0?` If "${m}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let A of n)if(A instanceof RegExp){A.lastIndex=0;let v=A.exec(s);A.lastIndex=0,v&&l.push(U("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:v.index===void 0?void 0:ot(s,v.index),filePath:g,suggestion:"Remove infrastructure imports from domain/application layers."+E}))}else s.includes(A)&&l.push(U("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:ot(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=me(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:ot(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}b||A.typeOnly||!Da(A.value)&&!La(A.value)||l.push(U("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:ot(s,A.index),source:A.value,target:A.value,filePath:g,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+E,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let v=A.check({source:s,context:a});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)He(A.value)&&!t.has(A.value)&&l.push(U("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:ot(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(!He(A.value))continue;let v=e.architectureProfile.resolveLayer(A.value);if(!v)continue;let P=me(e.architectureProfile.rules,m,v);P&&l.push(U("LAYER_REFERENCE_VIOLATION",P.message??`Layer "${m}" must not reference "${v}" through "${A.value}".`,{line:ot(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,a);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(...Me(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=Se(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 Xr(e.typescript,p))A.has(P.capability)&&(P.source==="ambient-global"&&jt(P.symbol,v)||P.source==="import-based"&&Se(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(...Va(e.typescript,s,a,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}}}}i(eo,"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")}`}i(B,"deterministicHash");function D(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(D).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${D(t[n])}`).join(",")}}`}i(D,"stableSerialize");var Ce="1.2";var Cs=["network","filesystem","clock","randomness","environment","process","persistence"];function V(e,t){let n=D(e),r=D(t);return n<r?-1:n>r?1:0}i(V,"compareCanonical");function W(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(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(D(t))}i(it,"resolvedFactsEvidenceRequirementsHash");function ja(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),a=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),b=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(V),E=(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(D(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:a,intentReferences:l,safetyUses:c,classShapes:g,arkRunKernelCalls:m,arkRunManagedNews:h,arkRunCompositionRootHits:p,arkRunDeclarations:f,arkOrderPlaneCalls:u,arkOrderGenericUpdates:y,arkOrderRootHits:b,arkOrderXiFieldWrites:E,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:v}}i(ja,"canonicalResolvedFactsInput");function ws(e){let t=ja(e);return{...t,factsHash:B(D(t))}}i(ws,"createCanonicalResolvedCandidateFacts");function Vn(e){return ws(Os(L(e,"$"),!1))}i(Vn,"createResolvedCandidateFacts");function L(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(L,"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"}.`)}i($,"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}i(T,"requiredText");function he(e,t,n){if(e[t]!==void 0)return T(e,t,n)}i(he,"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 a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(M,"requiredProjectPath");function H(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(H,"requiredBoolean");function xs(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(xs,"requiredInteger");function Y(e,t,n){let r=xs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Y,"requiredPositiveInteger");function K(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(K,"requiredArray");function Re(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Re,"enumValue");function st(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(st,"parseStringArray");function Ba(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(Ba,"assertUnique");function Os(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=Re(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Re(e,"completeness",["complete","partial","unavailable"],"$"),o=K(e,"completenessReasons","$").map((S,C)=>{let R=`$.completenessReasons[${C}]`,d=L(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=K(e,"files","$").map((S,C)=>{let R=`$.files[${C}]`,d=L(S,R);return $(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:M(d,"path",R),contentHash:T(d,"contentHash",R),parseStatus:Re(d,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:xs(d,"parseDiagnosticCount",R),exportsOnlyTypes:H(d,"exportsOnlyTypes",R),typeOnlyExportNames:st(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:H(d,"hasTopLevelSideEffects",R)}}),a=K(e,"dependencies","$").map((S,C)=>{let R=`$.dependencies[${C}]`,d=L(S,R);$(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let N=he(d,"specifier",R),F=he(d,"target",R),ne=Re(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(ne==="resolved-project"&&!F)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(ne!=="resolved-project"&&F)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(ne!=="dynamic"&&!N)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:M(d,"from",R),...N?{specifier:N}:{},kind:Re(d,"kind",["import","export","dynamic-import","require"],R),typeOnly:H(d,"typeOnly",R),line:Y(d,"line",R),resolution:ne,...F?{target:M(d,"target",R)}:{},...d.namedBindings!==void 0?{namedBindings:st(d.namedBindings,`${R}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:H(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:H(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:H(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:H(d,"portProofEligible",R)}:{}}}),l=K(e,"capabilityUses","$").map((S,C)=>{let R=`$.capabilityUses[${C}]`,d=L(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:Re(d,"capability",Cs,R),source:Re(d,"source",["ambient-global","import-based"],R)}}),c=K(e,"ambientUses","$").map((S,C)=>{let R=`$.ambientUses[${C}]`,d=L(S,R);return $(d,["file","line","symbol"],R),{file:M(d,"file",R),line:Y(d,"line",R),symbol:T(d,"symbol",R)}}),g=K(e,"publishCalls","$").map((S,C)=>{let R=`$.publishCalls[${C}]`,d=L(S,R);$(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let N=he(d,"rawIntentName",R),F=he(d,"sourceIntent",R);return{file:M(d,"file",R),line:Y(d,"line",R),...N?{rawIntentName:N}:{},objectHasIntent:H(d,"objectHasIntent",R),arkPublishCandidate:H(d,"arkPublishCandidate",R),hasSource:H(d,"hasSource",R),...F?{sourceIntent:F}:{}}}),m=K(e,"intentReferences","$").map((S,C)=>{let R=`$.intentReferences[${C}]`,d=L(S,R);return $(d,["file","line","intent"],R),{file:M(d,"file",R),line:Y(d,"line",R),intent:T(d,"intent",R)}}),h=K(e,"safetyUses","$").map((S,C)=>{let R=`$.safetyUses[${C}]`,d=L(S,R);$(d,["file","line","kind","symbol"],R);let N=he(d,"symbol",R),F=Re(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if(F==="in-memory-store"&&!N)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if(F!=="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:F,...N?{symbol:N}:{}}});Ba(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 a)if(!p.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:K(e,"arkRunKernelCalls","$")).map((S,C)=>{let R=`$.arkRunKernelCalls[${C}]`,d=L(S,R);$(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let N=he(d,"receiver",R),F=he(d,"nameLiteral",R);return{file:M(d,"file",R),line:Y(d,"line",R),kind:Re(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:T(d,"callee",R),viaImport:H(d,"viaImport",R),...N?{receiver:N}:{},...F?{nameLiteral:F}:{}}}),b=(e.arkRunManagedNews===void 0?[]:K(e,"arkRunManagedNews","$")).map((S,C)=>{let R=`$.arkRunManagedNews[${C}]`,d=L(S,R);$(d,["file","line","typeName","importedFrom"],R);let N=he(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?[]:K(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let R=`$.arkRunCompositionRootHits[${C}]`,d=L(S,R);return $(d,["file","matchedRoot","hasKernelFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasKernelFactory:H(d,"hasKernelFactory",R)}}),v=e.arkRunDeclarations===void 0?[]:K(e,"arkRunDeclarations","$"),j=(e.arkOrderPlaneCalls===void 0?[]:K(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let R=`$.arkOrderPlaneCalls[${C}]`,d=L(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?[]:K(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let R=`$.arkOrderGenericUpdates[${C}]`,d=L(S,R);return $(d,["file","line","method"],R),{file:M(d,"file",R),line:Y(d,"line",R),method:T(d,"method",R)}}),pe=(e.arkOrderRootHits===void 0?[]:K(e,"arkOrderRootHits","$")).map((S,C)=>{let R=`$.arkOrderRootHits[${C}]`,d=L(S,R);return $(d,["file","matchedRoot","hasPlaneFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasPlaneFactory:H(d,"hasPlaneFactory",R)}}),ze=(e.arkOrderXiFieldWrites===void 0?[]:K(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let R=`$.arkOrderXiFieldWrites[${C}]`,d=L(S,R);return $(d,["file","line","key"],R),{file:M(d,"file",R),line:Y(d,"line",R),key:T(d,"key",R)}}),Sn=(e.arkOrderIngestWritesXi===void 0?[]:K(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let R=`$.arkOrderIngestWritesXi[${C}]`,d=L(S,R);return $(d,["file","line"],R),{file:M(d,"file",R),line:Y(d,"line",R)}}),vr=(e.arkOrderReleaseKeyCounts===void 0?[]:K(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let R=`$.arkOrderReleaseKeyCounts[${C}]`,d=L(S,R);return $(d,["file","line","keyCount"],R),{file:M(d,"file",R),line:Y(d,"line",R),keyCount:Y(d,"keyCount",R)}}),It=v.map((S,C)=>{let R=`$.arkRunDeclarations[${C}]`,d=L(S,R);return $(d,["file","line","uses","reactsTo","raises","sends"],R),{file:M(d,"file",R),line:Y(d,"line",R),uses:st(d.uses,`${R}.uses`),reactsTo:st(d.reactsTo,`${R}.reactsTo`),raises:st(d.raises,`${R}.raises`),sends:st(d.sends,`${R}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",g],["$.intentReferences",m],["$.safetyUses",h],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",It],["$.arkOrderPlaneCalls",j],["$.arkOrderGenericUpdates",_],["$.arkOrderRootHits",pe],["$.arkOrderXiFieldWrites",ze],["$.arkOrderIngestWritesXi",Sn],["$.arkOrderReleaseKeyCounts",vr]])for(let R of C)if(!p.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let xe=he(e,"projectPackageName","$"),br=(e.classShapes===void 0?[]:K(e,"classShapes","$")).map((S,C)=>{let R=`$.classShapes[${C}]`,d=L(S,R);$(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let N=K(d,"mutatingMethods",R).map((F,ne)=>{let wn=`${R}.mutatingMethods[${ne}]`,Er=L(F,wn);return $(Er,["name","referencesGuardOrPublish"],wn),{name:T(Er,"name",wn),referencesGuardOrPublish:H(Er,"referencesGuardOrPublish",wn)}});return{file:M(d,"file",R),className:T(d,"className",R),exported:H(d,"exported",R),hasPublicMutableFields:H(d,"hasPublicMutableFields",R),hasPublicSetters:H(d,"hasPublicSetters",R),hasPublicConstructor:H(d,"hasPublicConstructor",R),hasStaticFactory:H(d,"hasStaticFactory",R),mutatingMethods:N,...d.dataOnly===void 0?{}:{dataOnly:H(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","$"),...xe?{projectPackageName:xe}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:g,intentReferences:m,safetyUses:h,classShapes:br,arkRunKernelCalls:u,arkRunManagedNews:b,arkRunCompositionRootHits:A,arkRunDeclarations:It,arkOrderPlaneCalls:j,arkOrderGenericUpdates:_,arkOrderRootHits:pe,arkOrderXiFieldWrites:ze,arkOrderIngestWritesXi:Sn,arkOrderReleaseKeyCounts:vr}}i(Os,"parseResolvedFactsInput");function Ae(e){let t=L(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=ws(Os(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(Ae,"loadResolvedCandidateFacts");var Wa=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},Z={type:"integer",minimum:1},G={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},jn={$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:Z,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:Z,symbol:x,capability:{enum:Wa},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:G,line:Z,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:G,line:Z,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:Z,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:G,line:Z,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:Z,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:Z,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:Z,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:Z,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:G,line:Z,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:Z,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:G,line:Z}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:G,line:Z,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 Bn="1.0";function Q(e){return`${e.from}->${e.to}`}i(Q,"dependencyKey");function Yt(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.`}:{}}}i(Yt,"dependencyFinding");function Ke(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])),a=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(a.has(Q(p))){t.push(Yt("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let f={from:p.to,to:p.from};a.has(Q(f))?(l.add(Q(f)),t.push(Yt("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(Yt("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[...a].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({...Yt("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)))a.has(p)||g.has(f.from)||g.has(f.to)||!c.has(f.from)&&!c.has(f.to)||t.push({...Yt("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}}i(Ke,"analyzeArchitectureConvergence");var Ps="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",qa=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var _s={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Uu={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ps,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:Ps},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:[...qa]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:_s,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:_s}}}};function Xt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Xt,"emptyEffectiveArkRules");function Ns(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}))}}}i(Ns,"effectiveContractPolicyPayload");function Ts(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i(Ts,"formatCoverageDiscards");function za(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(za,"isUnderCoverageRoot");function Ya(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Ya,"titleMatchesInvariant");function Xa(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(Xa,"symbolPresent");function Ds(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=Ts(s),l=Ts(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=[],b=u.coverage?.test!==!1,E=u.coverage?.symbol,A,v;if(!r&&b){let _;for(let z of n){let pe=e.fileContents[z];if(!(!pe||!Ya(pe,u.id))){if(!m||za(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")}E&&Xa(e.fileContents,E)&&y.push("symbol");let j=(u.coverage?.test===!0||!!E||u.coverage===void 0)&&y.length>0||u.coverage?.test===!1&&!E?!0:y.length>0,k=r&&b&&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:a),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)}}i(Ds,"evaluateInvariantCoverage");function Ls(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(Ls,"canPromoteInvariant");var qn="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}})}i(O,"addFinding");function q(e){return[...new Set(e??[])].sort()}i(q,"sortedUnique");function ae(e,t,n,r,o){let s=q(n),a=q(r),l=new Set(s),c=new Set(a),g=a.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:a}),m.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(ae,"compareStringSets");function Zt(e,t,n,r,o,s,a){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(Zt,"compareBoolean");function Wn(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(Wn,"keyed");function Za(e,t,n){let r=Wn(t,s=>s.name),o=Wn(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 a=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!a&&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(a&&!l){O(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;ae(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ae(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=Un(a),m=Un(l);ae(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."}),ae(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(a.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(a.intentPrefixes),after:q(l.intentPrefixes)}),Zt(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Zt(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Za,"compareLayers");function Ja(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Wn(t,r),s=Wn(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 a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(a),c=s.values.get(a),g=`$.rules[${a}]`;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)&&($s(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."),$s(e,`${g}.allowedCrossSlice`,"cross-slice-allowance",q((l.allowedCrossSlice??[]).map(Fs)),q((c.allowedCrossSlice??[]).map(Fs)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Ja,"compareRules");function Fs(e){return JSON.stringify([e.from,e.to])}i(Fs,"crossSliceKey");function $s(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(m=>!r.includes(m)),c=r.filter(m=>!o.includes(m)),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:a,before:r,after:o})}i($s,"compareDeclaredExceptions");function Qa(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,l=o[s]??0;a!==l&&O(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Zt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Qa,"compareSafety");function to(e){return e.mode==="enforced"?"enforced":"advisory"}i(to,"arkRunMode");function no(e){return e.mode==="enforced"?"enforced":"advisory"}i(no,"arkOrderMode");function el(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 (${no(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 a=no(r),l=no(o);if(a!==l){let c=a==="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:a,after:l})}ae(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."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(el,"compareArkOrder");function tl(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 (${to(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 a=to(r),l=to(o);if(a!==l){let c=a==="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:a,after:l})}ae(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."}),ae(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."}),Zt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(tl,"compareArkRun");function nl(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(nl,"overallClassification");function Ms(e,t){return`${e}::${t}`}i(Ms,"ruleKey");function Hs(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Ms(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Ms(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Hs,"indexEffectiveRules");function rl(e,t,n,r,o,s){let a=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=Hs(r),h=Hs(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 b=f.mode==="advisory"&&u.mode==="enforced";O(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:b?"strengthening":"weakening",message:b?`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 E=a?.get(u.id),A=Ls(E);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})}}i(rl,"compareArkRules");function zn(e,t,n){let r=[];ae(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ae(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."}),ae(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."}),Zt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&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}),Za(r,e.layers,t.layers),Ja(r,e.rules,t.rules),Qa(r,e,t),rl(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),tl(r,e,t),el(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:qn,classification:nl(r),findings:r}}i(zn,"classifyArkPolicyDelta");function Yn(e,t){if(!e||e.schemaVersion!==qn||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=q(e.findingIds),r=q(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(Yn,"policyDeltaAcknowledgementMatches");function Ge(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Ge,"normalizePath");function Ks(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Ks,"isIdentifierStart");function Xn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Xn,"isIdentifierCharacter");function ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ee,"skipWhitespace");function Jt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Jt,"readString");function se(e,t,n){return e.startsWith(t,n)&&!Xn(e[n-1])&&!Xn(e[n+t.length])}i(se,"isWordAt");function Gs(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(!se(e,"type",n))return!1;let o=ee(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||se(e,"as",o)||!Ks(e[o]))return!1;for(n=o;n<e.length&&Xn(e[n]);)n+=1;if(n=ee(e,n),se(e,"as",n)){if(n=ee(e,n+2),!Ks(e[n]))return!1;for(;n<e.length&&Xn(e[n]);)n+=1}r=!0}return!1}i(Gs,"bracedNamedBindingsAreTypeOnly");function ol(e,t){if(t=ee(e,t+6),e[t]==="(")return Jt(e,ee(e,t+1));let n=!1;if(se(e,"type",t)){let o=ee(e,t+4);e[o]!==","&&!se(e,"from",o)&&(n=!0)}else Gs(e,t)&&(n=!0);let r=Us(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(ol,"specifierAfterImport");function sl(e,t){t=t+6;let n=ee(e,t),r=!1;if(se(e,"type",n)){let s=ee(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Gs(e,n)&&(r=!0);let o=Us(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(sl,"specifierAfterExport");function Us(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(se(e,"from",t))return Jt(e,ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Jt(e,t);if(t>0&&(se(e,"import",t)||se(e,"export",t)))return}}i(Us,"specifierInStaticStatement");function il(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i(il,"skipTemplateLiteral");function al(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=Jt(e,r);return o?{...o,requireCall:!0}:void 0}i(al,"specifierAfterRequire");function ll(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=il(e,n);continue}if(r==="'"||r==='"'){let s=Jt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&se(e,"import",n)?ol(e,n):r==="e"&&se(e,"export",n)?sl(e,n):r==="r"&&se(e,"require",n)?al(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(ll,"moduleSpecifiers");function Vs(e,t){let n=[],r=[];for(let o of ll(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let g=Vt(s);if(!g)continue;let m=e.content.slice(0,o.offset).split(`
|
|
24
|
+
`).length;r.push({file:e.path,symbol:s,capability:g,evidence:{kind:"import",file:e.path,line:m,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
|
|
25
|
+
`).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=cl(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(Vs,"moduleFactsFor");function cl(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(cl,"resolveSpecifier");function js(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=me(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(js,"violationsFor");var dl={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 pl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(pl,"hasActiveArkRules");function ul(e,t){return pl(e,t)?B(D(Ns({config:e,arkRules:t,warnings:[]}))):B(D(e))}i(ul,"policyHashFor");function Qt(e,t,n){let r=typeof e=="string"?hs(e,t):Mr(e,t),o=n?.arkRules??Xt();return{...r,arkRules:o,policyHash:ul(r.config,o)}}i(Qt,"loadContract");function ro(e){let t=Qt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Qt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=zn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,a=s&&Yn(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(ro,"analyzePolicyDelta");function at(e){let t=e.files.map(h=>{let p=Ge(h.path);return{path:p,content:h.content,contentHash:B(h.content),layer:ie(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=Vs(h,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=js(r,e.contract.config),a=new Map(e.contract.config.layers.map(h=>[h.name,h])),l=new Map(e.contract.config.layers.map(h=>[h.name,new Set(nt(h))]));for(let h of o){let p=n.get(h.file)?.layer;if(!p)continue;let f=a.get(p),u=Se(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"?[]:[{...dl}],m={schemaVersion:Bn,policyHash:e.contract.policyHash,compilerOptionsHash:B(D(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}}i(at,"analyzeProject");function en(e){let t=new Map(e.files.map(n=>[Ge(n.path),n]));for(let n of e.changes){let r=Ge(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return at({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(en,"analyzeChange");function oo(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(oo,"explainViolation");function Zn(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let h of[...e.get(c)??[]].sort())e.has(h)&&(n.has(h)?o.has(h)&&r.set(c,Math.min(r.get(c)??0,n.get(h)??0)):(l(h),r.set(c,Math.min(r.get(c)??0,r.get(h)??0))));if(r.get(c)!==n.get(c))return;let g=[],m;do{if(m=s.pop(),m===void 0)break;o.delete(m),g.push(m)}while(m!==c);g.length>1&&a.push(g.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.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"}))}i(Zn,"detectArchitectureCycles");function Ue(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=_r(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,g=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=c?zo(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,h=l.message?m?`${l.message} (${m})`:l.message:m?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${m}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message: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=Zn(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(Ue,"evaluateArchitectureGraph");var fl=["no-anemic-model"];function Bs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Bs,"escapeGlobLiteral");function gl(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+=Bs(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Bs(o)}return new RegExp(`^${n}$`)}i(gl,"globToRegExp");function lt(e,t){return!t||t.length===0?!0:t.some(n=>gl(n).test(e))}i(lt,"matchesAppliesTo");function ml(e){return fl.includes(e)}i(ml,"isTier2");function Ws(e){return e.mode==="enforced"&&!ml(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Ws,"severityFor");function Ve(e,t,n,r=1){let{severity:o,failsStrict:s}=Ws(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(Ve,"baseViolation");function Jn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Jn,"isInRuleLayer");function Qn(e,t,n){return t.filter(r=>!(!r.exported||!lt(r.file,e.appliesTo)||!Jn(r.file,e,n)))}i(Qn,"shapesForRule");function yl(e,t,n){let r=[];for(let o of Qn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Ve(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(yl,"evaluateAggregatePrivateState");function hl(e,t,n){let r=[];for(let o of Qn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Ve(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(hl,"evaluateAlwaysValidFactory");function Rl(e,t,n){let r=[];for(let o of Qn(e,t,n))for(let s of o.mutatingMethods)s.referencesGuardOrPublish||r.push(Ve(e,o.file,`Mutating method ${o.className}.${s.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(Rl,"evaluateDomainEventOnMutation");function Al(e,t){let n=[];for(let r of t.files)lt(r,e.appliesTo)&&Jn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ve(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Al,"evaluateOrchestrationOnly");function kl(e,t){let n=[];for(let r of t.files)lt(r,e.appliesTo)&&Jn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ve(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(kl,"evaluateThinAdapter");function Il(e,t){let n=[];for(let r of t.files)lt(r,e.appliesTo)&&Jn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Ve(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(Il,"evaluateWritesViaAggregate");function vl(e,t,n){let r=[];for(let o of Qn(e,t,n))if(o.dataOnly===!0){let s=Ve(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(vl,"evaluateNoAnemicModel");function qs(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(...yl(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...hl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Rl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Al(n,e));break;case"thin-adapter":t.push(...kl(n,e));break;case"writes-via-aggregate":t.push(...Il(n,e));break;case"no-anemic-model":t.push(...vl(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(qs,"evaluateArkRuleSensors");function zs(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=>lt(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=Ws(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>lt(l,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(zs,"collectEmptyAppliesToFindings");var bl=/\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)/,El=/\.(?: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,Sl=/\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*=)/,Cl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,wl=/\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*=/,xl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Ol(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(wl.source,"g"))??[],r=t.match(new RegExp(xl.source,"g"))??[],o=(t.match(/\bif\s*\(/g)??[]).length,s=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&o+s>=6,l=bl.test(t),c=Sl.test(t)||Cl.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&&El.test(t);return!a&&!h&&!p?null:{...a?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{},...p?{persistenceWrite:!0}:{}}}i(Ol,"deriveArkRuleFileHints");function Ys(e){let t={};for(let[n,r]of Object.entries(e)){let o=Ol(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}i(Ys,"buildArkRuleFileHints");function Pl(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(Pl,"normalizeExtraMergeTeethClassification");function er(e){let t=Pl(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(er,"extraMergeTeethAllowed");function Xs(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Xs,"classifyResolvedLayerCoverage");var _l=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Sf=new Set(_l);function Zs(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Zs,"isArkRunKernelModuleSpecifier");var Nl=["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"],so=new Set(Nl);function Js(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(so.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(so.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:so.has(e.slice(0,r))}i(Js,"isArkRunTransportBypassSpecifier");var Tl=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Lf=new Set(Tl);var Qs={"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"},Dl="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ni(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(ni,"isDomainRoleLayer");function Ll(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Ll,"compareFindings");function ke(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Qs[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:Qs[t],fromLayer:s?.fromLayer,target:s?.target})}}i(ke,"finding");function Fl(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(Fl,"bagForFile");function ei(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(ei,"emitKinds");function ti(e){return e==="subscribe"||e==="register-handler"}i(ti,"handleKinds");function $l(e){return e==="resolve"||e==="resolve-singleton"}i($l,"dependKinds");function Ml(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ke(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let l=s.get(a.matchedRoot)??[];l.push(a),s.set(a.matchedRoot,l)}for(let a of o){let l=[...s.get(a)??[]].sort((g,m)=>g.file.localeCompare(m.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(g=>g.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Ml,"evaluateMissingRoot");function Hl(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!Zs(c))continue;let g=r(l.from);g&&ni(g,s.get(g)??[])&&a.push(ke(e,"arkrun-kernel-in-domain",l.from,l.line,`${g} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:g,target:c},o))}return a}i(Hl,"evaluateKernelInDomain");function Kl(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(m=>[m.name,m.intentPrefixes??[]])),c=new Set(r.filter(m=>m.hasKernelFactory).map(m=>m.file)),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||!a.has(p)||ni(p,l.get(p)??[])||g.push(ke(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}i(Kl,"evaluateDirectNew");function Gl(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:a};for(let c of t){if(!ei(c.kind)&&!ti(c.kind)&&!$l(c.kind))continue;let g=r(c.file);if(!g||!l.has(g))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:Dl,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=Fl(n,c.file);if(ei(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;s.push(ke(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(ti(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;s.push(ke(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(ke(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:a}}i(Gl,"evaluateUndeclared");function Ul(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!Js(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(ke(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}i(Ul,"evaluateTransportBypass");function ri(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=er(e.classification),r=Gl(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Ml(t,e.compositionRootHits,n),...Hl(t,e.layers,e.dependencies,e.layerForFile,n),...Kl(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Ul(t,e.dependencies,e.layerForFile,n)].sort(Ll),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,g=`${l.code}\0${l.file??""}\0${l.message}`;return c<g?-1:c>g?1:0});return{findings:o,completenessReasons:s}}i(ri,"evaluateArkRunSensors");function oi(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(oi,"isArkOrderModuleSpecifier");var si={"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"};function Vl(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Vl,"isDomainRoleLayer");function Ie(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:si[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:si[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Ie,"finding");function ii(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=er(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Ie(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(Ie(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(Ie(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||!oi(g))continue;let m=e.layerForFile(c.from);m&&Vl(m,s.get(m)??[])&&r.push(Ie(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(Ie(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];a.length>t.maxXiKeys&&r.push(Ie(t,"arkorder-too-many-params","ark.config.json",1,`arkOrder.xiKeys has ${a.length} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(a.length)},n));for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Ie(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(Ie(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let g=e.layerForFile(c.file);!g||!l.has(g)||r.push(Ie(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:[]}}i(ii,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}i(J,"configWarning");function tn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(f=>typeof f!="string"))&&s.push(J("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(J("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let f of["maxTsSuppressions","maxAnyCasts"]){let u=t.safety[f];u!==void 0&&(!Number.isInteger(u)||u<0)&&s.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${f} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...a.map(f=>f.name).filter(Boolean),...l.map(f=>f.name).filter(f=>!!f)]);a.length===0&&s.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let g=new Set,m=new Set;for(let f of a){if(!f.name){s.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}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(J("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${f.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:f.name}));let u=Array.isArray(f.patterns)?f.patterns:[];if(u.length===0){s.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${f.name}" has no file patterns and will never classify files.`,{layer:f.name}));continue}for(let y of u){let b;try{b=ge(y)}catch(A){s.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${f.name}" has an invalid pattern "${y}": ${A instanceof Error?A.message:String(A)}`,{layer:f.name,pattern:y}));continue}let E=f.optional===!0||f.reserved===!0||f.allowEmpty===!0;!r.some(A=>b.test(A))&&!E&&s.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${f.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:f.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let f of m)s.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${f}" is configured more than once.`,{layer:f}));if(c.size>0)for(let f of n??[])f.from&&!c.has(f.from)&&s.push(J("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${f.from}".`,{fromLayer:f.from,toLayer:f.to})),f.to&&!c.has(f.to)&&s.push(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${f.to}".`,{fromLayer:f.from,toLayer:f.to}));let h=new Set;if(a.length>1)for(let f of r){let u=-1,y=[];for(let b of a)for(let E of b.patterns??[]){if(!ge(E).test(f))continue;let A=Pr(E,f);A>u?(u=A,y=[b.name]):A===u&&!y.includes(b.name)&&y.push(b.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&s.push(J("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let p=r.filter(f=>!ie(f,a));return p.length>0&&s.push(J("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}i(tn,"collectAnalysisConfigWarnings");function jl(e,t){return t.some(n=>{try{return ge(n).test(e)}catch{return!1}})}i(jl,"matchesAny");function Bl(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:b})=>({file:y,line:b})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:b})=>({file:y,line:b})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!jl(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:a,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(a.length>r){let y=a[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];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}}i(Bl,"evaluateSafety");function Wl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(Wl,"ambientForbiddenGlobal");function ai(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Qr(e,n.length>0?n:Jr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(ai,"intentLayer");function ql(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!Wl(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let l=o.get(a),c=l?.forbiddenGlobals??[],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"&&jt(s.symbol,c))){if(s.source==="import-based"){let m=Se(s.symbol,c);if(m){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...g?{edgeKind:g}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${m}".`});continue}}nt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...g?{edgeKind:g}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let c of Bt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!s.sourceIntent)continue;let l=ai(s.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let l=ai(s.intent,e.contract);if(!l)continue;let c=me(e.contract.config.rules,a,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.intent,message:c.message??`${a} must not reference ${l} intent ${s.intent}.`})}return r}i(ql,"contentViolations");function zl(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 F=`${d.code}\0${d.file??""}\0${d.message}`,ne=`${N.code}\0${N.file??""}\0${N.message}`;return F<ne?-1:F>ne?1:0}),a=t.files.map(d=>({...d,layer:ie(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let N=d.target?l.get(d.target)??ie(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=tn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),m=Bl(e,t),h=e.contract.arkRules??Xt(),p=a.map(d=>d.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Ys(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...qs({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:i(d=>l.get(d)??ie(d,e.contract.config.layers),"layerForFile"),fileHints:u}),...zs(h,p)],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,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.`})),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,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?Ds({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=Xs(a),_=ri({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ie(d,e.contract.config.layers),"layerForFile"),classification:k}),z=e.contract.config.arkRun?.mode,pe=_.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}:{}})),En=_.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})),ze=ii({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ie(d,e.contract.config.layers),"layerForFile"),classification:k}),Ir=e.contract.config.arkOrder?.mode,Sn=ze.findings.filter(()=>Ir==="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}:{}})),wo=ze.findings.filter(()=>Ir!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),It=[...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,...ze.completenessReasons],xe=Ue({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...ql(e,t,l),...b,...P,...pe,...Sn],edges:c,warnings:[...g,...m.warnings,...E,...j,...En,...wo],safety:m.report}),Cn=o==="complete"&&It.length>0?"partial":o,br=Cn==="complete"?s:[...s,...It].sort((d,N)=>{let F=`${d.code}\0${d.file??""}\0${d.message}`,ne=`${N.code}\0${N.file??""}\0${N.message}`;return F<ne?-1:F>ne?1:0}),S=xe.violations.filter(d=>d.failsStrict!==!1),C=Cn==="complete"&&S.length===0,R=C&&xe.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Cn,completenessReasons:br,valid:C,strictValid:R,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:m.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:xe.violations,warnings:xe.warnings}}}i(zl,"analyzeCanonicalResolvedProject");function ct(e){return zl({contract:e.contract,facts:Ae(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(ct,"analyzeResolvedProject");function li(e){return B(D(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(li,"analysisTreeHash");function io(e){let t=at(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,"/"),b=Ge(u.path);if(!b||b===".."||b.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(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in u&&u.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:b,delete:!0}:{path:b,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 a=en({...e,changes:r}),l=new Map(a.ir.files.map(u=>[u.path,u])),c=a.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=Ue({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(u=>u.path),contentViolations:c,edges:a.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=Ge(u.path),b=n.get(y),E=l.get(y);return{path:y,operation:"delete"in u&&u.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...E?{candidateContentHash:E.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?Ke({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:a.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"&&a.valid&&p.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:li(t.ir.files),candidateTreeHash:li(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:m,violations:h,warnings:g.warnings}}i(io,"preflightChange");function Yl(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(Yl,"canonicalChangePath");function Xl(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(Xl,"identityViolations");function Zl(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(Zl,"preparedChange");function ao(e){let t=Ae(e.baseFacts),n=Ae(e.candidateFacts),r=ct({contract:e.contract,facts:t}),o=ct({contract:e.contract,facts:n}),s=new Map(t.files.map(f=>[f.path,f])),a=new Map(n.files.map(f=>[f.path,f])),l=Xl(t,n),c=new Map,g=[];for(let f of e.changes){let u=Yl(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),b=a.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.`}),b&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:u,line:1,message:`Candidate facts still contain deleted file ${u}.`});else{let E="content"in f?f.content:"",A=B(E);b?b.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:u,line:1,expectedContentHash:A,candidateContentHash:b.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(Zl(f,u,s,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let f of new Set([...s.keys(),...a.keys()])){if(c.has(f))continue;let u=s.get(f),y=a.get(f);u&&y&&D(u)===D(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?Ke({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}}i(ao,"preflightResolvedChange");var tr="docs/diagnostics.md",ci="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}:{}}}i(I,"entry");var nn=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() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. 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 or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. 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 + release, then preflight again. 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.")]),lo=new Map(nn.map(e=>[e.ruleId,e])),di=Object.freeze(nn.map(e=>e.ruleId));function pi(e){return typeof e=="string"&&e.length>0&&lo.has(e)}i(pi,"isKnownDiagnosticCode");function ui(e){return typeof e!="string"||e.length===0?!1:lo.has(e)?!0:e.startsWith("ARKRULE_")}i(ui,"isCataloguedOrArkRuleFamily");function rn(e){if(!(typeof e!="string"||e.length===0))return lo.get(e)}i(rn,"getDiagnosticCatalogEntry");function co(e){return`#${rn(e)?.docsAnchor??e}`}i(co,"diagnosticDocsFragment");function fi(e){return`${tr}${co(e)}`}i(fi,"diagnosticDocsPath");function gi(){return{schemaVersion:"1.0",docsPath:tr,codes:nn}}i(gi,"serializeDiagnosticCatalog");function mi(e){return rn(e)?.fix}i(mi,"catalogFixForRuleId");function yi(e){return rn(e)?.why}i(yi,"catalogWhyForRuleId");var hi="1.1";var Ri="1.0";var dt=class{static{i(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function Jl(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(Jl,"initialState");var nr=class{static{i(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new dt,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)??Jl(r),s=await r.project(t,o);await this.store.save(r.name,s);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function on(e){return new nr(e)}i(on,"createProjectionRegistry");var sn="1.0";function Ql(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(Ql,"policyId");var po=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function an(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,a=e.projections,l=e.eventContracts,c=e.observability,g=t?t.list().map(E=>({name:E.name,dependencies:t.getDependencies(E.name),productions:t.getProductions(E.name)})):[],m=t?t.getAllRelationships():[],h=n?n.getPolicies().map(E=>({id:Ql(E.name),name:E.name,severity:E.severity,tags:E.tags?[...E.tags]:void 0,owner:E.owner,version:E.version,rationale:E.rationale,enforcementMode:E.enforcementMode,deprecated:E.deprecated,replacedBy:E.replacedBy,description:E.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],f=o?o.toJSON():{nodes:[],edges:[]},u=p.filter(E=>(E.emits?.length??0)>0||(E.consumes?.length??0)>0).map(E=>({entity:E.name,emits:E.emits,consumes:E.consumes})),y=a?a.list().map(E=>({name:E.name,sourceIntents:E.sourceIntents,checkpoint:a.getCheckpoint(E.name)})):[],b={schemaVersion:"1.0",version:xn,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 po(b)}i(an,"createArkManifest");var Ai=0;function ki(e){return Ai+=1,`${e}-${Date.now()}-${Ai}`}i(ki,"createWorkflowId");function uo(e){return e instanceof Error?e.message:String(e)}i(uo,"errorMessage");function ec(e){return new Promise(t=>{setTimeout(t,e)})}i(ec,"sleep");async function tc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((a,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}i(tc,"withTimeout");var pt=class{static{i(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let a=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||a){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},fo=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new pt}bus;options;static{i(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),a={id:r.id??ki(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:t}),this.executeSnapshot(a,o,r.tx)}async resume(t,n={}){let r=await this.get(t,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(t,n,r){try{let o=n.steps.filter(s=>!t.completedSteps.includes(s.name));for(let s of o)await this.runStep(t,s,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=uo(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=s;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let l;try{l=await tc(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<s){o.delayMs&&await ec(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:a,error:uo(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(a=>t.completedSteps.includes(a.name));for(let a=s.length-1;a>=0;a-=1){let l=s[a];if(l.compensate)try{await Promise.resolve(l.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:l.name})}catch(c){await this.audit("workflow.step.failed",t,{step:l.name,compensation:!0,error:uo(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function ut(e,t){return new fo(e,t)}i(ut,"createWorkflowEngine");function go(e,t,n={}){let r=ut(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??ki(e.name),a="idle",l=[];return{id:s,definition:e,get status(){return a},get completedSteps(){return[...l]},async run(c){a="running",l=[];try{let g=await r.start(e.name,c,{id:s});a=g.status==="waiting"?"idle":g.status,l=[...g.completedSteps]}catch(g){let m=await r.get(s);throw a=m?.status==="waiting"?"idle":m?.status??"failed",l=m?.completedSteps??[],g}}}}i(go,"createSaga");ft();dr();Rn();vn();vn();async function bn(e,t={}){let n=Rt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(_i(),Pi));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(bn,"startArkRunInspector");dr();vn();ft();Rn();ft();var Pc=new Set(["singleton","transient"]);function Ni(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return t}i(Ni,"cloneComponent");function _c(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Pc.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(_c,"closedLifetime");function Ti(){let e=new Map,t=new Map,n=new Set;function r(a){let l=e.get(a);if(!l)throw new Error(`ArkRun component "${a}" is not registered.`);return l}i(r,"mustRecord");function o(a,l){if(!l.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return l.factory()}finally{n.delete(a)}}i(o,"instantiate");function s(a,l){if(t.has(a))return t.get(a);let c=o(a,l);return t.set(a,c),c}return i(s,"singleton"),{register(a){let l=typeof a?.id=="string"?a.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=_c(a.lifetime),g=yo({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!g)throw new Error("ArkRun component id must be a non-empty string.");let m=typeof a.factory=="function"?a.factory:void 0;return e.set(l,{component:g,factory:m}),Ni(g)},resolve(a){let l=r(a);return l.component.lifetime==="transient"?o(a,l):s(a,l)},resolveSingleton(a){let l=r(a);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return s(a,l)},snapshotComponents(){return[...e.values()].map(a=>Ni(a.component))}}}i(Ti,"createComponentRegistry");Rn();function Nc(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new fe(e.source,t.source);return t.source=e.source,t}i(Nc,"stampMetadata");function Tc(){}i(Tc,"ignoreDetachedFailure");async function vo(e,t,n,r={}){let o=hn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Nc(r),a=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let l=Promise.resolve(e.broker.send(a));o.awaitHandoff?await l:l.then(void 0,Tc)}return o}i(vo,"sendOnArkRunTransport");var Rr=1e3,Di=0;function Dc(){return Di+=1,`ark-kernel-${Date.now()}-${Di}`}i(Dc,"nextKernelInstanceId");function kt(e={}){let t=e.strict??!0,n=e.instanceId??Dc(),r=e.profile??Fe,o=e.maxHistorySize??Rr,s=Et(),a=Ft(),l=e.metadata??Ut(),c=e.auditTrail??Lt({maxRecords:o}),g=e.eventContracts??Tt(),m=e.eventBuffer??e.outbox??new Ee,h=e.projections??on({auditTrail:c}),p=new ve([xt(r),...e.policies??[]]),f=i(()=>{$t(s,a,{requireRegisteredTargets:!0})},"syncGraph"),u=e.ephemeral??!0,y=e.broker,b=new Ze({intentRegistry:s,dependencyGraph:a,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)}}),E=ut(b,{auditTrail:c}),A=Dt({registry:s,eventBus:b,graph:a}),v=Ti(),P=typeof y?.send=="function",j={instanceId:n,profile:r,registry:s,graph:a,metadata:l,auditTrail:c,eventContracts:g,eventBuffer:m,outbox:m,projections:h,policyEngine:p,eventBus:b,workflowEngine:E,observability:A,publisher(k){let _=b.createPublisher(k);return{source:_.source,publish:_.publish,send(z,pe,En={}){return vo({eventBus:b,broker:y,defaultEphemeral:u},z,pe,{...En,source:_.source})}}},send(k,_,z={}){return vo({eventBus:b,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 ce({kernelInstanceId:n,components:v.snapshotComponents()})},requestGraph(k){return yn({kernelInstanceId:n,components:v.snapshotComponents()},k)},getInspectorSnapshot(k){return In({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:v.snapshotComponents()},observability:A.report(),ephemeralDefault:u,brokerBound:P})},startInspector(k){return bn(j,k)},syncGraph:f,manifest(){return f(),an({registry:s,policyEngine:p,metadata:l,graph:a,profile:r,projections:h,eventContracts:g,observability:A})}};return j}i(kt,"createArkKernel");function Ar(e={}){return kt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Ar,"createStrictArkKernel");function bo(e,t={}){let{profileName:n,...r}=t;return{...r,profile:Gt(e,{name:n})}}i(bo,"createOptionsFromConfig");function Eo(e,t={}){return kt(bo(e,t))}i(Eo,"createArkKernelFromConfig");function So(e,t={}){return Ar(bo(e,t))}i(So,"createStrictArkKernelFromConfig");function Co(e,t={}){return kr(bo(e,t))}i(Co,"createLenientArkKernelFromConfig");function kr(e={}){return kt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(kr,"createLenientArkKernel");0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_RUN_COMPONENT_LIFETIMES,ARK_RUN_EPHEMERAL_DEFAULT,ARK_RUN_GRAPH_DEFAULT_SLICE,ARK_RUN_GRAPH_NODE_KINDS,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,ARK_RUN_GRAPH_SCHEMA_VERSION,ARK_RUN_GRAPH_SLICES,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,ARK_RUN_INSPECTOR_DEFAULT_HOST,ARK_RUN_INSPECTOR_DEFAULT_PORT,ARK_RUN_INSPECTOR_EVENTS_PATH,ARK_RUN_INSPECTOR_GRAPH_PATH,ARK_RUN_INSPECTOR_SCHEMA_VERSION,ARK_RUN_INSPECTOR_SNAPSHOT_PATH,ARK_RUN_INSPECTOR_SSE_EVENT,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,ARK_RUN_TRANSPORT_KINDS,ArkRunInspectorBindError,ArkRunInspectorProductionError,DEFAULT_MAX_HISTORY_SIZE,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EventContractRegistryImpl,EventContractViolationError,InMemoryAuditStore,InMemoryEventBuffer,InMemoryOutboxStore,InMemoryReadModelStore,InMemoryWorkflowStore,IntentRegistry,InvalidArkRunGraphQueryError,InvalidArkRunSendOptionError,InvalidIntentNameError,LayerPolicyContextError,MANIFEST_SCHEMA_VERSION,ObservedLayerFlowViolationError,POLICY_DELTA_SCHEMA_VERSION,PolicyEngine,PolicyViolationError,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,SourceMetadataOverrideError,UnknownEventSourceError,UnregisteredIntentError,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,architecturalPolicies,arkRunGraphQueryFromSearchParams,arkRunInspectorUrl,buildArkRunInspectorSnapshot,buildDependencyInformationPackage,buildPublishPolicyContext,catalogFixForRuleId,catalogWhyForRuleId,checkAdapterGovernance,checkContract,classifyArkPolicyDelta,closeArkRunGraphQuery,closedArkRunEphemeral,closedArkRunTransportKind,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapter,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createArkKernel,createArkKernelFromConfig,createArkManifest,createArkTestHarness,createAuditTrail,createDependencyGraph,createElevenLayerArkConfig,createEventBus,createEventContractRegistry,createIntentRegistry,createLenientArkKernel,createLenientArkKernelFromConfig,createMetadataRegistry,createObservabilityReporter,createProjectionRegistry,createResolvedCandidateFacts,createSaga,createStrictArkKernel,createStrictArkKernelFromConfig,createWorkflowEngine,defaultIntentRegistry,defineArchitectureProfilePolicy,defineIntent,defineLayerPolicy,definePolicy,definePort,definePublishPolicy,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,formatArkRunGraphMermaid,formatArkRunInspectorSseEvent,getDiagnosticCatalogEntry,isArkRunInspectorLoopbackHost,isArkRunInspectorProductionEnv,isCataloguedOrArkRuleFamily,isKnownDiagnosticCode,isLayerPolicy,loadContract,loadResolvedCandidateFacts,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,requestArkRunGraph,resolveArkRunInspectorBind,resolveArkRunSendPlan,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,stableSerialize,startArkRunInspector,syncRegistryToGraph,toAdapterDiagnostic,validateIntentName,version});
|