arkgate 4.8.6 → 4.8.8

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +55 -4
  2. package/README.md +37 -4
  3. package/bin/ark-dashboard.mjs +423 -0
  4. package/bin/ark-mcp-runtime.mjs +8 -2
  5. package/bin/ark.mjs +51 -3
  6. package/bin/lib/analysis-engine.mjs +5 -5
  7. package/bin/lib/doctor-human.mjs +9 -0
  8. package/bin/lib/doctor-plan.mjs +5 -1
  9. package/bin/lib/html-report.mjs +4 -2
  10. package/bin/lib/layer-description.mjs +27 -0
  11. package/bin/lib/prepare-write.mjs +7 -1
  12. package/dist/{configTypes-dy5PfTqS.d.ts → configTypes-0eHpocR3.d.ts} +4 -0
  13. package/dist/{diagnosticCatalog-D_DI7qrZ.d.ts → diagnosticCatalog-DxKCTBbp.d.ts} +3 -3
  14. package/dist/eslint/index.d.ts +1 -1
  15. package/dist/index.cjs +19 -19
  16. package/dist/index.d.ts +5 -4
  17. package/dist/index.js +20 -20
  18. package/dist/nestjs/index.cjs +5 -5
  19. package/dist/nestjs/index.d.ts +3 -3
  20. package/dist/nestjs/index.js +5 -5
  21. package/dist/runtime/index.cjs +15 -15
  22. package/dist/runtime/index.d.ts +6 -6
  23. package/dist/runtime/index.js +15 -15
  24. package/dist/{types-BuM8WNqe.d.ts → types-BK47clMl.d.ts} +1 -1
  25. package/dist/{types-DrqsOiTY.d.ts → types-DxvmJO-D.d.ts} +106 -2
  26. package/docs/README.md +12 -4
  27. package/docs/agent-guide.md +36 -1
  28. package/docs/ai-gates.md +13 -1
  29. package/docs/arkorder.md +11 -1
  30. package/docs/configuration.md +25 -3
  31. package/docs/develop.md +13 -6
  32. package/docs/enthusiast/README.md +13 -2
  33. package/docs/package-surface.md +21 -5
  34. package/docs/product-voice.md +25 -2
  35. package/docs/use.md +11 -3
  36. package/package.json +3 -1
  37. package/server.json +2 -2
  38. package/templates/agent-skills/ark-adopt/SKILL.md +19 -1
  39. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  40. package/templates/agent-skills/ark-contract/SKILL.md +1 -1
  41. package/templates/agent-skills/ark-place/SKILL.md +18 -4
  42. package/templates/skills/ark-adopt.md +19 -1
  43. package/templates/skills/ark-autopilot.md +1 -1
  44. package/templates/skills/ark-contract.md +1 -1
  45. package/templates/skills/ark-place.md +18 -4
@@ -1,25 +1,25 @@
1
- "use strict";var ja=Object.create;var vt=Object.defineProperty;var Ba=Object.getOwnPropertyDescriptor;var Wa=Object.getOwnPropertyNames;var qa=Object.getPrototypeOf,za=Object.prototype.hasOwnProperty;var a=(e,t)=>vt(e,"name",{value:t,configurable:!0});var Et=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Do=(e,t)=>{for(var n in t)vt(e,n,{get:t[n],enumerable:!0})},Lo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wa(t))!za.call(e,o)&&o!==n&&vt(e,o,{get:()=>t[o],enumerable:!(r=Ba(t,o))||r.enumerable});return e};var Ya=(e,t,n)=>(n=e!=null?ja(qa(e)):{},Lo(t||!e||!e.__esModule?vt(n,"default",{value:e,enumerable:!0}):n,e)),Xa=e=>Lo(vt({},"__esModule",{value:!0}),e);function yo(e,t){return e<t?-1:e>t?1:0}function uc(e){return[...new Set(e)].sort(yo)}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 uc(t)}function fc(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function gc(e){return typeof e=="string"&&pc.has(e)?e:"singleton"}function xa(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(yo)){if(n.length===0)continue;let r=fc(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function mc(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=xa(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function ho(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:gc(t.lifetime),uses:ln(t.uses),reactsTo:ln(t.reactsTo),raises:ln(t.raises),sends:ln(t.sends)},o=mc(t.extendedInfo);return o&&(r.extendedInfo=o),r}function hc(e){return xa(e)}function Ro(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.xiHash=="string"?t.xiHash.trim():"";if(!n)return;let r=t.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,s=typeof o.kind=="string"?o.kind.trim():"";if(!s)return;let i=t.residual;if(i===null||typeof i!="object"||Array.isArray(i))return;let l=i,c=typeof l.kind=="string"&&yc.has(l.kind)?l.kind:void 0;if(!c)return;let g={kind:s},m=hc(o.payload);m&&(g.payload=m);let h={kind:c};return typeof l.reasonCode=="string"&&l.reasonCode.length>0&&(h.reasonCode=l.reasonCode),typeof l.eventId=="string"&&l.eventId.length>0&&(h.eventId=l.eventId),typeof l.target=="string"&&l.target.length>0&&(h.target=l.target),{xiHash:n,event:g,residual:h}}function Rc(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=Ro(n);r&&t.push(r)}return t}function ce(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let i of n){let l=ho(i);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((i,l)=>yo(i.id,l.id));let s=Rc(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function Ao(e,t){let n=Ro(t),r=e.decisionTape??[],o=n?[...r,n]:[...r];return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components,...o.length>0?{decisionTape:o}:{}}}var cn,rr,wa,pc,yc,ft=Et(()=>{"use strict";cn="1.0",rr=["singleton","transient"],wa=["absorb","escalate_up","hold"],pc=new Set(rr);a(yo,"compare");a(uc,"uniqueSorted");a(ln,"nameList");a(fc,"jsonPrimitive");a(gc,"closedLifetime");a(xa,"sanitizeMetadata");a(mc,"sanitizeArkRunExtendedInfo");a(ho,"sanitizeArkRunComponent");yc=new Set(wa);a(hc,"sanitizeTapePayload");a(Ro,"sanitizeDecisionTapeRecord");a(Rc,"sanitizeDecisionTape");a(ce,"buildDependencyInformationPackage");a(Ao,"appendDecisionTape")});function un(e,t){return e<t?-1:e>t?1:0}function Eo(e){return[...new Set(e)].sort(un)}function Pa(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function bo(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 Eo(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 Eo(n)}function Da(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=>Da(e,n)):!1}function La(e){if(e==null||e==="")return lr;if(typeof e=="string"&&Ac.has(e))return e;throw new X("slice")}function Fa(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 _a(e,t){if(e==null||e==="")return Pa();if(typeof e=="string"||Array.isArray(e))return{...Pa(),tokens:de(e,t)};if(typeof e!="object")throw new X(t);let n=e;for(let r of Object.keys(n))if(!Ic.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(!kc.has(n))throw new X("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:La(t.slice),nodeIds:de(t.nodeIds,"nodeIds"),degreesOfSeparation:Fa(t.degreesOfSeparation),include:_a(t.include,"include"),exclude:_a(t.exclude,"exclude")}}function mn(e){let t={};e.slice&&(t.slice=La(e.slice));let n=de(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=Fa(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 vc(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 Na(e,t){if(!bo(t))return!0;let n=vc(e);return t.tokens.some(r=>n.some(o=>Da(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 Ec(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return ce({kernelInstanceId:t.kernelInstanceId,components:t.components})}return ce({})}function bc(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 sr(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 ar(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 Sc(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(pn(n,bc(s)),t==="technical"){for(let i of s.uses)pn(n,n.get(i)??sr(i)),ar(r,o,s.id,i,"uses");continue}for(let i of s.raises)pn(n,n.get(i)??sr(i)),ar(r,o,s.id,i,"raises");for(let i of s.reactsTo)pn(n,n.get(i)??sr(i)),ar(r,o,i,s.id,"reactsTo");for(let i of s.sends)pn(n,n.get(i)??sr(i)),ar(r,o,s.id,i,"sends")}return{nodes:n,edges:r}}function Cc(e){let t=new Map,n=a((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])},"push");for(let r of e)n(r.from,r.to),n(r.to,r.from);return t}function wc(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let s=new Set,i=o.map(l=>({id:l,depth:0}));for(;i.length>0;){let l=i.shift();if(!(!l||s.has(l.id))&&(s.add(l.id),!(n!==null&&l.depth>=n)))for(let c of r.get(l.id)??[])!s.has(c)&&e.has(c)&&i.push({id:c,depth:l.depth+1})}return s}function fn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function Ta(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function xc(e){let t=new Set,n=new Map;for(let r of e){let o=fn(r),s=o,i=2;for(;t.has(s);)s=`${o}_${i}`,i+=1;t.add(s),n.set(r,s)}return n}function dr(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=xc(n),o=Eo(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],i=a((l,c)=>{let g=r.get(l.id)??fn(l.id),m=Ta(l.label??l.id);s.push(`${c}${g}["${m}"]`)},"emitNode");for(let l of o){let c=fn(`group_${l}`);s.push(` subgraph ${c}["${Ta(l)}"]`);for(let g of e.nodes)g.group===l&&i(g," ");s.push(" end")}for(let l of e.nodes)l.group||i(l," ");for(let l of e.edges){let c=r.get(l.from)??fn(l.from),g=r.get(l.to)??fn(l.to);s.push(` ${c} -->|${l.kind}| ${g}`)}return s.join(`
2
- `)}function Oc(e,t,n){let r=new Set(e.keys());if(bo(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&Na(c,n.include)}))),bo(n.exclude))for(let l of[...r]){let c=e.get(l);c&&Na(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=wc(r,n.nodeIds,n.degreesOfSeparation,Cc(o)));let s=[...r].sort(un).map(l=>e.get(l)).filter(l=>!!l),i=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:i}}function yn(e={},t={}){let n=Ec(e),r=gn(t),o=Sc(n.components,r.slice),s=Oc(o.nodes,o.edges,r),i={schemaVersion:ir,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return i.mermaid=dr(i),i}var ir,lr,cr,So,Co,wo,X,Ac,kc,Ic,pr=Et(()=>{"use strict";ft();ir="1.0",lr="process",cr=["process","technical"],So=["component","interaction"],Co=["raises","reactsTo","sends"],wo=["uses"],X=class extends Error{static{a(this,"InvalidArkRunGraphQueryError")}option;constructor(t,n){super(n??(t==="slice"?'ArkRun graph slice must be "process" or "technical".':t==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${t} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=t}},Ac=new Set(cr),kc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Ic=new Set(["ids","labels","tags","groups","architectureKinds"]);a(un,"compare");a(Eo,"uniqueSorted");a(Pa,"emptyMatch");a(bo,"matchHasCriteria");a(de,"nameList");a(Da,"globMatch");a(dn,"anyGlob");a(La,"closedSlice");a(Fa,"closedDegrees");a(_a,"closedMatch");a(gn,"closeArkRunGraphQuery");a(mn,"arkRunGraphQueryFromSearchParams");a(vc,"nodeFields");a(Na,"nodeMatches");a(Ec,"asPackage");a(bc,"componentNode");a(sr,"interactionNode");a(pn,"addNode");a(ar,"addEdge");a(Sc,"buildSlice");a(Cc,"adjacency");a(wc,"neighborhood");a(fn,"mermaidSafeId");a(Ta,"mermaidLabel");a(xc,"uniqueMermaidIds");a(dr,"formatArkRunGraphMermaid");a(Oc,"filterGraph");a(yn,"requestArkRunGraph")});function ur(e){if(e===void 0)return"local";if(typeof e=="string"&&Pc.has(e))return e;throw new je("transport")}function fr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new je("ephemeral")}function hn(e){let t=ur(e.transport),n=fr(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,Pc,je,Rn=Et(()=>{"use strict";gt=["local","localBlocking","broker"],Be=!0,Pc=new Set(gt),je=class extends Error{static{a(this,"InvalidArkRunSendOptionError")}option;constructor(t){super(t==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=t}};a(ur,"closedArkRunTransportKind");a(fr,"closedArkRunEphemeral");a(hn,"resolveArkRunSendPlan")});function kn(e){return e==="production"}function Nc(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 $a(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=$a(t);if(n)return qe(n);let r=Nc(t);return r!==void 0&&r[0]===127}function Ma(e){if(e===void 0)return An;if(typeof e!="string")throw new te(String(e));let t=e.trim();if(_c.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=$a(n);return r?Ma(r):n}function Tc(e){if(e===void 0)return mr;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:Ma(e.host),port:Tc(e.port)}}function we(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function Dc(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function Lc(e){return{kinds:[...gt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:hr}}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:gr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Lc(e),observability:Dc(e.observability)??{}}}function At(e){return`event: ${yr}
1
+ "use strict";var ra=Object.create;var $t=Object.defineProperty;var oa=Object.getOwnPropertyDescriptor;var sa=Object.getOwnPropertyNames;var ia=Object.getPrototypeOf,aa=Object.prototype.hasOwnProperty;var i=(e,t)=>$t(e,"name",{value:t,configurable:!0});var Kt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Wo=(e,t)=>{for(var n in t)$t(e,n,{get:t[n],enumerable:!0})},qo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sa(t))!aa.call(e,o)&&o!==n&&$t(e,o,{get:()=>t[o],enumerable:!(r=oa(t,o))||r.enumerable});return e};var la=(e,t,n)=>(n=e!=null?ra(ia(e)):{},qo(t||!e||!e.__esModule?$t(n,"default",{value:e,enumerable:!0}):n,e)),ca=e=>qo($t({},"__esModule",{value:!0}),e);function Oo(e,t){return e<t?-1:e>t?1:0}function Sc(e){return[...new Set(e)].sort(Oo)}function vn(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return Sc(t)}function wc(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Cc(e){return typeof e=="string"&&vc.has(e)?e:"singleton"}function Hi(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(Oo)){if(n.length===0)continue;let r=wc(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function xc(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=vn(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=Hi(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Po(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:Cc(t.lifetime),uses:vn(t.uses),reactsTo:vn(t.reactsTo),raises:vn(t.raises),sends:vn(t.sends)},o=xc(t.extendedInfo);return o&&(r.extendedInfo=o),r}function Pc(e){return Hi(e)}function _o(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.xiHash=="string"?t.xiHash.trim():"";if(!n)return;let r=t.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,s=typeof o.kind=="string"?o.kind.trim():"";if(!s)return;let a=t.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let l=a,c=typeof l.kind=="string"&&Oc.has(l.kind)?l.kind:void 0;if(!c)return;let f={kind:s},g=Pc(o.payload);g&&(f.payload=g);let h={kind:c};return typeof l.reasonCode=="string"&&l.reasonCode.length>0&&(h.reasonCode=l.reasonCode),typeof l.eventId=="string"&&l.eventId.length>0&&(h.eventId=l.eventId),typeof l.target=="string"&&l.target.length>0&&(h.target=l.target),{xiHash:n,event:f,residual:h}}function _c(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=_o(n);r&&t.push(r)}return t}function fe(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let a of n){let l=Po(a);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((a,l)=>Oo(a.id,l.id));let s=_c(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function No(e,t){let n=_o(t),r=e.decisionTape??[],o=n?[...r,n]:[...r];return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components,...o.length>0?{decisionTape:o}:{}}}var Sn,hr,Ki,vc,Oc,St=Kt(()=>{"use strict";Sn="1.0",hr=["singleton","transient"],Ki=["absorb","escalate_up","hold"],vc=new Set(hr);i(Oo,"compare");i(Sc,"uniqueSorted");i(vn,"nameList");i(wc,"jsonPrimitive");i(Cc,"closedLifetime");i(Hi,"sanitizeMetadata");i(xc,"sanitizeArkRunExtendedInfo");i(Po,"sanitizeArkRunComponent");Oc=new Set(Ki);i(Pc,"sanitizeTapePayload");i(_o,"sanitizeDecisionTapeRecord");i(_c,"sanitizeDecisionTape");i(fe,"buildDependencyInformationPackage");i(No,"appendDecisionTape")});function xn(e,t){return e<t?-1:e>t?1:0}function Fo(e){return[...new Set(e)].sort(xn)}function Gi(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Mo(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function me(e,t){if(e==null||e==="")return[];if(typeof e=="string")return Fo(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 Fo(n)}function Wi(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 wn(e,t){return e?t.some(n=>Wi(e,n)):!1}function qi(e){if(e==null||e==="")return br;if(typeof e=="string"&&Nc.has(e))return e;throw new X("slice")}function zi(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 Gi();if(typeof e=="string"||Array.isArray(e))return{...Gi(),tokens:me(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:me(n.ids,t),labels:me(n.labels,t),tags:me(n.tags,t),groups:me(n.groups,t),architectureKinds:me(n.architectureKinds,t)}}function Pn(e={}){if(e==null||e==="")return Pn({});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(!Tc.has(n))throw new X("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:qi(t.slice),nodeIds:me(t.nodeIds,"nodeIds"),degreesOfSeparation:zi(t.degreesOfSeparation),include:Vi(t.include,"include"),exclude:Vi(t.exclude,"exclude")}}function _n(e){let t={};e.slice&&(t.slice=qi(e.slice));let n=me(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=zi(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=me(e.include??void 0,"include");o.length>0&&(t.include=o);let s=me(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function Lc(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 ji(e,t){if(!Mo(t))return!0;let n=Lc(e);return t.tokens.some(r=>n.some(o=>Wi(o,r)))||wn(e.id,t.ids)||wn(e.label,t.labels)||e.tags?.some(r=>wn(r,t.tags))||wn(e.group,t.groups)?!0:wn(e.architectureKind,t.architectureKinds)}function Fc(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return fe({kernelInstanceId:t.kernelInstanceId,components:t.components})}return fe({})}function Mc(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 Ar(e){return{id:e,kind:"interaction"}}function Cn(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function kr(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 $c(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Cn(n,Mc(s)),t==="technical"){for(let a of s.uses)Cn(n,n.get(a)??Ar(a)),kr(r,o,s.id,a,"uses");continue}for(let a of s.raises)Cn(n,n.get(a)??Ar(a)),kr(r,o,s.id,a,"raises");for(let a of s.reactsTo)Cn(n,n.get(a)??Ar(a)),kr(r,o,a,s.id,"reactsTo");for(let a of s.sends)Cn(n,n.get(a)??Ar(a)),kr(r,o,s.id,a,"sends")}return{nodes:n,edges:r}}function Kc(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 Hc(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 On(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function Bi(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Uc(e){let t=new Set,n=new Map;for(let r of e){let o=On(r),s=o,a=2;for(;t.has(s);)s=`${o}_${a}`,a+=1;t.add(s),n.set(r,s)}return n}function vr(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=Uc(n),o=Fo(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],a=i((l,c)=>{let f=r.get(l.id)??On(l.id),g=Bi(l.label??l.id);s.push(`${c}${f}["${g}"]`)},"emitNode");for(let l of o){let c=On(`group_${l}`);s.push(` subgraph ${c}["${Bi(l)}"]`);for(let f of e.nodes)f.group===l&&a(f," ");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)??On(l.from),f=r.get(l.to)??On(l.to);s.push(` ${c} -->|${l.kind}| ${f}`)}return s.join(`
2
+ `)}function Gc(e,t,n){let r=new Set(e.keys());if(Mo(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&ji(c,n.include)}))),Mo(n.exclude))for(let l of[...r]){let c=e.get(l);c&&ji(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=Hc(r,n.nodeIds,n.degreesOfSeparation,Kc(o)));let s=[...r].sort(xn).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>xn(l.from,c.from)||xn(l.kind,c.kind)||xn(l.to,c.to));return{nodes:s,edges:a}}function Nn(e={},t={}){let n=Fc(e),r=Pn(t),o=$c(n.components,r.slice),s=Gc(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=vr(a),a}var Ir,br,Er,$o,Ko,Ho,X,Nc,Tc,Dc,Sr=Kt(()=>{"use strict";St();Ir="1.0",br="process",Er=["process","technical"],$o=["component","interaction"],Ko=["raises","reactsTo","sends"],Ho=["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}},Nc=new Set(Er),Tc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Dc=new Set(["ids","labels","tags","groups","architectureKinds"]);i(xn,"compare");i(Fo,"uniqueSorted");i(Gi,"emptyMatch");i(Mo,"matchHasCriteria");i(me,"nameList");i(Wi,"globMatch");i(wn,"anyGlob");i(qi,"closedSlice");i(zi,"closedDegrees");i(Vi,"closedMatch");i(Pn,"closeArkRunGraphQuery");i(_n,"arkRunGraphQueryFromSearchParams");i(Lc,"nodeFields");i(ji,"nodeMatches");i(Fc,"asPackage");i(Mc,"componentNode");i(Ar,"interactionNode");i(Cn,"addNode");i(kr,"addEdge");i($c,"buildSlice");i(Kc,"adjacency");i(Hc,"neighborhood");i(On,"mermaidSafeId");i(Bi,"mermaidLabel");i(Uc,"uniqueMermaidIds");i(vr,"formatArkRunGraphMermaid");i(Gc,"filterGraph");i(Nn,"requestArkRunGraph")});function wr(e){if(e===void 0)return"local";if(typeof e=="string"&&Vc.has(e))return e;throw new tt("transport")}function Cr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new tt("ephemeral")}function Tn(e){let t=wr(e.transport),n=Cr(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 wt,nt,Vc,tt,Dn=Kt(()=>{"use strict";wt=["local","localBlocking","broker"],nt=!0,Vc=new Set(wt),tt=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(wr,"closedArkRunTransportKind");i(Cr,"closedArkRunEphemeral");i(Tn,"resolveArkRunSendPlan")});function Fn(e){return e==="production"}function Bc(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 Yi(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function ot(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=Yi(t);if(n)return ot(n);let r=Bc(t);return r!==void 0&&r[0]===127}function Xi(e){if(e===void 0)return Ln;if(typeof e!="string")throw new oe(String(e));let t=e.trim();if(jc.has(t.toLowerCase())||!ot(t))throw new oe(t);let n=t.toLowerCase();if(n==="localhost")return Ln;if(n==="[::1]")return"::1";let r=Yi(n);return r?Xi(r):n}function Wc(e){if(e===void 0)return Or;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new oe(`port:${String(e)}`);return e}function Nt(e={}){if(Fn(e.nodeEnv)||Fn(e.processNodeEnv))throw new rt;return{host:Xi(e.host),port:Wc(e.port)}}function ge(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function qc(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function zc(e){return{kinds:[...wt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:_r}}function Ne(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Yc(e){let t=Ne(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=Ne(t.event),o=r&&typeof r.intent=="string"?r.intent:typeof t.intent=="string"?t.intent:void 0,s={id:t.id,status:n,attempts:typeof t.attempts=="number"&&Number.isFinite(t.attempts)?t.attempts:0};return o&&(s.intent=o),typeof t.error=="string"&&t.error.length>0&&(s.error=t.error),typeof t.updatedAt=="string"&&(s.updatedAt=t.updatedAt),s}function Nr(e){if(typeof e!="number"||!Number.isFinite(e))return ee;let t=Math.trunc(e);return t<0?0:t>ee?ee:t}function Le(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function Tt(e={}){let t=Ne(e),n=Ne(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let a=Ne(s);if(!a)continue;let l=a.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let f=a.kind==="memory"||a.kind==="durable"?a.kind:Le(c,l).kind;o.push({role:l,id:c,kind:f})}return{durability:{stores:o}}}function Fe(e=[],t={}){let n=Nr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let a of r){let l=Yc(a);l&&(l.status==="pending"?o.push(l):s.push(l))}return{available:!0,pendingCount:o.length,failedCount:s.length,pending:o.slice(0,n),failed:s.slice(0,n),sampleLimit:n}}function Te(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:ee}}function Xc(e){let t=Ne(e);if(!t||typeof t.id!="string")return;let n=typeof t.workflowName=="string"?t.workflowName:typeof t.name=="string"?t.name:void 0;if(!n)return;let r={id:t.id,name:n,status:typeof t.status=="string"?t.status:"unknown"};return typeof t.currentStep=="string"&&(r.currentStep=t.currentStep),typeof t.error=="string"&&t.error.length>0&&(r.error=t.error),r}function Zc(e){return e==="idle"||e==="waiting"}function Me(e=[],t={}){let n=Nr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,a=0,l=0,c=0;for(let f of r){let g=Xc(f);g&&(o.push(g),g.status==="running"?s+=1:g.status==="compensating"?a+=1:g.status==="failed"?l+=1:Zc(g.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function De(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:ee}}function Jc(e){if(e===void 0)return;let t=Ne(e);if(!t||t.available===!1)return Te();let n=Nr(t.sampleLimit);if(Array.isArray(t.pending)||Array.isArray(t.failed)||Array.isArray(t.records)){let r=[...Array.isArray(t.pending)?t.pending:[],...Array.isArray(t.failed)?t.failed:[],...Array.isArray(t.records)?t.records:[]],o=Fe(r,{sampleLimit:n}),s=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,a=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:s,failedCount:a,sampleLimit:n}}return Te()}function Qc(e){if(e===void 0)return;let t=Ne(e);if(!t||t.available===!1)return De();let n=Nr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=Me(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,s=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,a=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:s,compensatingCount:a,failedCount:l,pendingCount:c,sampleLimit:n}}return De()}function Mn(e={}){let t=Nt({host:e.host,port:e.port}),n=fe({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=Jc(e.outbox),o=Qc(e.workflows),s={schemaVersion:xr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:zc(e),observability:qc(e.observability)??{},hardening:Tt(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function Dt(e){return`event: ${Pr}
3
3
  data: ${JSON.stringify(e)}
4
4
 
5
- `}var gr,An,mr,mt,yt,ht,yr,hr,We,te,_c,vn=Et(()=>{"use strict";ft();Rn();gr="1.0",An="127.0.0.1",mr=0,mt="/snapshot",yt="/events",ht="/graph",yr="snapshot",hr="in-process-local",We=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},te=class extends Error{static{a(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},_c=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a(kn,"isArkRunInspectorProductionEnv");a(Nc,"ipv4Octets");a($a,"unwrapIpv4Mapped");a(qe,"isArkRunInspectorLoopbackHost");a(Ma,"closedHost");a(Tc,"closedPort");a(Rt,"resolveArkRunInspectorBind");a(we,"arkRunInspectorUrl");a(Dc,"jsonClone");a(Lc,"closedTransportFacts");a(In,"buildArkRunInspectorSnapshot");a(At,"formatArkRunInspectorSseEvent")});var Ka={};Do(Ka,{listenArkRunInspector:()=>Hc});function Fc(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function $c(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Mc(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Rr(e,t,n){e.writeHead(t,Fc()),e.end(JSON.stringify(n))}function Kc(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 Hc(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,i=t.bind,l=a(()=>e.getInspectorSnapshot(i),"snapshot"),c=n.createServer((g,m)=>{let h=Mc(g.url),p=h.pathname;if(g.method==="GET"&&(p==="/"||p===mt)){Rr(m,200,l());return}if(g.method==="GET"&&p===ht){try{Rr(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){Rr(m,400,{error:f.message,option:f.option});return}throw f}return}if(g.method==="GET"&&p===yt){m.writeHead(200,$c()),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=a(()=>{r.delete(m),f&&(clearInterval(f),o.delete(f))},"drop");g.on("close",u),m.on("close",u);return}Rr(m,404,{error:"not found"})});try{await new Promise((g,m)=>{let h=a(p=>m(p),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{i=Kc(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:i.host,port:i.port,url:we(i.host,i.port,"/"),snapshotUrl:we(i.host,i.port,mt),eventsUrl:we(i.host,i.port,yt),graphUrl:we(i.host,i.port,ht),close(){for(let g of o)clearInterval(g);o.clear();for(let g of r)g.end();return r.clear(),new Promise((g,m)=>{c.close(h=>{h?m(h):g()})})}}}var Ha=Et(()=>{"use strict";pr();vn();a(Fc,"jsonHeaders");a($c,"sseHeaders");a(Mc,"requestUrl");a(Rr,"writeJson");a(Kc,"boundAddress");a(Hc,"listenArkRunInspector")});var Wc={};Do(Wc,{ANALYSIS_IR_SCHEMA_VERSION:()=>Bn,ARK_ANALYSIS_RESULT_SCHEMA:()=>Ho,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Pn,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ba,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Ea,ARK_RUN_COMPONENT_LIFETIMES:()=>rr,ARK_RUN_EPHEMERAL_DEFAULT:()=>Be,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>lr,ARK_RUN_GRAPH_NODE_KINDS:()=>So,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>Co,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>ir,ARK_RUN_GRAPH_SLICES:()=>cr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>wo,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>cn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>An,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>mr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>yt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>ht,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>gr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>mt,ARK_RUN_INSPECTOR_SSE_EVENT:()=>yr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>hr,ARK_RUN_TRANSPORT_KINDS:()=>gt,ArkRunInspectorBindError:()=>te,ArkRunInspectorProductionError:()=>We,DEFAULT_MAX_HISTORY_SIZE:()=>Ar,DIAGNOSTIC_CATALOG:()=>nn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ma,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>ya,EventContractRegistryImpl:()=>Je,EventContractViolationError:()=>De,InMemoryAuditStore:()=>Qe,InMemoryEventBuffer:()=>be,InMemoryOutboxStore:()=>Lr,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:()=>Ee,UnregisteredIntentError:()=>_e,analyzeArchitectureConvergence:()=>He,analyzeChange:()=>en,analyzePolicyDelta:()=>oo,analyzeProject:()=>it,analyzeResolvedProject:()=>ct,appendDecisionTape:()=>Ao,architecturalPolicies:()=>_n,arkRunGraphQueryFromSearchParams:()=>mn,arkRunInspectorUrl:()=>we,buildArkRunInspectorSnapshot:()=>In,buildDependencyInformationPackage:()=>ce,buildPublishPolicyContext:()=>Ot,catalogFixForRuleId:()=>Ia,catalogWhyForRuleId:()=>va,checkAdapterGovernance:()=>Hn,checkContract:()=>Vr,classifyArkPolicyDelta:()=>zn,closeArkRunGraphQuery:()=>gn,closedArkRunEphemeral:()=>fr,closedArkRunTransportKind:()=>ur,collectAnalysisConfigWarnings:()=>tn,collectForbiddenCapabilityUses:()=>Me,compareInformationPackages:()=>or,createAICodeGate:()=>to,createAdapter:()=>Ur,createAdapterResult:()=>Ko,createArchitectureProfile:()=>Ht,createArchitectureProfileFromArkConfig:()=>Gt,createArkKernel:()=>kt,createArkKernelFromConfig:()=>Po,createArkManifest:()=>an,createArkTestHarness:()=>$r,createAuditTrail:()=>Lt,createDependencyGraph:()=>Ft,createElevenLayerArkConfig:()=>Hr,createEventBus:()=>Dr,createEventContractRegistry:()=>Tt,createIntentRegistry:()=>bt,createLenientArkKernel:()=>Ir,createLenientArkKernelFromConfig:()=>No,createMetadataRegistry:()=>Ut,createObservabilityReporter:()=>Dt,createProjectionRegistry:()=>on,createResolvedCandidateFacts:()=>Vn,createSaga:()=>mo,createStrictArkKernel:()=>kr,createStrictArkKernelFromConfig:()=>_o,createWorkflowEngine:()=>ut,defaultIntentRegistry:()=>wr,defineArchitectureProfilePolicy:()=>xt,defineIntent:()=>Cr,defineLayerPolicy:()=>Ct,definePolicy:()=>Pe,definePort:()=>Gr,definePublishPolicy:()=>xr,detectArchitectureCycles:()=>Zn,deterministicHash:()=>B,diagnosticDocsFragment:()=>po,diagnosticDocsPath:()=>Aa,elevenLayerProfile:()=>Fe,evaluateArchitectureGraph:()=>Ue,explainViolation:()=>so,extractSemanticDependencies:()=>$e,formatArkRunGraphMermaid:()=>dr,formatArkRunInspectorSseEvent:()=>At,getDiagnosticCatalogEntry:()=>rn,isArkRunInspectorLoopbackHost:()=>qe,isArkRunInspectorProductionEnv:()=>kn,isCataloguedOrArkRuleFamily:()=>Ra,isKnownDiagnosticCode:()=>ha,isLayerPolicy:()=>wt,loadContract:()=>Qt,loadResolvedCandidateFacts:()=>Ae,policyDeltaAcknowledgementMatches:()=>Yn,preflightChange:()=>io,preflightResolvedChange:()=>lo,replayInformationPackages:()=>vo,requestArkRunGraph:()=>yn,resolveArkRunInspectorBind:()=>Rt,resolveArkRunSendPlan:()=>hn,resolvedFactsEvidenceRequirementsHash:()=>at,serializeDiagnosticCatalog:()=>ka,shadowInformationPackage:()=>Io,stableSerialize:()=>D,startArkRunInspector:()=>En,syncRegistryToGraph:()=>$t,toAdapterDiagnostic:()=>On,validateIntentName:()=>St,version:()=>xn});module.exports=Xa(Wc);var xn="4.8.6";var Za=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ja=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Qa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ei(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Za.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ja.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Qa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(ei,"classifyLayerImportKind");function ti(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=ei(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}a(ti,"layerImportNextAction");function ni(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(ni,"arkRunCallSiteName");function ri(e){let t=ni(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(ri,"arkRunNextAction");function le(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ti(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 ri(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(le,"deterministicNextAction");var Pn="1.5",oi="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}a(w,"text");function Fo(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(Fo,"positiveInteger");function Mo(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}a(Mo,"adapterFindingTargetKey");function $o(e){let t=new Map;return e.map(n=>{let r=Mo(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a($o,"adapterFindingOccurrenceTargetKeys");function si(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(si,"adapterFindingRefFromTargetKey");function ai(e){return`${oi}#${e}`}a(ai,"adapterDocsCodePath");function ii(e,t,n){return le({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}a(ii,"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)}:{}},i=n??Mo(e),l=si(i);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:Fo(e.line,1),column:Fo(e.column,1)},evidence:s,nextAction:w(e.nextAction)??ii(r,s,e),findingRef:l,targetKey:i,docsCodePath:ai(r)}}a(On,"toAdapterDiagnostic");function Ko(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(h=>({code:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],i=e.warnings??[],l=$o(s),c=$o(i),g=[...s.map((h,p)=>On(h,"error",l[p])),...i.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}}a(Ko,"createAdapterResult");var Ho={$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{a(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=a(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Go=new Oe;function Cr(e,t){return Go.define(e,t)}a(Cr,"defineIntent");function bt(){return new Oe}a(bt,"createIntentRegistry");var wr=Go;var Uo=["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(!Uo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Uo.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}a(St,"validateIntentName");var ue=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
5
+ `}var xr,Ln,Or,Ct,xt,Ot,Pt,_t,Pr,_r,ee,rt,oe,jc,$n=Kt(()=>{"use strict";St();Dn();xr="1.0",Ln="127.0.0.1",Or=0,Ct="/snapshot",xt="/events",Ot="/graph",Pt="/outbox",_t="/workflows",Pr="snapshot",_r="in-process-local",ee=32,rt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},oe=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"}},jc=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Fn,"isArkRunInspectorProductionEnv");i(Bc,"ipv4Octets");i(Yi,"unwrapIpv4Mapped");i(ot,"isArkRunInspectorLoopbackHost");i(Xi,"closedHost");i(Wc,"closedPort");i(Nt,"resolveArkRunInspectorBind");i(ge,"arkRunInspectorUrl");i(qc,"jsonClone");i(zc,"closedTransportFacts");i(Ne,"asRecord");i(Yc,"closedOutboxSummary");i(Nr,"closedSampleLimit");i(Le,"classifyArkRunInspectorStoreDurability");i(Tt,"buildArkRunInspectorHardening");i(Fe,"buildArkRunInspectorOutboxMonitor");i(Te,"unavailableArkRunInspectorOutboxMonitor");i(Xc,"closedWorkflowSummary");i(Zc,"isPendingWorkflowStatus");i(Me,"buildArkRunInspectorWorkflowsMonitor");i(De,"unavailableArkRunInspectorWorkflowsMonitor");i(Jc,"closedOutboxMonitor");i(Qc,"closedWorkflowsMonitor");i(Mn,"buildArkRunInspectorSnapshot");i(Dt,"formatArkRunInspectorSseEvent")});var Zi={};Wo(Zi,{listenArkRunInspector:()=>id});function ed(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function td(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nd(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function $e(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,ed()),e.end(JSON.stringify(n))}catch{}}function rd(e,t){let n=e.address();if(n===null||typeof n=="string")throw new oe(t.host);if(!ot(n.address))throw new oe(n.address);return{host:t.host,port:n.port}}async function od(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Te();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Fe([...n??[],...r??[]],{sampleLimit:ee})}async function sd(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?De():Me(await e.workflowEngine.list(),{sampleLimit:ee})}async function id(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((f,g)=>{let h=nd(f.url),p=h.pathname;if(f.method==="GET"&&(p==="/"||p===Ct)){$e(g,200,l());return}if(f.method==="GET"&&p===Ot){try{$e(g,200,e.requestGraph(_n({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(u){if(u instanceof X){$e(g,400,{error:u.message,option:u.option});return}throw u}return}if(f.method==="GET"&&p===Pt){od(e).then(u=>$e(g,200,u)).catch(u=>{$e(g,500,{error:u instanceof Error?u.message:"outbox monitor failed"})});return}if(f.method==="GET"&&p===_t){sd(e).then(u=>$e(g,200,u)).catch(u=>{$e(g,500,{error:u instanceof Error?u.message:"workflows monitor failed"})});return}if(f.method==="GET"&&p===xt){g.writeHead(200,td()),g.flushHeaders(),g.write(Dt(l())),r.add(g);let u=s>0?setInterval(()=>{g.write(Dt(l()))},s):void 0;u&&o.add(u);let m=i(()=>{r.delete(g),u&&(clearInterval(u),o.delete(u))},"drop");f.on("close",m),g.on("close",m);return}$e(g,404,{error:"not found"})});try{await new Promise((f,g)=>{let h=i(p=>g(p),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{a=rd(c,t.bind),f()}catch(p){g(p instanceof Error?p:new oe(t.bind.host))}})})}catch(f){throw await new Promise(g=>{c.close(()=>g())}),f}return{host:a.host,port:a.port,url:ge(a.host,a.port,"/"),snapshotUrl:ge(a.host,a.port,Ct),eventsUrl:ge(a.host,a.port,xt),graphUrl:ge(a.host,a.port,Ot),outboxUrl:ge(a.host,a.port,Pt),workflowsUrl:ge(a.host,a.port,_t),close(){for(let f of o)clearInterval(f);o.clear();for(let f of r)f.end();return r.clear(),new Promise((f,g)=>{c.close(h=>{h?g(h):f()})})}}}var Ji=Kt(()=>{"use strict";Sr();$n();i(ed,"jsonHeaders");i(td,"sseHeaders");i(nd,"requestUrl");i($e,"writeJson");i(rd,"boundAddress");i(od,"resolveOutboxMonitor");i(sd,"resolveWorkflowsMonitor");i(id,"listenArkRunInspector")});var ud={};Wo(ud,{ANALYSIS_IR_SCHEMA_VERSION:()=>sr,ARK_ANALYSIS_RESULT_SCHEMA:()=>Jo,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>jn,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Fi,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Li,ARK_RUN_COMPONENT_LIFETIMES:()=>hr,ARK_RUN_EPHEMERAL_DEFAULT:()=>nt,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>br,ARK_RUN_GRAPH_NODE_KINDS:()=>$o,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>Ko,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>Ir,ARK_RUN_GRAPH_SLICES:()=>Er,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>Ho,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>Sn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>Ln,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>Or,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>xt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>Ot,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT:()=>ee,ARK_RUN_INSPECTOR_OUTBOX_PATH:()=>Pt,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>xr,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>Ct,ARK_RUN_INSPECTOR_SSE_EVENT:()=>Pr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>_r,ARK_RUN_INSPECTOR_WORKFLOWS_PATH:()=>_t,ARK_RUN_TRANSPORT_KINDS:()=>wt,ArkRunInspectorBindError:()=>oe,ArkRunInspectorProductionError:()=>rt,DEFAULT_MAX_HISTORY_SIZE:()=>Tr,DIAGNOSTIC_CATALOG:()=>An,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ci,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>gr,DIAGNOSTIC_RULE_IDS:()=>xi,EventContractRegistryImpl:()=>dt,EventContractViolationError:()=>Be,InMemoryAuditStore:()=>pt,InMemoryEventBuffer:()=>Oe,InMemoryOutboxStore:()=>qr,InMemoryReadModelStore:()=>bt,InMemoryWorkflowStore:()=>Et,IntentRegistry:()=>He,InvalidArkRunGraphQueryError:()=>X,InvalidArkRunSendOptionError:()=>tt,InvalidIntentNameError:()=>Ve,LayerPolicyContextError:()=>je,MANIFEST_SCHEMA_VERSION:()=>bn,ObservedLayerFlowViolationError:()=>We,POLICY_DELTA_SCHEMA_VERSION:()=>ar,PolicyEngine:()=>Ce,PolicyViolationError:()=>he,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>or,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>_e,SourceMetadataOverrideError:()=>Re,UnknownEventSourceError:()=>xe,UnregisteredIntentError:()=>Ge,analyzeArchitectureConvergence:()=>Ze,analyzeChange:()=>hn,analyzePolicyDelta:()=>Ro,analyzeProject:()=>At,analyzeResolvedProject:()=>It,appendDecisionTape:()=>No,architecturalPolicies:()=>Bn,arkRunGraphQueryFromSearchParams:()=>_n,arkRunInspectorUrl:()=>ge,buildArkRunInspectorHardening:()=>Tt,buildArkRunInspectorOutboxMonitor:()=>Fe,buildArkRunInspectorSnapshot:()=>Mn,buildArkRunInspectorWorkflowsMonitor:()=>Me,buildDependencyInformationPackage:()=>fe,buildPublishPolicyContext:()=>Bt,catalogFixForRuleId:()=>Ti,catalogWhyForRuleId:()=>Di,checkAdapterGovernance:()=>er,checkContract:()=>to,classifyArkPolicyDelta:()=>lr,classifyArkRunInspectorStoreDurability:()=>Le,closeArkRunGraphQuery:()=>Pn,closedArkRunEphemeral:()=>Cr,closedArkRunTransportKind:()=>wr,collectAnalysisConfigWarnings:()=>Rn,collectForbiddenCapabilityUses:()=>Ye,compareInformationPackages:()=>Rr,createAICodeGate:()=>mo,createAdapter:()=>eo,createAdapterResult:()=>Zo,createArchitectureProfile:()=>nn,createArchitectureProfileFromArkConfig:()=>rn,createArkKernel:()=>Lt,createArkKernelFromConfig:()=>Vo,createArkManifest:()=>En,createArkTestHarness:()=>Yr,createAuditTrail:()=>Zt,createDependencyGraph:()=>Jt,createElevenLayerArkConfig:()=>Jr,createEventBus:()=>Wr,createEventContractRegistry:()=>Yt,createIntentRegistry:()=>Ht,createLenientArkKernel:()=>Lr,createLenientArkKernelFromConfig:()=>Bo,createMetadataRegistry:()=>on,createObservabilityReporter:()=>Xt,createProjectionRegistry:()=>In,createResolvedCandidateFacts:()=>rr,createSaga:()=>xo,createStrictArkKernel:()=>Dr,createStrictArkKernelFromConfig:()=>jo,createWorkflowEngine:()=>vt,defaultIntentRegistry:()=>Kr,defineArchitectureProfilePolicy:()=>jt,defineIntent:()=>$r,defineLayerPolicy:()=>Gt,definePolicy:()=>Ue,definePort:()=>Qr,definePublishPolicy:()=>Hr,detectArchitectureCycles:()=>pr,deterministicHash:()=>W,diagnosticDocsFragment:()=>vo,diagnosticDocsPath:()=>_i,elevenLayerProfile:()=>qe,evaluateArchitectureGraph:()=>Qe,explainViolation:()=>Ao,extractSemanticDependencies:()=>ze,formatArkRunGraphMermaid:()=>vr,formatArkRunInspectorSseEvent:()=>Dt,getDiagnosticCatalogEntry:()=>kn,isArkRunInspectorLoopbackHost:()=>ot,isArkRunInspectorProductionEnv:()=>Fn,isCataloguedOrArkRuleFamily:()=>Pi,isKnownDiagnosticCode:()=>Oi,isLayerPolicy:()=>Vt,loadContract:()=>yn,loadResolvedCandidateFacts:()=>ve,policyDeltaAcknowledgementMatches:()=>cr,preflightChange:()=>Io,preflightResolvedChange:()=>bo,replayInformationPackages:()=>Lo,requestArkRunGraph:()=>Nn,resolveArkRunInspectorBind:()=>Nt,resolveArkRunSendPlan:()=>Tn,resolvedFactsEvidenceRequirementsHash:()=>Rt,serializeDiagnosticCatalog:()=>Ni,shadowInformationPackage:()=>Do,stableSerialize:()=>F,startArkRunInspector:()=>Kn,syncRegistryToGraph:()=>Qt,toAdapterDiagnostic:()=>Vn,unavailableArkRunInspectorOutboxMonitor:()=>Te,unavailableArkRunInspectorWorkflowsMonitor:()=>De,validateIntentName:()=>Ut,version:()=>Gn});module.exports=ca(ud);var Gn="4.8.8";var da=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,pa=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,ua=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function fa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return da.test(n)?"pure-shared":r==="PersistenceAdapters"&&(pa.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":ua.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(fa,"classifyLayerImportKind");function ma(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=fa(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(ma,"layerImportNextAction");function ga(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ga,"arkRunCallSiteName");function ya(e){let t=ga(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(ya,"arkRunNextAction");function ue(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ma(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 ya(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ue,"deterministicNextAction");var jn="1.5",ha="docs/diagnostics.md";function C(e){return typeof e=="string"&&e.length>0?e:void 0}i(C,"text");function zo(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(zo,"positiveInteger");function Xo(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(Xo,"adapterFindingTargetKey");function Yo(e){let t=new Map;return e.map(n=>{let r=Xo(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(Yo,"adapterFindingOccurrenceTargetKeys");function Ra(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(Ra,"adapterFindingRefFromTargetKey");function Aa(e){return`${ha}#${e}`}i(Aa,"adapterDocsCodePath");function ka(e,t,n){return ue({ruleId:e,target:C(t.target)??C(n.target)??void 0,fromLayer:C(t.fromLayer)??void 0,toLayer:C(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:C(t.edgeKind)??void 0,capability:C(t.capability)??C(n.capability)??void 0,arkruleId:C(t.arkruleId)??void 0,arkruleSource:C(t.arkruleSource)??void 0})}i(ka,"nextActionForDiagnostic");function Vn(e,t="error",n){let r=C(e.ruleId)??C(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...C(e.target)?{target:C(e.target)}:{},...C(e.fromLayer)?{fromLayer:C(e.fromLayer)}:{},...C(e.toLayer)?{toLayer:C(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}:{},...C(e.capability)?{capability:C(e.capability)}:{},...C(e.edgeKind)?{edgeKind:C(e.edgeKind)}:{},...C(e.arkruleId)?{arkruleId:C(e.arkruleId)}:{},...C(e.arkruleSource)?{arkruleSource:C(e.arkruleSource)}:{}},a=n??Xo(e),l=Ra(a);return{ruleId:r,severity:o,message:C(e.message)??r,location:{file:C(e.file)??"<unknown>",line:zo(e.line,1),column:zo(e.column,1)},evidence:s,nextAction:C(e.nextAction)??ka(r,s,e),findingRef:l,targetKey:a,docsCodePath:Aa(r)}}i(Vn,"toAdapterDiagnostic");function Zo(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:C(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:C(h.message)??`Analysis ${t}: required evidence is incomplete.`,...C(h.file)?{file:C(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...C(e.policyHash)?{policyHash:C(e.policyHash)}:{},...C(e.resolverIdentity)?{resolverIdentity:C(e.resolverIdentity)}:{},...C(e.factsHash)?{factsHash:C(e.factsHash)}:{},...C(e.candidateTreeHash)?{candidateTreeHash:C(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=Yo(s),c=Yo(a),f=[...s.map((h,p)=>Vn(h,"error",l[p])),...a.map((h,p)=>Vn(h,"warning",c[p]))],g={schemaVersion:jn,completenessReasons:r,diagnostics:f};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...h}:{...g,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...o}:{...g,mode:n,valid:!1,completeness:t,...o}}i(Zo,"createAdapterResult");var Jo={$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:jn},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 He=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 Qo=new He;function $r(e,t){return Qo.define(e,t)}i($r,"defineIntent");function Ht(){return new He}i(Ht,"createIntentRegistry");var Kr=Qo;var es=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Ut(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!es.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${es.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(Ut,"validateIntentName");var he=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 ve=class{static{a(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let i=s.check(t);if(i!==!0){if(i===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(i))for(let l of i)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:i.message,details:i.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new 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}}a(Pe,"definePolicy");function li(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}a(li,"defaultLayerOf");function Vo(e,t){return t.resolveLayer?.(e)??li(e)}a(Vo,"resolveLayer");function ci(e,t,n){return e===n.from&&t===n.to}a(ci,"matchesRule");function Ct(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Pe({name:t,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(i=>i.kind==="declared"||i.kind==="produces").map(i=>({from:i.from,to:i.to})),...(r.relationships??[]).filter(i=>i.kind==="dependsOn").map(i=>({from:i.from,to:i.to}))],s=[];for(let i of o){let l=Vo(i.from,e),c=Vo(i.to,e);for(let g of e.rules)!g.allowed&&ci(l,c,g)&&s.push({policyName:t,severity:n,message:g.message??`Layer violation: ${i.from} (${l}) must not relate to ${i.to} (${c})`})}return s.length>0?s:!0},"check")})}a(Ct,"defineLayerPolicy");function wt(e){return e.tags?.includes("layer")??!1}a(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})}a(xt,"defineArchitectureProfilePolicy");function Ot(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}a(Ot,"buildPublishPolicyContext");function xr(e){return Pe(e)}a(xr,"definePublishPolicy");var _e=class extends Error{static{a(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},Ne=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Te=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},De=class extends Error{static{a(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Ee=class extends Error{static{a(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},fe=class extends Error{static{a(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},Le=class extends Error{static{a(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function 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)}}a(Pt,"assertIntentAllowed");function jo(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Ee(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Ee(e.intent,e.metadata.source)}}a(jo,"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)}a(_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}a(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}a(Xe,"clonePatchValue");function Or(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let i=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=Xe(s);continue}if(Ye(r[o])&&Ye(s)){r[o]=Or(r[o],s,i);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=Pr(r[o],s,i);continue}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}return r}a(Or,"mergeRecordPatch");function Pr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let i=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=Xe(o);return}if(Ye(r[s])&&Ye(o)){r[s]=Or(r[s],o,i);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=Pr(r[s],o,i);return}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}),r}a(Pr,"mergeArrayPatch");function Bo(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 Pr(e,t)}if(e===void 0)return Xe(t);if(!Ye(e))throw new Error("Object interceptor patch requires an object payload.");return Or(e,t)}a(Bo,"applyPayloadPatch");async function Wo(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:a(c=>{s.push(c)},"intercept")})),s.length===0)continue;let i=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:i}]}};for(let c of s)l={...l,payload:Bo(l.payload,c),metadata:{...l.metadata}};_t(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=i,t.appendTrace({type:"event.intercepted",timestamp:i,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(i){await di(o,r,i,t)}}return r}a(Wo,"applyInterceptors");async function di(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}a(di,"recordInterceptorError");var qo=new Map;function zo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(zo,"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}a(Nn,"normalizeGlobSeparators");function pi(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(pi,"bracesBalanced");function ge(e){let t=qo.get(e);if(t)return t;let n=Nn(e),r=pi(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=zo(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+=zo(c)}let i=new RegExp(`^${o}$`);return qo.set(e,i),i}a(ge,"globToRegExp");function ui(e){return Nn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(ui,"concreteGlobSegments");function _r(e,t){let n=Nn(String(e)),r=ui(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let g of r){let m=-1;for(let h=l;h<i.length;h+=1)if(i[h]===g){m=h;break}if(m<0)return s;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+o}a(_r,"patternSpecificity");function ae(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>ge(i).test(n))){for(let i of s.patterns??[])if(ge(i).test(n)){let l=_r(i,n);l>o&&(o=l,r=s.name)}}return r}a(ae,"layerForRelativePath");function Yo(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}a(Yo,"sliceIdForPath");function fi(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 i=o[s];if((i==="**"||i==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(fi,"inferSliceFoldersFromPatterns");function gi(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 fi(r?.patterns)}a(gi,"resolveSliceFolders");function Xo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(Xo,"normalizeSegments");function Qo(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Qo,"trimTrailingSlashes");var mi=["src","app"];function yi(e){let t=Qo(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(yi,"isBlanketRoot");function Zo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Xo(n);for(let s of t){if(typeof s!="string"||s.length===0||yi(s))continue;if(s.includes("*")){let c=Qo(s.toLowerCase());if(ge(c).test(r)||ge(`${c}/**`).test(r))return!0;continue}let i=Xo(s);if(i.length===0)continue;let l=mi.includes(o[0])&&i[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+i.length>o.length)continue;let g=!0;for(let m=0;m<i.length;m+=1)if(o[c+m]!==i[m]){g=!1;break}if(g)return!0}}return!1}a(Zo,"pathUnderSharedRoot");function Jo(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(Jo,"sliceMatchesDeclaration");function hi(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Jo(r.from,t)&&Jo(r.to,n))}a(hi,"crossSliceEdgeAllowed");function Ri(e){if(!e.fromPath||!e.toPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0,n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(Ri,"peerIsolationDecision");function es(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(es,"peerIsolationDenyExplanation");function me(e,t,n,r){return Nr(e,t,n,r)?.rule}a(me,"findDeniedEdgeRule");function Nr(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,i=r?.toPath,l=gi(o,t,r?.layers),c=s&&i?Yo(s,l):void 0,g=s&&i?Yo(i,l):void 0,m=Ri({fromPath:s,toPath:i,folderCount:l.length,fromSlice:c,toSlice:g,fromShared:!c&&Zo(s,o.sharedRoots),toShared:!g&&Zo(i,o.sharedRoots),crossSliceAllowed:hi(o.allowedCrossSlice,c,g)});if(m.denied)return{rule:o,peerIsolationReason:m.reason,fromSlice:c,toSlice:g};continue}if(t!==n)return{rule:o}}}a(Nr,"findDeniedEdgeDecision");async function ts(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let i=me(r.rules,o,s);if(!i)return;let l=t.mode,c=i.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,g={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:i};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:g}),await t.recordAudit("layer.observedViolation",e,g),l==="hard")throw new Le(n,e.intent,o,s,c)}a(ts,"assertObservedLayerFlowAllowed");async function ns(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))}a(ns,"enforcePublishPolicy");function Ai(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}a(Ai,"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{}}a(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)}})}}a(Tn,"recordAudit");async function rs(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)}a(rs,"recordRawPublishDiagnostic");async function os(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Ai(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}a(os,"recordSuccessfulPublish");function Tr(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}a(Tr,"enrichMetadata");var ss=0;function ki(){return ss+=1,`interceptor-${Date.now()}-${ss}`}a(ki,"nextInterceptorRegistrationId");var Ze=class{static{a(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new 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,i=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,g=typeof t!="function";if(g){let p=t,f=r??n??{};c={...p,metadata:Tr(p.metadata,f,this.recording.instanceId)}}else{let p=t,f=n,u=r??{},y=p(f);c={...y,metadata:Tr(y.metadata,u,this.recording.instanceId)}}g&&this.strictRegistry&&await rs(this.recording,c),Pt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),jo(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),_t(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Wo(c,{interceptorsForIntent:a(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),_t(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await ts(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let m=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await ns(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((p,f,u)=>this.safeHook(p,f,u),"safeHook")}),await os(this.recording,c,s?m.length:0,o.tx);let h=(async()=>{s&&await Promise.all(m.map(p=>this.invokeHandler(p,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return i?await h:h.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return Pt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,s={},i)=>{if(s.source&&s.source!==n)throw new fe(n,s.source);await this.publish(r,o,{...s,source:n},i)},"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 i=this.subscriptions.indexOf(o);i>=0&&this.subscriptions.splice(i,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Pt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:ki(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let i=this.interceptorsByIntent.get(o)??[];return i.push(s),this.interceptorsByIntent.set(o,i),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){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 Dr(e){return new Ze(e)}a(Dr,"createEventBus");function Ii(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}a(Ii,"formatStandardSchemaPath");function vi(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}a(vi,"actualType");function Ei(e,t){return e?`${e}.${t}`:t}a(Ei,"formatPath");function as(e,t,n,r,o){let s=vi(e);if(t.type!=="unknown"&&s!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${s}.`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}is(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((i,l)=>{as(i,t.items,`${n}[${l}]`,r,o)})}a(as,"validateSchemaField");function is(e,t,n,r,o){for(let[s,i]of Object.entries(t)){let l=Ei(o,s),c=e[s];if(c===void 0){i.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}as(c,i,l,n,r)}}a(is,"validateObjectSchema");var Je=class{static{a(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(is(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let i of Object.keys(s))r.schema[i]||o.push({intent:t.intent,version:r.version,field:i,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let i=r.standardSchema["~standard"].validate(t.payload);if(i instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(i.issues)for(let l of i.issues)o.push({intent:t.intent,version:r.version,field:Ii(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}a(Tt,"createEventContractRegistry");var ls=0;function bi(){return ls+=1,`outbox-${Date.now()}-${ls}`}a(bi,"nextOutboxId");function cs(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}a(cs,"cloneRecord");var be=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:bi(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),cs(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(cs)}async clear(){this.records.clear()}},Lr=be;function Fr(e){return`${e.from}->${e.to}`}a(Fr,"flowKey");function ds(e){let t=new Set,n=[];for(let r of e){let o=Fr(r);t.has(o)||(t.add(o),n.push(r))}return n}a(ds,"uniqueFlows");function ps(e,t){let n=new Set(t.map(Fr));return e.filter(r=>!n.has(Fr(r)))}a(ps,"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})),i=n?.getHistory().map(y=>({from:y.event.metadata.source,to:y.event.intent}))??[],l=i.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="observed").map(y=>({from:y.from,to:y.to})),c=ds([...o,...s]),g=ds([...i,...l]),m=g.filter(y=>!y.from||y.from==="unknown"),h=t?Array.from(new Set(g.map(y=>y.from).filter(y=>y&&y!=="unknown"&&!t.has(y)))):[],p=t?Array.from(new Set(g.map(y=>y.to).filter(y=>!t.has(y)))):[],f=new Set(g.flatMap(y=>[y.from,y.to])),u=t?t.list().map(y=>y.name).filter(y=>!f.has(y)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:g,declaredButUnobserved:ps(c,g),observedButUndeclared:ps(g.filter(y=>y.from!=="unknown"),c),unknownSources:m,unregisteredObservedSources:h,unregisteredObservedIntents:p,registeredButNeverObserved:u}}}}a(Dt,"createObservabilityReporter");function $r(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}a($r,"createArkTestHarness");var us=0;function Si(){return us+=1,`audit-${Date.now()}-${us}`}a(Si,"createAuditId");function Ci(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}a(Ci,"matchesQuery");var Qe=class{constructor(t){this.maxRecords=t}maxRecords;static{a(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>Ci(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Dn=class{constructor(t){this.store=t}store;static{a(this,"AuditTrailImpl")}async record(t){let n={id:Si(),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))}a(Lt,"createAuditTrail");var Ln=class{static{a(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
7
+ ${n}`),this.name="PolicyViolationError",this.violations=t}};var Ce=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 he(n.hardViolations);return n}clear(){this.policies.length=0}};function Ue(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(Ue,"definePolicy");function Ia(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Ia,"defaultLayerOf");function ts(e,t){return t.resolveLayer?.(e)??Ia(e)}i(ts,"resolveLayer");function ba(e,t,n){return e===n.from&&t===n.to}i(ba,"matchesRule");function Gt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Ue({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=ts(a.from,e),c=ts(a.to,e);for(let f of e.rules)!f.allowed&&ba(l,c,f)&&s.push({policyName:t,severity:n,message:f.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(Gt,"defineLayerPolicy");function Vt(e){return e.tags?.includes("layer")??!1}i(Vt,"isLayerPolicy");var Bn={layerIsolation(){return Bn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return Gt({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 jt(e,t={}){return Gt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(jt,"defineArchitectureProfilePolicy");function Bt(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(Bt,"buildPublishPolicyContext");function Hr(e){return Ue(e)}i(Hr,"definePublishPolicy");var Ge=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}},Ve=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}},je=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"}},Be=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}},xe=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}},Re=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}},We=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 Wt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Ut(e);if(!n.valid)throw new Ve(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Ge(e)}}i(Wt,"assertIntentAllowed");function ns(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new xe(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new xe(e.intent,e.metadata.source)}}i(ns,"assertSourceAllowed");function qt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Be(e.intent,n.issues)}i(qt,"assertContractAllowed");function at(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(at,"isPlainRecord");function lt(e){return Array.isArray(e)?e.map(lt):at(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,lt(n)])):e}i(lt,"clonePatchValue");function Ur(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]=lt(s);continue}if(at(r[o])&&at(s)){r[o]=Ur(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=Gr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Ur,"mergeRecordPatch");function Gr(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]=lt(o);return}if(at(r[s])&&at(o)){r[s]=Ur(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=Gr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(Gr,"mergeArrayPatch");function rs(e,t){if(Array.isArray(t)){if(e===void 0)return lt(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return Gr(e,t)}if(e===void 0)return lt(t);if(!at(e))throw new Error("Object interceptor patch requires an object payload.");return Ur(e,t)}i(rs,"applyPayloadPatch");async function os(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:rs(l.payload,c),metadata:{...l.metadata}};qt(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 Ea(o,r,a,t)}}return r}i(os,"applyInterceptors");async function Ea(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(Ea,"recordInterceptorError");var ss=new Map;function is(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(is,"escapeLiteral");function Wn(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(Wn,"normalizeGlobSeparators");function va(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(va,"bracesBalanced");function Ae(e){let t=ss.get(e);if(t)return t;let n=Wn(e),r=va(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=is(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=is(c)}let a=new RegExp(`^${o}$`);return ss.set(e,a),a}i(Ae,"globToRegExp");function Sa(e){return Wn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Sa,"concreteGlobSegments");function Vr(e,t){let n=Wn(String(e)),r=Sa(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 f of r){let g=-1;for(let h=l;h<a.length;h+=1)if(a[h]===f){g=h;break}if(g<0)return s;c=g,l=g+1}return(c+1)*1e6+r.length*1e4+o}i(Vr,"patternSpecificity");function ce(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Ae(a).test(n))){for(let a of s.patterns??[])if(Ae(a).test(n)){let l=Vr(a,n);l>o&&(o=l,r=s.name)}}return r}i(ce,"layerForRelativePath");function as(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(as,"sliceIdForPath");function wa(e){let t=new Set;for(let n of e??[]){let o=Wn(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(wa,"inferSliceFoldersFromPatterns");function Ca(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 wa(r?.patterns)}i(Ca,"resolveSliceFolders");function ls(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(ls,"normalizeSegments");function ps(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(ps,"trimTrailingSlashes");var xa=["src","app"];function Oa(e){let t=ps(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Oa,"isBlanketRoot");function cs(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=ls(n);for(let s of t){if(typeof s!="string"||s.length===0||Oa(s))continue;if(s.includes("*")){let c=ps(s.toLowerCase());if(Ae(c).test(r)||Ae(`${c}/**`).test(r))return!0;continue}let a=ls(s);if(a.length===0)continue;let l=xa.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let f=!0;for(let g=0;g<a.length;g+=1)if(o[c+g]!==a[g]){f=!1;break}if(f)return!0}}return!1}i(cs,"pathUnderSharedRoot");function ds(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(ds,"sliceMatchesDeclaration");function Pa(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&ds(r.from,t)&&ds(r.to,n))}i(Pa,"crossSliceEdgeAllowed");function _a(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(_a,"peerIsolationDecision");function us(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(us,"peerIsolationDenyExplanation");function ke(e,t,n,r){return jr(e,t,n,r)?.rule}i(ke,"findDeniedEdgeRule");function jr(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=Ca(o,t,r?.layers),c=s&&a?as(s,l):void 0,f=s&&a?as(a,l):void 0,g=_a({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:f,fromShared:!c&&cs(s,o.sharedRoots),toShared:!f&&cs(a,o.sharedRoots),crossSliceAllowed:Pa(o.allowedCrossSlice,c,f)});if(g.denied)return{rule:o,peerIsolationReason:g.reason,fromSlice:c,toSlice:f};continue}if(t!==n)return{rule:o}}}i(jr,"findDeniedEdgeDecision");async function fs(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=ke(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}).`,f={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:f}),await t.recordAudit("layer.observedViolation",e,f),l==="hard")throw new We(n,e.intent,o,s,c)}i(fs,"assertObservedLayerFlowAllowed");async function ms(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof he&&(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(ms,"enforcePublishPolicy");function Na(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(Na,"appendHistory");function zt(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(zt,"appendTrace");async function qn(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){zt(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(qn,"recordAudit");async function gs(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."};zt(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 qn(e,"event.rawPublish",t,n)}i(gs,"recordRawPublishDiagnostic");async function ys(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Na(e,o),await e.eventBuffer?.enqueue(t,r),zt(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 qn(e,"event.published",t,{subscribersNotified:n}),o}i(ys,"recordSuccessfulPublish");function Br(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(Br,"enrichMetadata");var hs=0;function Ta(){return hs+=1,`interceptor-${Date.now()}-${hs}`}i(Ta,"nextInterceptorRegistrationId");var ct=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 Ce(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Vt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new je;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=Bt({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,f=typeof t!="function";if(f){let p=t,u=r??n??{};c={...p,metadata:Br(p.metadata,u,this.recording.instanceId)}}else{let p=t,u=n,m=r??{},y=p(u);c={...y,metadata:Br(y.metadata,m,this.recording.instanceId)}}f&&this.strictRegistry&&await gs(this.recording,c),Wt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),ns(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),qt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await os(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,u,m)=>this.recordAudit(p,u,m),"recordAudit")}),qt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await fs(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,u,m)=>this.recordAudit(p,u,m),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let g=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await ms(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,u,m)=>this.recordAudit(p,u,m),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((p,u,m)=>this.safeHook(p,u,m),"safeHook")}),await ys(this.recording,c,s?g.length:0,o.tx);let h=(async()=>{s&&await Promise.all(g.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 Wt(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 Re(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Wt(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;Wt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Ta(),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){zt(this.recording,t)}async recordAudit(t,n,r){await qn(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 Wr(e){return new ct(e)}i(Wr,"createEventBus");function Da(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(Da,"formatStandardSchemaPath");function La(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(La,"actualType");function Fa(e,t){return e?`${e}.${t}`:t}i(Fa,"formatPath");function Rs(e,t,n,r,o){let s=La(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}As(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{Rs(a,t.items,`${n}[${l}]`,r,o)})}i(Rs,"validateSchemaField");function As(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=Fa(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}Rs(c,a,l,n,r)}}i(As,"validateObjectSchema");var dt=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(As(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:Da(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 Yt(){return new dt}i(Yt,"createEventContractRegistry");var ks=0;function Ma(){return ks+=1,`outbox-${Date.now()}-${ks}`}i(Ma,"nextOutboxId");function Is(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Is,"cloneRecord");var Oe=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),Is(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(Is)}async clear(){this.records.clear()}},qr=Oe;function zr(e){return`${e.from}->${e.to}`}i(zr,"flowKey");function bs(e){let t=new Set,n=[];for(let r of e){let o=zr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(bs,"uniqueFlows");function Es(e,t){let n=new Set(t.map(zr));return e.filter(r=>!n.has(zr(r)))}i(Es,"difference");function Xt(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=bs([...o,...s]),f=bs([...a,...l]),g=f.filter(y=>!y.from||y.from==="unknown"),h=t?Array.from(new Set(f.map(y=>y.from).filter(y=>y&&y!=="unknown"&&!t.has(y)))):[],p=t?Array.from(new Set(f.map(y=>y.to).filter(y=>!t.has(y)))):[],u=new Set(f.flatMap(y=>[y.from,y.to])),m=t?t.list().map(y=>y.name).filter(y=>!u.has(y)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:f,declaredButUnobserved:Es(c,f),observedButUndeclared:Es(f.filter(y=>y.from!=="unknown"),c),unknownSources:g,unregisteredObservedSources:h,unregisteredObservedIntents:p,registeredButNeverObserved:m}}}}i(Xt,"createObservabilityReporter");function Yr(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(Yr,"createArkTestHarness");var vs=0;function $a(){return vs+=1,`audit-${Date.now()}-${vs}`}i($a,"createAuditId");function Ka(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(Ka,"matchesQuery");var pt=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=>Ka(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},zn=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:$a(),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 Zt(e={}){return new zn(e.store??new pt(e.maxRecords))}i(Zt,"createAuditTrail");var Yn=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 i=t.resolveLayer(s)??"Unclassified",l=n.get(i)??[];l.push(s),n.set(i,l)}let r=`flowchart TD
11
- `;for(let s of t.layers){let i=n.get(s.name)??[];if(i.length!==0){r+=` subgraph ${this.safeId(s.name)}[${s.name}]
12
- `;for(let l of i)r+=` ${this.safeId(l)}[${l}]
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
+ `;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 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
- `}for(let s of this.edges){let i=s.kind?`|${s.kind}|`:"";r+=` ${this.safeId(s.from)} -->${i} ${this.safeId(s.to)}
18
- `}return r.trim()}detectViolations(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.message}`)}return n}ensureNode(t){this.nodes.has(t)||this.nodes.set(t,{id:t})}addEdge(t){this.edges.some(r=>r.from===t.from&&r.to===t.to&&r.kind===t.kind)||this.edges.push(t)}findSimpleCycles(){let t=new Map;for(let l of this.edges)t.has(l.from)||t.set(l.from,[]),t.get(l.from).push(l.to);let n=[],r=new Set,o=[],s=a(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))s(c);else if(o.includes(c)){let g=o.indexOf(c),m=o.slice(g).concat(c);n.push(m)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||s(l);let i=new Set(n.map(l=>l.join("->")));return Array.from(i).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function Ft(){return new Ln}a(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"))}a($t,"syncRegistryToGraph");var et={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},fs={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}}},gs={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)}a(Mt,"isObject");function ms(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}a(ms,"declaredLayerNames");function ys(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}}a(ys,"defaultedArkRun");function hs(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}}a(hs,"defaultedArkOrder");function Rs(e,t){let n=e.arkRun;if(n===void 0||!Mt(n))return;let r=ms(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Rs,"validateArkRunExtra");function As(e,t){let n=e.arkOrder;if(n===void 0||!Mt(n))return;let r=ms(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(As,"validateArkOrderExtra");var oe="1.3",$n="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",ks=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],wi=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function xi(){let e=[];for(let t of ks)for(let n of ks)t===n||wi.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(xi,"createDefaultRules");var Mn=xi(),Mr=[{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},Is={$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:fs,arkOrder:gs}},ye=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
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 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 f=o.indexOf(c),g=o.slice(f).concat(c);n.push(g)}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 Jt(){return new Yn}i(Jt,"createDependencyGraph");function Qt(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(Qt,"syncRegistryToGraph");var ut={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ss={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...ut,default:[]},kernelRoots:{...ut},managedLayers:{...ut,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},ws={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...ut,default:[]},managedLayers:{...ut,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...ut,default:[]}}};function en(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(en,"isObject");function Cs(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)en(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Cs,"declaredLayerNames");function xs(e){if(!en(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(xs,"defaultedArkRun");function Os(e){if(!en(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(Os,"defaultedArkOrder");function Ps(e,t){let n=e.arkRun;if(n===void 0||!en(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(Ps,"validateArkRunExtra");function _s(e,t){let n=e.arkOrder;if(n===void 0||!en(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(_s,"validateArkOrderExtra");var ae="1.3",Zn="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ns=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ha=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ua(){let e=[];for(let t of Ns)for(let n of Ns)t===n||Ha.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Ua,"createDefaultRules");var Jn=Ua(),Xr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ie={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ts={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Zn,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:Zn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ae,default:ae},name:{type:"string",minLength:1},include:{...ie,minItems:1,default:["src"]},exclude:{...ie,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Jn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ie,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ie,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ie,minItems:1},exclude:ie,intentPrefixes:ie,description:{type:"string",minLength:1},forbiddenGlobals:ie,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ie,minItems:1},sharedRoots:{...ie,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...ie,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...ie,minItems:1}}},arkRun:Ss,arkOrder:ws}},Ie=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 vs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(vs,"isObject");function Fn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Fn,"propertyPath");function tt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(tt,"valueType");function Oi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Oi,"resolveSchemaRef");function Kt(e,t,n,r,o){if(t.$ref){let s=Oi(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Kt(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(!vs(e)){o.push({path:n,message:`must be an object; received ${tt(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Fn(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Fn(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||Kt(e[l],i,Fn(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Kt(e[i],l,Fn(n,i),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(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>Kt(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${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}`})}}a(Kt,"validateNode");function Pi(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=ys(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=hs(e.arkOrder)),t}a(Pi,"defaultedConfig");function _i(e){return e===oe?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(_i,"migratedFromOf");function Ni(){let e=new Set([oe]);for(let t of Mr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Ni,"knownInputVersions");function Ti(e,t="ark.config.json"){if(!vs(e))throw new ye(t,[{path:"$",message:`must be an object; received ${tt(e)}`}]);let n=Ni(),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},i=0;for(;o!==oe&&i<Mr.length+1;){i+=1;let l=Mr.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:Pi(s),migratedFrom:_i(r)}}a(Ti,"migrateArkConfig");function Kr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ti(e,t),o=[];if(Kt(n,Is,"$",Is,o),Rs(n,o),As(n,o),o.length>0)throw new ye(t,o);return{config:n,migratedFrom:r}}a(Kr,"loadArkConfigContract");function Es(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 Kr(n,t)}a(Es,"parseArkConfigJson");function bs(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}a(bs,"withArkConfigMetadata");function Di(e){return e.endsWith(".")?e:`${e}.`}a(Di,"normalizePrefix");function Li(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}a(Li,"byLongestPrefix");function Ht(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Di)})),n=[...t].sort(Li),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(i=>o.startsWith(i)))?.name}}}a(Ht,"createArchitectureProfile");function Gt(e,t={}){return Ht({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}a(Gt,"createArchitectureProfileFromArkConfig");var Fi=[{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=Ht({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Fi,rules:Mn.map(e=>({...e}))}),$i={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 bs({include:e.include??[t],layers:Fe.layers.map(o=>({name:o.name,patterns:($i[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Fe.rules]})}a(Hr,"createElevenLayerArkConfig");var Kn=class{static{a(this,"MetadataRegistryImpl")}entities=new Map;entity(t,n,r={}){if(this.entities.has(t)&&!r.allowOverwrite)throw new Error(`Entity metadata "${t}" is already registered.`);let o={name:t,fields:{},...n};return this.entities.set(t,o),o}getEntity(t){return this.entities.get(t)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(t){return this.listEntities().filter(n=>n.emits?.includes(t)||n.consumes?.includes(t))}validate(){let t=[];for(let n of this.entities.values()){n.name.trim()||t.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||t.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&t.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&t.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:t.length===0,issues:t}}toJSON(){return this.listEntities()}};function Ut(){return new Kn}a(Ut,"createMetadataRegistry");function Gr(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}a(Gr,"definePort");function Ur(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=>!Ss(t,g));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let i={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=Hn(i);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
21
- `));return i}a(Ur,"createAdapter");function Vr(e,t=[]){let n=t.filter(r=>!Ss(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}a(Vr,"checkContract");function Hn(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}a(Hn,"checkAdapterGovernance");function Ss(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}a(Ss,"hasMember");var Br=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),qr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),zr=Object.freeze(Object.keys(qr).sort()),jr=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"}),Wr=Object.freeze({process:Object.freeze(["process","node:process"])});function Vt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=jr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=jr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:jr[e.slice(0,s)]??null}a(Vt,"capabilityForModuleSpecifier");function Se(e,t){for(let n of t)if(Wr[n]?.includes(e))return n;return null}a(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=qr[r];if(o)return o}return null}a(Gn,"capabilityForAmbientName");function nt(e){if(e?.pure===!0)return[...Br].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Br.includes(r));return[...new Set(n)].sort()}a(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}a(jt,"ambientCoveredByForbiddenGlobals");function Un(e){let t=new Set,n=new Set,r=Object.keys(qr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(i=>i===o||i.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let i of s)t.add(`ambient:${i}`);for(let i of Wr[o]??[])t.add(`import-exact:${i}`)}for(let o of nt(e)){if(t.add(`import:${o}`),o==="process")for(let s of Wr.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()}}a(Un,"loweredLayerCoverage");function rt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(rt,"literalText");function xs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(xs,"lineOf");function Cs(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}a(Cs,"isTypeOnlyReference");function Os(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}a(Os,"singleFileChecker");function Yr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Yr,"symbolAt");function Xr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Yr(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Xr,"localDeclaration");function $e(e,t){let n,r=[],o=a((i,l,c,g=!1)=>r.push({specifier:c,kind:l,line:xs(t,i),typeOnly:g,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",rt(e,i.moduleSpecifier),Cs(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",rt(e,i.moduleSpecifier),Cs(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",rt(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Xr(e,n??(n=Os(e,t)),t,i.expression);(l||g)&&o(i,g?"require":"dynamic-import",rt(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a($e,"extractSemanticDependencies");function Mi(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}}a(Mi,"staticAccessPath");function Ki(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}a(Ki,"runtimeIdentifierReference");function ws(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}a(ws,"bestForbiddenMatch");function Me(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Os(e,t),s=new Map,i=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations)e.isIdentifier(f.name)&&i.add(f.name.text);let l=a(p=>{let f=Mi(e,p);if(!f)return;let u=Yr(o,f.root),y=u?s.get(u):void 0;return y?[...y,...f.segments.slice(1)]:Xr(e,o,t,f.root)||i.has(f.root.text)?void 0:f.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations){if(!f.initializer||!e.isIdentifier(f.name))continue;let u=l(f.initializer),y=Yr(o,f.name);!u||!y||s.set(y,u)}let c=[],g=new Set,m=a((p,f)=>{let u=xs(t,f),y=`${p}:${f.getStart(t)}`;g.has(y)||(g.add(y),c.push({name:p,line:u,node:f}))},"flag"),h=a(p=>{let f=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!f){let u=l(p),y=u?ws(r,u):void 0;y&&m(y,p)}else e.isIdentifier(p)&&r.has(p.text)&&Ki(e,p)&&!Xr(e,o,t,p)&&m(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let u=l(p.initializer);if(u)for(let y of p.name.elements){if(!e.isIdentifier(y.name))continue;let E=y.propertyName?rt(e,y.propertyName)??y.propertyName.text:y.name.text,b=ws(r,[...u,E]);b&&m(b,p.initializer)}}e.forEachChild(p,h)},"visit");return h(t),c}a(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=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,zr)){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))}a(Zr,"collectCapabilityUses");var Jr={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."},Qr=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 eo(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}a(eo,"resolveIntentLayer");function Ke(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(Ke,"looksLikeArkIntent");function Bt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ke(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Jr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Jr.PUBLISH_MISSING_SOURCE}),t}a(Bt,"classifyPublishFacts");function U(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(U,"violation");function ot(e,t){return e.slice(0,t).split(`
22
- `).length}a(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}a(Hi,"extractQuotedStrings");function Gi(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),i=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(i)||r.kind==="export"&&/\bexport\s+type\b/.test(i);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}a(Gi,"extractModuleSpecifiers");function Ui(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(Ui,"extractQuotedStringsAst");function Vi(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}a(Vi,"hasInfrastructureToken");function ji(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(ji,"isKnownInfrastructurePackage");function Bi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(Bi,"layerHasInfrastructureRole");function qt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(qt,"tsStringLiteralText");function Wi(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(Wi,"tsPropertyName");function Ps(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Wi(e,r.name)===n)}a(Ps,"tsObjectProperty");function zt(e,t,n){return Ps(e,t,n)!==void 0}a(zt,"tsObjectHasProperty");function Wt(e,t,n){let r=Ps(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Wt,"tsObjectPropertyValue");function qi(e,t){let n=Wt(e,t,"metadata");return zt(e,n,"source")}a(qi,"tsObjectHasMetadataSource");function _s(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?_s(e,t.name):!1:!1}a(_s,"tsLooksLikeIntentCreatorExpression");function zi(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}a(zi,"tsIsPublishCall");function Yi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=qt(e,n);return r!==void 0&&Ke(r)||zt(e,n,"intent")||_s(e,n)}a(Yi,"tsIsArkPublishCandidate");function Xi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return qi(e,n)||zt(e,r,"source")||zt(e,o,"source")}a(Xi,"tsPublishHasSource");function Zi(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"))}a(Zi,"tsPublishSourceLiteral");function Ji(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],g=a(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),m=a(h=>{if(zi(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:Yi(e,h),hasSource:Xi(e,h)}))c.push(U(y.ruleId,y.message,{line:g(h),filePath:i}));let u=Zi(e,h);if(r&&l&&u&&Ke(u)){let y=r.resolveLayer(u);y&&y!==l&&c.push(U("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${y}, but the target file is classified as ${l}.`,{line:g(h),filePath:i,target:u,fromLayer:l,toLayer:y}))}}e.forEachChild(h,m)},"visit");return m(o),c}a(Ji,"analyzePublishAst");function to(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,g=c?.filePath,m=c?.layer,h=e.typescript,p=h?h.createSourceFile(g??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,f=p?$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})):Gi(s),y=e.typescript?Ui(e.typescript,s):Hi(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(g))for(let A of f?.filter(({unresolved:v})=>v)??[]){let v=A.kind==="require";l.push(U(v?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${v?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:g}))}let E=m!==void 0&&(r.has(m)||Bi(m)),b=m!==void 0?` If "${m}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let A of n)if(A instanceof RegExp){A.lastIndex=0;let v=A.exec(s);A.lastIndex=0,v&&l.push(U("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:v.index===void 0?void 0:ot(s,v.index),filePath:g,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else s.includes(A)&&l.push(U("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line: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}E||A.typeOnly||!Vi(A.value)&&!ji(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."+b,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let v=A.check({source:s,context:i});if(v!==!0)if(Array.isArray(v))for(let P of v)l.push(U("POLICY_VIOLATION",P.message,{filePath:g,suggestion:`Fix violation of policy "${A.name}".`}));else v===!1?l.push(U("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(U("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let A of y)Ke(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(!Ke(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,i);l.push(...v)}catch(v){l.push(U("EXTENSION_ERROR",`Extension "${A.name}" failed: ${v instanceof Error?v.message:String(v)}`))}if(e.typescript&&p&&m&&e.forbiddenGlobals?.[m]?.length)try{let A=e.forbiddenGlobals[m];l.push(...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 Zr(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(...Ji(e.typescript,s,i,e.architectureProfile))}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}a(to,"createAICodeGate");function B(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(B,"deterministicHash");function 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(",")}}`}a(D,"stableSerialize");var Ce="1.2";var Ns=["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}a(V,"compareCanonical");function W(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(W,"sortedUnique");function at(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))}a(at,"resolvedFactsEvidenceRequirementsHash");function Qi(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(V),n=e.files.map(k=>({...k,typeOnlyExportNames:W(k.typeOnlyExportNames)})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:W(k.namedBindings)}:{}})).sort(V),o=e.capabilityUses.map(k=>({...k})).sort(V),s=e.ambientUses.map(k=>({...k})).sort(V),i=e.publishCalls.map(k=>({...k})).sort(V),l=e.intentReferences.map(k=>({...k})).sort(V),c=e.safetyUses.map(k=>({...k})).sort(V),g=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(_=>({..._}))})).sort(V),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(V),h=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(V),p=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(V),f=(e.arkRunDeclarations??[]).map(k=>({...k,uses:W(k.uses),reactsTo:W(k.reactsTo),raises:W(k.raises),sends:W(k.sends)})).sort(V),u=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(V),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(V),E=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(V),b=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(V),A=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(V),v=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(V),P=e.files.map(({path:k,contentHash:_})=>({path:k,contentHash:_})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),j=B(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:i,intentReferences:l,safetyUses:c,classShapes:g,arkRunKernelCalls:m,arkRunManagedNews:h,arkRunCompositionRootHits:p,arkRunDeclarations:f,arkOrderPlaneCalls:u,arkOrderGenericUpdates:y,arkOrderRootHits:E,arkOrderXiFieldWrites:b,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:v}}a(Qi,"canonicalResolvedFactsInput");function Ts(e){let t=Qi(e);return{...t,factsHash:B(D(t))}}a(Ts,"createCanonicalResolvedCandidateFacts");function Vn(e){return Ts(Ls(L(e,"$"),!1))}a(Vn,"createResolvedCandidateFacts");function L(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(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"}.`)}a($,"assertOnlyKeys");function T(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}a(T,"requiredText");function he(e,t,n){if(e[t]!==void 0)return T(e,t,n)}a(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 i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(M,"requiredProjectPath");function K(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(K,"requiredBoolean");function Ds(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}a(Ds,"requiredInteger");function Y(e,t,n){let r=Ds(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(Y,"requiredPositiveInteger");function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(H,"requiredArray");function 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}a(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]}a(st,"parseStringArray");function el(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}a(el,"assertUnique");function Ls(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=H(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=H(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:Ds(d,"parseDiagnosticCount",R),exportsOnlyTypes:K(d,"exportsOnlyTypes",R),typeOnlyExportNames:st(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:K(d,"hasTopLevelSideEffects",R)}}),i=H(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:K(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:K(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:K(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:K(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:K(d,"portProofEligible",R)}:{}}}),l=H(e,"capabilityUses","$").map((S,C)=>{let R=`$.capabilityUses[${C}]`,d=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",Ns,R),source:Re(d,"source",["ambient-global","import-based"],R)}}),c=H(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=H(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:K(d,"objectHasIntent",R),arkPublishCandidate:K(d,"arkPublishCandidate",R),hasSource:K(d,"hasSource",R),...F?{sourceIntent:F}:{}}}),m=H(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=H(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}:{}}});el(s,S=>S.path,"$.files");let p=new Set(s.map(S=>S.path));for(let S of s){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of i)if(!p.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:H(e,"arkRunKernelCalls","$")).map((S,C)=>{let R=`$.arkRunKernelCalls[${C}]`,d=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:K(d,"viaImport",R),...N?{receiver:N}:{},...F?{nameLiteral:F}:{}}}),E=(e.arkRunManagedNews===void 0?[]:H(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?[]:H(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:K(d,"hasKernelFactory",R)}}),v=e.arkRunDeclarations===void 0?[]:H(e,"arkRunDeclarations","$"),j=(e.arkOrderPlaneCalls===void 0?[]:H(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let R=`$.arkOrderPlaneCalls[${C}]`,d=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?[]:H(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?[]:H(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:K(d,"hasPlaneFactory",R)}}),ze=(e.arkOrderXiFieldWrites===void 0?[]:H(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?[]:H(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)}}),Er=(e.arkOrderReleaseKeyCounts===void 0?[]:H(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",E],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",It],["$.arkOrderPlaneCalls",j],["$.arkOrderGenericUpdates",_],["$.arkOrderRootHits",pe],["$.arkOrderXiFieldWrites",ze],["$.arkOrderIngestWritesXi",Sn],["$.arkOrderReleaseKeyCounts",Er]])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?[]:H(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=H(d,"mutatingMethods",R).map((F,ne)=>{let wn=`${R}.mutatingMethods[${ne}]`,Sr=L(F,wn);return $(Sr,["name","referencesGuardOrPublish"],wn),{name:T(Sr,"name",wn),referencesGuardOrPublish:K(Sr,"referencesGuardOrPublish",wn)}});return{file:M(d,"file",R),className:T(d,"className",R),exported:K(d,"exported",R),hasPublicMutableFields:K(d,"hasPublicMutableFields",R),hasPublicSetters:K(d,"hasPublicSetters",R),hasPublicConstructor:K(d,"hasPublicConstructor",R),hasStaticFactory:K(d,"hasStaticFactory",R),mutatingMethods:N,...d.dataOnly===void 0?{}:{dataOnly:K(d,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:T(e,"resolverIdentity","$"),compilerIdentity:T(e,"compilerIdentity","$"),compilerOptionsHash:T(e,"compilerOptionsHash","$"),tsconfigHash:T(e,"tsconfigHash","$"),evidenceRequirementsHash:T(e,"evidenceRequirementsHash","$"),...xe?{projectPackageName:xe}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:g,intentReferences:m,safetyUses:h,classShapes:br,arkRunKernelCalls:u,arkRunManagedNews:E,arkRunCompositionRootHits:A,arkRunDeclarations:It,arkOrderPlaneCalls:j,arkOrderGenericUpdates:_,arkOrderRootHits:pe,arkOrderXiFieldWrites:ze,arkOrderIngestWritesXi:Sn,arkOrderReleaseKeyCounts:Er}}a(Ls,"parseResolvedFactsInput");function Ae(e){let t=L(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=Ts(Ls(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}a(Ae,"loadResolvedCandidateFacts");var tl=["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:tl},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}`}a(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.`}:{}}}a(Yt,"dependencyFinding");function He(e){let t=[],n=new Map(e.changeMap.map.files.map(p=>[p.path,p])),r=new Map(e.changes.map(p=>[p.path,p])),o=new Map(e.changeMap.map.dependencies.map(p=>[Q(p),p])),s=new Map(e.baseDependencies.map(p=>[Q(p),p])),i=new Map(e.candidateDependencies.map(p=>[Q(p),p]));for(let p of[...n.values()].sort((f,u)=>f.path.localeCompare(u.path))){let f=r.get(p.path);f?f.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${f.operation}.`,nextAction:`Change ${p.path} to the planned ${p.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${p.path}`,classification:"satisfied",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} matches the planned ${p.operation} operation.`}):t.push({id:`missing:file:${p.path}`,classification:"missing",subject:"file",path:p.path,expectedOperation:p.operation,message:`${p.path} was planned as ${p.operation} but is absent from the actual change.`,nextAction:`${p.operation[0].toUpperCase()}${p.operation.slice(1)} ${p.path} in the complete change set, then preflight again.`})}for(let p of[...r.values()].sort((f,u)=>f.path.localeCompare(u.path)))n.has(p.path)||t.push({id:`unplanned:file:${p.path}`,classification:"unplanned",subject:"file",path:p.path,actualOperation:p.operation,message:`${p.path} has an unplanned ${p.operation} operation.`,nextAction:`Remove ${p.path} from the change set, then preflight again.`});let l=new Set;for(let p of[...o.values()].sort((f,u)=>Q(f).localeCompare(Q(u)))){if(i.has(Q(p))){t.push(Yt("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let f={from:p.to,to:p.from};i.has(Q(f))?(l.add(Q(f)),t.push(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[...i].sort(([u],[y])=>u.localeCompare(y)))s.has(p)||o.has(p)||l.has(p)||!c.has(f.from)&&!c.has(f.to)||t.push({...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)))i.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}}a(He,"analyzeArchitectureConvergence");var Fs="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",nl=["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},Qu={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Fs,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:Fs},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:[...nl]},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:[]}}a(Xt,"emptyEffectiveArkRules");function Ms(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}a(Ms,"effectiveContractPolicyPayload");function Ks(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}a(Ks,"formatCoverageDiscards");function rl(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}a(rl,"isUnderCoverageRoot");function ol(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}a(ol,"titleMatchesInvariant");function sl(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}a(sl,"symbolPresent");function Hs(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,i=Ks(s),l=Ks(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",g=(e.coverageRoots??[]).filter(u=>typeof u=="string"&&u.length>0),m=g.length>0,h=g.join(", "),p=[],f=[];for(let u of t){let y=[],E=u.coverage?.test!==!1,b=u.coverage?.symbol,A,v;if(!r&&E){let _;for(let z of n){let pe=e.fileContents[z];if(!(!pe||!ol(pe,u.id))){if(!m||rl(z,g)){A=z,v=m?!1:void 0;break}_??=z}}A===void 0&&_!==void 0&&(A=_,v=!0),A!==void 0&&y.push("test-title")}b&&sl(e.fileContents,b)&&y.push("symbol");let j=(u.coverage?.test===!0||!!b||u.coverage===void 0)&&y.length>0||u.coverage?.test===!1&&!b?!0:y.length>0,k=r&&E&&y.length===0;if(p.push({invariantId:u.id,layer:u.provenance.layer,sourceFile:u.provenance.sourceFile,mode:u.mode,covered:j&&!k,evidence:y,partial:k,description:u.description,...A!==void 0?{testEvidenceFile:A}:{},...v!==void 0?{outsideDeclaredRoots:v}:{}}),v===!0&&A!==void 0&&f.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${u.id} is covered only by ${A}, which is outside the declared coverage roots (${h}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:A,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:"warning",failsStrict:!1}),!j||k){let _=u.mode==="enforced"&&!k,z=r||n.length===0?"never-had-tests":"tests-disappeared";f.push({ruleId:"INVARIANT_UNCOVERED",message:(k?o?`Invariant ${u.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${u.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:z==="tests-disappeared"?`Invariant ${u.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${u.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(k&&o?l:i),file:u.provenance.sourceFile,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:_?"error":"warning",failsStrict:_,kind:z})}}return{coverage:p,violations:f,partial:p.some(u=>u.partial)}}a(Hs,"evaluateInvariantCoverage");function Gs(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a(Gs,"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}})}a(O,"addFinding");function q(e){return[...new Set(e??[])].sort()}a(q,"sortedUnique");function ie(e,t,n,r,o){let s=q(n),i=q(r),l=new Set(s),c=new Set(i),g=i.filter(h=>!l.has(h)),m=s.filter(h=>!c.has(h));g.length===0&&m.length===0||(g.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),m.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(ie,"compareStringSets");function Zt(e,t,n,r,o,s,i){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(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()}}a(Wn,"keyed");function al(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 i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){O(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(i&&!l){O(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;ie(e,`${c}.patterns`,i.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ie(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=Un(i),m=Un(l);ie(e,`${c}.forbiddenGlobals`,g.rawGlobals,m.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ie(e,`${c}.capabilities`,g.atoms,m.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),q(i.intentPrefixes).join("\0")!==q(l.intentPrefixes).join("\0")&&O(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:q(i.intentPrefixes),after:q(l.intentPrefixes)}),Zt(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Zt(e,`${c}.optional`,i.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}a(al,"compareLayers");function il(e,t,n){let r=a(i=>`${i.from}->${i.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 i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),g=`$.rules[${i}]`;if(!l&&c){c.allowed===!1&&O(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&O(e,{kind:"deny-removed",path:g,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&O(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${g}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let m=l.peerIsolation===!0,h=c.peerIsolation===!0;if(m!==h){let p=l.from===l.to&&c.from===c.to;O(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${g}.peerIsolation`,classification:p?h?"strengthening":"weakening":"judgment-required",message:p?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:m,after:h})}q(l.sliceFolders).join("\0")!==q(c.sliceFolders).join("\0")&&O(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:q(l.sliceFolders),after:q(c.sliceFolders)}),!(!m&&!h)&&(Vs(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."),Vs(e,`${g}.allowedCrossSlice`,"cross-slice-allowance",q((l.allowedCrossSlice??[]).map(Us)),q((c.allowedCrossSlice??[]).map(Us)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}a(il,"compareRules");function Us(e){return JSON.stringify([e.from,e.to])}a(Us,"crossSliceKey");function Vs(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(m=>!r.includes(m)),c=r.filter(m=>!o.includes(m)),g=l.length>0&&c.length>0;O(e,{kind:g?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:g?"judgment-required":l.length>0?"weakening":"strengthening",message:g?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(Vs,"compareDeclaredExceptions");function ll(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&O(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Zt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(ll,"compareSafety");function no(e){return e.mode==="enforced"?"enforced":"advisory"}a(no,"arkRunMode");function ro(e){return e.mode==="enforced"?"enforced":"advisory"}a(ro,"arkOrderMode");function cl(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 (${ro(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=ro(r),l=ro(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}ie(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ie(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(cl,"compareArkOrder");function dl(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 (${no(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=no(r),l=no(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}ie(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ie(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Zt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(dl,"compareArkRun");function pl(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}a(pl,"overallClassification");function js(e,t){return`${e}::${t}`}a(js,"ruleKey");function Bs(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(js(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(js(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Bs,"indexEffectiveRules");function ul(e,t,n,r,o,s){let i=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},g=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of g){let f=l[p],u=c[p],y=`$.arkRules[${p}]`;if(f===void 0&&u!==void 0){O(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:u});continue}if(f!==void 0&&u===void 0){O(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:f});continue}f!==u&&O(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:f,after:u})}let m=Bs(r),h=Bs(o);for(let p of[...new Set([...m.structure.keys(),...h.structure.keys()])].sort()){let f=m.structure.get(p),u=h.structure.get(p),y=`$.arkRules.structure[${p}]`;if(!f&&u){O(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(f&&!u){O(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${f.id} was removed.`,before:f});continue}if(!(!f||!u)){if(f.mode!==u.mode){let E=f.mode==="advisory"&&u.mode==="enforced";O(e,{kind:E?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:E?"strengthening":"weakening",message:E?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}f.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:f.sensor,after:u.sensor})}}for(let p of[...new Set([...m.invariants.keys(),...h.invariants.keys()])].sort()){let f=m.invariants.get(p),u=h.invariants.get(p),y=`$.arkRules.invariants[${p}]`;if(!f&&u){O(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(f&&!u){O(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${f.id} was removed.`,before:f});continue}if(!(!f||!u)&&f.mode!==u.mode)if(f.mode==="advisory"&&u.mode==="enforced"){let b=i?.get(u.id),A=Gs(b);A.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:f.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${A.reason}`,before:f.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}}a(ul,"compareArkRules");function zn(e,t,n){let r=[];ie(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ie(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ie(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),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",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&O(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),al(r,e.layers,t.layers),il(r,e.rules,t.rules),ll(r,e,t),ul(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),dl(r,e,t),cl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:qn,classification:pl(r),findings:r}}a(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])}a(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("/")}a(Ge,"normalizePath");function Ws(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(Ws,"isIdentifierStart");function Xn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(Xn,"isIdentifierCharacter");function ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(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}}a(Jt,"readString");function se(e,t,n){return e.startsWith(t,n)&&!Xn(e[n-1])&&!Xn(e[n+t.length])}a(se,"isWordAt");function qs(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)||!Ws(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),!Ws(e[n]))return!1;for(;n<e.length&&Xn(e[n]);)n+=1}r=!0}return!1}a(qs,"bracedNamedBindingsAreTypeOnly");function fl(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 qs(e,t)&&(n=!0);let r=zs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(fl,"specifierAfterImport");function gl(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 qs(e,n)&&(r=!0);let o=zs(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(gl,"specifierAfterExport");function zs(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}}a(zs,"specifierInStaticStatement");function ml(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}a(ml,"skipTemplateLiteral");function yl(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}a(yl,"specifierAfterRequire");function hl(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=ml(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)?fl(e,n):r==="e"&&se(e,"export",n)?gl(e,n):r==="r"&&se(e,"require",n)?yl(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(hl,"moduleSpecifiers");function Ys(e,t){let n=[],r=[];for(let o of hl(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 i=e.content.slice(0,o.offset).split(`
25
- `).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=Rl(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}a(Ys,"moduleFactsFor");function Rl(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let i=n.get(s);if(i)return i}}a(Rl,"resolveSpecifier");function Xs(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}a(Xs,"violationsFor");var Al={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 kl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(kl,"hasActiveArkRules");function Il(e,t){return kl(e,t)?B(D(Ms({config:e,arkRules:t,warnings:[]}))):B(D(e))}a(Il,"policyHashFor");function Qt(e,t,n){let r=typeof e=="string"?Es(e,t):Kr(e,t),o=n?.arkRules??Xt();return{...r,arkRules:o,policyHash:Il(r.config,o)}}a(Qt,"loadContract");function oo(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,i=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:i,valid:!s||i}}a(oo,"analyzePolicyDelta");function it(e){let t=e.files.map(h=>{let p=Ge(h.path);return{path:p,content:h.content,contentHash:B(h.content),layer:ae(p,e.contract.config.layers)??null}}).sort((h,p)=>h.path.localeCompare(p.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let p=Ys(h,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=Xs(r,e.contract.config),i=new Map(e.contract.config.layers.map(h=>[h.name,h])),l=new Map(e.contract.config.layers.map(h=>[h.name,new Set(nt(h))]));for(let h of o){let p=n.get(h.file)?.layer;if(!p)continue;let f=i.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"?[]:[{...Al}],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}}a(it,"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 it({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(en,"analyzeChange");function so(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}a(so,"explainViolation");function Zn(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let h of[...e.get(c)??[]].sort())e.has(h)&&(n.has(h)?o.has(h)&&r.set(c,Math.min(r.get(c)??0,n.get(h)??0)):(l(h),r.set(c,Math.min(r.get(c)??0,r.get(h)??0))));if(r.get(c)!==n.get(c))return;let g=[],m;do{if(m=s.pop(),m===void 0)break;o.delete(m),g.push(m)}while(m!==c);g.length>1&&i.push(g.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,g)=>c[0]<g[0]?-1:c[0]>g[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(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 i=Nr(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i)continue;let l=i.rule,c=!!l.peerIsolation,g=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=c?es(i.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:i.fromSlice,toSlice:i.toSlice}):void 0,h=l.message?m?`${l.message} (${m})`:l.message:m?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${m}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:g?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...g?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Zn(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}a(Ue,"evaluateArchitectureGraph");var vl=["no-anemic-model"];function Zs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Zs,"escapeGlobLiteral");function El(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+=Zs(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Zs(o)}return new RegExp(`^${n}$`)}a(El,"globToRegExp");function lt(e,t){return!t||t.length===0?!0:t.some(n=>El(n).test(e))}a(lt,"matchesAppliesTo");function bl(e){return vl.includes(e)}a(bl,"isTier2");function Js(e){return e.mode==="enforced"&&!bl(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Js,"severityFor");function Ve(e,t,n,r=1){let{severity:o,failsStrict:s}=Js(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}a(Ve,"baseViolation");function Jn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(Jn,"isInRuleLayer");function Qn(e,t,n){return t.filter(r=>!(!r.exported||!lt(r.file,e.appliesTo)||!Jn(r.file,e,n)))}a(Qn,"shapesForRule");function Sl(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}a(Sl,"evaluateAggregatePrivateState");function Cl(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}a(Cl,"evaluateAlwaysValidFactory");function wl(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}a(wl,"evaluateDomainEventOnMutation");function xl(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}a(xl,"evaluateOrchestrationOnly");function Ol(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}a(Ol,"evaluateThinAdapter");function Pl(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}a(Pl,"evaluateWritesViaAggregate");function _l(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}a(_l,"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(...Sl(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Cl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...wl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...xl(n,e));break;case"thin-adapter":t.push(...Ol(n,e));break;case"writes-via-aggregate":t.push(...Pl(n,e));break;case"no-anemic-model":t.push(..._l(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}a(Qs,"evaluateArkRuleSensors");function ea(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:i,failsStrict:l}=Js(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>lt(l,o.appliesTo)))continue;let i=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a(ea,"collectEmptyAppliesToFindings");var Nl=/\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)/,Tl=/\.(?: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,Dl=/\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*=)/,Ll=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Fl=/\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*=/,$l=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Ml(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(Fl.source,"g"))??[],r=t.match(new RegExp($l.source,"g"))??[],o=(t.match(/\bif\s*\(/g)??[]).length,s=(t.match(/\bswitch\s*\(/g)??[]).length,i=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&o+s>=6,l=Nl.test(t),c=Dl.test(t)||Ll.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&&Tl.test(t);return!i&&!h&&!p?null:{...i?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{},...p?{persistenceWrite:!0}:{}}}a(Ml,"deriveArkRuleFileHints");function ta(e){let t={};for(let[n,r]of Object.entries(e)){let o=Ml(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}a(ta,"buildArkRuleFileHints");function Kl(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}a(Kl,"normalizeExtraMergeTeethClassification");function er(e){let t=Kl(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}a(er,"extraMergeTeethAllowed");function na(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(na,"classifyResolvedLayerCoverage");var Hl=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Ff=new Set(Hl);function ra(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(ra,"isArkRunKernelModuleSpecifier");var Gl=["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"],ao=new Set(Gl);function oa(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(ao.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(ao.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:ao.has(e.slice(0,r))}a(oa,"isArkRunTransportBypassSpecifier");var Ul=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Wf=new Set(Ul);var sa={"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"},Vl="ARKRUN_INTERACTION_NAME_INCOMPLETE";function la(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(la,"isDomainRoleLayer");function jl(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(jl,"compareFindings");function ke(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:sa[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:sa[t],fromLayer:s?.fromLayer,target:s?.target})}}a(ke,"finding");function Bl(e,t){let n=[],r=[],o=[],s=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),o.push(...i.raises),s.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}a(Bl,"bagForFile");function aa(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(aa,"emitKinds");function ia(e){return e==="subscribe"||e==="register-handler"}a(ia,"handleKinds");function Wl(e){return e==="resolve"||e==="resolve-singleton"}a(Wl,"dependKinds");function ql(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 i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((g,m)=>g.file.localeCompare(m.file));if(l.length===0){r.push(ke(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(g=>g.hasKernelFactory))continue;let c=l[0];r.push(ke(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(ql,"evaluateMissingRoot");function zl(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!ra(c))continue;let g=r(l.from);g&&la(g,s.get(g)??[])&&i.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 i}a(zl,"evaluateKernelInDomain");function Yl(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(m=>[m.name,m.intentPrefixes??[]])),c=new Set(r.filter(m=>m.hasKernelFactory).map(m=>m.file)),g=[];for(let m of n){if(c.has(m.file))continue;let h=m.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let p=o(m.file);!p||!i.has(p)||la(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}a(Yl,"evaluateDirectNew");function Xl(e,t,n,r,o){let s=[],i=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:i};for(let c of t){if(!aa(c.kind)&&!ia(c.kind)&&!Wl(c.kind))continue;let g=r(c.file);if(!g||!l.has(g))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:Vl,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=Bl(n,c.file);if(aa(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(ia(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:i}}a(Xl,"evaluateUndeclared");function Zl(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!oa(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(ke(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}a(Zl,"evaluateTransportBypass");function ca(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=er(e.classification),r=Xl(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...ql(t,e.compositionRootHits,n),...zl(t,e.layers,e.dependencies,e.layerForFile,n),...Yl(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Zl(t,e.dependencies,e.layerForFile,n)].sort(jl),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,g=`${l.code}\0${l.file??""}\0${l.message}`;return c<g?-1:c>g?1:0});return{findings:o,completenessReasons:s}}a(ca,"evaluateArkRunSensors");function da(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(da,"isArkOrderModuleSpecifier");var pa={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Jl(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(Jl,"isDomainRoleLayer");function Ie(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:pa[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:pa[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Ie,"finding");function ua(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||!da(g))continue;let m=e.layerForFile(c.from);m&&Jl(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 i=t.xiKeys??[];i.length>t.maxXiKeys&&r.push(Ie(t,"arkorder-too-many-params","ark.config.json",1,`arkOrder.xiKeys has ${i.length} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(i.length)},n));for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(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 i.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:[]}}a(ua,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}a(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 i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(f=>f.name).filter(Boolean),...l.map(f=>f.name).filter(f=>!!f)]);i.length===0&&s.push(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 i){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 E;try{E=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 b=f.optional===!0||f.reserved===!0||f.allowEmpty===!0;!r.some(A=>E.test(A))&&!b&&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(i.length>1)for(let f of r){let u=-1,y=[];for(let E of i)for(let b of E.patterns??[]){if(!ge(b).test(f))continue;let A=_r(b,f);A>u?(u=A,y=[E.name]):A===u&&!y.includes(E.name)&&y.push(E.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&s.push(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=>!ae(f,i));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}a(tn,"collectAnalysisConfigWarnings");function Ql(e,t){return t.some(n=>{try{return ge(n).test(e)}catch{return!1}})}a(Ql,"matchesAny");function ec(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:E})=>({file:y,line:E})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:E})=>({file:y,line:E})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Ql(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),g=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),m=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),h={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:g,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],f=c.filter(y=>y.kind==="import");if(f.length>0){let y=f[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${f.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let u=c.filter(y=>y.kind==="require");if(u.length>0){let y=u[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let y=i[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(g.length>0){let y=g[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${g.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return m.length>0&&p.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${m.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:p}}a(ec,"evaluateSafety");function tc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(tc,"ambientForbiddenGlobal");function fa(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return eo(e,n.length>0?n:Qr.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(fa,"intentLayer");function nc(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let i=n.get(s.file);!i||!tc(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],g=s.source==="import-based"?t.dependencies.find(m=>m.from===s.file&&m.line===s.line&&m.specifier===s.symbol&&!m.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&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:i,target:s.symbol,...g?{edgeKind:g}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${m}".`});continue}}nt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...g?{edgeKind:g}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of 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:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=fa(s.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let s of t.intentReferences){let i=n.get(s.file);if(!i)continue;let l=fa(s.intent,e.contract);if(!l)continue;let c=me(e.contract.config.rules,i,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,message:c.message??`${i} must not reference ${l} intent ${s.intent}.`})}return r}a(nc,"contentViolations");function rc(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((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}),i=t.files.map(d=>({...d,layer:ae(d.path,e.contract.config.layers)??null})),l=new Map(i.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let N=d.target?l.get(d.target)??ae(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...N?{toLayer:N}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),g=tn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(d=>d.path)}),m=ec(e,t),h=e.contract.arkRules??Xt(),p=i.map(d=>d.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?ta(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Qs({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),fileHints:u}),...ea(h,p)],E=y.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),b=y.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),v=(h.invariants?.length??0)>0?Hs({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=na(i),_=ca({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),classification:k}),z=e.contract.config.arkRun?.mode,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}:{}})),bn=_.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=ua({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),classification:k}),vr=e.contract.config.arkOrder?.mode,Sn=ze.findings.filter(()=>vr==="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}:{}})),To=ze.findings.filter(()=>vr!=="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:i.filter(d=>d.layer).map(d=>d.path),contentViolations:[...nc(e,t,l),...E,...P,...pe,...Sn],edges:c,warnings:[...g,...m.warnings,...b,...j,...bn,...To],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:i,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:xe.violations,warnings:xe.warnings}}}a(rc,"analyzeCanonicalResolvedProject");function ct(e){return rc({contract:e.contract,facts:Ae(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}a(ct,"analyzeResolvedProject");function ga(e){return B(D(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(ga,"analysisTreeHash");function io(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 y=u.path.replace(/\\/g,"/"),E=Ge(u.path);if(!E||E===".."||E.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(E)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:E,line:1,message:`The atomic change set contains more than one operation for ${E}.`});continue}o.add(E),"delete"in u&&u.delete&&!n.has(E)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:E,line:1,message:`Cannot delete ${E} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:E,delete:!0}:{path:E,content:"content"in u?u.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=en({...e,changes:r}),l=new Map(i.ir.files.map(u=>[u.path,u])),c=i.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let y=l.get(u.evidence.file)?.layer;return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:u.message}}),g=Ue({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(u=>u.path),contentViolations:c,edges:i.ir.edges.filter(u=>!!u.fromLayer).map(u=>({from:u.from,fromLayer:u.fromLayer,...u.to?{to:u.to}:{},...u.toLayer?{toLayer:u.toLayer}:{},line:u.evidence.line,kind:"import",...u.typeOnly?{typeOnly:!0}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(u=>{let y=Ge(u.path),E=n.get(y),b=l.get(y);return{path:y,operation:"delete"in u&&u.delete?"delete":E?"update":"create",...E?{beforeContentHash:E.contentHash}:{},...b?{candidateContentHash:b.contentHash}:{}}}).sort((u,y)=>u.path.localeCompare(y.path)),h=[...s,...g.violations].map(u=>({...u,nextAction:le(u)})),p=h.filter(u=>u.failsStrict!==!1),f=e.changeMap?He({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:i.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&p.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:ga(t.ir.files),candidateTreeHash:ga(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:m,violations:h,warnings:g.warnings}}a(io,"preflightChange");function oc(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}a(oc,"canonicalChangePath");function sc(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}a(sc,"identityViolations");function ac(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}a(ac,"preparedChange");function lo(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])),i=new Map(n.files.map(f=>[f.path,f])),l=sc(t,n),c=new Map,g=[];for(let f of e.changes){let u=oc(f.path);if(!u){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(u)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:u,line:1,message:`The atomic change set contains more than one operation for ${u}.`});continue}c.set(u,f);let y=s.get(u),E=i.get(u);if("delete"in f&&f.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:u,line:1,message:`Cannot delete ${u} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:u,line:1,message:`Candidate facts still contain deleted file ${u}.`});else{let b="content"in f?f.content:"",A=B(b);E?E.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:u,line:1,expectedContentHash:A,candidateContentHash:E.contentHash,message:`Candidate facts for ${u} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:u,line:1,message:`Candidate facts do not contain changed file ${u}.`})}g.push(ac(f,u,s,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let f of new Set([...s.keys(),...i.keys()])){if(c.has(f))continue;let u=s.get(f),y=i.get(f);u&&y&&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?He({changeMap:e.changeMap,changes:g,baseDependencies:r.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:o.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0,h=[...l,...o.ir.violations].map(f=>({...f,nextAction:le(f)})),p=h.filter(f=>f.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:g.sort((f,u)=>f.path<u.path?-1:f.path>u.path?1:0),violations:h,warnings:o.ir.warnings}}a(lo,"preflightResolvedChange");var tr="docs/diagnostics.md",ma="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(I,"entry");var 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() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe."),I("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),I("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease then apply(ProposeResult), then preflight again. Never mechanical-safe."),I("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),I("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),I("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),I("ARKORDER_UNVALVED_RELEASE","arkorder","Unvalved second freeze of \u03BE","release() ran after a pattern was already frozen and the new \u03BE differs. First freeze is release(); later pattern change is proposeRelease then apply.","Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe."),I("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),I("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),I("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),I("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),I("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),I("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),I("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),I("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),I("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),I("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),I("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),I("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),I("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),I("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),I("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),I("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),I("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),I("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),I("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),I("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),I("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),I("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),I("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),I("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),I("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),I("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),I("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),I("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),I("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),I("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),co=new Map(nn.map(e=>[e.ruleId,e])),ya=Object.freeze(nn.map(e=>e.ruleId));function ha(e){return typeof e=="string"&&e.length>0&&co.has(e)}a(ha,"isKnownDiagnosticCode");function Ra(e){return typeof e!="string"||e.length===0?!1:co.has(e)?!0:e.startsWith("ARKRULE_")}a(Ra,"isCataloguedOrArkRuleFamily");function rn(e){if(!(typeof e!="string"||e.length===0))return co.get(e)}a(rn,"getDiagnosticCatalogEntry");function po(e){return`#${rn(e)?.docsAnchor??e}`}a(po,"diagnosticDocsFragment");function Aa(e){return`${tr}${po(e)}`}a(Aa,"diagnosticDocsPath");function ka(){return{schemaVersion:"1.0",docsPath:tr,codes:nn}}a(ka,"serializeDiagnosticCatalog");function Ia(e){return rn(e)?.fix}a(Ia,"catalogFixForRuleId");function va(e){return rn(e)?.why}a(va,"catalogWhyForRuleId");var Ea="1.1";var ba="1.0";var dt=class{static{a(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function ic(e){return typeof e.initialState=="function"?e.initialState():e.initialState}a(ic,"initialState");var nr=class{static{a(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)??ic(r),s=await r.project(t,o);await this.store.save(r.name,s);let i=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(i?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function on(e){return new nr(e)}a(on,"createProjectionRegistry");var sn="1.0";function lc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(lc,"policyId");var uo=class{constructor(t){this.data=t}data;static{a(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,i=e.projections,l=e.eventContracts,c=e.observability,g=t?t.list().map(b=>({name:b.name,dependencies:t.getDependencies(b.name),productions:t.getProductions(b.name)})):[],m=t?t.getAllRelationships():[],h=n?n.getPolicies().map(b=>({id:lc(b.name),name:b.name,severity:b.severity,tags:b.tags?[...b.tags]:void 0,owner:b.owner,version:b.version,rationale:b.rationale,enforcementMode:b.enforcementMode,deprecated:b.deprecated,replacedBy:b.replacedBy,description:b.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],f=o?o.toJSON():{nodes:[],edges:[]},u=p.filter(b=>(b.emits?.length??0)>0||(b.consumes?.length??0)>0).map(b=>({entity:b.name,emits:b.emits,consumes:b.consumes})),y=i?i.list().map(b=>({name:b.name,sourceIntents:b.sourceIntents,checkpoint:i.getCheckpoint(b.name)})):[],E={schemaVersion:"1.0",version: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 uo(E)}a(an,"createArkManifest");var Sa=0;function Ca(e){return Sa+=1,`${e}-${Date.now()}-${Sa}`}a(Ca,"createWorkflowId");function fo(e){return e instanceof Error?e.message:String(e)}a(fo,"errorMessage");function cc(e){return new Promise(t=>{setTimeout(t,e)})}a(cc,"sleep");async function dc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((i,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}a(dc,"withTimeout");var pt=class{static{a(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let i=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||i){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},go=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new pt}bus;options;static{a(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),i={id:r.id??Ca(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(i,r.tx),await this.audit("workflow.started",i,{workflowName:t}),this.executeSnapshot(i,o,r.tx)}async resume(t,n={}){let r=await this.get(t,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(t,n,r){try{let o=n.steps.filter(s=>!t.completedSteps.includes(s.name));for(let s of o)await this.runStep(t,s,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=fo(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let i=1;i<=s;i+=1){t.attempts[n.name]=i,await this.store.save(t,r);let l;try{l=await dc(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(i<s){o.delayMs&&await cc(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:i,error:fo(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:i});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(i=>t.completedSteps.includes(i.name));for(let i=s.length-1;i>=0;i-=1){let l=s[i];if(l.compensate)try{await Promise.resolve(l.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:l.name})}catch(c){await this.audit("workflow.step.failed",t,{step:l.name,compensation:!0,error:fo(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 go(e,t)}a(ut,"createWorkflowEngine");function mo(e,t,n={}){let r=ut(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??Ca(e.name),i="idle",l=[];return{id:s,definition:e,get status(){return i},get completedSteps(){return[...l]},async run(c){i="running",l=[];try{let g=await r.start(e.name,c,{id:s});i=g.status==="waiting"?"idle":g.status,l=[...g.completedSteps]}catch(g){let m=await r.get(s);throw i=m?.status==="waiting"?"idle":m?.status??"failed",l=m?.completedSteps??[],g}}}}a(mo,"createSaga");ft();function Oa(e){return Object.keys(e).sort()}a(Oa,"sortedKeys");function ko(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],g=Math.max(l.length,c.length);for(let m=0;m<g;m+=1)ko(l[m],c[m],`${n}[${m}]`,r);return}let o=e,s=t,i=new Set([...Oa(o),...Oa(s)]);for(let l of[...i].sort())ko(o[l],s[l],n?`${n}.${l}`:l,r)}a(ko,"walk");function Io(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}a(Io,"shadowInformationPackage");function or(e,t){let n=[];return ko(e,t,"",n),{equal:n.length===0,diffs:n}}a(or,"compareInformationPackages");function vo(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(or(e[n-1],e[n]));return t}a(vo,"replayInformationPackages");pr();Rn();vn();vn();async function En(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(()=>(Ha(),Ka));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}a(En,"startArkRunInspector");pr();vn();ft();Rn();ft();var Gc=new Set(["singleton","transient"]);function Ga(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return t}a(Ga,"cloneComponent");function Uc(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Gc.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(Uc,"closedLifetime");function Ua(){let e=new Map,t=new Map,n=new Set;function r(i){let l=e.get(i);if(!l)throw new Error(`ArkRun component "${i}" is not registered.`);return l}a(r,"mustRecord");function o(i,l){if(!l.factory)throw new Error(`ArkRun component "${i}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(i))throw new Error(`ArkRun component "${i}" has a circular resolve.`);n.add(i);try{return l.factory()}finally{n.delete(i)}}a(o,"instantiate");function s(i,l){if(t.has(i))return t.get(i);let c=o(i,l);return t.set(i,c),c}return a(s,"singleton"),{register(i){let l=typeof i?.id=="string"?i.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=Uc(i.lifetime),g=ho({id:l,lifetime:c,uses:i.uses,reactsTo:i.reactsTo,raises:i.raises,sends:i.sends,extendedInfo:i.extendedInfo});if(!g)throw new Error("ArkRun component id must be a non-empty string.");let m=typeof i.factory=="function"?i.factory:void 0;return e.set(l,{component:g,factory:m}),Ga(g)},resolve(i){let l=r(i);return l.component.lifetime==="transient"?o(i,l):s(i,l)},resolveSingleton(i){let l=r(i);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${i}" is transient; resolveSingleton requires lifetime "singleton".`);return s(i,l)},snapshotComponents(){return[...e.values()].map(i=>Ga(i.component))}}}a(Ua,"createComponentRegistry");Rn();function Vc(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}a(Vc,"stampMetadata");function jc(){}a(jc,"ignoreDetachedFailure");async function xo(e,t,n,r={}){let o=hn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Vc(r),i=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let l=Promise.resolve(e.broker.send(i));o.awaitHandoff?await l:l.then(void 0,jc)}return o}a(xo,"sendOnArkRunTransport");var Ar=1e3,Va=0;function Bc(){return Va+=1,`ark-kernel-${Date.now()}-${Va}`}a(Bc,"nextKernelInstanceId");function kt(e={}){let t=e.strict??!0,n=e.instanceId??Bc(),r=e.profile??Fe,o=e.maxHistorySize??Ar,s=bt(),i=Ft(),l=e.metadata??Ut(),c=e.auditTrail??Lt({maxRecords:o}),g=e.eventContracts??Tt(),m=e.eventBuffer??e.outbox??new be,h=e.projections??on({auditTrail:c}),p=new ve([xt(r),...e.policies??[]]),f=a(()=>{$t(s,i,{requireRegisteredTargets:!0})},"syncGraph"),u=e.ephemeral??!0,y=e.broker,E=new Ze({intentRegistry:s,dependencyGraph:i,policyEngine:p,strictRegistry:!0,validateIntentNaming:!0,auditTrail:c,eventContracts:g,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:m,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async k=>{await h.apply(k)}}),b=ut(E,{auditTrail:c}),A=Dt({registry:s,eventBus:E,graph:i}),v=Ua(),P=typeof y?.send=="function",j={instanceId:n,profile:r,registry:s,graph:i,metadata:l,auditTrail:c,eventContracts:g,eventBuffer:m,outbox:m,projections:h,policyEngine:p,eventBus:E,workflowEngine:b,observability:A,publisher(k){let _=E.createPublisher(k);return{source:_.source,publish:_.publish,send(z,pe,bn={}){return xo({eventBus:E,broker:y,defaultEphemeral:u},z,pe,{...bn,source:_.source})}}},send(k,_,z={}){return xo({eventBus:E,broker:y,defaultEphemeral:u},k,_,z)},register(k){return v.register(k)},resolve(k){return v.resolve(k)},resolveSingleton(k){return v.resolveSingleton(k)},getDependencyInformationPackage(){return 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 En(j,k)},syncGraph:f,manifest(){return f(),an({registry:s,policyEngine:p,metadata:l,graph:i,profile:r,projections:h,eventContracts:g,observability:A})}};return j}a(kt,"createArkKernel");function kr(e={}){return kt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}a(kr,"createStrictArkKernel");function Oo(e,t={}){let{profileName:n,...r}=t;return{...r,profile:Gt(e,{name:n})}}a(Oo,"createOptionsFromConfig");function Po(e,t={}){return kt(Oo(e,t))}a(Po,"createArkKernelFromConfig");function _o(e,t={}){return kr(Oo(e,t))}a(_o,"createStrictArkKernelFromConfig");function No(e,t={}){return Ir(Oo(e,t))}a(No,"createLenientArkKernelFromConfig");function Ir(e={}){return kt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}a(Ir,"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,appendDecisionTape,architecturalPolicies,arkRunGraphQueryFromSearchParams,arkRunInspectorUrl,buildArkRunInspectorSnapshot,buildDependencyInformationPackage,buildPublishPolicyContext,catalogFixForRuleId,catalogWhyForRuleId,checkAdapterGovernance,checkContract,classifyArkPolicyDelta,closeArkRunGraphQuery,closedArkRunEphemeral,closedArkRunTransportKind,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,compareInformationPackages,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,replayInformationPackages,requestArkRunGraph,resolveArkRunInspectorBind,resolveArkRunSendPlan,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,shadowInformationPackage,stableSerialize,startArkRunInspector,syncRegistryToGraph,toAdapterDiagnostic,validateIntentName,version});
20
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ds(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Ds,"isObject");function Xn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Xn,"propertyPath");function ft(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ft,"valueType");function Ga(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Ga,"resolveSchemaRef");function tn(e,t,n,r,o){if(t.$ref){let s=Ga(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}tn(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(!Ds(e)){o.push({path:n,message:`must be an object; received ${ft(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Xn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Xn(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||tn(e[l],a,Xn(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&tn(e[a],l,Xn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${ft(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)=>tn(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 ${ft(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 ${ft(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${ft(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(tn,"validateNode");function Va(e){let t={...e,$schema:e.$schema===void 0?Zn:e.$schema,schemaVersion:e.schemaVersion===void 0?ae:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Jn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=xs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Os(e.arkOrder)),t}i(Va,"defaultedConfig");function ja(e){return e===ae?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(ja,"migratedFromOf");function Ba(){let e=new Set([ae]);for(let t of Xr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Ba,"knownInputVersions");function Wa(e,t="ark.config.json"){if(!Ds(e))throw new Ie(t,[{path:"$",message:`must be an object; received ${ft(e)}`}]);let n=Ba(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ae}`}]);if(r!=="unversioned"&&!n.has(r))throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);let o=r,s={...e},a=0;for(;o!==ae&&a<Xr.length+1;){a+=1;let l=Xr.find(c=>c.from===o);if(!l)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ae}`}]);o=l.to,s.schemaVersion=o}if(o!==ae)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);return{candidate:Va(s),migratedFrom:ja(r)}}i(Wa,"migrateArkConfig");function Zr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Wa(e,t),o=[];if(tn(n,Ts,"$",Ts,o),Ps(n,o),_s(n,o),o.length>0)throw new Ie(t,o);return{config:n,migratedFrom:r}}i(Zr,"loadArkConfigContract");function Ls(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Ie(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Zr(n,t)}i(Ls,"parseArkConfigJson");function Fs(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Zn,schemaVersion:ae};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Fs,"withArkConfigMetadata");function qa(e){return e.endsWith(".")?e:`${e}.`}i(qa,"normalizePrefix");function za(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(za,"byLongestPrefix");function nn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(qa)})),n=[...t].sort(za),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(nn,"createArchitectureProfile");function rn(e,t={}){return nn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}i(rn,"createArchitectureProfileFromArkConfig");var Ya=[{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}],qe=nn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ya,rules:Jn.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 Jr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Fs({include:e.include??[t],layers:qe.layers.map(o=>({name:o.name,patterns:(Xa[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...qe.rules]})}i(Jr,"createElevenLayerArkConfig");var Qn=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 on(){return new Qn}i(on,"createMetadataRegistry");function Qr(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}i(Qr,"definePort");function eo(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(f=>!Ms(t,f));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=er(a);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
21
+ `));return a}i(eo,"createAdapter");function to(e,t=[]){let n=t.filter(r=>!Ms(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(to,"checkContract");function er(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(er,"checkAdapterGovernance");function Ms(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(Ms,"hasMember");var ro=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),so=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),io=Object.freeze(Object.keys(so).sort()),no=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"}),oo=Object.freeze({process:Object.freeze(["process","node:process"])});function sn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=no[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=no[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:no[e.slice(0,s)]??null}i(sn,"capabilityForModuleSpecifier");function Pe(e,t){for(let n of t)if(oo[n]?.includes(e))return n;return null}i(Pe,"forbiddenGlobalForModuleSpecifier");function tr(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=so[r];if(o)return o}return null}i(tr,"capabilityForAmbientName");function mt(e){if(e?.pure===!0)return[...ro].sort();let n=(e?.capabilities?.deny??[]).filter(r=>ro.includes(r));return[...new Set(n)].sort()}i(mt,"effectiveCapabilityDeny");function an(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(an,"ambientCoveredByForbiddenGlobals");function nr(e){let t=new Set,n=new Set,r=Object.keys(so);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 oo[o]??[])t.add(`import-exact:${a}`)}for(let o of mt(e)){if(t.add(`import:${o}`),o==="process")for(let s of oo.process)t.add(`import-exact:${s}`);for(let s of r)tr(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(nr,"loweredLayerCoverage");function gt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(gt,"literalText");function Hs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Hs,"lineOf");function $s(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($s,"isTypeOnlyReference");function Us(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(Us,"singleFileChecker");function ao(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(ao,"symbolAt");function lo(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):ao(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(lo,"localDeclaration");function ze(e,t){let n,r=[],o=i((a,l,c,f=!1)=>r.push({specifier:c,kind:l,line:Hs(t,a),typeOnly:f,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",gt(e,a.moduleSpecifier),$s(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",gt(e,a.moduleSpecifier),$s(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",gt(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!lo(e,n??(n=Us(e,t)),t,a.expression);(l||f)&&o(a,f?"require":"dynamic-import",gt(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(ze,"extractSemanticDependencies");function Za(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=gt(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(Za,"staticAccessPath");function Ja(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(Ja,"runtimeIdentifierReference");function Ks(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(Ks,"bestForbiddenMatch");function Ye(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Us(e,t),s=new Map,a=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let u of p.declarationList.declarations)e.isIdentifier(u.name)&&a.add(u.name.text);let l=i(p=>{let u=Za(e,p);if(!u)return;let m=ao(o,u.root),y=m?s.get(m):void 0;return y?[...y,...u.segments.slice(1)]:lo(e,o,t,u.root)||a.has(u.root.text)?void 0:u.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let u of p.declarationList.declarations){if(!u.initializer||!e.isIdentifier(u.name))continue;let m=l(u.initializer),y=ao(o,u.name);!m||!y||s.set(y,m)}let c=[],f=new Set,g=i((p,u)=>{let m=Hs(t,u),y=`${p}:${u.getStart(t)}`;f.has(y)||(f.add(y),c.push({name:p,line:m,node:u}))},"flag"),h=i(p=>{let u=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!u){let m=l(p),y=m?Ks(r,m):void 0;y&&g(y,p)}else e.isIdentifier(p)&&r.has(p.text)&&Ja(e,p)&&!lo(e,o,t,p)&&g(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let m=l(p.initializer);if(m)for(let y of p.name.elements){if(!e.isIdentifier(y.name))continue;let v=y.propertyName?gt(e,y.propertyName)??y.propertyName.text:y.name.text,E=Ks(r,[...m,v]);E&&g(E,p.initializer)}}e.forEachChild(p,h)},"visit");return h(t),c}i(Ye,"collectForbiddenCapabilityUses");function co(e,t,n){let r=[];for(let o of n?.dependencies??ze(e,t)){if(o.typeOnly||!o.specifier)continue;let s=sn(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ye(e,t,io)){let s=tr(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(co,"collectCapabilityUses");var po={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."},uo=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 fo(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(fo,"resolveIntentLayer");function Xe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Xe,"looksLikeArkIntent");function ln(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Xe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:po.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:po.PUBLISH_MISSING_SOURCE}),t}i(ln,"classifyPublishFacts");function j(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(j,"violation");function yt(e,t){return e.slice(0,t).split(`
22
+ `).length}i(yt,"lineOf");function Qa(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(Qa,"extractQuotedStrings");function el(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(el,"extractModuleSpecifiers");function tl(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(tl,"extractQuotedStringsAst");function nl(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(nl,"hasInfrastructureToken");function rl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(rl,"isKnownInfrastructurePackage");function ol(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(ol,"layerHasInfrastructureRole");function dn(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(dn,"tsStringLiteralText");function sl(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(sl,"tsPropertyName");function Gs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:sl(e,r.name)===n)}i(Gs,"tsObjectProperty");function pn(e,t,n){return Gs(e,t,n)!==void 0}i(pn,"tsObjectHasProperty");function cn(e,t,n){let r=Gs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(cn,"tsObjectPropertyValue");function il(e,t){let n=cn(e,t,"metadata");return pn(e,n,"source")}i(il,"tsObjectHasMetadataSource");function Vs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Vs(e,t.name):!1:!1}i(Vs,"tsLooksLikeIntentCreatorExpression");function al(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(al,"tsIsPublishCall");function ll(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=dn(e,n);return r!==void 0&&Xe(r)||pn(e,n,"intent")||Vs(e,n)}i(ll,"tsIsArkPublishCandidate");function cl(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return il(e,n)||pn(e,r,"source")||pn(e,o,"source")}i(cl,"tsPublishHasSource");function dl(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=cn(e,n,"metadata");return dn(e,cn(e,s,"source"))??dn(e,cn(e,r,"source"))??dn(e,cn(e,o,"source"))}i(dl,"tsPublishSourceLiteral");function pl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],f=i(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),g=i(h=>{if(al(e,h)){let p=h.arguments[0],u=dn(e,p);for(let y of ln({publishCall:!0,rawIntentName:u,objectHasIntent:pn(e,p,"intent"),arkPublishCandidate:ll(e,h),hasSource:cl(e,h)}))c.push(j(y.ruleId,y.message,{line:f(h),filePath:a}));let m=dl(e,h);if(r&&l&&m&&Xe(m)){let y=r.resolveLayer(m);y&&y!==l&&c.push(j("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${m}" resolves to ${y}, but the target file is classified as ${l}.`,{line:f(h),filePath:a,target:m,fromLayer:l,toLayer:y}))}}e.forEachChild(h,g)},"visit");return g(o),c}i(pl,"analyzePublishAst");function mo(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,f=c?.filePath,g=c?.layer,h=e.typescript,p=h?h.createSourceFile(f??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,u=p?ze(e.typescript,p):void 0,m=u?u.filter(A=>A.specifier!==void 0).map(A=>({value:A.specifier,index:A.node.getStart(p),kind:A.kind,typeOnly:A.typeOnly})):el(s),y=e.typescript?tl(e.typescript,s):Qa(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(f))for(let A of u?.filter(({unresolved:b})=>b)??[]){let b=A.kind==="require";l.push(j(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:f}))}let v=g!==void 0&&(r.has(g)||ol(g)),E=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let A of n)if(A instanceof RegExp){A.lastIndex=0;let b=A.exec(s);A.lastIndex=0,b&&l.push(j("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:b.index===void 0?void 0:yt(s,b.index),filePath:f,suggestion:"Remove infrastructure imports from domain/application layers."+E}))}else s.includes(A)&&l.push(j("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:yt(s,s.indexOf(A)),filePath:f}));for(let A of m){let b=e.resolveImportTarget?.(A.value,f)??(e.resolveImportLayer?{layer:e.resolveImportLayer(A.value,f)}:void 0),O=typeof f=="string"?e.resolveImportTarget?.(f)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,L=b?.layer;if(L&&g){let I=ke(e.architectureProfile?.rules,g,L,{fromPath:O?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(I){if(A.typeOnly&&!I.peerIsolation)continue;let N=!!I.peerIsolation;l.push(j("LAYER_IMPORT_VIOLATION",I.message??(N?`Layer "${g}" must not import across slices into "${L}".`:`Layer "${g}" must not import "${L}".`),{line:yt(s,A.index),source:A.value,target:A.value,filePath:f,fromLayer:g,toLayer:L,suggestion:N?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:A.kind,peerIsolation:N,...A.typeOnly?{typeOnly:!0}:{}}}));continue}continue}v||A.typeOnly||!nl(A.value)&&!rl(A.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:yt(s,A.index),source:A.value,target:A.value,filePath:f,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+E,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let b=A.check({source:s,context:a});if(b!==!0)if(Array.isArray(b))for(let O of b)l.push(j("POLICY_VIOLATION",O.message,{filePath:f,suggestion:`Fix violation of policy "${A.name}".`}));else b===!1?l.push(j("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(j("POLICY_VIOLATION",b.message))}if(o&&t.size>0)for(let A of y)Xe(A.value)&&!t.has(A.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:yt(s,A.index),filePath:f,target:A.value,suggestion:`Register intent "${A.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let A of y){if(!Xe(A.value))continue;let b=e.architectureProfile.resolveLayer(A.value);if(!b)continue;let O=ke(e.architectureProfile.rules,g,b);O&&l.push(j("LAYER_REFERENCE_VIOLATION",O.message??`Layer "${g}" must not reference "${b}" through "${A.value}".`,{line:yt(s,A.index),filePath:f,target:A.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O}}))}if(e.extensions)for(let A of e.extensions)try{let b=A.analyze(s,a);l.push(...b)}catch(b){l.push(j("EXTENSION_ERROR",`Extension "${A.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&p&&g&&e.forbiddenGlobals?.[g]?.length)try{let A=e.forbiddenGlobals[g];l.push(...Ye(e.typescript,p,A).map(b=>j("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:f,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of u??[]){if(b.typeOnly||!b.specifier)continue;let O=Pe(b.specifier,A);O&&l.push(j("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${O}".`,{line:b.line,filePath:f,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:O},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript&&p&&g&&e.capabilityWalls?.[g]?.length)try{let A=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let O of co(e.typescript,p))A.has(O.capability)&&(O.source==="ambient-global"&&an(O.symbol,b)||O.source==="import-based"&&Pe(O.symbol,b)||l.push(j("CAPABILITY_VIOLATION",O.source==="import-based"?`${g} denies the ${O.capability} capability; found import of "${O.symbol}".`:`${g} denies the ${O.capability} capability; found ambient "${O.symbol}".`,{line:O.line,filePath:f,target:O.symbol,capability:O.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript)try{l.push(...pl(e.typescript,s,a,e.architectureProfile))}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(mo,"createAICodeGate");function W(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(W,"deterministicHash");function F(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(F).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${F(t[n])}`).join(",")}}`}i(F,"stableSerialize");var _e="1.2";var js=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=F(e),r=F(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 Rt(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 W(F(t))}i(Rt,"resolvedFactsEvidenceRequirementsHash");function ul(e){let t=e.completenessReasons.map(I=>({code:I.code,message:I.message,...I.file?{file:I.file}:{}})).sort(B),n=e.files.map(I=>({...I,typeOnlyExportNames:q(I.typeOnlyExportNames)})).sort((I,N)=>I.path<N.path?-1:I.path>N.path?1:0),r=e.dependencies.map(I=>({...I,...I.namedBindings?{namedBindings:q(I.namedBindings)}:{}})).sort(B),o=e.capabilityUses.map(I=>({...I})).sort(B),s=e.ambientUses.map(I=>({...I})).sort(B),a=e.publishCalls.map(I=>({...I})).sort(B),l=e.intentReferences.map(I=>({...I})).sort(B),c=e.safetyUses.map(I=>({...I})).sort(B),f=(e.classShapes??[]).map(I=>({...I,mutatingMethods:[...I.mutatingMethods??[]].map(N=>({...N}))})).sort(B),g=(e.arkRunKernelCalls??[]).map(I=>({...I})).sort(B),h=(e.arkRunManagedNews??[]).map(I=>({...I})).sort(B),p=(e.arkRunCompositionRootHits??[]).map(I=>({...I})).sort(B),u=(e.arkRunDeclarations??[]).map(I=>({...I,uses:q(I.uses),reactsTo:q(I.reactsTo),raises:q(I.raises),sends:q(I.sends)})).sort(B),m=(e.arkOrderPlaneCalls??[]).map(I=>({...I})).sort(B),y=(e.arkOrderGenericUpdates??[]).map(I=>({...I})).sort(B),v=(e.arkOrderRootHits??[]).map(I=>({...I})).sort(B),E=(e.arkOrderXiFieldWrites??[]).map(I=>({...I})).sort(B),A=(e.arkOrderIngestWritesXi??[]).map(I=>({...I})).sort(B),b=(e.arkOrderReleaseKeyCounts??[]).map(I=>({...I})).sort(B),O=e.files.map(({path:I,contentHash:N})=>({path:I,contentHash:N})).sort((I,N)=>I.path<N.path?-1:I.path>N.path?1:0),L=W(F(O));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:L,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:f,arkRunKernelCalls:g,arkRunManagedNews:h,arkRunCompositionRootHits:p,arkRunDeclarations:u,arkOrderPlaneCalls:m,arkOrderGenericUpdates:y,arkOrderRootHits:v,arkOrderXiFieldWrites:E,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:b}}i(ul,"canonicalResolvedFactsInput");function Bs(e){let t=ul(e);return{...t,factsHash:W(F(t))}}i(Bs,"createCanonicalResolvedCandidateFacts");function rr(e){return Bs(qs(M(e,"$"),!1))}i(rr,"createResolvedCandidateFacts");function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(M,"asRecord");function K(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(K,"assertOnlyKeys");function D(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(D,"requiredText");function be(e,t,n){if(e[t]!==void 0)return D(e,t,n)}i(be,"optionalText");function H(e,t,n){let r=D(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(H,"requiredProjectPath");function U(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(U,"requiredBoolean");function Ws(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(Ws,"requiredInteger");function Y(e,t,n){let r=Ws(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Y,"requiredPositiveInteger");function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(G,"requiredArray");function Ee(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(Ee,"enumValue");function ht(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(ht,"parseStringArray");function fl(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(fl,"assertUnique");function qs(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ee(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ee(e,"completeness",["complete","partial","unavailable"],"$"),o=G(e,"completenessReasons","$").map((S,w)=>{let R=`$.completenessReasons[${w}]`,d=M(S,R);K(d,["code","message","file"],R);let _=d.file===void 0?void 0:H(d,"file",R);return{code:D(d,"code",R),message:D(d,"message",R),..._?{file:_}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=G(e,"files","$").map((S,w)=>{let R=`$.files[${w}]`,d=M(S,R);return K(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:H(d,"path",R),contentHash:D(d,"contentHash",R),parseStatus:Ee(d,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:Ws(d,"parseDiagnosticCount",R),exportsOnlyTypes:U(d,"exportsOnlyTypes",R),typeOnlyExportNames:ht(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:U(d,"hasTopLevelSideEffects",R)}}),a=G(e,"dependencies","$").map((S,w)=>{let R=`$.dependencies[${w}]`,d=M(S,R);K(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let _=be(d,"specifier",R),$=be(d,"target",R),se=Ee(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(se==="resolved-project"&&!$)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(se!=="resolved-project"&&$)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(se!=="dynamic"&&!_)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:H(d,"from",R),..._?{specifier:_}:{},kind:Ee(d,"kind",["import","export","dynamic-import","require"],R),typeOnly:U(d,"typeOnly",R),line:Y(d,"line",R),resolution:se,...$?{target:H(d,"target",R)}:{},...d.namedBindings!==void 0?{namedBindings:ht(d.namedBindings,`${R}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:U(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:U(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:U(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:U(d,"portProofEligible",R)}:{}}}),l=G(e,"capabilityUses","$").map((S,w)=>{let R=`$.capabilityUses[${w}]`,d=M(S,R);return K(d,["file","line","symbol","capability","source"],R),{file:H(d,"file",R),line:Y(d,"line",R),symbol:D(d,"symbol",R),capability:Ee(d,"capability",js,R),source:Ee(d,"source",["ambient-global","import-based"],R)}}),c=G(e,"ambientUses","$").map((S,w)=>{let R=`$.ambientUses[${w}]`,d=M(S,R);return K(d,["file","line","symbol"],R),{file:H(d,"file",R),line:Y(d,"line",R),symbol:D(d,"symbol",R)}}),f=G(e,"publishCalls","$").map((S,w)=>{let R=`$.publishCalls[${w}]`,d=M(S,R);K(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let _=be(d,"rawIntentName",R),$=be(d,"sourceIntent",R);return{file:H(d,"file",R),line:Y(d,"line",R),..._?{rawIntentName:_}:{},objectHasIntent:U(d,"objectHasIntent",R),arkPublishCandidate:U(d,"arkPublishCandidate",R),hasSource:U(d,"hasSource",R),...$?{sourceIntent:$}:{}}}),g=G(e,"intentReferences","$").map((S,w)=>{let R=`$.intentReferences[${w}]`,d=M(S,R);return K(d,["file","line","intent"],R),{file:H(d,"file",R),line:Y(d,"line",R),intent:D(d,"intent",R)}}),h=G(e,"safetyUses","$").map((S,w)=>{let R=`$.safetyUses[${w}]`,d=M(S,R);K(d,["file","line","kind","symbol"],R);let _=be(d,"symbol",R),$=Ee(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if($==="in-memory-store"&&!_)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if($!=="in-memory-store"&&_)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:H(d,"file",R),line:Y(d,"line",R),kind:$,..._?{symbol:_}:{}}});fl(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 m=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((S,w)=>{let R=`$.arkRunKernelCalls[${w}]`,d=M(S,R);K(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let _=be(d,"receiver",R),$=be(d,"nameLiteral",R);return{file:H(d,"file",R),line:Y(d,"line",R),kind:Ee(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:D(d,"callee",R),viaImport:U(d,"viaImport",R),..._?{receiver:_}:{},...$?{nameLiteral:$}:{}}}),v=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((S,w)=>{let R=`$.arkRunManagedNews[${w}]`,d=M(S,R);K(d,["file","line","typeName","importedFrom"],R);let _=be(d,"importedFrom",R);return{file:H(d,"file",R),line:Y(d,"line",R),typeName:D(d,"typeName",R),..._?{importedFrom:_}:{}}}),A=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((S,w)=>{let R=`$.arkRunCompositionRootHits[${w}]`,d=M(S,R);return K(d,["file","matchedRoot","hasKernelFactory"],R),{file:H(d,"file",R),matchedRoot:D(d,"matchedRoot",R),hasKernelFactory:U(d,"hasKernelFactory",R)}}),b=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),L=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((S,w)=>{let R=`$.arkOrderPlaneCalls[${w}]`,d=M(S,R);return K(d,["file","line","callee"],R),{file:H(d,"file",R),line:Y(d,"line",R),callee:D(d,"callee",R)}}),N=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((S,w)=>{let R=`$.arkOrderGenericUpdates[${w}]`,d=M(S,R);return K(d,["file","line","method"],R),{file:H(d,"file",R),line:Y(d,"line",R),method:D(d,"method",R)}}),ye=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((S,w)=>{let R=`$.arkOrderRootHits[${w}]`,d=M(S,R);return K(d,["file","matchedRoot","hasPlaneFactory"],R),{file:H(d,"file",R),matchedRoot:D(d,"matchedRoot",R),hasPlaneFactory:U(d,"hasPlaneFactory",R)}}),T=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((S,w)=>{let R=`$.arkOrderXiFieldWrites[${w}]`,d=M(S,R);return K(d,["file","line","key"],R),{file:H(d,"file",R),line:Y(d,"line",R),key:D(d,"key",R)}}),Z=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((S,w)=>{let R=`$.arkOrderIngestWritesXi[${w}]`,d=M(S,R);return K(d,["file","line"],R),{file:H(d,"file",R),line:Y(d,"line",R)}}),Ft=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((S,w)=>{let R=`$.arkOrderReleaseKeyCounts[${w}]`,d=M(S,R);return K(d,["file","line","keyCount"],R),{file:H(d,"file",R),line:Y(d,"line",R),keyCount:Y(d,"keyCount",R)}}),Mt=b.map((S,w)=>{let R=`$.arkRunDeclarations[${w}]`,d=M(S,R);return K(d,["file","line","uses","reactsTo","raises","sends"],R),{file:H(d,"file",R),line:Y(d,"line",R),uses:ht(d.uses,`${R}.uses`),reactsTo:ht(d.reactsTo,`${R}.reactsTo`),raises:ht(d.raises,`${R}.raises`),sends:ht(d.sends,`${R}.sends`)}});for(let[S,w]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",f],["$.intentReferences",g],["$.safetyUses",h],["$.arkRunKernelCalls",m],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",Mt],["$.arkOrderPlaneCalls",L],["$.arkOrderGenericUpdates",N],["$.arkOrderRootHits",ye],["$.arkOrderXiFieldWrites",T],["$.arkOrderIngestWritesXi",Z],["$.arkOrderReleaseKeyCounts",Ft]])for(let R of w)if(!p.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let Ke=be(e,"projectPackageName","$"),Fr=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((S,w)=>{let R=`$.classShapes[${w}]`,d=M(S,R);K(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let _=G(d,"mutatingMethods",R).map(($,se)=>{let Un=`${R}.mutatingMethods[${se}]`,Mr=M($,Un);return K(Mr,["name","referencesGuardOrPublish"],Un),{name:D(Mr,"name",Un),referencesGuardOrPublish:U(Mr,"referencesGuardOrPublish",Un)}});return{file:H(d,"file",R),className:D(d,"className",R),exported:U(d,"exported",R),hasPublicMutableFields:U(d,"hasPublicMutableFields",R),hasPublicSetters:U(d,"hasPublicSetters",R),hasPublicConstructor:U(d,"hasPublicConstructor",R),hasStaticFactory:U(d,"hasStaticFactory",R),mutatingMethods:_,...d.dataOnly===void 0?{}:{dataOnly:U(d,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:D(e,"resolverIdentity","$"),compilerIdentity:D(e,"compilerIdentity","$"),compilerOptionsHash:D(e,"compilerOptionsHash","$"),tsconfigHash:D(e,"tsconfigHash","$"),evidenceRequirementsHash:D(e,"evidenceRequirementsHash","$"),...Ke?{projectPackageName:Ke}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:f,intentReferences:g,safetyUses:h,classShapes:Fr,arkRunKernelCalls:m,arkRunManagedNews:v,arkRunCompositionRootHits:A,arkRunDeclarations:Mt,arkOrderPlaneCalls:L,arkOrderGenericUpdates:N,arkOrderRootHits:ye,arkOrderXiFieldWrites:T,arkOrderIngestWritesXi:Z,arkOrderReleaseKeyCounts:Ft}}i(qs,"parseResolvedFactsInput");function ve(e){let t=M(e,"$"),n=D(t,"factsHash","$"),r=D(t,"candidateTreeHash","$"),o=Bs(qs(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(ve,"loadResolvedCandidateFacts");var ml=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},J={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},or={$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:J,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:J,symbol:x,capability:{enum:ml},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:J,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:J,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:J,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:J,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:J,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:J,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:J,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:J,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:J,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:V,line:J,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:J}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:J,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 sr="1.0";function ne(e){return`${e.from}->${e.to}`}i(ne,"dependencyKey");function un(e,t,n,r="dependency"){return{id:`${e}:${r}:${ne(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ne(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ne(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ne(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ne(t)} from the candidate, then preflight again.`}:{}}}i(un,"dependencyFinding");function Ze(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=>[ne(p),p])),s=new Map(e.baseDependencies.map(p=>[ne(p),p])),a=new Map(e.candidateDependencies.map(p=>[ne(p),p]));for(let p of[...n.values()].sort((u,m)=>u.path.localeCompare(m.path))){let u=r.get(p.path);u?u.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:u.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${u.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:u.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((u,m)=>u.path.localeCompare(m.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((u,m)=>ne(u).localeCompare(ne(m)))){if(a.has(ne(p))){t.push(un("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let u={from:p.to,to:p.from};a.has(ne(u))?(l.add(ne(u)),t.push(un("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(un("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,u]of[...a].sort(([m],[y])=>m.localeCompare(y)))s.has(p)||o.has(p)||l.has(p)||!c.has(u.from)&&!c.has(u.to)||t.push({...un("unplanned",u,`${u.from} -> ${u.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,u]of[...s].sort(([m],[y])=>m.localeCompare(y)))a.has(p)||f.has(u.from)||f.has(u.to)||!c.has(u.from)&&!c.has(u.to)||t.push({...un("unplanned",u,`${u.from} -> ${u.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((p,u)=>g[p.classification]-g[u.classification]||(p.subject===u.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(u.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(Ze,"analyzeArchitectureConvergence");var zs="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",gl=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Ys={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},kf={$schema:"https://json-schema.org/draft/2020-12/schema",$id:zs,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:zs},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:[...gl]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ys,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:Ys}}}};function fn(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(fn,"emptyEffectiveArkRules");function go(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}i(go,"omitLayerDescriptions");function Xs(e){let{stewards:t,...n}=go(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(Xs,"effectiveContractPolicyPayload");function Zs(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(Zs,"formatCoverageDiscards");function yl(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(yl,"isUnderCoverageRoot");function hl(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(hl,"titleMatchesInvariant");function Rl(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(Rl,"symbolPresent");function Js(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=Zs(s),l=Zs(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",f=(e.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),g=f.length>0,h=f.join(", "),p=[],u=[];for(let m of t){let y=[],v=m.coverage?.test!==!1,E=m.coverage?.symbol,A,b;if(!r&&v){let N;for(let te of n){let ye=e.fileContents[te];if(!(!ye||!hl(ye,m.id))){if(!g||yl(te,f)){A=te,b=g?!1:void 0;break}N??=te}}A===void 0&&N!==void 0&&(A=N,b=!0),A!==void 0&&y.push("test-title")}E&&Rl(e.fileContents,E)&&y.push("symbol");let L=(m.coverage?.test===!0||!!E||m.coverage===void 0)&&y.length>0||m.coverage?.test===!1&&!E?!0:y.length>0,I=r&&v&&y.length===0;if(p.push({invariantId:m.id,layer:m.provenance.layer,sourceFile:m.provenance.sourceFile,mode:m.mode,covered:L&&!I,evidence:y,partial:I,description:m.description,...A!==void 0?{testEvidenceFile:A}:{},...b!==void 0?{outsideDeclaredRoots:b}:{}}),b===!0&&A!==void 0&&u.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${m.id} is covered only by ${A}, which is outside the declared coverage roots (${h}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:A,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:"warning",failsStrict:!1}),!L||I){let N=m.mode==="enforced"&&!I,te=r||n.length===0?"never-had-tests":"tests-disappeared";u.push({ruleId:"INVARIANT_UNCOVERED",message:(I?o?`Invariant ${m.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${m.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:te==="tests-disappeared"?`Invariant ${m.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${m.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(I&&o?l:a),file:m.provenance.sourceFile,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:N?"error":"warning",failsStrict:N,kind:te})}}return{coverage:p,violations:u,partial:p.some(m=>m.partial)}}i(Js,"evaluateInvariantCoverage");function Qs(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(Qs,"canPromoteInvariant");var ar="1.0";function P(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(P,"addFinding");function z(e){return[...new Set(e??[])].sort()}i(z,"sortedUnique");function de(e,t,n,r,o){let s=z(n),a=z(r),l=new Set(s),c=new Set(a),f=a.filter(h=>!l.has(h)),g=s.filter(h=>!c.has(h));f.length===0&&g.length===0||(f.length>0&&P(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),g.length>0&&P(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(de,"compareStringSets");function mn(e,t,n,r,o,s,a){if(n===r)return;P(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(mn,"compareBoolean");function ir(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(ir,"keyed");function Al(e,t,n){let r=ir(t,s=>s.name),o=ir(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&P(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!a&&l){P(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){P(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;de(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),de(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=nr(a),g=nr(l);de(e,`${c}.forbiddenGlobals`,f.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),de(e,`${c}.capabilities`,f.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),z(a.intentPrefixes).join("\0")!==z(l.intentPrefixes).join("\0")&&P(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:z(a.intentPrefixes),after:z(l.intentPrefixes)}),mn(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."),mn(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(Al,"compareLayers");function kl(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=ir(t,r),s=ir(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&P(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(a),c=s.values.get(a),f=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&P(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&P(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&P(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let g=l.peerIsolation===!0,h=c.peerIsolation===!0;if(g!==h){let p=l.from===l.to&&c.from===c.to;P(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.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:g,after:h})}z(l.sliceFolders).join("\0")!==z(c.sliceFolders).join("\0")&&P(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:z(l.sliceFolders),after:z(c.sliceFolders)}),!(!g&&!h)&&(ti(e,`${f}.sharedRoots`,"shared-roots",z(l.sharedRoots),z(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."),ti(e,`${f}.allowedCrossSlice`,"cross-slice-allowance",z((l.allowedCrossSlice??[]).map(ei)),z((c.allowedCrossSlice??[]).map(ei)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(kl,"compareRules");function ei(e){return JSON.stringify([e.from,e.to])}i(ei,"crossSliceKey");function ti(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(g=>!r.includes(g)),c=r.filter(g=>!o.includes(g)),f=l.length>0&&c.length>0;P(e,{kind:f?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:f?"judgment-required":l.length>0?"weakening":"strengthening",message:f?`${s} Entries were added and removed in the same change.`:l.length>0?s:a,before:r,after:o})}i(ti,"compareDeclaredExceptions");function Il(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,l=o[s]??0;a!==l&&P(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])mn(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Il,"compareSafety");function yo(e){return e.mode==="enforced"?"enforced":"advisory"}i(yo,"arkRunMode");function ho(e){return e.mode==="enforced"?"enforced":"advisory"}i(ho,"arkOrderMode");function bl(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${ho(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=ho(r),l=ho(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}de(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),de(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(bl,"compareArkOrder");function El(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${yo(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=yo(r),l=yo(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}de(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),de(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),mn(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(El,"compareArkRun");function vl(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(vl,"overallClassification");function ni(e,t){return`${e}::${t}`}i(ni,"ruleKey");function ri(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(ni(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(ni(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(ri,"indexEffectiveRules");function Sl(e,t,n,r,o,s){let a=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},f=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of f){let u=l[p],m=c[p],y=`$.arkRules[${p}]`;if(u===void 0&&m!==void 0){P(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:m});continue}if(u!==void 0&&m===void 0){P(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:u});continue}u!==m&&P(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:u,after:m})}let g=ri(r),h=ri(o);for(let p of[...new Set([...g.structure.keys(),...h.structure.keys()])].sort()){let u=g.structure.get(p),m=h.structure.get(p),y=`$.arkRules.structure[${p}]`;if(!u&&m){P(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${m.id} was added (${m.mode}).`,after:m});continue}if(u&&!m){P(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${u.id} was removed.`,before:u});continue}if(!(!u||!m)){if(u.mode!==m.mode){let v=u.mode==="advisory"&&m.mode==="enforced";P(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${m.id} was promoted to enforced.`:`Structure ArkRule ${m.id} was demoted to advisory.`,before:u.mode,after:m.mode})}u.sensor!==m.sensor&&P(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${m.id} changed sensor identity.`,before:u.sensor,after:m.sensor})}}for(let p of[...new Set([...g.invariants.keys(),...h.invariants.keys()])].sort()){let u=g.invariants.get(p),m=h.invariants.get(p),y=`$.arkRules.invariants[${p}]`;if(!u&&m){P(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${m.id} was added (${m.mode}).`,after:m});continue}if(u&&!m){P(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${u.id} was removed.`,before:u});continue}if(!(!u||!m)&&u.mode!==m.mode)if(u.mode==="advisory"&&m.mode==="enforced"){let E=a?.get(m.id),A=Qs(E);A.ok?P(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${m.id} was promoted to enforced (coverage evidence present).`,before:u.mode,after:m.mode}):P(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${m.id} cannot be promoted to enforced: ${A.reason}`,before:u.mode,after:m.mode})}else P(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${m.id} was demoted to advisory.`,before:u.mode,after:m.mode})}}i(Sl,"compareArkRules");function lr(e,t,n){let r=[];de(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),de(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),de(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),mn(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";P(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&P(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Al(r,e.layers,t.layers),kl(r,e.rules,t.rules),Il(r,e,t),Sl(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),El(r,e,t),bl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:ar,classification:vl(r),findings:r}}i(lr,"classifyArkPolicyDelta");function cr(e,t){if(!e||e.schemaVersion!==ar||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=z(e.findingIds),r=z(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(cr,"policyDeltaAcknowledgementMatches");function Je(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(Je,"normalizePath");function oi(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(oi,"isIdentifierStart");function dr(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(dr,"isIdentifierCharacter");function re(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(re,"skipWhitespace");function gn(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(gn,"readString");function le(e,t,n){return e.startsWith(t,n)&&!dr(e[n-1])&&!dr(e[n+t.length])}i(le,"isWordAt");function si(e,t){let n=re(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=re(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!le(e,"type",n))return!1;let o=re(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||le(e,"as",o)||!oi(e[o]))return!1;for(n=o;n<e.length&&dr(e[n]);)n+=1;if(n=re(e,n),le(e,"as",n)){if(n=re(e,n+2),!oi(e[n]))return!1;for(;n<e.length&&dr(e[n]);)n+=1}r=!0}return!1}i(si,"bracedNamedBindingsAreTypeOnly");function wl(e,t){if(t=re(e,t+6),e[t]==="(")return gn(e,re(e,t+1));let n=!1;if(le(e,"type",t)){let o=re(e,t+4);e[o]!==","&&!le(e,"from",o)&&(n=!0)}else si(e,t)&&(n=!0);let r=ii(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(wl,"specifierAfterImport");function Cl(e,t){t=t+6;let n=re(e,t),r=!1;if(le(e,"type",n)){let s=re(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else si(e,n)&&(r=!0);let o=ii(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(Cl,"specifierAfterExport");function ii(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return gn(e,re(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return gn(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(ii,"specifierInStaticStatement");function xl(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(xl,"skipTemplateLiteral");function Ol(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=re(e,t+7);if(e[r]!=="(")return;r=re(e,r+1);let o=gn(e,r);return o?{...o,requireCall:!0}:void 0}i(Ol,"specifierAfterRequire");function Pl(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=xl(e,n);continue}if(r==="'"||r==='"'){let s=gn(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&le(e,"import",n)?wl(e,n):r==="e"&&le(e,"export",n)?Cl(e,n):r==="r"&&le(e,"require",n)?Ol(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(Pl,"moduleSpecifiers");function ai(e,t){let n=[],r=[];for(let o of Pl(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let f=sn(s);if(!f)continue;let g=e.content.slice(0,o.offset).split(`
24
+ `).length;r.push({file:e.path,symbol:s,capability:f,evidence:{kind:"import",file:e.path,line:g,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
25
+ `).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=_l(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(ai,"moduleFactsFor");function _l(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(_l,"resolveSpecifier");function li(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ke(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(li,"violationsFor");var Nl={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function Tl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Tl,"hasActiveArkRules");function Dl(e,t){return Tl(e,t)?W(F(Xs({config:e,arkRules:t,warnings:[]}))):W(F(go(e)))}i(Dl,"policyHashFor");function yn(e,t,n){let r=typeof e=="string"?Ls(e,t):Zr(e,t),o=n?.arkRules??fn();return{...r,arkRules:o,policyHash:Dl(r.config,o)}}i(yn,"loadContract");function Ro(e){let t=yn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=yn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=lr(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&&cr(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=Je(h.path);return{path:p,content:h.content,contentHash:W(h.content),layer:ce(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=ai(h,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=li(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(mt(h))]));for(let h of o){let p=n.get(h.file)?.layer;if(!p)continue;let u=a.get(p),m=Pe(h.symbol,u?.forbiddenGlobals??[]);if(m){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${h.symbol}" because it is the import form of forbidden global "${m}".`,symbol:h.symbol,evidence:h.evidence});continue}l.get(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",f=c==="complete"?[]:[{...Nl}],g={schemaVersion:sr,policyHash:e.contract.policyHash,compilerOptionsHash:W(F(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:f,valid:c==="complete"&&s.length===0,ir:g}}i(At,"analyzeProject");function hn(e){let t=new Map(e.files.map(n=>[Je(n.path),n]));for(let n of e.changes){let r=Je(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(hn,"analyzeChange");function Ao(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(Ao,"explainViolation");function pr(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 f=[],g;do{if(g=s.pop(),g===void 0)break;o.delete(g),f.push(g)}while(g!==c);f.length>1&&a.push(f.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[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(pr,"detectArchitectureCycles");function Qe(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=jr(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,f=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),g=c?us(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,h=l.message?g?`${l.message} (${g})`:l.message:g?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${g}`:`${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:f?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...f?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=pr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(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(Qe,"evaluateArchitectureGraph");var Ll=["no-anemic-model"];function ci(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ci,"escapeGlobLiteral");function Fl(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+=ci(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ci(o)}return new RegExp(`^${n}$`)}i(Fl,"globToRegExp");function kt(e,t){return!t||t.length===0?!0:t.some(n=>Fl(n).test(e))}i(kt,"matchesAppliesTo");function Ml(e){return Ll.includes(e)}i(Ml,"isTier2");function di(e){return e.mode==="enforced"&&!Ml(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(di,"severityFor");function et(e,t,n,r=1){let{severity:o,failsStrict:s}=di(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(et,"baseViolation");function ur(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(ur,"isInRuleLayer");function fr(e,t,n){return t.filter(r=>!(!r.exported||!kt(r.file,e.appliesTo)||!ur(r.file,e,n)))}i(fr,"shapesForRule");function $l(e,t,n){let r=[];for(let o of fr(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(et(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i($l,"evaluateAggregatePrivateState");function Kl(e,t,n){let r=[];for(let o of fr(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(et(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Kl,"evaluateAlwaysValidFactory");function Hl(e,t,n){let r=[];for(let o of fr(e,t,n))for(let s of o.mutatingMethods)s.referencesGuardOrPublish||r.push(et(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(Hl,"evaluateDomainEventOnMutation");function Ul(e,t){let n=[];for(let r of t.files)kt(r,e.appliesTo)&&ur(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(et(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Ul,"evaluateOrchestrationOnly");function Gl(e,t){let n=[];for(let r of t.files)kt(r,e.appliesTo)&&ur(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(et(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Gl,"evaluateThinAdapter");function Vl(e,t){let n=[];for(let r of t.files)kt(r,e.appliesTo)&&ur(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(et(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(Vl,"evaluateWritesViaAggregate");function jl(e,t,n){let r=[];for(let o of fr(e,t,n))if(o.dataOnly===!0){let s=et(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(jl,"evaluateNoAnemicModel");function pi(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(...$l(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Kl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Hl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Ul(n,e));break;case"thin-adapter":t.push(...Gl(n,e));break;case"writes-via-aggregate":t.push(...Vl(n,e));break;case"no-anemic-model":t.push(...jl(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(pi,"evaluateArkRuleSensors");function ui(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=>kt(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=di(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=>kt(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(ui,"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)/,Wl=/\.(?: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,ql=/\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*=)/,zl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Yl=/\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 Zl(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(Yl.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=ql.test(t)||zl.test(t),f=n.length>=1||r.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=l&&f||c&&f||l&&g&&(o>=4||n.length>=1)||c&&l,p=l&&Wl.test(t);return!a&&!h&&!p?null:{...a?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{},...p?{persistenceWrite:!0}:{}}}i(Zl,"deriveArkRuleFileHints");function fi(e){let t={};for(let[n,r]of Object.entries(e)){let o=Zl(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}i(fi,"buildArkRuleFileHints");function Jl(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(Jl,"normalizeExtraMergeTeethClassification");function mr(e){let t=Jl(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(mr,"extraMergeTeethAllowed");function mi(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(mi,"classifyResolvedLayerCoverage");var Ql=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var nm=new Set(Ql);function gi(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(gi,"isArkRunKernelModuleSpecifier");var ec=["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"],ko=new Set(ec);function yi(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(ko.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(ko.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:ko.has(e.slice(0,r))}i(yi,"isArkRunTransportBypassSpecifier");var tc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],um=new Set(tc);var hi={"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"},nc="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ki(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(ki,"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 Se(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:hi[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:ue({ruleId:hi[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Se,"finding");function oc(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(oc,"bagForFile");function Ri(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Ri,"emitKinds");function Ai(e){return e==="subscribe"||e==="register-handler"}i(Ai,"handleKinds");function sc(e){return e==="resolve"||e==="resolve-singleton"}i(sc,"dependKinds");function ic(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Se(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((f,g)=>f.file.localeCompare(g.file));if(l.length===0){r.push(Se(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(f=>f.hasKernelFactory))continue;let c=l[0];r.push(Se(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(ic,"evaluateMissingRoot");function ac(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||!gi(c))continue;let f=r(l.from);f&&ki(f,s.get(f)??[])&&a.push(Se(e,"arkrun-kernel-in-domain",l.from,l.line,`${f} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:f,target:c},o))}return a}i(ac,"evaluateKernelInDomain");function lc(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(g=>[g.name,g.intentPrefixes??[]])),c=new Set(r.filter(g=>g.hasKernelFactory).map(g=>g.file)),f=[];for(let g of n){if(c.has(g.file))continue;let h=g.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let p=o(g.file);!p||!a.has(p)||ki(p,l.get(p)??[])||f.push(Se(e,"arkrun-direct-new",g.file,g.line,`${p} must not construct ${g.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:g.typeName},s))}return f}i(lc,"evaluateDirectNew");function cc(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(!Ri(c.kind)&&!Ai(c.kind)&&!sc(c.kind))continue;let f=r(c.file);if(!f||!l.has(f))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:nc,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let g=oc(n,c.file);if(Ri(c.kind)){if(g.raises.has(c.nameLiteral)||g.sends.has(c.nameLiteral))continue;s.push(Se(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:f,target:c.nameLiteral},o));continue}if(Ai(c.kind)){if(g.reactsTo.has(c.nameLiteral))continue;s.push(Se(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:f,target:c.nameLiteral},o));continue}g.uses.has(c.nameLiteral)||s.push(Se(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:f,target:c.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(cc,"evaluateUndeclared");function dc(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||!yi(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(Se(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(dc,"evaluateTransportBypass");function Ii(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=mr(e.classification),r=cc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...ic(t,e.compositionRootHits,n),...ac(t,e.layers,e.dependencies,e.layerForFile,n),...lc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...dc(t,e.dependencies,e.layerForFile,n)].sort(rc),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,f=`${l.code}\0${l.file??""}\0${l.message}`;return c<f?-1:c>f?1:0});return{findings:o,completenessReasons:s}}i(Ii,"evaluateArkRunSensors");function bi(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(bi,"isArkOrderModuleSpecifier");var Ei={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function pc(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(pc,"isDomainRoleLayer");function we(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Ei[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:ue({ruleId:Ei[t],fromLayer:s?.fromLayer,target:s?.target})}}i(we,"finding");function vi(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=mr(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(we(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 f of e.planeRootHits){let g=c.get(f.matchedRoot)??[];g.push(f),c.set(f.matchedRoot,g)}for(let f of o){let g=c.get(f)??[];if(g.length===0){r.push(we(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(f)} matched no governed files and has no createOrderPlane factory.`,{target:f},n));continue}g.some(h=>h.hasPlaneFactory)||r.push(we(t,"arkorder-missing-plane",g[0].file,1,`ArkOrder plane root ${JSON.stringify(f)} has no createOrderPlane factory.`,{target:f},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let f=c.specifier;if(!f||!bi(f))continue;let g=e.layerForFile(c.from);g&&pc(g,s.get(g)??[])&&r.push(we(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:g,target:f},n))}for(let c of e.genericUpdates)r.push(we(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(we(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(we(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(we(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 f=e.layerForFile(c.file);!f||!l.has(f)||r.push(we(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:f,target:c.key},n))}return r.sort((c,f)=>c.file.localeCompare(f.file)||c.ruleId.localeCompare(f.ruleId)||c.line-f.line),{findings:r,completenessReasons:[]}}i(vi,"evaluateArkOrderSensors");function Q(e,t,n={}){return{ruleId:e,message:t,...n}}i(Q,"configWarning");function Rn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(u=>typeof u!="string"))&&s.push(Q("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(Q("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let u of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[u];m!==void 0&&(!Number.isInteger(m)||m<0)&&s.push(Q("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${u} 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(u=>u.name).filter(Boolean),...l.map(u=>u.name).filter(u=>!!u)]);a.length===0&&s.push(Q("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let f=new Set,g=new Set;for(let u of a){if(!u.name){s.push(Q("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}f.has(u.name)&&g.add(u.name),f.add(u.name),u.forbiddenGlobals!==void 0&&(!Array.isArray(u.forbiddenGlobals)||u.forbiddenGlobals.some(y=>typeof y!="string"))&&s.push(Q("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${u.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:u.name}));let m=Array.isArray(u.patterns)?u.patterns:[];if(m.length===0){s.push(Q("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${u.name}" has no file patterns and will never classify files.`,{layer:u.name}));continue}for(let y of m){let v;try{v=Ae(y)}catch(A){s.push(Q("CONFIG_INVALID_LAYER_PATTERN",`Layer "${u.name}" has an invalid pattern "${y}": ${A instanceof Error?A.message:String(A)}`,{layer:u.name,pattern:y}));continue}let E=u.optional===!0||u.reserved===!0||u.allowEmpty===!0;!r.some(A=>v.test(A))&&!E&&s.push(Q("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${u.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:u.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let u of g)s.push(Q("CONFIG_DUPLICATE_LAYER",`Layer "${u}" is configured more than once.`,{layer:u}));if(c.size>0)for(let u of n??[])u.from&&!c.has(u.from)&&s.push(Q("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${u.from}".`,{fromLayer:u.from,toLayer:u.to})),u.to&&!c.has(u.to)&&s.push(Q("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${u.to}".`,{fromLayer:u.from,toLayer:u.to}));let h=new Set;if(a.length>1)for(let u of r){let m=-1,y=[];for(let v of a)for(let E of v.patterns??[]){if(!Ae(E).test(u))continue;let A=Vr(E,u);A>m?(m=A,y=[v.name]):A===m&&!y.includes(v.name)&&y.push(v.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&s.push(Q("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(u=>!ce(u,a));return p.length>0&&s.push(Q("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(Rn,"collectAnalysisConfigWarnings");function uc(e,t){return t.some(n=>{try{return Ae(n).test(e)}catch{return!1}})}i(uc,"matchesAny");function fc(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:v})=>({file:y,line:v})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:v})=>({file:y,line:v})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!uc(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),f=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),h={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:f,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],u=c.filter(y=>y.kind==="import");if(u.length>0){let y=u[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${u.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let m=c.filter(y=>y.kind==="require");if(m.length>0){let y=m[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${m.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];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(f.length>0){let y=f[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${f.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&p.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:p}}i(fc,"evaluateSafety");function mc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(mc,"ambientForbiddenGlobal");function Si(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return fo(e,n.length>0?n:uo.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Si,"intentLayer");function gc(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||!mc(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??[],f=s.source==="import-based"?t.dependencies.find(g=>g.from===s.file&&g.line===s.line&&g.specifier===s.symbol&&!g.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&an(s.symbol,c))){if(s.source==="import-based"){let g=Pe(s.symbol,c);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...f?{edgeKind:f}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${g}".`});continue}}mt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...f?{edgeKind:f}:{},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 ln({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=Si(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=Si(s.intent,e.contract);if(!l)continue;let c=ke(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(gc,"contentViolations");function yc(e){let{facts:t}=e,n=Rt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,_)=>{let $=`${d.code}\0${d.file??""}\0${d.message}`,se=`${_.code}\0${_.file??""}\0${_.message}`;return $<se?-1:$>se?1:0}),a=t.files.map(d=>({...d,layer:ce(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let _=d.target?l.get(d.target)??ce(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,..._?{toLayer:_}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),f=Rn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),g=fc(e,t),h=e.contract.arkRules??fn(),p=a.map(d=>d.path),m={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?fi(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...pi({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),fileHints:m}),...ui(h,p)],v=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).`})),b=(h.invariants?.length??0)>0?Js({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},O=b.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),L=b.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${d.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),I=mi(a),N=Ii({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:I}),te=e.contract.config.arkRun?.mode,ye=N.findings.filter(()=>te==="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}:{}})),st=N.findings.filter(()=>te!=="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})),T=vi({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:I}),pe=e.contract.config.arkOrder?.mode,Z=T.findings.filter(()=>pe==="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}:{}})),it=T.findings.filter(()=>pe!=="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})),Mt=[...b.partial&&b.coverage.some(d=>d.mode==="enforced"&&d.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...N.completenessReasons,...T.completenessReasons],Ke=Qe({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...gc(e,t,l),...v,...O,...ye,...Z],edges:c,warnings:[...f,...g.warnings,...E,...L,...st,...it],safety:g.report}),Hn=o==="complete"&&Mt.length>0?"partial":o,Fr=Hn==="complete"?s:[...s,...Mt].sort((d,_)=>{let $=`${d.code}\0${d.file??""}\0${d.message}`,se=`${_.code}\0${_.file??""}\0${_.message}`;return $<se?-1:$>se?1:0}),S=Ke.violations.filter(d=>d.failsStrict!==!1),w=Hn==="complete"&&S.length===0,R=w&&Ke.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Hn,completenessReasons:Fr,valid:w,strictValid:R,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Ke.violations,warnings:Ke.warnings}}}i(yc,"analyzeCanonicalResolvedProject");function It(e){return yc({contract:e.contract,facts:ve(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(It,"analyzeResolvedProject");function wi(e){return W(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(wi,"analysisTreeHash");function Io(e){let t=At(e),n=new Map(t.ir.files.map(m=>[m.path,m])),r=[],o=new Set,s=[];for(let m of e.changes){let y=m.path.replace(/\\/g,"/"),v=Je(m.path);if(!v||v===".."||v.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(v)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}o.add(v),"delete"in m&&m.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 m&&m.delete?{path:v,delete:!0}:{path:v,content:"content"in m?m.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=hn({...e,changes:r}),l=new Map(a.ir.files.map(m=>[m.path,m])),c=a.ir.violations.filter(m=>m.ruleId==="CAPABILITY_VIOLATION"||m.ruleId==="FORBIDDEN_GLOBAL").map(m=>{let y=l.get(m.evidence.file)?.layer;return{ruleId:m.ruleId,file:m.evidence.file,line:m.evidence.line,target:m.symbol,...m.capability?{capability:m.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:m.message}}),f=Qe({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(m=>m.path),contentViolations:c,edges:a.ir.edges.filter(m=>!!m.fromLayer).map(m=>({from:m.from,fromLayer:m.fromLayer,...m.to?{to:m.to}:{},...m.toLayer?{toLayer:m.toLayer}:{},line:m.evidence.line,kind:"import",...m.typeOnly?{typeOnly:!0}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(m=>{let y=Je(m.path),v=n.get(y),E=l.get(y);return{path:y,operation:"delete"in m&&m.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},...E?{candidateContentHash:E.contentHash}:{}}}).sort((m,y)=>m.path.localeCompare(y.path)),h=[...s,...f.violations].map(m=>({...m,nextAction:ue(m)})),p=h.filter(m=>m.failsStrict!==!1),u=e.changeMap?Ze({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:a.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&p.length===0&&(u?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:wi(t.ir.files),candidateTreeHash:wi(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...u?{convergence:u}:{},changes:g,violations:h,warnings:f.warnings}}i(Io,"preflightChange");function hc(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(hc,"canonicalChangePath");function Rc(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(Rc,"identityViolations");function Ac(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(Ac,"preparedChange");function bo(e){let t=ve(e.baseFacts),n=ve(e.candidateFacts),r=It({contract:e.contract,facts:t}),o=It({contract:e.contract,facts:n}),s=new Map(t.files.map(u=>[u.path,u])),a=new Map(n.files.map(u=>[u.path,u])),l=Rc(t,n),c=new Map,f=[];for(let u of e.changes){let m=hc(u.path);if(!m){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(m)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:m,line:1,message:`The atomic change set contains more than one operation for ${m}.`});continue}c.set(m,u);let y=s.get(m),v=a.get(m);if("delete"in u&&u.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:m,line:1,message:`Cannot delete ${m} because it is not present in the supplied base facts.`}),v&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:m,line:1,message:`Candidate facts still contain deleted file ${m}.`});else{let E="content"in u?u.content:"",A=W(E);v?v.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:m,line:1,expectedContentHash:A,candidateContentHash:v.contentHash,message:`Candidate facts for ${m} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:m,line:1,message:`Candidate facts do not contain changed file ${m}.`})}f.push(Ac(u,m,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 u of new Set([...s.keys(),...a.keys()])){if(c.has(u))continue;let m=s.get(u),y=a.get(u);m&&y&&F(m)===F(y)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:u,line:1,message:`Candidate facts change ${u}, but the atomic change set does not declare it.`})}let g=e.changeMap?Ze({changeMap:e.changeMap,changes:f,baseDependencies:r.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:o.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0,h=[...l,...o.ir.violations].map(u=>({...u,nextAction:ue(u)})),p=h.filter(u=>u.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:f.sort((u,m)=>u.path<m.path?-1:u.path>m.path?1:0),violations:h,warnings:o.ir.warnings}}i(bo,"preflightResolvedChange");var gr="docs/diagnostics.md",Ci="1.0";function k(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(k,"entry");var An=Object.freeze([k("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),k("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),k("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),k("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),k("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),k("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),k("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),k("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),k("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),k("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),k("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),k("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),k("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),k("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),k("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),k("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),k("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),k("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),k("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),k("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),k("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),k("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),k("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),k("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),k("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),k("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),k("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),k("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),k("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe."),k("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),k("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),k("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease then apply(ProposeResult), then preflight again. Never mechanical-safe."),k("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),k("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),k("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),k("ARKORDER_UNVALVED_RELEASE","arkorder","Unvalved second freeze of \u03BE","release() ran after a pattern was already frozen and the new \u03BE differs. First freeze is release(); later pattern change is proposeRelease then apply.","Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe."),k("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),k("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),k("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),k("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),k("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),k("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),k("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),k("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),k("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),k("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),k("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),k("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),k("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),k("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),k("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),k("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),k("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),k("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),k("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),k("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),k("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),k("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),k("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),k("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),k("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),k("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),k("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),k("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),k("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),k("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),k("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),k("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Eo=new Map(An.map(e=>[e.ruleId,e])),xi=Object.freeze(An.map(e=>e.ruleId));function Oi(e){return typeof e=="string"&&e.length>0&&Eo.has(e)}i(Oi,"isKnownDiagnosticCode");function Pi(e){return typeof e!="string"||e.length===0?!1:Eo.has(e)?!0:e.startsWith("ARKRULE_")}i(Pi,"isCataloguedOrArkRuleFamily");function kn(e){if(!(typeof e!="string"||e.length===0))return Eo.get(e)}i(kn,"getDiagnosticCatalogEntry");function vo(e){return`#${kn(e)?.docsAnchor??e}`}i(vo,"diagnosticDocsFragment");function _i(e){return`${gr}${vo(e)}`}i(_i,"diagnosticDocsPath");function Ni(){return{schemaVersion:"1.0",docsPath:gr,codes:An}}i(Ni,"serializeDiagnosticCatalog");function Ti(e){return kn(e)?.fix}i(Ti,"catalogFixForRuleId");function Di(e){return kn(e)?.why}i(Di,"catalogWhyForRuleId");var Li="1.1";var Fi="1.0";var bt=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 kc(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(kc,"initialState");var yr=class{static{i(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new bt,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)??kc(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 In(e){return new yr(e)}i(In,"createProjectionRegistry");var bn="1.0";function Ic(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(Ic,"policyId");var So=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function En(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,f=t?t.list().map(E=>({name:E.name,dependencies:t.getDependencies(E.name),productions:t.getProductions(E.name)})):[],g=t?t.getAllRelationships():[],h=n?n.getPolicies().map(E=>({id:Ic(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():[],u=o?o.toJSON():{nodes:[],edges:[]},m=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)})):[],v={schemaVersion:"1.0",version:Gn,exportedAt:new Date().toISOString(),intents:f,relationships:g,policies:h,entities:p,graph:u,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:y,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:m}};return new So(v)}i(En,"createArkManifest");var Mi=0;function $i(e){return Mi+=1,`${e}-${Date.now()}-${Mi}`}i($i,"createWorkflowId");function wo(e){return e instanceof Error?e.message:String(e)}i(wo,"errorMessage");function bc(e){return new Promise(t=>{setTimeout(t,e)})}i(bc,"sleep");async function Ec(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(Ec,"withTimeout");var Et=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()}},Co=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new Et}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??$i(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=wo(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 Ec(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<s){o.delayMs&&await bc(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:wo(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:wo(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function vt(e,t){return new Co(e,t)}i(vt,"createWorkflowEngine");function xo(e,t,n={}){let r=vt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??$i(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 f=await r.start(e.name,c,{id:s});a=f.status==="waiting"?"idle":f.status,l=[...f.completedSteps]}catch(f){let g=await r.get(s);throw a=g?.status==="waiting"?"idle":g?.status??"failed",l=g?.completedSteps??[],f}}}}i(xo,"createSaga");St();function Ui(e){return Object.keys(e).sort()}i(Ui,"sortedKeys");function To(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],f=Math.max(l.length,c.length);for(let g=0;g<f;g+=1)To(l[g],c[g],`${n}[${g}]`,r);return}let o=e,s=t,a=new Set([...Ui(o),...Ui(s)]);for(let l of[...a].sort())To(o[l],s[l],n?`${n}.${l}`:l,r)}i(To,"walk");function Do(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}i(Do,"shadowInformationPackage");function Rr(e,t){let n=[];return To(e,t,"",n),{equal:n.length===0,diffs:n}}i(Rr,"compareInformationPackages");function Lo(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Rr(e[n-1],e[n]));return t}i(Lo,"replayInformationPackages");Sr();Dn();$n();$n();async function Kn(e,t={}){let n=Nt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Ji(),Zi));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(Kn,"startArkRunInspector");Sr();$n();St();Dn();St();var ad=new Set(["singleton","transient"]);function Qi(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(Qi,"cloneComponent");function ld(e){if(e===void 0)return"singleton";if(typeof e=="string"&&ad.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(ld,"closedLifetime");function ea(){let e=new Map,t=new Map,n=new Set;function r(a){let l=e.get(a);if(!l)throw new Error(`ArkRun component "${a}" is not registered.`);return l}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=ld(a.lifetime),f=Po({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!f)throw new Error("ArkRun component id must be a non-empty string.");let g=typeof a.factory=="function"?a.factory:void 0;return e.set(l,{component:f,factory:g}),Qi(f)},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=>Qi(a.component))}}}i(ea,"createComponentRegistry");Dn();function cd(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Re(e.source,t.source);return t.source=e.source,t}i(cd,"stampMetadata");function dd(){}i(dd,"ignoreDetachedFailure");async function Uo(e,t,n,r={}){let o=Tn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=cd(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,dd)}return o}i(Uo,"sendOnArkRunTransport");var Tr=1e3,ta=0;function pd(){return ta+=1,`ark-kernel-${Date.now()}-${ta}`}i(pd,"nextKernelInstanceId");function na(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}i(na,"portConstructorId");function Lt(e={}){let t=e.strict??!0,n=e.instanceId??pd(),r=e.profile??qe,o=e.maxHistorySize??Tr,s=Ht(),a=Jt(),l=e.metadata??on(),c=e.auditTrail===void 0,f=e.auditTrail??Zt({maxRecords:o}),g=e.eventContracts??Yt(),h=e.eventBuffer===void 0&&e.outbox===void 0,p=e.eventBuffer??e.outbox??new Oe,u=e.projections??In({auditTrail:f}),m=new Ce([jt(r),...e.policies??[]]),y=i(()=>{Qt(s,a,{requireRegisteredTargets:!0})},"syncGraph"),v=e.ephemeral??!0,E=e.broker,A=new ct({intentRegistry:s,dependencyGraph:a,policyEngine:m,strictRegistry:!0,validateIntentNaming:!0,auditTrail:f,eventContracts:g,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:p,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async T=>{await u.apply(T)}}),b=vt(A,{auditTrail:f}),O=Xt({registry:s,eventBus:A,graph:a}),L=ea(),I=typeof E?.send=="function",N=h?"InMemoryEventBuffer":na(p,"EventBufferStore"),te=c?"InMemoryAuditStore":na(f,"AuditTrail"),ye=Tt({stores:[Le(N,"outbox"),Le(te,"audit"),Le("InMemoryWorkflowStore","workflow")]}),st={instanceId:n,profile:r,registry:s,graph:a,metadata:l,auditTrail:f,eventContracts:g,eventBuffer:p,outbox:p,projections:u,policyEngine:m,eventBus:A,workflowEngine:b,observability:O,publisher(T){let pe=A.createPublisher(T);return{source:pe.source,publish:pe.publish,send(Z,it,Ft={}){return Uo({eventBus:A,broker:E,defaultEphemeral:v},Z,it,{...Ft,source:pe.source})}}},send(T,pe,Z={}){return Uo({eventBus:A,broker:E,defaultEphemeral:v},T,pe,Z)},register(T){return L.register(T)},resolve(T){return L.resolve(T)},resolveSingleton(T){return L.resolveSingleton(T)},getDependencyInformationPackage(){return fe({kernelInstanceId:n,components:L.snapshotComponents()})},requestGraph(T){return Nn({kernelInstanceId:n,components:L.snapshotComponents()},T)},getInspectorSnapshot(T){return Mn({kernelInstanceId:n,host:T?.host,port:T?.port,package:{kernelInstanceId:n,components:L.snapshotComponents()},observability:O.report(),ephemeralDefault:v,brokerBound:I,hardening:ye})},startInspector(T){return Kn({getInspectorSnapshot:i(Z=>st.getInspectorSnapshot(Z),"getInspectorSnapshot"),requestGraph:i(Z=>st.requestGraph(Z),"requestGraph"),async listInspectorOutbox(){let[Z,it]=await Promise.all([p.list("pending"),p.list("failed")]);return Fe([...Z,...it],{sampleLimit:ee})},async listInspectorWorkflows(){return Me(await b.list(),{sampleLimit:ee})}},T)},syncGraph:y,manifest(){return y(),En({registry:s,policyEngine:m,metadata:l,graph:a,profile:r,projections:u,eventContracts:g,observability:O})}};return st}i(Lt,"createArkKernel");function Dr(e={}){return Lt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Dr,"createStrictArkKernel");function Go(e,t={}){let{profileName:n,...r}=t;return{...r,profile:rn(e,{name:n})}}i(Go,"createOptionsFromConfig");function Vo(e,t={}){return Lt(Go(e,t))}i(Vo,"createArkKernelFromConfig");function jo(e,t={}){return Dr(Go(e,t))}i(jo,"createStrictArkKernelFromConfig");function Bo(e,t={}){return Lr(Go(e,t))}i(Bo,"createLenientArkKernelFromConfig");function Lr(e={}){return Lt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(Lr,"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_MONITOR_SAMPLE_LIMIT,ARK_RUN_INSPECTOR_OUTBOX_PATH,ARK_RUN_INSPECTOR_SCHEMA_VERSION,ARK_RUN_INSPECTOR_SNAPSHOT_PATH,ARK_RUN_INSPECTOR_SSE_EVENT,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,ARK_RUN_INSPECTOR_WORKFLOWS_PATH,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,appendDecisionTape,architecturalPolicies,arkRunGraphQueryFromSearchParams,arkRunInspectorUrl,buildArkRunInspectorHardening,buildArkRunInspectorOutboxMonitor,buildArkRunInspectorSnapshot,buildArkRunInspectorWorkflowsMonitor,buildDependencyInformationPackage,buildPublishPolicyContext,catalogFixForRuleId,catalogWhyForRuleId,checkAdapterGovernance,checkContract,classifyArkPolicyDelta,classifyArkRunInspectorStoreDurability,closeArkRunGraphQuery,closedArkRunEphemeral,closedArkRunTransportKind,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,compareInformationPackages,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,replayInformationPackages,requestArkRunGraph,resolveArkRunInspectorBind,resolveArkRunSendPlan,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,shadowInformationPackage,stableSerialize,startArkRunInspector,syncRegistryToGraph,toAdapterDiagnostic,unavailableArkRunInspectorOutboxMonitor,unavailableArkRunInspectorWorkflowsMonitor,validateIntentName,version});