arkgate 4.8.2 → 4.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +257 -3
  2. package/README.md +47 -9
  3. package/bin/ark-check-runtime.mjs +340 -5
  4. package/bin/ark-layer-match.mjs +170 -13
  5. package/bin/ark-mcp-runtime.mjs +9 -2
  6. package/bin/lib/analysis-completeness.mjs +86 -0
  7. package/bin/lib/analysis-engine.mjs +6 -6
  8. package/bin/lib/architecture-scan.mjs +2 -0
  9. package/bin/lib/ark-order-facts.mjs +59 -0
  10. package/bin/lib/ark-order-sensors.mjs +31 -2
  11. package/bin/lib/arkrule-file-hints.mjs +6 -2
  12. package/bin/lib/arkrules-contract.mjs +9 -1
  13. package/bin/lib/arkrules-sensors.mjs +22 -2
  14. package/bin/lib/check-args.mjs +66 -0
  15. package/bin/lib/config-contract.mjs +26 -0
  16. package/bin/lib/config-extras.mjs +2 -0
  17. package/bin/lib/design-smells.mjs +85 -0
  18. package/bin/lib/diagnostic-catalog.mjs +8 -2
  19. package/bin/lib/first-run-help.mjs +12 -0
  20. package/bin/lib/invariant-coverage-io.mjs +175 -19
  21. package/bin/lib/invariant-coverage.mjs +110 -7
  22. package/bin/lib/literal-path-drift-io.mjs +569 -0
  23. package/bin/lib/literal-path-drift.mjs +761 -0
  24. package/bin/lib/policy-delta-io.mjs +5 -0
  25. package/bin/lib/remediation.mjs +24 -1
  26. package/bin/lib/resolved-candidate-facts.mjs +31 -0
  27. package/bin/lib/rules-under-contract.mjs +5 -0
  28. package/bin/lib/scan-files.mjs +54 -0
  29. package/bin/lib/sensor-promote-cli.mjs +372 -0
  30. package/bin/lib/sensor-promote-io.mjs +246 -0
  31. package/bin/lib/sensor-promotion.mjs +363 -0
  32. package/dist/{configTypes-BdCe_gvv.d.ts → configTypes-dy5PfTqS.d.ts} +36 -0
  33. package/dist/{diagnosticCatalog-CPzH-MLN.d.ts → diagnosticCatalog-DgTs0abp.d.ts} +169 -11
  34. package/dist/eslint/index.cjs +5 -5
  35. package/dist/eslint/index.d.ts +34 -1
  36. package/dist/eslint/index.js +5 -5
  37. package/dist/index.cjs +31 -31
  38. package/dist/index.d.ts +85 -7
  39. package/dist/index.js +31 -31
  40. package/dist/nestjs/index.cjs +5 -5
  41. package/dist/nestjs/index.d.ts +3 -3
  42. package/dist/nestjs/index.js +5 -5
  43. package/dist/runtime/index.cjs +13 -13
  44. package/dist/runtime/index.d.ts +6 -6
  45. package/dist/runtime/index.js +13 -13
  46. package/dist/{types-DCSlrRnV.d.ts → types-BuM8WNqe.d.ts} +1 -1
  47. package/dist/{types-C9KApBzX.d.ts → types-D95drJ3_.d.ts} +1 -1
  48. package/docs/README.md +4 -4
  49. package/docs/agent-guide.md +182 -0
  50. package/docs/configuration.md +89 -9
  51. package/docs/develop.md +24 -2
  52. package/docs/diagnostics.md +79 -1
  53. package/docs/enthusiast/README.md +6 -4
  54. package/docs/package-surface.md +36 -4
  55. package/docs/product-voice.md +15 -5
  56. package/docs/use.md +8 -5
  57. package/package.json +2 -2
  58. package/schemas/ark.arkrules.schema.json +1 -0
  59. package/schemas/ark.config.schema.json +72 -0
  60. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  61. package/server.json +3 -3
  62. package/templates/agent-skills/README.md +1 -1
  63. package/templates/agent-skills/ark-adopt/SKILL.md +13 -3
  64. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  65. package/templates/agent-skills/ark-contract/SKILL.md +4 -0
  66. package/templates/agent-skills/ark-coverage/SKILL.md +1 -0
  67. package/templates/agent-skills/ark-place/SKILL.md +6 -2
  68. package/templates/arkrules/ApplicationOrchestration.json +6 -0
  69. package/templates/skills/ark-adopt.md +13 -3
  70. package/templates/skills/ark-autopilot.md +1 -1
  71. package/templates/skills/ark-contract.md +4 -0
  72. package/templates/skills/ark-coverage.md +1 -0
  73. package/templates/skills/ark-place.md +6 -2
@@ -1,25 +1,25 @@
1
- var eo=Object.defineProperty;var i=(e,t)=>eo(e,"name",{value:t,configurable:!0});var lt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var da=(e,t)=>{for(var n in t)eo(e,n,{get:t[n],enumerable:!0})};function Lr(e,t){return e<t?-1:e>t?1:0}function Nc(e){return[...new Set(e)].sort(Lr)}function Ft(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return Nc(t)}function Tc(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Dc(e){return typeof e=="string"&&_c.has(e)?e:"singleton"}function Lc(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(Lr)){if(n.length===0)continue;let r=Tc(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function Fc(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=Ft(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=Lc(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Fr(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:Dc(t.lifetime),uses:Ft(t.uses),reactsTo:Ft(t.reactsTo),raises:Ft(t.raises),sends:Ft(t.sends)},o=Fc(t.extendedInfo);return o&&(r.extendedInfo=o),r}function ye(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let s of n){let a=Fr(s);!a||r.has(a.id)||(r.add(a.id),o.push(a))}return o.sort((s,a)=>Lr(s.id,a.id)),{schemaVersion:"1.0",kernelInstanceId:t,components:o}}var Dn,Dr,_c,tt=lt(()=>{"use strict";Dn="1.0",Dr=["singleton","transient"],_c=new Set(Dr);i(Lr,"compare");i(Nc,"uniqueSorted");i(Ft,"nameList");i(Tc,"jsonPrimitive");i(Dc,"closedLifetime");i(Lc,"sanitizeMetadata");i(Fc,"sanitizeArkRunExtendedInfo");i(Fr,"sanitizeArkRunComponent");i(ye,"buildDependencyInformationPackage")});function Ht(e,t){return e<t?-1:e>t?1:0}function $r(e){return[...new Set(e)].sort(Ht)}function js(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Mr(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function le(e,t){if(e==null||e==="")return[];if(typeof e=="string")return $r(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new W(t);let n=[];for(let r of e){if(typeof r!="string")throw new W(t);let o=r.trim();o.length>0&&n.push(o)}return $r(n)}function Js(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 $t(e,t){return e?t.some(n=>Js(e,n)):!1}function Qs(e){if(e==null||e==="")return Kr;if(typeof e=="string"&&$c.has(e))return e;throw new W("slice")}function Xs(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 W("degreesOfSeparation")}function Bs(e,t){if(e==null||e==="")return js();if(typeof e=="string"||Array.isArray(e))return{...js(),tokens:le(e,t)};if(typeof e!="object")throw new W(t);let n=e;for(let r of Object.keys(n))if(!Hc.has(r))throw new W(t);return{tokens:[],ids:le(n.ids,t),labels:le(n.labels,t),tags:le(n.tags,t),groups:le(n.groups,t),architectureKinds:le(n.architectureKinds,t)}}function $n(e={}){if(e==null||e==="")return $n({});if(typeof e!="object"||Array.isArray(e))throw new W("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!Mc.has(n))throw new W("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Qs(t.slice),nodeIds:le(t.nodeIds,"nodeIds"),degreesOfSeparation:Xs(t.degreesOfSeparation),include:Bs(t.include,"include"),exclude:Bs(t.exclude,"exclude")}}function Mn(e){let t={};e.slice&&(t.slice=Qs(e.slice));let n=le(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=Xs(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=le(e.include??void 0,"include");o.length>0&&(t.include=o);let s=le(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function Kc(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 qs(e,t){if(!Mr(t))return!0;let n=Kc(e);return t.tokens.some(r=>n.some(o=>Js(o,r)))||$t(e.id,t.ids)||$t(e.label,t.labels)||e.tags?.some(r=>$t(r,t.tags))||$t(e.group,t.groups)?!0:$t(e.architectureKind,t.architectureKinds)}function Gc(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return ye({kernelInstanceId:t.kernelInstanceId,components:t.components})}return ye({})}function Uc(e){let t={id:e.id,kind:"component",lifetime:e.lifetime},n=e.extendedInfo;return n?.label&&(t.label=n.label),n?.group&&(t.group=n.group),n?.architectureKind&&(t.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(t.tags=[...n.tags]),t}function Ln(e){return{id:e,kind:"interaction"}}function Mt(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function Fn(e,t,n,r,o){let s=`${n}\0${o}\0${r}`;t.has(s)||(t.add(s),e.push({from:n,to:r,kind:o}))}function Vc(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Mt(n,Uc(s)),t==="technical"){for(let a of s.uses)Mt(n,n.get(a)??Ln(a)),Fn(r,o,s.id,a,"uses");continue}for(let a of s.raises)Mt(n,n.get(a)??Ln(a)),Fn(r,o,s.id,a,"raises");for(let a of s.reactsTo)Mt(n,n.get(a)??Ln(a)),Fn(r,o,a,s.id,"reactsTo");for(let a of s.sends)Mt(n,n.get(a)??Ln(a)),Fn(r,o,s.id,a,"sends")}return{nodes:n,edges:r}}function jc(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 Bc(e,t,n,r){let o=t.filter(c=>e.has(c));if(o.length===0)return new Set;let s=new Set,a=o.map(c=>({id:c,depth:0}));for(;a.length>0;){let c=a.shift();if(!(!c||s.has(c.id))&&(s.add(c.id),!(n!==null&&c.depth>=n)))for(let l of r.get(c.id)??[])!s.has(l)&&e.has(l)&&a.push({id:l,depth:c.depth+1})}return s}function Kt(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function zs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function qc(e){let t=new Set,n=new Map;for(let r of e){let o=Kt(r),s=o,a=2;for(;t.has(s);)s=`${o}_${a}`,a+=1;t.add(s),n.set(r,s)}return n}function Ur(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(c=>c.id),r=qc(n),o=$r(e.nodes.map(c=>c.group).filter(c=>!!c)),s=[`flowchart ${t}`],a=i((c,l)=>{let m=r.get(c.id)??Kt(c.id),y=zs(c.label??c.id);s.push(`${l}${m}["${y}"]`)},"emitNode");for(let c of o){let l=Kt(`group_${c}`);s.push(` subgraph ${l}["${zs(c)}"]`);for(let m of e.nodes)m.group===c&&a(m," ");s.push(" end")}for(let c of e.nodes)c.group||a(c," ");for(let c of e.edges){let l=r.get(c.from)??Kt(c.from),m=r.get(c.to)??Kt(c.to);s.push(` ${l} -->|${c.kind}| ${m}`)}return s.join(`
2
- `)}function zc(e,t,n){let r=new Set(e.keys());if(Mr(n.include)&&(r=new Set([...r].filter(c=>{let l=e.get(c);return l!==void 0&&qs(l,n.include)}))),Mr(n.exclude))for(let c of[...r]){let l=e.get(c);l&&qs(l,n.exclude)&&r.delete(c)}let o=t.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=Bc(r,n.nodeIds,n.degreesOfSeparation,jc(o)));let s=[...r].sort(Ht).map(c=>e.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,l)=>Ht(c.from,l.from)||Ht(c.kind,l.kind)||Ht(c.to,l.to));return{nodes:s,edges:a}}function Hn(e={},t={}){let n=Gc(e),r=$n(t),o=Vc(n.components,r.slice),s=zc(o.nodes,o.edges,r),a={schemaVersion:Hr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=Ur(a),a}var Hr,Kr,Gr,Ws,Ys,Zs,W,$c,Mc,Hc,Kn=lt(()=>{"use strict";tt();Hr="1.0",Kr="process",Gr=["process","technical"],Ws=["component","interaction"],Ys=["raises","reactsTo","sends"],Zs=["uses"],W=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}},$c=new Set(Gr),Mc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Hc=new Set(["ids","labels","tags","groups","architectureKinds"]);i(Ht,"compare");i($r,"uniqueSorted");i(js,"emptyMatch");i(Mr,"matchHasCriteria");i(le,"nameList");i(Js,"globMatch");i($t,"anyGlob");i(Qs,"closedSlice");i(Xs,"closedDegrees");i(Bs,"closedMatch");i($n,"closeArkRunGraphQuery");i(Mn,"arkRunGraphQueryFromSearchParams");i(Kc,"nodeFields");i(qs,"nodeMatches");i(Gc,"asPackage");i(Uc,"componentNode");i(Ln,"interactionNode");i(Mt,"addNode");i(Fn,"addEdge");i(Vc,"buildSlice");i(jc,"adjacency");i(Bc,"neighborhood");i(Kt,"mermaidSafeId");i(zs,"mermaidLabel");i(qc,"uniqueMermaidIds");i(Ur,"formatArkRunGraphMermaid");i(zc,"filterGraph");i(Hn,"requestArkRunGraph")});function Vr(e){if(e===void 0)return"local";if(typeof e=="string"&&Wc.has(e))return e;throw new nt("transport")}function jr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new nt("ephemeral")}function Gn(e){let t=Vr(e.transport),n=jr(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,rt,Wc,nt,Ut=lt(()=>{"use strict";Gt=["local","localBlocking","broker"],rt=!0,Wc=new Set(Gt),nt=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(Vr,"closedArkRunTransportKind");i(jr,"closedArkRunEphemeral");i(Gn,"resolveArkRunSendPlan")});function Vn(e){return e==="production"}function Zc(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 ea(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function st(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=ea(t);if(n)return st(n);let r=Zc(t);return r!==void 0&&r[0]===127}function ta(e){if(e===void 0)return Un;if(typeof e!="string")throw new te(String(e));let t=e.trim();if(Yc.has(t.toLowerCase())||!st(t))throw new te(t);let n=t.toLowerCase();if(n==="localhost")return Un;if(n==="[::1]")return"::1";let r=ea(n);return r?ta(r):n}function Jc(e){if(e===void 0)return qr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new te(`port:${String(e)}`);return e}function qt(e={}){if(Vn(e.nodeEnv)||Vn(e.processNodeEnv))throw new ot;return{host:ta(e.host),port:Jc(e.port)}}function Oe(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 Xc(e){return{kinds:[...Gt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:Wr}}function jn(e={}){let t=qt({host:e.host,port:e.port}),n=ye({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]});return{schemaVersion:Br,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Xc(e),observability:Qc(e.observability)??{}}}function zt(e){return`event: ${zr}
1
+ var ro=Object.defineProperty;var i=(e,t)=>ro(e,"name",{value:t,configurable:!0});var at=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ii=(e,t)=>{for(var n in t)ro(e,n,{get:t[n],enumerable:!0})};function $r(e,t){return e<t?-1:e>t?1:0}function Yl(e){return[...new Set(e)].sort($r)}function _t(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return Yl(t)}function Xl(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Zl(e){return typeof e=="string"&&zl.has(e)?e:"singleton"}function Jl(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort($r)){if(n.length===0)continue;let r=Xl(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function Ql(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n={};typeof t.label=="string"&&t.label.length>0&&(n.label=t.label),typeof t.architectureKind=="string"&&t.architectureKind.length>0&&(n.architectureKind=t.architectureKind);let r=_t(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=Jl(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Mr(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:Zl(t.lifetime),uses:_t(t.uses),reactsTo:_t(t.reactsTo),raises:_t(t.raises),sends:_t(t.sends)},o=Ql(t.extendedInfo);return o&&(r.extendedInfo=o),r}function Re(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let s of n){let a=Mr(s);!a||r.has(a.id)||(r.add(a.id),o.push(a))}return o.sort((s,a)=>$r(s.id,a.id)),{schemaVersion:"1.0",kernelInstanceId:t,components:o}}var Dn,Fr,zl,tt=at(()=>{"use strict";Dn="1.0",Fr=["singleton","transient"],zl=new Set(Fr);i($r,"compare");i(Yl,"uniqueSorted");i(_t,"nameList");i(Xl,"jsonPrimitive");i(Zl,"closedLifetime");i(Jl,"sanitizeMetadata");i(Ql,"sanitizeArkRunExtendedInfo");i(Mr,"sanitizeArkRunComponent");i(Re,"buildDependencyInformationPackage")});function Dt(e,t){return e<t?-1:e>t?1:0}function Hr(e){return[...new Set(e)].sort(Dt)}function ti(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Kr(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function ce(e,t){if(e==null||e==="")return[];if(typeof e=="string")return Hr(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new J(t);let n=[];for(let r of e){if(typeof r!="string")throw new J(t);let o=r.trim();o.length>0&&n.push(o)}return Hr(n)}function li(e,t){if(t==="*")return e.length>0;if(!t.includes("*"))return e===t;let n="^";for(let r of t)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(e)}function Nt(e,t){return e?t.some(n=>li(e,n)):!1}function ci(e){if(e==null||e==="")return Ur;if(typeof e=="string"&&ec.has(e))return e;throw new J("slice")}function di(e){if(e==null||e==="")return null;if(typeof e=="string"&&/^(0|[1-9]\d*)$/.test(e))return Number(e);if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;throw new J("degreesOfSeparation")}function ni(e,t){if(e==null||e==="")return ti();if(typeof e=="string"||Array.isArray(e))return{...ti(),tokens:ce(e,t)};if(typeof e!="object")throw new J(t);let n=e;for(let r of Object.keys(n))if(!nc.has(r))throw new J(t);return{tokens:[],ids:ce(n.ids,t),labels:ce(n.labels,t),tags:ce(n.tags,t),groups:ce(n.groups,t),architectureKinds:ce(n.architectureKinds,t)}}function $n(e={}){if(e==null||e==="")return $n({});if(typeof e!="object"||Array.isArray(e))throw new J("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!tc.has(n))throw new J("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:ci(t.slice),nodeIds:ce(t.nodeIds,"nodeIds"),degreesOfSeparation:di(t.degreesOfSeparation),include:ni(t.include,"include"),exclude:ni(t.exclude,"exclude")}}function Mn(e){let t={};e.slice&&(t.slice=ci(e.slice));let n=ce(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=di(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=ce(e.include??void 0,"include");o.length>0&&(t.include=o);let s=ce(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function rc(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 ri(e,t){if(!Kr(t))return!0;let n=rc(e);return t.tokens.some(r=>n.some(o=>li(o,r)))||Nt(e.id,t.ids)||Nt(e.label,t.labels)||e.tags?.some(r=>Nt(r,t.tags))||Nt(e.group,t.groups)?!0:Nt(e.architectureKind,t.architectureKinds)}function oc(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return Re({kernelInstanceId:t.kernelInstanceId,components:t.components})}return Re({})}function sc(e){let t={id:e.id,kind:"component",lifetime:e.lifetime},n=e.extendedInfo;return n?.label&&(t.label=n.label),n?.group&&(t.group=n.group),n?.architectureKind&&(t.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(t.tags=[...n.tags]),t}function Ln(e){return{id:e,kind:"interaction"}}function Tt(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function Fn(e,t,n,r,o){let s=`${n}\0${o}\0${r}`;t.has(s)||(t.add(s),e.push({from:n,to:r,kind:o}))}function ic(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Tt(n,sc(s)),t==="technical"){for(let a of s.uses)Tt(n,n.get(a)??Ln(a)),Fn(r,o,s.id,a,"uses");continue}for(let a of s.raises)Tt(n,n.get(a)??Ln(a)),Fn(r,o,s.id,a,"raises");for(let a of s.reactsTo)Tt(n,n.get(a)??Ln(a)),Fn(r,o,a,s.id,"reactsTo");for(let a of s.sends)Tt(n,n.get(a)??Ln(a)),Fn(r,o,s.id,a,"sends")}return{nodes:n,edges:r}}function ac(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 lc(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 Lt(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function oi(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function cc(e){let t=new Set,n=new Map;for(let r of e){let o=Lt(r),s=o,a=2;for(;t.has(s);)s=`${o}_${a}`,a+=1;t.add(s),n.set(r,s)}return n}function jr(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=cc(n),o=Hr(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],a=i((l,c)=>{let g=r.get(l.id)??Lt(l.id),m=oi(l.label??l.id);s.push(`${c}${g}["${m}"]`)},"emitNode");for(let l of o){let c=Lt(`group_${l}`);s.push(` subgraph ${c}["${oi(l)}"]`);for(let g of e.nodes)g.group===l&&a(g," ");s.push(" end")}for(let l of e.nodes)l.group||a(l," ");for(let l of e.edges){let c=r.get(l.from)??Lt(l.from),g=r.get(l.to)??Lt(l.to);s.push(` ${c} -->|${l.kind}| ${g}`)}return s.join(`
2
+ `)}function dc(e,t,n){let r=new Set(e.keys());if(Kr(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&ri(c,n.include)}))),Kr(n.exclude))for(let l of[...r]){let c=e.get(l);c&&ri(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=lc(r,n.nodeIds,n.degreesOfSeparation,ac(o)));let s=[...r].sort(Dt).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Dt(l.from,c.from)||Dt(l.kind,c.kind)||Dt(l.to,c.to));return{nodes:s,edges:a}}function Hn(e={},t={}){let n=oc(e),r=$n(t),o=ic(n.components,r.slice),s=dc(o.nodes,o.edges,r),a={schemaVersion:Gr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return a.mermaid=jr(a),a}var Gr,Ur,Vr,si,ii,ai,J,ec,tc,nc,Kn=at(()=>{"use strict";tt();Gr="1.0",Ur="process",Vr=["process","technical"],si=["component","interaction"],ii=["raises","reactsTo","sends"],ai=["uses"],J=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}},ec=new Set(Vr),tc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),nc=new Set(["ids","labels","tags","groups","architectureKinds"]);i(Dt,"compare");i(Hr,"uniqueSorted");i(ti,"emptyMatch");i(Kr,"matchHasCriteria");i(ce,"nameList");i(li,"globMatch");i(Nt,"anyGlob");i(ci,"closedSlice");i(di,"closedDegrees");i(ni,"closedMatch");i($n,"closeArkRunGraphQuery");i(Mn,"arkRunGraphQueryFromSearchParams");i(rc,"nodeFields");i(ri,"nodeMatches");i(oc,"asPackage");i(sc,"componentNode");i(Ln,"interactionNode");i(Tt,"addNode");i(Fn,"addEdge");i(ic,"buildSlice");i(ac,"adjacency");i(lc,"neighborhood");i(Lt,"mermaidSafeId");i(oi,"mermaidLabel");i(cc,"uniqueMermaidIds");i(jr,"formatArkRunGraphMermaid");i(dc,"filterGraph");i(Hn,"requestArkRunGraph")});function Br(e){if(e===void 0)return"local";if(typeof e=="string"&&pc.has(e))return e;throw new nt("transport")}function Wr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new nt("ephemeral")}function Gn(e){let t=Br(e.transport),n=Wr(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",s=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:s,awaitHandoff:n||s}}var Ft,rt,pc,nt,$t=at(()=>{"use strict";Ft=["local","localBlocking","broker"],rt=!0,pc=new Set(Ft),nt=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(Br,"closedArkRunTransportKind");i(Wr,"closedArkRunEphemeral");i(Gn,"resolveArkRunSendPlan")});function Vn(e){return e==="production"}function fc(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 pi(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function st(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=pi(t);if(n)return st(n);let r=fc(t);return r!==void 0&&r[0]===127}function ui(e){if(e===void 0)return Un;if(typeof e!="string")throw new se(String(e));let t=e.trim();if(uc.has(t.toLowerCase())||!st(t))throw new se(t);let n=t.toLowerCase();if(n==="localhost")return Un;if(n==="[::1]")return"::1";let r=pi(n);return r?ui(r):n}function gc(e){if(e===void 0)return zr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new se(`port:${String(e)}`);return e}function Gt(e={}){if(Vn(e.nodeEnv)||Vn(e.processNodeEnv))throw new ot;return{host:ui(e.host),port:gc(e.port)}}function _e(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function mc(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function yc(e){return{kinds:[...Ft],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:Xr}}function jn(e={}){let t=Gt({host:e.host,port:e.port}),n=Re({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]});return{schemaVersion:qr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:yc(e),observability:mc(e.observability)??{}}}function Ut(e){return`event: ${Yr}
3
3
  data: ${JSON.stringify(e)}
4
4
 
5
- `}var Br,Un,qr,Vt,jt,Bt,zr,Wr,ot,te,Yc,Wt=lt(()=>{"use strict";tt();Ut();Br="1.0",Un="127.0.0.1",qr=0,Vt="/snapshot",jt="/events",Bt="/graph",zr="snapshot",Wr="in-process-local",ot=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},te=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},Yc=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Vn,"isArkRunInspectorProductionEnv");i(Zc,"ipv4Octets");i(ea,"unwrapIpv4Mapped");i(st,"isArkRunInspectorLoopbackHost");i(ta,"closedHost");i(Jc,"closedPort");i(qt,"resolveArkRunInspectorBind");i(Oe,"arkRunInspectorUrl");i(Qc,"jsonClone");i(Xc,"closedTransportFacts");i(jn,"buildArkRunInspectorSnapshot");i(zt,"formatArkRunInspectorSseEvent")});var na={};da(na,{listenArkRunInspector:()=>ol});function el(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function tl(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function nl(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Bn(e,t,n){e.writeHead(t,el()),e.end(JSON.stringify(n))}function rl(e,t){let n=e.address();if(n===null||typeof n=="string")throw new te(t.host);if(!st(n.address))throw new te(n.address);return{host:t.host,port:n.port}}async function ol(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,c=i(()=>e.getInspectorSnapshot(a),"snapshot"),l=n.createServer((m,y)=>{let h=nl(m.url),d=h.pathname;if(m.method==="GET"&&(d==="/"||d===Vt)){Bn(y,200,c());return}if(m.method==="GET"&&d===Bt){try{Bn(y,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(p){if(p instanceof W){Bn(y,400,{error:p.message,option:p.option});return}throw p}return}if(m.method==="GET"&&d===jt){y.writeHead(200,tl()),y.flushHeaders(),y.write(zt(c())),r.add(y);let p=s>0?setInterval(()=>{y.write(zt(c()))},s):void 0;p&&o.add(p);let u=i(()=>{r.delete(y),p&&(clearInterval(p),o.delete(p))},"drop");m.on("close",u),y.on("close",u);return}Bn(y,404,{error:"not found"})});try{await new Promise((m,y)=>{let h=i(d=>y(d),"onError");l.once("error",h),l.listen({host:t.bind.host,port:t.bind.port},()=>{l.off("error",h);try{a=rl(l,t.bind),m()}catch(d){y(d instanceof Error?d:new te(t.bind.host))}})})}catch(m){throw await new Promise(y=>{l.close(()=>y())}),m}return{host:a.host,port:a.port,url:Oe(a.host,a.port,"/"),snapshotUrl:Oe(a.host,a.port,Vt),eventsUrl:Oe(a.host,a.port,jt),graphUrl:Oe(a.host,a.port,Bt),close(){for(let m of o)clearInterval(m);o.clear();for(let m of r)m.end();return r.clear(),new Promise((m,y)=>{l.close(h=>{h?y(h):m()})})}}}var ra=lt(()=>{"use strict";Kn();Wt();i(el,"jsonHeaders");i(tl,"sseHeaders");i(nl,"requestUrl");i(Bn,"writeJson");i(rl,"boundAddress");i(ol,"listenArkRunInspector")});var Yn="4.8.2";var pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ua=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,fa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ma(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ua.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":fa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(ma,"classifyLayerImportKind");function ya(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=ma(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(ya,"layerImportNextAction");function ga(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ga,"arkRunCallSiteName");function ha(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(ha,"arkRunNextAction");function ce(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ya(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return ha(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ce,"deterministicNextAction");var Jn="1.5",Ra="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function to(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(to,"positiveInteger");function ro(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(ro,"adapterFindingTargetKey");function no(e){let t=new Map;return e.map(n=>{let r=ro(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(no,"adapterFindingOccurrenceTargetKeys");function Aa(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(Aa,"adapterFindingRefFromTargetKey");function ka(e){return`${Ra}#${e}`}i(ka,"adapterDocsCodePath");function Ia(e,t,n){return ce({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}i(Ia,"nextActionForDiagnostic");function Zn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},a=n??ro(e),c=Aa(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:to(e.line,1),column:to(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ia(r,s,e),findingRef:c,targetKey:a,docsCodePath:ka(r)}}i(Zn,"toAdapterDiagnostic");function Ea(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(h=>({code:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=no(s),l=no(a),m=[...s.map((h,d)=>Zn(h,"error",c[d])),...a.map((h,d)=>Zn(h,"warning",l[d]))],y={schemaVersion:Jn,completenessReasons:r,diagnostics:m};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...y,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...h}:{...y,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...y,mode:n,valid:e.valid,completeness:t,...o}:{...y,mode:n,valid:!1,completeness:t,...o}}i(Ea,"createAdapterResult");var va={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const: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 De=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 oo=new De;function so(e,t){return oo.define(e,t)}i(so,"defineIntent");function Zt(){return new De}i(Zt,"createIntentRegistry");var ao=oo;var io=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Jt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!io.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${io.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(Jt,"validateIntentName");var he=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
5
+ `}var qr,Un,zr,Mt,Ht,Kt,Yr,Xr,ot,se,uc,Vt=at(()=>{"use strict";tt();$t();qr="1.0",Un="127.0.0.1",zr=0,Mt="/snapshot",Ht="/events",Kt="/graph",Yr="snapshot",Xr="in-process-local",ot=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},se=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"}},uc=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(Vn,"isArkRunInspectorProductionEnv");i(fc,"ipv4Octets");i(pi,"unwrapIpv4Mapped");i(st,"isArkRunInspectorLoopbackHost");i(ui,"closedHost");i(gc,"closedPort");i(Gt,"resolveArkRunInspectorBind");i(_e,"arkRunInspectorUrl");i(mc,"jsonClone");i(yc,"closedTransportFacts");i(jn,"buildArkRunInspectorSnapshot");i(Ut,"formatArkRunInspectorSseEvent")});var fi={};Ii(fi,{listenArkRunInspector:()=>Ic});function hc(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Rc(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Ac(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Bn(e,t,n){e.writeHead(t,hc()),e.end(JSON.stringify(n))}function kc(e,t){let n=e.address();if(n===null||typeof n=="string")throw new se(t.host);if(!st(n.address))throw new se(n.address);return{host:t.host,port:n.port}}async function Ic(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((g,m)=>{let h=Ac(g.url),p=h.pathname;if(g.method==="GET"&&(p==="/"||p===Mt)){Bn(m,200,l());return}if(g.method==="GET"&&p===Kt){try{Bn(m,200,e.requestGraph(Mn({slice:h.searchParams.get("slice"),nodeIds:h.searchParams.get("nodeIds"),degreesOfSeparation:h.searchParams.get("degreesOfSeparation"),include:h.searchParams.get("include"),exclude:h.searchParams.get("exclude")})))}catch(f){if(f instanceof J){Bn(m,400,{error:f.message,option:f.option});return}throw f}return}if(g.method==="GET"&&p===Ht){m.writeHead(200,Rc()),m.flushHeaders(),m.write(Ut(l())),r.add(m);let f=s>0?setInterval(()=>{m.write(Ut(l()))},s):void 0;f&&o.add(f);let u=i(()=>{r.delete(m),f&&(clearInterval(f),o.delete(f))},"drop");g.on("close",u),m.on("close",u);return}Bn(m,404,{error:"not found"})});try{await new Promise((g,m)=>{let h=i(p=>m(p),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{a=kc(c,t.bind),g()}catch(p){m(p instanceof Error?p:new se(t.bind.host))}})})}catch(g){throw await new Promise(m=>{c.close(()=>m())}),g}return{host:a.host,port:a.port,url:_e(a.host,a.port,"/"),snapshotUrl:_e(a.host,a.port,Mt),eventsUrl:_e(a.host,a.port,Ht),graphUrl:_e(a.host,a.port,Kt),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 gi=at(()=>{"use strict";Kn();Vt();i(hc,"jsonHeaders");i(Rc,"sseHeaders");i(Ac,"requestUrl");i(Bn,"writeJson");i(kc,"boundAddress");i(Ic,"listenArkRunInspector")});var Zn="4.8.4";var vi=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,bi=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ei=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Si(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return vi.test(n)?"pure-shared":r==="PersistenceAdapters"&&(bi.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ei.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Si,"classifyLayerImportKind");function Ci(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=Si(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(Ci,"layerImportNextAction");function wi(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(wi,"arkRunCallSiteName");function xi(e){let t=wi(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(xi,"arkRunNextAction");function le(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ci(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 xi(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease(), then preflight again. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(le,"deterministicNextAction");var Qn="1.5",Oi="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}i(w,"text");function oo(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(oo,"positiveInteger");function io(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(io,"adapterFindingTargetKey");function so(e){let t=new Map;return e.map(n=>{let r=io(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(so,"adapterFindingOccurrenceTargetKeys");function Pi(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(Pi,"adapterFindingRefFromTargetKey");function _i(e){return`${Oi}#${e}`}i(_i,"adapterDocsCodePath");function Ni(e,t,n){return le({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}i(Ni,"nextActionForDiagnostic");function Jn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},a=n??io(e),l=Pi(a);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:oo(e.line,1),column:oo(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ni(r,s,e),findingRef:l,targetKey:a,docsCodePath:_i(r)}}i(Jn,"toAdapterDiagnostic");function Ti(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(h=>({code:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=so(s),c=so(a),g=[...s.map((h,p)=>Jn(h,"error",l[p])),...a.map((h,p)=>Jn(h,"warning",c[p]))],m={schemaVersion:Qn,completenessReasons:r,diagnostics:g};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...m,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...h}:{...m,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...o}:{...m,mode:n,valid:!1,completeness:t,...o}}i(Ti,"createAdapterResult");var Di={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:Qn},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var Te=class{static{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 ao=new Te;function lo(e,t){return ao.define(e,t)}i(lo,"defineIntent");function Yt(){return new Te}i(Yt,"createIntentRegistry");var co=ao;var po=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Xt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!po.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${po.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(Xt,"validateIntentName");var Ae=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{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let c of a)n.push({policyName:s.name,severity:s.severity,message:c.message,details:c.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new he(n.hardViolations);return n}clear(){this.policies.length=0}};function Le(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(Le,"definePolicy");function ba(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(ba,"defaultLayerOf");function co(e,t){return t.resolveLayer?.(e)??ba(e)}i(co,"resolveLayer");function Sa(e,t,n){return e===n.from&&t===n.to}i(Sa,"matchesRule");function Qt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Le({name:t,severity:n,tags:["layer"],check:i(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],s=[];for(let a of o){let c=co(a.from,e),l=co(a.to,e);for(let m of e.rules)!m.allowed&&Sa(c,l,m)&&s.push({policyName:t,severity:n,message:m.message??`Layer violation: ${a.from} (${c}) must not relate to ${a.to} (${l})`})}return s.length>0?s:!0},"check")})}i(Qt,"defineLayerPolicy");function Xt(e){return e.tags?.includes("layer")??!1}i(Xt,"isLayerPolicy");var Qn={layerIsolation(){return Qn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return Qt({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 en(e,t={}){return Qt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(en,"defineArchitectureProfilePolicy");function tn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(tn,"buildPublishPolicyContext");function lo(e){return Le(e)}i(lo,"definePublishPolicy");var Fe=class extends Error{static{i(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},$e=class extends Error{static{i(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Me=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"}},He=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},be=class extends Error{static{i(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},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}},Ke=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 dt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Jt(e);if(!n.valid)throw new $e(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Fe(e)}}i(dt,"assertIntentAllowed");function po(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new be(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new be(e.intent,e.metadata.source)}}i(po,"assertSourceAllowed");function pt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new He(e.intent,n.issues)}i(pt,"assertContractAllowed");function Ge(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Ge,"isPlainRecord");function Ue(e){return Array.isArray(e)?e.map(Ue):Ge(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ue(n)])):e}i(Ue,"clonePatchValue");function Xn(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]=Ue(s);continue}if(Ge(r[o])&&Ge(s)){r[o]=Xn(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=er(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(Xn,"mergeRecordPatch");function er(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]=Ue(o);return}if(Ge(r[s])&&Ge(o)){r[s]=Xn(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=er(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(er,"mergeArrayPatch");function uo(e,t){if(Array.isArray(t)){if(e===void 0)return Ue(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return er(e,t)}if(e===void 0)return Ue(t);if(!Ge(e))throw new Error("Object interceptor patch requires an object payload.");return Xn(e,t)}i(uo,"applyPayloadPatch");async function fo(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:i(l=>{s.push(l)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let l of s)c={...c,payload:uo(c.payload,l),metadata:{...c.metadata}};pt(c,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=c,o.lastInterceptedAt=a,t.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await Ca(o,r,a,t)}}return r}i(fo,"applyInterceptors");async function Ca(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(Ca,"recordInterceptorError");var mo=new Map;function yo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(yo,"escapeLiteral");function nn(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(nn,"normalizeGlobSeparators");function wa(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(wa,"bracesBalanced");function Se(e){let t=mo.get(e);if(t)return t;let n=nn(e),r=wa(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=yo(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=yo(l)}let a=new RegExp(`^${o}$`);return mo.set(e,a),a}i(Se,"globToRegExp");function xa(e){return nn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(xa,"concreteGlobSegments");function tr(e,t){let n=nn(String(e)),r=xa(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let m of r){let y=-1;for(let h=c;h<a.length;h+=1)if(a[h]===m){y=h;break}if(y<0)return s;l=y,c=y+1}return(l+1)*1e6+r.length*1e4+o}i(tr,"patternSpecificity");function ne(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Se(a).test(n))){for(let a of s.patterns??[])if(Se(a).test(n)){let c=tr(a,n);c>o&&(o=c,r=s.name)}}return r}i(ne,"layerForRelativePath");function go(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(go,"sliceIdForPath");function Pa(e){let t=new Set;for(let n of e??[]){let o=nn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(Pa,"inferSliceFoldersFromPatterns");function Oa(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 Pa(r?.patterns)}i(Oa,"resolveSliceFolders");function _a(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(_a,"peerIsolationMustDeny");function re(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=Oa(o,t,r?.layers),l=s&&a?go(s,c):void 0,m=s&&a?go(a,c):void 0;if(_a({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:m}))return o;continue}if(t!==n)return o}}i(re,"findDeniedEdgeRule");async function ho(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=re(r.rules,o,s);if(!a)return;let c=t.mode,l=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,m={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:c,message:l,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:m}),await t.recordAudit("layer.observedViolation",e,m),c==="hard")throw new Ke(n,e.intent,o,s,l)}i(ho,"assertObservedLayerFlowAllowed");async function Ro(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(Ro,"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 ut(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(ut,"appendTrace");async function rn(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){ut(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(rn,"recordAudit");async function Ao(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."};ut(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 rn(e,"event.rawPublish",t,n)}i(Ao,"recordRawPublishDiagnostic");async function ko(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Na(e,o),await e.eventBuffer?.enqueue(t,r),ut(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 rn(e,"event.published",t,{subscribersNotified:n}),o}i(ko,"recordSuccessfulPublish");function nr(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}i(nr,"enrichMetadata");var Io=0;function Ta(){return Io+=1,`interceptor-${Date.now()}-${Io}`}i(Ta,"nextInterceptorRegistrationId");var Ve=class{static{i(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new ve(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Xt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Me;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=tn({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,l,m=typeof t!="function";if(m){let d=t,p=r??n??{};l={...d,metadata:nr(d.metadata,p,this.recording.instanceId)}}else{let d=t,p=n,u=r??{},f=d(p);l={...f,metadata:nr(f.metadata,u,this.recording.instanceId)}}m&&this.strictRegistry&&await Ao(this.recording,l),dt(l.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),po(l,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),pt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),l=await fo(l,{interceptorsForIntent:i(d=>this.interceptorsByIntent.get(d)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),pt(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await ho(l,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(l.metadata.source,l.intent);let y=[...this.subscriptionsByIntent.get(l.intent)??[]];this.policyEngine&&await Ro(l,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(d=>this.appendTrace(d),"appendTrace"),recordAudit:i((d,p,u)=>this.recordAudit(d,p,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((d,p,u)=>this.safeHook(d,p,u),"safeHook")}),await ko(this.recording,l,s?y.length:0,o.tx);let h=(async()=>{s&&await Promise.all(y.map(d=>this.invokeHandler(d,l))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(l),"onPublish",l)})();return a?await h:h.then(void 0,()=>{}),l}createPublisher(t){let n=typeof t=="string"?t:t.name;return dt(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;dt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let c=this.subscriptionsByIntent.get(r);if(!c)return;let l=c.indexOf(o);l>=0&&c.splice(l,1),c.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;dt(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){ut(this.recording,t)}async recordAudit(t,n,r){await rn(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 Eo(e){return new Ve(e)}i(Eo,"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 vo(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}bo(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,c)=>{vo(a,t.items,`${n}[${c}]`,r,o)})}i(vo,"validateSchemaField");function bo(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let c=Fa(o,s),l=e[s];if(l===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}vo(l,a,c,n,r)}}i(bo,"validateObjectSchema");var ft=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(bo(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(s))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let c of a.issues)o.push({intent:t.intent,version:r.version,field:Da(c.path),message:c.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function on(){return new ft}i(on,"createEventContractRegistry");var So=0;function $a(){return So+=1,`outbox-${Date.now()}-${So}`}i($a,"nextOutboxId");function Co(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Co,"cloneRecord");var Ce=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:$a(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Co(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(Co)}async clear(){this.records.clear()}},wo=Ce;function rr(e){return`${e.from}->${e.to}`}i(rr,"flowKey");function xo(e){let t=new Set,n=[];for(let r of e){let o=rr(r);t.has(o)||(t.add(o),n.push(r))}return n}i(xo,"uniqueFlows");function Po(e,t){let n=new Set(t.map(rr));return e.filter(r=>!n.has(rr(r)))}i(Po,"difference");function sn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="produces").map(f=>({from:f.from,to:f.to})),a=n?.getHistory().map(f=>({from:f.event.metadata.source,to:f.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(f=>f.kind==="observed").map(f=>({from:f.from,to:f.to})),l=xo([...o,...s]),m=xo([...a,...c]),y=m.filter(f=>!f.from||f.from==="unknown"),h=t?Array.from(new Set(m.map(f=>f.from).filter(f=>f&&f!=="unknown"&&!t.has(f)))):[],d=t?Array.from(new Set(m.map(f=>f.to).filter(f=>!t.has(f)))):[],p=new Set(m.flatMap(f=>[f.from,f.to])),u=t?t.list().map(f=>f.name).filter(f=>!p.has(f)):[];return{generatedAt:new Date().toISOString(),declaredProductions:l,observedProductions:m,declaredButUnobserved:Po(l,m),observedButUndeclared:Po(m.filter(f=>f.from!=="unknown"),l),unknownSources:y,unregisteredObservedSources:h,unregisteredObservedIntents:d,registeredButNeverObserved:u}}}}i(sn,"createObservabilityReporter");function Oo(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(Oo,"createArkTestHarness");var _o=0;function Ma(){return _o+=1,`audit-${Date.now()}-${_o}`}i(Ma,"createAuditId");function Ha(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}i(Ha,"matchesQuery");var mt=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>Ha(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},an=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:Ma(),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 cn(e={}){return new an(e.store??new mt(e.maxRecords))}i(cn,"createAuditTrail");var ln=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
7
+ ${n}`),this.name="PolicyViolationError",this.violations=t}};var Ee=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 Ae(n.hardViolations);return n}clear(){this.policies.length=0}};function De(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}i(De,"definePolicy");function Li(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(Li,"defaultLayerOf");function uo(e,t){return t.resolveLayer?.(e)??Li(e)}i(uo,"resolveLayer");function Fi(e,t,n){return e===n.from&&t===n.to}i(Fi,"matchesRule");function Zt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return De({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=uo(a.from,e),c=uo(a.to,e);for(let g of e.rules)!g.allowed&&Fi(l,c,g)&&s.push({policyName:t,severity:n,message:g.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(Zt,"defineLayerPolicy");function Jt(e){return e.tags?.includes("layer")??!1}i(Jt,"isLayerPolicy");var er={layerIsolation(){return er.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return Zt({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function Qt(e,t={}){return Zt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(Qt,"defineArchitectureProfilePolicy");function en(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(en,"buildPublishPolicyContext");function fo(e){return De(e)}i(fo,"definePublishPolicy");var Le=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}},Fe=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}},$e=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"}},Me=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}},Se=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}},ke=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}},He=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 lt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Xt(e);if(!n.valid)throw new Fe(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Le(e)}}i(lt,"assertIntentAllowed");function go(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Se(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Se(e.intent,e.metadata.source)}}i(go,"assertSourceAllowed");function ct(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Me(e.intent,n.issues)}i(ct,"assertContractAllowed");function Ke(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Ke,"isPlainRecord");function Ge(e){return Array.isArray(e)?e.map(Ge):Ke(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ge(n)])):e}i(Ge,"clonePatchValue");function tr(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]=Ge(s);continue}if(Ke(r[o])&&Ke(s)){r[o]=tr(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=nr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(tr,"mergeRecordPatch");function nr(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]=Ge(o);return}if(Ke(r[s])&&Ke(o)){r[s]=tr(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=nr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(nr,"mergeArrayPatch");function mo(e,t){if(Array.isArray(t)){if(e===void 0)return Ge(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return nr(e,t)}if(e===void 0)return Ge(t);if(!Ke(e))throw new Error("Object interceptor patch requires an object payload.");return tr(e,t)}i(mo,"applyPayloadPatch");async function yo(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:mo(l.payload,c),metadata:{...l.metadata}};ct(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 $i(o,r,a,t)}}return r}i(yo,"applyInterceptors");async function $i(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($i,"recordInterceptorError");var ho=new Map;function Ro(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ro,"escapeLiteral");function tn(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(tn,"normalizeGlobSeparators");function Mi(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(Mi,"bracesBalanced");function pe(e){let t=ho.get(e);if(t)return t;let n=tn(e),r=Mi(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Ro(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+=Ro(c)}let a=new RegExp(`^${o}$`);return ho.set(e,a),a}i(pe,"globToRegExp");function Hi(e){return tn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Hi,"concreteGlobSegments");function rr(e,t){let n=tn(String(e)),r=Hi(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let g of r){let m=-1;for(let h=l;h<a.length;h+=1)if(a[h]===g){m=h;break}if(m<0)return s;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+o}i(rr,"patternSpecificity");function ie(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>pe(a).test(n))){for(let a of s.patterns??[])if(pe(a).test(n)){let l=rr(a,n);l>o&&(o=l,r=s.name)}}return r}i(ie,"layerForRelativePath");function Ao(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(Ao,"sliceIdForPath");function Ki(e){let t=new Set;for(let n of e??[]){let o=tn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(Ki,"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 Ki(r?.patterns)}i(Gi,"resolveSliceFolders");function ko(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(ko,"normalizeSegments");function bo(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(bo,"trimTrailingSlashes");var Ui=["src","app"];function Vi(e){let t=bo(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Vi,"isBlanketRoot");function Io(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=ko(n);for(let s of t){if(typeof s!="string"||s.length===0||Vi(s))continue;if(s.includes("*")){let c=bo(s.toLowerCase());if(pe(c).test(r)||pe(`${c}/**`).test(r))return!0;continue}let a=ko(s);if(a.length===0)continue;let l=Ui.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let g=!0;for(let m=0;m<a.length;m+=1)if(o[c+m]!==a[m]){g=!1;break}if(g)return!0}}return!1}i(Io,"pathUnderSharedRoot");function vo(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(vo,"sliceMatchesDeclaration");function ji(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&vo(r.from,t)&&vo(r.to,n))}i(ji,"crossSliceEdgeAllowed");function Bi(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(Bi,"peerIsolationDecision");function Eo(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(Eo,"peerIsolationDenyExplanation");function ue(e,t,n,r){return or(e,t,n,r)?.rule}i(ue,"findDeniedEdgeRule");function or(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,l=Gi(o,t,r?.layers),c=s&&a?Ao(s,l):void 0,g=s&&a?Ao(a,l):void 0,m=Bi({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:g,fromShared:!c&&Io(s,o.sharedRoots),toShared:!g&&Io(a,o.sharedRoots),crossSliceAllowed:ji(o.allowedCrossSlice,c,g)});if(m.denied)return{rule:o,peerIsolationReason:m.reason,fromSlice:c,toSlice:g};continue}if(t!==n)return{rule:o}}}i(or,"findDeniedEdgeDecision");async function So(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=ue(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,g={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:g}),await t.recordAudit("layer.observedViolation",e,g),l==="hard")throw new He(n,e.intent,o,s,c)}i(So,"assertObservedLayerFlowAllowed");async function Co(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Ae&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}i(Co,"enforcePublishPolicy");function Wi(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(Wi,"appendHistory");function dt(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}i(dt,"appendTrace");async function nn(e,t,n,r){if(e.auditTrail)try{await e.auditTrail.record({type:t,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){dt(e,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}i(nn,"recordAudit");async function wo(e,t){let n={intent:t.intent,source:t.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};dt(e,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:n}),await nn(e,"event.rawPublish",t,n)}i(wo,"recordRawPublishDiagnostic");async function xo(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Wi(e,o),await e.eventBuffer?.enqueue(t,r),dt(e,{type:"event.published",timestamp:o.publishedAt,intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{subscribersNotified:n}}),await nn(e,"event.published",t,{subscribersNotified:n}),o}i(xo,"recordSuccessfulPublish");function sr(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}i(sr,"enrichMetadata");var Oo=0;function qi(){return Oo+=1,`interceptor-${Date.now()}-${Oo}`}i(qi,"nextInterceptorRegistrationId");var Ue=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 Ee(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Jt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new $e;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=en({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,g=typeof t!="function";if(g){let p=t,f=r??n??{};c={...p,metadata:sr(p.metadata,f,this.recording.instanceId)}}else{let p=t,f=n,u=r??{},y=p(f);c={...y,metadata:sr(y.metadata,u,this.recording.instanceId)}}g&&this.strictRegistry&&await wo(this.recording,c),lt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),go(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await yo(c,{interceptorsForIntent:i(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await So(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let m=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await Co(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(p=>this.appendTrace(p),"appendTrace"),recordAudit:i((p,f,u)=>this.recordAudit(p,f,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((p,f,u)=>this.safeHook(p,f,u),"safeHook")}),await xo(this.recording,c,s?m.length:0,o.tx);let h=(async()=>{s&&await Promise.all(m.map(p=>this.invokeHandler(p,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return a?await h:h.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return lt(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 ke(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;lt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let 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;lt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:qi(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){dt(this.recording,t)}async recordAudit(t,n,r){await nn(this.recording,t,n,r)}async invokeHandler(t,n){try{await Promise.resolve(t.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:t.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,t.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(t,n,r){try{await Promise.resolve(t())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function Po(e){return new Ue(e)}i(Po,"createEventBus");function zi(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(zi,"formatStandardSchemaPath");function Yi(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(Yi,"actualType");function Xi(e,t){return e?`${e}.${t}`:t}i(Xi,"formatPath");function _o(e,t,n,r,o){let s=Yi(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}No(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{_o(a,t.items,`${n}[${l}]`,r,o)})}i(_o,"validateSchemaField");function No(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=Xi(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}_o(c,a,l,n,r)}}i(No,"validateObjectSchema");var pt=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(No(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:zi(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function rn(){return new pt}i(rn,"createEventContractRegistry");var To=0;function Zi(){return To+=1,`outbox-${Date.now()}-${To}`}i(Zi,"nextOutboxId");function Do(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Do,"cloneRecord");var Ce=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Zi(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Do(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(Do)}async clear(){this.records.clear()}},Lo=Ce;function ir(e){return`${e.from}->${e.to}`}i(ir,"flowKey");function Fo(e){let t=new Set,n=[];for(let r of e){let o=ir(r);t.has(o)||(t.add(o),n.push(r))}return n}i(Fo,"uniqueFlows");function $o(e,t){let n=new Set(t.map(ir));return e.filter(r=>!n.has(ir(r)))}i($o,"difference");function on(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})),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=Fo([...o,...s]),g=Fo([...a,...l]),m=g.filter(y=>!y.from||y.from==="unknown"),h=t?Array.from(new Set(g.map(y=>y.from).filter(y=>y&&y!=="unknown"&&!t.has(y)))):[],p=t?Array.from(new Set(g.map(y=>y.to).filter(y=>!t.has(y)))):[],f=new Set(g.flatMap(y=>[y.from,y.to])),u=t?t.list().map(y=>y.name).filter(y=>!f.has(y)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:g,declaredButUnobserved:$o(c,g),observedButUndeclared:$o(g.filter(y=>y.from!=="unknown"),c),unknownSources:m,unregisteredObservedSources:h,unregisteredObservedIntents:p,registeredButNeverObserved:u}}}}i(on,"createObservabilityReporter");function Mo(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(Mo,"createArkTestHarness");var Ho=0;function Ji(){return Ho+=1,`audit-${Date.now()}-${Ho}`}i(Ji,"createAuditId");function Qi(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(Qi,"matchesQuery");var ut=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=>Qi(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},sn=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:Ji(),timestamp:t.timestamp??new Date().toISOString(),type:t.type,source:t.source,actor:t.actor,intent:t.intent,correlationId:t.correlationId,causationId:t.causationId,subject:t.subject,details:t.details};return await this.store.append(n),n}async query(t){return this.store.query(t)}async clear(){await this.store.clear()}};function an(e={}){return new sn(e.store??new ut(e.maxRecords))}i(an,"createAuditTrail");var ln=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
8
8
  `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";t+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
9
9
  `}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(t+=` ${this.safeId(r)}
10
- `);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let a=t.resolveLayer(s)??"Unclassified",c=n.get(a)??[];c.push(s),n.set(a,c)}let r=`flowchart TD
10
+ `);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let a=t.resolveLayer(s)??"Unclassified",l=n.get(a)??[];l.push(s),n.set(a,l)}let r=`flowchart TD
11
11
  `;for(let s of t.layers){let a=n.get(s.name)??[];if(a.length!==0){r+=` subgraph ${this.safeId(s.name)}[${s.name}]
12
- `;for(let c of a)r+=` ${this.safeId(c)}[${c}]
12
+ `;for(let l of a)r+=` ${this.safeId(l)}[${l}]
13
13
  `;r+=` end
14
14
  `}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
15
15
  `;for(let s of o)r+=` ${this.safeId(s)}[${s}]
16
16
  `;r+=` end
17
17
  `}for(let s of this.edges){let a=s.kind?`|${s.kind}|`:"";r+=` ${this.safeId(s.from)} -->${a} ${this.safeId(s.to)}
18
- `}return r.trim()}detectViolations(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.message}`)}return n}ensureNode(t){this.nodes.has(t)||this.nodes.set(t,{id:t})}addEdge(t){this.edges.some(r=>r.from===t.from&&r.to===t.to&&r.kind===t.kind)||this.edges.push(t)}findSimpleCycles(){let t=new Map;for(let c of this.edges)t.has(c.from)||t.set(c.from,[]),t.get(c.from).push(c.to);let n=[],r=new Set,o=[],s=i(c=>{r.add(c),o.push(c);for(let l of t.get(c)||[])if(!r.has(l))s(l);else if(o.includes(l)){let m=o.indexOf(l),y=o.slice(m).concat(l);n.push(y)}o.pop()},"dfs");for(let c of t.keys())r.has(c)||s(c);let a=new Set(n.map(c=>c.join("->")));return Array.from(a).map(c=>c.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function dn(){return new ln}i(dn,"createDependencyGraph");function pn(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(pn,"syncRegistryToGraph");var yt={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},No={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...yt,default:[]},kernelRoots:{...yt},managedLayers:{...yt,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},To={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...yt,default:[]},managedLayers:{...yt,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7}}};function gt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(gt,"isObject");function Do(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)gt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Do,"declaredLayerNames");function Lo(e){if(!gt(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(Lo,"defaultedArkRun");function Fo(e){if(!gt(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}}i(Fo,"defaultedArkOrder");function $o(e,t){let n=e.arkRun;if(n===void 0||!gt(n))return;let r=Do(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($o,"validateArkRunExtra");function Mo(e,t){let n=e.arkOrder;if(n===void 0||!gt(n))return;let r=Do(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(Mo,"validateArkOrderExtra");var Q="1.3",fn="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ho=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ka=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ga(){let e=[];for(let t of Ho)for(let n of Ho)t===n||Ka.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Ga,"createDefaultRules");var mn=Ga(),or=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],de={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ko={$schema:"https://json-schema.org/draft/2020-12/schema",$id:fn,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:fn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:Q,default:Q},name:{type:"string",minLength:1},include:{...de,minItems:1,default:["src"]},exclude:{...de,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:{...de,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...de,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...de,minItems:1},exclude:de,intentPrefixes:de,description:{type:"string",minLength:1},forbiddenGlobals:de,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:{...de,minItems: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}}},arkRun:No,arkOrder:To}},pe=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
18
+ `}return r.trim()}detectViolations(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.message}`)}return n}ensureNode(t){this.nodes.has(t)||this.nodes.set(t,{id:t})}addEdge(t){this.edges.some(r=>r.from===t.from&&r.to===t.to&&r.kind===t.kind)||this.edges.push(t)}findSimpleCycles(){let t=new Map;for(let l of this.edges)t.has(l.from)||t.set(l.from,[]),t.get(l.from).push(l.to);let n=[],r=new Set,o=[],s=i(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))s(c);else if(o.includes(c)){let g=o.indexOf(c),m=o.slice(g).concat(c);n.push(m)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||s(l);let a=new Set(n.map(l=>l.join("->")));return Array.from(a).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function cn(){return new ln}i(cn,"createDependencyGraph");function dn(e,t,n={}){let r=n.requireRegisteredTargets??!1;for(let o of e.getAllRelationships())r&&!e.has(o.to)||(o.kind==="dependsOn"?t.registerDependency(o.from,o.to,"declared"):t.registerDependency(o.from,o.to,"produces"))}i(dn,"syncRegistryToGraph");var Ve={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ko={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Ve,default:[]},kernelRoots:{...Ve},managedLayers:{...Ve,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Go={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Ve,default:[]},managedLayers:{...Ve,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Ve,default:[]}}};function ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ft,"isObject");function Uo(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)ft(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Uo,"declaredLayerNames");function Vo(e){if(!ft(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Vo,"defaultedArkRun");function jo(e){if(!ft(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(jo,"defaultedArkOrder");function Bo(e,t){let n=e.arkRun;if(n===void 0||!ft(n))return;let r=Uo(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(Bo,"validateArkRunExtra");function Wo(e,t){let n=e.arkOrder;if(n===void 0||!ft(n))return;let r=Uo(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(Wo,"validateArkOrderExtra");var re="1.3",un="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",qo=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],ea=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function ta(){let e=[];for(let t of qo)for(let n of qo)t===n||ea.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(ta,"createDefaultRules");var fn=ta(),ar=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ne={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},zo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:un,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:un,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:re,default:re},name:{type:"string",minLength:1},include:{...ne,minItems:1,default:["src"]},exclude:{...ne,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:fn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ne,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ne,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ne,minItems:1},exclude:ne,intentPrefixes:ne,description:{type:"string",minLength:1},forbiddenGlobals:ne,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ne,minItems:1},sharedRoots:{...ne,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...ne,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...ne,minItems:1}}},arkRun:Ko,arkOrder:Go}},fe=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 Go(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Go,"isObject");function un(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(un,"propertyPath");function je(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(je,"valueType");function Ua(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Ua,"resolveSchemaRef");function ht(e,t,n,r,o){if(t.$ref){let s=Ua(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ht(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Go(e)){o.push({path:n,message:`must be an object; received ${je(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:un(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:un(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||ht(e[c],a,un(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&ht(e[a],c,un(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${je(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>ht(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${je(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${je(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${je(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(ht,"validateNode");function Va(e){let t={...e,$schema:e.$schema===void 0?fn:e.$schema,schemaVersion:e.schemaVersion===void 0?Q: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=Lo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Fo(e.arkOrder)),t}i(Va,"defaultedConfig");function ja(e){return e===Q?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(ja,"migratedFromOf");function Ba(){let e=new Set([Q]);for(let t of or)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Ba,"knownInputVersions");function qa(e,t="ark.config.json"){if(!Go(e))throw new pe(t,[{path:"$",message:`must be an object; received ${je(e)}`}]);let n=Ba(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${Q}`}]);if(r!=="unversioned"&&!n.has(r))throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${Q}`}]);let o=r,s={...e},a=0;for(;o!==Q&&a<or.length+1;){a+=1;let c=or.find(l=>l.from===o);if(!c)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${Q}`}]);o=c.to,s.schemaVersion=o}if(o!==Q)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${Q}`}]);return{candidate:Va(s),migratedFrom:ja(r)}}i(qa,"migrateArkConfig");function sr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=qa(e,t),o=[];if(ht(n,Ko,"$",Ko,o),$o(n,o),Mo(n,o),o.length>0)throw new pe(t,o);return{config:n,migratedFrom:r}}i(sr,"loadArkConfigContract");function Uo(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new pe(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return sr(n,t)}i(Uo,"parseArkConfigJson");function Vo(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:fn,schemaVersion:Q};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Vo,"withArkConfigMetadata");function za(e){return e.endsWith(".")?e:`${e}.`}i(za,"normalizePrefix");function Wa(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(Wa,"byLongestPrefix");function yn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(za)})),n=[...t].sort(Wa),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(yn,"createArchitectureProfile");function gn(e,t={}){return yn({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(gn,"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}],Be=yn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ya,rules:mn.map(e=>({...e}))}),Za={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 jo(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Vo({include:e.include??[t],layers:Be.layers.map(o=>({name:o.name,patterns:(Za[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Be.rules]})}i(jo,"createElevenLayerArkConfig");var hn=class{static{i(this,"MetadataRegistryImpl")}entities=new Map;entity(t,n,r={}){if(this.entities.has(t)&&!r.allowOverwrite)throw new Error(`Entity metadata "${t}" is already registered.`);let o={name:t,fields:{},...n};return this.entities.set(t,o),o}getEntity(t){return this.entities.get(t)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(t){return this.listEntities().filter(n=>n.emits?.includes(t)||n.consumes?.includes(t))}validate(){let t=[];for(let n of this.entities.values()){n.name.trim()||t.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||t.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&t.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&t.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:t.length===0,issues:t}}toJSON(){return this.listEntities()}};function Rn(){return new hn}i(Rn,"createMetadataRegistry");function Bo(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}i(Bo,"definePort");function qo(e,t,n,r={}){let o=Array.isArray(n)?{...r,requiredKeys:n}:{...n??{}},s=o.requiredKeys;if(s&&s.length>0){let l=s.filter(m=>!Wo(t,m));if(l.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${l.join(", ")}`)}let a={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},c=ar(a);if(!c.ok)throw new Error(c.issues.map(l=>l.message).join(`
21
- `));return a}i(qo,"createAdapter");function zo(e,t=[]){let n=t.filter(r=>!Wo(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(zo,"checkContract");function ar(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(ar,"checkAdapterGovernance");function Wo(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(Wo,"hasMember");var cr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),dr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),pr=Object.freeze(Object.keys(dr).sort()),ir=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"}),lr=Object.freeze({process:Object.freeze(["process","node:process"])});function Rt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ir[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=ir[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:ir[e.slice(0,s)]??null}i(Rt,"capabilityForModuleSpecifier");function Ae(e,t){for(let n of t)if(lr[n]?.includes(e))return n;return null}i(Ae,"forbiddenGlobalForModuleSpecifier");function An(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=dr[r];if(o)return o}return null}i(An,"capabilityForAmbientName");function qe(e){if(e?.pure===!0)return[...cr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>cr.includes(r));return[...new Set(n)].sort()}i(qe,"effectiveCapabilityDeny");function At(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(At,"ambientCoveredByForbiddenGlobals");function kn(e){let t=new Set,n=new Set,r=Object.keys(dr);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 lr[o]??[])t.add(`import-exact:${a}`)}for(let o of qe(e)){if(t.add(`import:${o}`),o==="process")for(let s of lr.process)t.add(`import-exact:${s}`);for(let s of r)An(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(kn,"loweredLayerCoverage");function ze(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ze,"literalText");function Jo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Jo,"lineOf");function Yo(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(Yo,"isTypeOnlyReference");function Qo(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(Qo,"singleFileChecker");function ur(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(ur,"symbolAt");function fr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):ur(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(fr,"localDeclaration");function We(e,t){let n,r=[],o=i((a,c,l,m=!1)=>r.push({specifier:l,kind:c,line:Jo(t,a),typeOnly:m,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",ze(e,a.moduleSpecifier),Yo(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",ze(e,a.moduleSpecifier),Yo(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",ze(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,m=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!fr(e,n??(n=Qo(e,t)),t,a.expression);(c||m)&&o(a,m?"require":"dynamic-import",ze(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(We,"extractSemanticDependencies");function Ja(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=ze(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(Ja,"staticAccessPath");function Qa(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(Qa,"runtimeIdentifierReference");function Zo(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(Zo,"bestForbiddenMatch");function Ye(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Qo(e,t),s=new Map,a=new Set;for(let d of t.statements)if(e.isVariableStatement(d))for(let p of d.declarationList.declarations)e.isIdentifier(p.name)&&a.add(p.name.text);let c=i(d=>{let p=Ja(e,d);if(!p)return;let u=ur(o,p.root),f=u?s.get(u):void 0;return f?[...f,...p.segments.slice(1)]:fr(e,o,t,p.root)||a.has(p.root.text)?void 0:p.segments},"resolvePath");for(let d of t.statements)if(e.isVariableStatement(d))for(let p of d.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let u=c(p.initializer),f=ur(o,p.name);!u||!f||s.set(f,u)}let l=[],m=new Set,y=i((d,p)=>{let u=Jo(t,p),f=`${d}:${p.getStart(t)}`;m.has(f)||(m.add(f),l.push({name:d,line:u,node:p}))},"flag"),h=i(d=>{let p=d.parent&&(e.isPropertyAccessExpression(d.parent)||e.isElementAccessExpression(d.parent))&&d.parent.expression===d;if((e.isPropertyAccessExpression(d)||e.isElementAccessExpression(d))&&!p){let u=c(d),f=u?Zo(r,u):void 0;f&&y(f,d)}else e.isIdentifier(d)&&r.has(d.text)&&Qa(e,d)&&!fr(e,o,t,d)&&y(d.text,d);if(e.isVariableDeclaration(d)&&e.isObjectBindingPattern(d.name)&&d.initializer){let u=c(d.initializer);if(u)for(let f of d.name.elements){if(!e.isIdentifier(f.name))continue;let v=f.propertyName?ze(e,f.propertyName)??f.propertyName.text:f.name.text,b=Zo(r,[...u,v]);b&&y(b,d.initializer)}}e.forEachChild(d,h)},"visit");return h(t),l}i(Ye,"collectForbiddenCapabilityUses");function mr(e,t,n){let r=[];for(let o of n?.dependencies??We(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Rt(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,pr)){let s=An(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(mr,"collectCapabilityUses");var yr={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."},gr=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 hr(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(hr,"resolveIntentLayer");function we(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(we,"looksLikeArkIntent");function kt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&we(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:yr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:yr.PUBLISH_MISSING_SOURCE}),t}i(kt,"classifyPublishFacts");function F(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(F,"violation");function Ze(e,t){return e.slice(0,t).split(`
22
- `).length}i(Ze,"lineOf");function Xa(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(Xa,"extractQuotedStrings");function ei(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:c})}}return t.sort((r,o)=>r.index-o.index)}i(ei,"extractModuleSpecifiers");function ti(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(ti,"extractQuotedStringsAst");function ni(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(ni,"hasInfrastructureToken");function ri(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(ri,"isKnownInfrastructurePackage");function oi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(oi,"layerHasInfrastructureRole");function Et(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Et,"tsStringLiteralText");function si(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(si,"tsPropertyName");function Xo(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:si(e,r.name)===n)}i(Xo,"tsObjectProperty");function vt(e,t,n){return Xo(e,t,n)!==void 0}i(vt,"tsObjectHasProperty");function It(e,t,n){let r=Xo(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(It,"tsObjectPropertyValue");function ai(e,t){let n=It(e,t,"metadata");return vt(e,n,"source")}i(ai,"tsObjectHasMetadataSource");function es(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?es(e,t.name):!1:!1}i(es,"tsLooksLikeIntentCreatorExpression");function ii(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(ii,"tsIsPublishCall");function ci(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Et(e,n);return r!==void 0&&we(r)||vt(e,n,"intent")||es(e,n)}i(ci,"tsIsArkPublishCandidate");function li(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return ai(e,n)||vt(e,r,"source")||vt(e,o,"source")}i(li,"tsPublishHasSource");function di(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=It(e,n,"metadata");return Et(e,It(e,s,"source"))??Et(e,It(e,r,"source"))??Et(e,It(e,o,"source"))}i(di,"tsPublishSourceLiteral");function pi(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,l=[],m=i(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),y=i(h=>{if(ii(e,h)){let d=h.arguments[0],p=Et(e,d);for(let f of kt({publishCall:!0,rawIntentName:p,objectHasIntent:vt(e,d,"intent"),arkPublishCandidate:ci(e,h),hasSource:li(e,h)}))l.push(F(f.ruleId,f.message,{line:m(h),filePath:a}));let u=di(e,h);if(r&&c&&u&&we(u)){let f=r.resolveLayer(u);f&&f!==c&&l.push(F("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${f}, but the target file is classified as ${c}.`,{line:m(h),filePath:a,target:u,fromLayer:c,toLayer:f}))}}e.forEachChild(h,y)},"visit");return y(o),l}i(pi,"analyzePublishAst");function ts(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],l=a,m=l?.filePath,y=l?.layer,h=e.typescript,d=h?h.createSourceFile(m??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,p=d?We(e.typescript,d):void 0,u=p?p.filter(I=>I.specifier!==void 0).map(I=>({value:I.specifier,index:I.node.getStart(d),kind:I.kind,typeOnly:I.typeOnly})):ei(s),f=e.typescript?ti(e.typescript,s):Xa(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(m))for(let I of p?.filter(({unresolved:k})=>k)??[]){let k=I.kind==="require";c.push(F(k?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${k?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:I.line,filePath:m}))}let v=y!==void 0&&(r.has(y)||oi(y)),b=y!==void 0?` If "${y}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let I of n)if(I instanceof RegExp){I.lastIndex=0;let k=I.exec(s);I.lastIndex=0,k&&c.push(F("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${I}`,{line:k.index===void 0?void 0:Ze(s,k.index),filePath:m,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else s.includes(I)&&c.push(F("FORBIDDEN_SUBSTRING",`Forbidden substring: ${I}`,{line:Ze(s,s.indexOf(I)),filePath:m}));for(let I of u){let k=e.resolveImportTarget?.(I.value,m)??(e.resolveImportLayer?{layer:e.resolveImportLayer(I.value,m)}:void 0),C=typeof m=="string"?e.resolveImportTarget?.(m)??(e.resolveImportLayer?{layer:y,relPath:void 0}:void 0):void 0,Y=k?.layer;if(Y&&y){let _=re(e.architectureProfile?.rules,y,Y,{fromPath:C?.relPath,toPath:k?.relPath,layers:e.architectureLayers});if(_){if(I.typeOnly&&!_.peerIsolation)continue;let j=!!_.peerIsolation;c.push(F("LAYER_IMPORT_VIOLATION",_.message??(j?`Layer "${y}" must not import across slices into "${Y}".`:`Layer "${y}" must not import "${Y}".`),{line:Ze(s,I.index),source:I.value,target:I.value,filePath:m,fromLayer:y,toLayer:Y,suggestion:j?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:I.kind,peerIsolation:j,...I.typeOnly?{typeOnly:!0}:{}}}));continue}continue}v||I.typeOnly||!ni(I.value)&&!ri(I.value)||c.push(F("FORBIDDEN_IMPORT",`Forbidden ${I.kind} target: "${I.value}".`,{line:Ze(s,I.index),source:I.value,target:I.value,filePath:m,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:I.kind}}))}if(e.policies)for(let I of e.policies){let k=I.check({source:s,context:a});if(k!==!0)if(Array.isArray(k))for(let C of k)c.push(F("POLICY_VIOLATION",C.message,{filePath:m,suggestion:`Fix violation of policy "${I.name}".`}));else k===!1?c.push(F("POLICY_VIOLATION",`Policy ${I.name} failed on generated code`)):c.push(F("POLICY_VIOLATION",k.message))}if(o&&t.size>0)for(let I of f)we(I.value)&&!t.has(I.value)&&c.push(F("UNKNOWN_INTENT",`Unknown intent reference: "${I.value}"`,{line:Ze(s,I.index),filePath:m,target:I.value,suggestion:`Register intent "${I.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&y)for(let I of f){if(!we(I.value))continue;let k=e.architectureProfile.resolveLayer(I.value);if(!k)continue;let C=re(e.architectureProfile.rules,y,k);C&&c.push(F("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${y}" must not reference "${k}" through "${I.value}".`,{line:Ze(s,I.index),filePath:m,target:I.value,fromLayer:y,toLayer:k,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let I of e.extensions)try{let k=I.analyze(s,a);c.push(...k)}catch(k){c.push(F("EXTENSION_ERROR",`Extension "${I.name}" failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&d&&y&&e.forbiddenGlobals?.[y]?.length)try{let I=e.forbiddenGlobals[y];c.push(...Ye(e.typescript,d,I).map(k=>F("FORBIDDEN_GLOBAL",`${y} must not use the ambient global "${k.name}".`,{line:k.line,filePath:m,target:k.name,fromLayer:y,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let k of p??[]){if(k.typeOnly||!k.specifier)continue;let C=Ae(k.specifier,I);C&&c.push(F("FORBIDDEN_GLOBAL",`${y} must not use module "${k.specifier}" because it is the import form of forbidden global "${C}".`,{line:k.line,filePath:m,source:k.specifier,target:k.specifier,fromLayer:y,details:{importKind:k.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(I){c.push(F("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&d&&y&&e.capabilityWalls?.[y]?.length)try{let I=new Set(e.capabilityWalls[y]),k=e.forbiddenGlobals?.[y]??[];for(let C of mr(e.typescript,d))I.has(C.capability)&&(C.source==="ambient-global"&&At(C.symbol,k)||C.source==="import-based"&&Ae(C.symbol,k)||c.push(F("CAPABILITY_VIOLATION",C.source==="import-based"?`${y} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${y} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:m,target:C.symbol,capability:C.capability,fromLayer:y,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(I){c.push(F("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript)try{c.push(...pi(e.typescript,s,a,e.architectureProfile))}catch(I){c.push(F("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${I instanceof Error?I.message:String(I)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}i(ts,"createAICodeGate");function K(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(K,"deterministicHash");function D(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(D).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${D(t[n])}`).join(",")}}`}i(D,"stableSerialize");var xe="1.2";var ns=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=D(e),r=D(t);return n<r?-1:n>r?1:0}i(B,"compareCanonical");function q(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(q,"sortedUnique");function bt(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 K(D(t))}i(bt,"resolvedFactsEvidenceRequirementsHash");function ui(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(B),n=e.files.map(k=>({...k,typeOnlyExportNames:q(k.typeOnlyExportNames)})).sort((k,C)=>k.path<C.path?-1:k.path>C.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:q(k.namedBindings)}:{}})).sort(B),o=e.capabilityUses.map(k=>({...k})).sort(B),s=e.ambientUses.map(k=>({...k})).sort(B),a=e.publishCalls.map(k=>({...k})).sort(B),c=e.intentReferences.map(k=>({...k})).sort(B),l=e.safetyUses.map(k=>({...k})).sort(B),m=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(C=>({...C}))})).sort(B),y=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(B),h=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(B),d=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(B),p=(e.arkRunDeclarations??[]).map(k=>({...k,uses:q(k.uses),reactsTo:q(k.reactsTo),raises:q(k.raises),sends:q(k.sends)})).sort(B),u=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(B),f=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(B),v=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(B),b=e.files.map(({path:k,contentHash:C})=>({path:k,contentHash:C})).sort((k,C)=>k.path<C.path?-1:k.path>C.path?1:0),I=K(D(b));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:I,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:l,classShapes:m,arkRunKernelCalls:y,arkRunManagedNews:h,arkRunCompositionRootHits:d,arkRunDeclarations:p,arkOrderPlaneCalls:u,arkOrderGenericUpdates:f,arkOrderRootHits:v}}i(ui,"canonicalResolvedFactsInput");function rs(e){let t=ui(e);return{...t,factsHash:K(D(t))}}i(rs,"createCanonicalResolvedCandidateFacts");function Rr(e){return rs(ss($(e,"$"),!1))}i(Rr,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i($,"asRecord");function M(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(M,"assertOnlyKeys");function T(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(T,"requiredText");function ue(e,t,n){if(e[t]!==void 0)return T(e,t,n)}i(ue,"optionalText");function G(e,t,n){let r=T(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let c of o.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(G,"requiredProjectPath");function L(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(L,"requiredBoolean");function os(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(os,"requiredInteger");function oe(e,t,n){let r=os(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(oe,"requiredPositiveInteger");function U(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(U,"requiredArray");function fe(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(fe,"enumValue");function Je(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(Je,"parseStringArray");function fi(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(fi,"assertUnique");function ss(e,t){M(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=fe(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=fe(e,"completeness",["complete","partial","unavailable"],"$"),o=U(e,"completenessReasons","$").map((S,P)=>{let R=`$.completenessReasons[${P}]`,A=$(S,R);M(A,["code","message","file"],R);let N=A.file===void 0?void 0:G(A,"file",R);return{code:T(A,"code",R),message:T(A,"message",R),...N?{file:N}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=U(e,"files","$").map((S,P)=>{let R=`$.files[${P}]`,A=$(S,R);return M(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:G(A,"path",R),contentHash:T(A,"contentHash",R),parseStatus:fe(A,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:os(A,"parseDiagnosticCount",R),exportsOnlyTypes:L(A,"exportsOnlyTypes",R),typeOnlyExportNames:Je(A.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:L(A,"hasTopLevelSideEffects",R)}}),a=U(e,"dependencies","$").map((S,P)=>{let R=`$.dependencies[${P}]`,A=$(S,R);M(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let N=ue(A,"specifier",R),H=ue(A,"target",R),ge=fe(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(ge==="resolved-project"&&!H)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(ge!=="resolved-project"&&H)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(ge!=="dynamic"&&!N)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:G(A,"from",R),...N?{specifier:N}:{},kind:fe(A,"kind",["import","export","dynamic-import","require"],R),typeOnly:L(A,"typeOnly",R),line:oe(A,"line",R),resolution:ge,...H?{target:G(A,"target",R)}:{},...A.namedBindings!==void 0?{namedBindings:Je(A.namedBindings,`${R}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:L(A,"targetTypeOnlyExports",R)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:L(A,"sourcePureTypeModule",R)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:L(A,"namedBindingsTypeOnly",R)}:{},...A.portProofEligible!==void 0?{portProofEligible:L(A,"portProofEligible",R)}:{}}}),c=U(e,"capabilityUses","$").map((S,P)=>{let R=`$.capabilityUses[${P}]`,A=$(S,R);return M(A,["file","line","symbol","capability","source"],R),{file:G(A,"file",R),line:oe(A,"line",R),symbol:T(A,"symbol",R),capability:fe(A,"capability",ns,R),source:fe(A,"source",["ambient-global","import-based"],R)}}),l=U(e,"ambientUses","$").map((S,P)=>{let R=`$.ambientUses[${P}]`,A=$(S,R);return M(A,["file","line","symbol"],R),{file:G(A,"file",R),line:oe(A,"line",R),symbol:T(A,"symbol",R)}}),m=U(e,"publishCalls","$").map((S,P)=>{let R=`$.publishCalls[${P}]`,A=$(S,R);M(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let N=ue(A,"rawIntentName",R),H=ue(A,"sourceIntent",R);return{file:G(A,"file",R),line:oe(A,"line",R),...N?{rawIntentName:N}:{},objectHasIntent:L(A,"objectHasIntent",R),arkPublishCandidate:L(A,"arkPublishCandidate",R),hasSource:L(A,"hasSource",R),...H?{sourceIntent:H}:{}}}),y=U(e,"intentReferences","$").map((S,P)=>{let R=`$.intentReferences[${P}]`,A=$(S,R);return M(A,["file","line","intent"],R),{file:G(A,"file",R),line:oe(A,"line",R),intent:T(A,"intent",R)}}),h=U(e,"safetyUses","$").map((S,P)=>{let R=`$.safetyUses[${P}]`,A=$(S,R);M(A,["file","line","kind","symbol"],R);let N=ue(A,"symbol",R),H=fe(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if(H==="in-memory-store"&&!N)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if(H!=="in-memory-store"&&N)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:G(A,"file",R),line:oe(A,"line",R),kind:H,...N?{symbol:N}:{}}});fi(s,S=>S.path,"$.files");let d=new Set(s.map(S=>S.path));for(let S of s){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!d.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:U(e,"arkRunKernelCalls","$")).map((S,P)=>{let R=`$.arkRunKernelCalls[${P}]`,A=$(S,R);M(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let N=ue(A,"receiver",R),H=ue(A,"nameLiteral",R);return{file:G(A,"file",R),line:oe(A,"line",R),kind:fe(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:T(A,"callee",R),viaImport:L(A,"viaImport",R),...N?{receiver:N}:{},...H?{nameLiteral:H}:{}}}),v=(e.arkRunManagedNews===void 0?[]:U(e,"arkRunManagedNews","$")).map((S,P)=>{let R=`$.arkRunManagedNews[${P}]`,A=$(S,R);M(A,["file","line","typeName","importedFrom"],R);let N=ue(A,"importedFrom",R);return{file:G(A,"file",R),line:oe(A,"line",R),typeName:T(A,"typeName",R),...N?{importedFrom:N}:{}}}),I=(e.arkRunCompositionRootHits===void 0?[]:U(e,"arkRunCompositionRootHits","$")).map((S,P)=>{let R=`$.arkRunCompositionRootHits[${P}]`,A=$(S,R);return M(A,["file","matchedRoot","hasKernelFactory"],R),{file:G(A,"file",R),matchedRoot:T(A,"matchedRoot",R),hasKernelFactory:L(A,"hasKernelFactory",R)}}),k=e.arkRunDeclarations===void 0?[]:U(e,"arkRunDeclarations","$"),Y=(e.arkOrderPlaneCalls===void 0?[]:U(e,"arkOrderPlaneCalls","$")).map((S,P)=>{let R=`$.arkOrderPlaneCalls[${P}]`,A=$(S,R);return M(A,["file","line","callee"],R),{file:G(A,"file",R),line:oe(A,"line",R),callee:T(A,"callee",R)}}),j=(e.arkOrderGenericUpdates===void 0?[]:U(e,"arkOrderGenericUpdates","$")).map((S,P)=>{let R=`$.arkOrderGenericUpdates[${P}]`,A=$(S,R);return M(A,["file","line","method"],R),{file:G(A,"file",R),line:oe(A,"line",R),method:T(A,"method",R)}}),_e=(e.arkOrderRootHits===void 0?[]:U(e,"arkOrderRootHits","$")).map((S,P)=>{let R=`$.arkOrderRootHits[${P}]`,A=$(S,R);return M(A,["file","matchedRoot","hasPlaneFactory"],R),{file:G(A,"file",R),matchedRoot:T(A,"matchedRoot",R),hasPlaneFactory:L(A,"hasPlaneFactory",R)}}),Ne=k.map((S,P)=>{let R=`$.arkRunDeclarations[${P}]`,A=$(S,R);return M(A,["file","line","uses","reactsTo","raises","sends"],R),{file:G(A,"file",R),line:oe(A,"line",R),uses:Je(A.uses,`${R}.uses`),reactsTo:Je(A.reactsTo,`${R}.reactsTo`),raises:Je(A.raises,`${R}.raises`),sends:Je(A.sends,`${R}.sends`)}});for(let[S,P]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",m],["$.intentReferences",y],["$.safetyUses",h],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",I],["$.arkRunDeclarations",Ne],["$.arkOrderPlaneCalls",Y],["$.arkOrderGenericUpdates",j],["$.arkOrderRootHits",_e]])for(let R of P)if(!d.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let Te=ue(e,"projectPackageName","$"),Wn=(e.classShapes===void 0?[]:U(e,"classShapes","$")).map((S,P)=>{let R=`$.classShapes[${P}]`,A=$(S,R);M(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let N=U(A,"mutatingMethods",R).map((H,ge)=>{let Ee=`${R}.mutatingMethods[${ge}]`,at=$(H,Ee);return M(at,["name","referencesGuardOrPublish"],Ee),{name:T(at,"name",Ee),referencesGuardOrPublish:L(at,"referencesGuardOrPublish",Ee)}});return{file:G(A,"file",R),className:T(A,"className",R),exported:L(A,"exported",R),hasPublicMutableFields:L(A,"hasPublicMutableFields",R),hasPublicSetters:L(A,"hasPublicSetters",R),hasPublicConstructor:L(A,"hasPublicConstructor",R),hasStaticFactory:L(A,"hasStaticFactory",R),mutatingMethods:N,...A.dataOnly===void 0?{}:{dataOnly:L(A,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:T(e,"resolverIdentity","$"),compilerIdentity:T(e,"compilerIdentity","$"),compilerOptionsHash:T(e,"compilerOptionsHash","$"),tsconfigHash:T(e,"tsconfigHash","$"),evidenceRequirementsHash:T(e,"evidenceRequirementsHash","$"),...Te?{projectPackageName:Te}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:l,publishCalls:m,intentReferences:y,safetyUses:h,classShapes:Wn,arkRunKernelCalls:u,arkRunManagedNews:v,arkRunCompositionRootHits:I,arkRunDeclarations:Ne,arkOrderPlaneCalls:Y,arkOrderGenericUpdates:j,arkOrderRootHits:_e}}i(ss,"parseResolvedFactsInput");function ke(e){let t=$(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=rs(ss(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(ke,"loadResolvedCandidateFacts");var mi=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},se={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Ar={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:x,message:x,file:V}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:V,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:se,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:V,line:se,symbol:x,capability:{enum:mi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:se,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:se,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:se,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:se,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:V,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:V,line:se,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:V,line:se,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:se,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:V,line:se,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:se,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},factsHash:x},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var kr="1.0";function Z(e){return`${e.from}->${e.to}`}i(Z,"dependencyKey");function St(e,t,n,r="dependency"){return{id:`${e}:${r}:${Z(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Z(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Z(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Z(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Z(t)} from the candidate, then preflight again.`}:{}}}i(St,"dependencyFinding");function Qe(e){let t=[],n=new Map(e.changeMap.map.files.map(d=>[d.path,d])),r=new Map(e.changes.map(d=>[d.path,d])),o=new Map(e.changeMap.map.dependencies.map(d=>[Z(d),d])),s=new Map(e.baseDependencies.map(d=>[Z(d),d])),a=new Map(e.candidateDependencies.map(d=>[Z(d),d]));for(let d of[...n.values()].sort((p,u)=>p.path.localeCompare(u.path))){let p=r.get(d.path);p?p.operation!==d.operation?t.push({id:`contradictory:file:${d.path}`,classification:"contradictory",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:p.operation,message:`${d.path} was planned as ${d.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${d.path} to the planned ${d.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${d.path}`,classification:"satisfied",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:p.operation,message:`${d.path} matches the planned ${d.operation} operation.`}):t.push({id:`missing:file:${d.path}`,classification:"missing",subject:"file",path:d.path,expectedOperation:d.operation,message:`${d.path} was planned as ${d.operation} but is absent from the actual change.`,nextAction:`${d.operation[0].toUpperCase()}${d.operation.slice(1)} ${d.path} in the complete change set, then preflight again.`})}for(let d of[...r.values()].sort((p,u)=>p.path.localeCompare(u.path)))n.has(d.path)||t.push({id:`unplanned:file:${d.path}`,classification:"unplanned",subject:"file",path:d.path,actualOperation:d.operation,message:`${d.path} has an unplanned ${d.operation} operation.`,nextAction:`Remove ${d.path} from the change set, then preflight again.`});let c=new Set;for(let d of[...o.values()].sort((p,u)=>Z(p).localeCompare(Z(u)))){if(a.has(Z(d))){t.push(St("satisfied",d,`${d.from} -> ${d.to} exists in the candidate architecture.`));continue}let p={from:d.to,to:d.from};a.has(Z(p))?(c.add(Z(p)),t.push(St("contradictory",d,`${d.from} -> ${d.to} was planned, but the candidate contains the reverse edge.`))):t.push(St("missing",d,`${d.from} -> ${d.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[d,p]of[...a].sort(([u],[f])=>u.localeCompare(f)))s.has(d)||o.has(d)||c.has(d)||!l.has(p.from)&&!l.has(p.to)||t.push({...St("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let m=new Set(e.changeMap.map.files.filter(d=>d.operation==="delete").map(d=>d.path));for(let[d,p]of[...s].sort(([u],[f])=>u.localeCompare(f)))a.has(d)||m.has(p.from)||m.has(p.to)||!l.has(p.from)&&!l.has(p.to)||t.push({...St("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let y={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((d,p)=>y[d.classification]-y[p.classification]||(d.subject===p.subject?0:d.subject==="file"?-1:1)||d.id.localeCompare(p.id));let h={satisfied:t.filter(d=>d.classification==="satisfied").length,missing:t.filter(d=>d.classification==="missing").length,contradictory:t.filter(d=>d.classification==="contradictory").length,unplanned:t.filter(d=>d.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}i(Qe,"analyzeArchitectureConvergence");var as="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",yi=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"];var is={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},gu={$schema:"https://json-schema.org/draft/2020-12/schema",$id:as,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:as},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:[...yi]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:is,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:is}}}};function Ct(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Ct,"emptyEffectiveArkRules");function cs(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(cs,"effectiveContractPolicyPayload");function gi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(gi,"titleMatchesInvariant");function hi(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(hi,"symbolPresent");function ls(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=[],a=[];for(let c of t){let l=[],m=c.coverage?.test!==!1,y=c.coverage?.symbol;if(!r&&m)for(let u of n){let f=e.fileContents[u];if(f&&gi(f,c.id)){l.push("test-title");break}}y&&hi(e.fileContents,y)&&l.push("symbol");let d=(c.coverage?.test===!0||!!y||c.coverage===void 0)&&l.length>0||c.coverage?.test===!1&&!y?!0:l.length>0,p=r&&m&&l.length===0;if(s.push({invariantId:c.id,layer:c.provenance.layer,sourceFile:c.provenance.sourceFile,mode:c.mode,covered:d&&!p,evidence:l,partial:p,description:c.description}),!d||p){let u=c.mode==="enforced"&&!p,f=r||n.length===0?"never-had-tests":"tests-disappeared";a.push({ruleId:"INVARIANT_UNCOVERED",message:p?o?`Invariant ${c.id} coverage cannot be proven (coverage file budget exhausted); reporting partial, not covered.`:`Invariant ${c.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:f==="tests-disappeared"?`Invariant ${c.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${c.id} is not covered by a test title or declared symbol (never-had-tests).`,file:c.provenance.sourceFile,line:1,arkruleId:c.id,arkruleSource:c.provenance.sourceFile,fromLayer:c.provenance.layer,severity:u?"error":"warning",failsStrict:u,kind:f})}}return{coverage:s,violations:a,partial:s.some(c=>c.partial)}}i(ls,"evaluateInvariantCoverage");function ds(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(ds,"canPromoteInvariant");var vr="1.0";function O(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(O,"addFinding");function X(e){return[...new Set(e??[])].sort()}i(X,"sortedUnique");function ae(e,t,n,r,o){let s=X(n),a=X(r),c=new Set(s),l=new Set(a),m=a.filter(h=>!c.has(h)),y=s.filter(h=>!l.has(h));m.length===0&&y.length===0||(m.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),y.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(ae,"compareStringSets");function wt(e,t,n,r,o,s,a){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(wt,"compareBoolean");function In(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(In,"keyed");function Ri(e,t,n){let r=In(t,s=>s.name),o=In(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&O(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),c=o.values.get(s),l=`$.layers[${s}]`;if(!a&&c){O(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){O(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;ae(e,`${l}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ae(e,`${l}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let m=kn(a),y=kn(c);ae(e,`${l}.forbiddenGlobals`,m.rawGlobals,y.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ae(e,`${l}.capabilities`,m.atoms,y.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),X(a.intentPrefixes).join("\0")!==X(c.intentPrefixes).join("\0")&&O(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:X(a.intentPrefixes),after:X(c.intentPrefixes)}),wt(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),wt(e,`${l}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Ri,"compareLayers");function Ai(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=In(t,r),s=In(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&O(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let c=o.values.get(a),l=s.values.get(a),m=`$.rules[${a}]`;if(!c&&l){l.allowed===!1&&O(e,{kind:"deny-added",path:m,classification:"strengthening",message:"A denied dependency edge was added.",after:l});continue}if(c&&!l){c.allowed===!1&&O(e,{kind:"deny-removed",path:m,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!l)continue;c.allowed!==l.allowed&&O(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${m}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:l.allowed});let y=c.peerIsolation===!0,h=l.peerIsolation===!0;if(y!==h){let d=c.from===c.to&&l.from===l.to;O(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${m}.peerIsolation`,classification:d?h?"strengthening":"weakening":"judgment-required",message:d?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:y,after:h})}X(c.sliceFolders).join("\0")!==X(l.sliceFolders).join("\0")&&O(e,{kind:"slice-folders-changed",path:`${m}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:X(c.sliceFolders),after:X(l.sliceFolders)})}}i(Ai,"compareRules");function ki(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,c=o[s]??0;a!==c&&O(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])wt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(ki,"compareSafety");function Ir(e){return e.mode==="enforced"?"enforced":"advisory"}i(Ir,"arkRunMode");function Er(e){return e.mode==="enforced"?"enforced":"advisory"}i(Er,"arkOrderMode");function Ii(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 (${Er(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=Er(r),c=Er(o);if(a!==c){let l=a==="advisory"&&c==="enforced";O(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:c})}ae(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Ii,"compareArkOrder");function Ei(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 (${Ir(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=Ir(r),c=Ir(o);if(a!==c){let l=a==="advisory"&&c==="enforced";O(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:c})}ae(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),wt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Ei,"compareArkRun");function vi(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(vi,"overallClassification");function ps(e,t){return`${e}::${t}`}i(ps,"ruleKey");function us(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(ps(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(ps(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(us,"indexEffectiveRules");function bi(e,t,n,r,o,s){let a=new Map((s??[]).map(d=>[d.invariantId,d])),c=t.arkRules??{},l=n.arkRules??{},m=[...new Set([...Object.keys(c),...Object.keys(l)])].sort();for(let d of m){let p=c[d],u=l[d],f=`$.arkRules[${d}]`;if(p===void 0&&u!==void 0){O(e,{kind:"arkrules-ref-added",path:f,classification:"strengthening",message:`ArkRules reference for layer ${d} was added.`,after:u});continue}if(p!==void 0&&u===void 0){O(e,{kind:"arkrules-ref-removed",path:f,classification:"weakening",message:`ArkRules reference for layer ${d} was removed.`,before:p});continue}p!==u&&O(e,{kind:"arkrules-ref-path-changed",path:f,classification:"judgment-required",message:`ArkRules file path for layer ${d} changed; verify the effective rules still match intent.`,before:p,after:u})}let y=us(r),h=us(o);for(let d of[...new Set([...y.structure.keys(),...h.structure.keys()])].sort()){let p=y.structure.get(d),u=h.structure.get(d),f=`$.arkRules.structure[${d}]`;if(!p&&u){O(e,{kind:"arkrule-structure-added",path:f,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(p&&!u){O(e,{kind:"arkrule-structure-removed",path:f,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!u)){if(p.mode!==u.mode){let v=p.mode==="advisory"&&u.mode==="enforced";O(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${f}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:p.mode,after:u.mode})}p.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${f}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:p.sensor,after:u.sensor})}}for(let d of[...new Set([...y.invariants.keys(),...h.invariants.keys()])].sort()){let p=y.invariants.get(d),u=h.invariants.get(d),f=`$.arkRules.invariants[${d}]`;if(!p&&u){O(e,{kind:"arkrule-invariant-added",path:f,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(p&&!u){O(e,{kind:"arkrule-invariant-removed",path:f,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!u)&&p.mode!==u.mode)if(p.mode==="advisory"&&u.mode==="enforced"){let b=a?.get(u.id),I=ds(b);I.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${f}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${f}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${I.reason}`,before:p.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${f}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:p.mode,after:u.mode})}}i(bi,"compareArkRules");function br(e,t,n){let r=[];ae(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ae(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ae(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),wt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let c=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&O(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Ri(r,e.layers,t.layers),Ai(r,e.rules,t.rules),ki(r,e,t),bi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Ei(r,e,t),Ii(r,e,t),r.sort((c,l)=>c.path.localeCompare(l.path)||c.id.localeCompare(l.id)),{schemaVersion:vr,classification:vi(r),findings:r}}i(br,"classifyArkPolicyDelta");function Sr(e,t){if(!e||e.schemaVersion!==vr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=X(e.findingIds),r=X(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(Sr,"policyDeltaAcknowledgementMatches");function Pe(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(Pe,"normalizePath");function fs(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(fs,"isIdentifierStart");function En(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(En,"isIdentifierCharacter");function J(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(J,"skipWhitespace");function xt(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(xt,"readString");function ee(e,t,n){return e.startsWith(t,n)&&!En(e[n-1])&&!En(e[n+t.length])}i(ee,"isWordAt");function ms(e,t){let n=J(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=J(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ee(e,"type",n))return!1;let o=J(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ee(e,"as",o)||!fs(e[o]))return!1;for(n=o;n<e.length&&En(e[n]);)n+=1;if(n=J(e,n),ee(e,"as",n)){if(n=J(e,n+2),!fs(e[n]))return!1;for(;n<e.length&&En(e[n]);)n+=1}r=!0}return!1}i(ms,"bracedNamedBindingsAreTypeOnly");function Si(e,t){if(t=J(e,t+6),e[t]==="(")return xt(e,J(e,t+1));let n=!1;if(ee(e,"type",t)){let o=J(e,t+4);e[o]!==","&&!ee(e,"from",o)&&(n=!0)}else ms(e,t)&&(n=!0);let r=ys(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Si,"specifierAfterImport");function Ci(e,t){t=t+6;let n=J(e,t),r=!1;if(ee(e,"type",n)){let s=J(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else ms(e,n)&&(r=!0);let o=ys(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(Ci,"specifierAfterExport");function ys(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ee(e,"from",t))return xt(e,J(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return xt(e,t);if(t>0&&(ee(e,"import",t)||ee(e,"export",t)))return}}i(ys,"specifierInStaticStatement");function wi(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(wi,"skipTemplateLiteral");function xi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=J(e,t+7);if(e[r]!=="(")return;r=J(e,r+1);let o=xt(e,r);return o?{...o,requireCall:!0}:void 0}i(xi,"specifierAfterRequire");function Pi(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=wi(e,n);continue}if(r==="'"||r==='"'){let s=xt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&ee(e,"import",n)?Si(e,n):r==="e"&&ee(e,"export",n)?Ci(e,n):r==="r"&&ee(e,"require",n)?xi(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(Pi,"moduleSpecifiers");function gs(e,t){let n=[],r=[];for(let o of Pi(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let m=Rt(s);if(!m)continue;let y=e.content.slice(0,o.offset).split(`
24
- `).length;r.push({file:e.path,symbol:s,capability:m,evidence:{kind:"import",file:e.path,line:y,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
25
- `).length,c={kind:"import",file:e.path,line:a,excerpt:o.excerpt},l=Oi(e.path,s,t);n.push({from:e.path,specifier:s,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}i(gs,"moduleFactsFor");function Oi(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(Oi,"resolveSpecifier");function hs(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=re(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(hs,"violationsFor");var _i={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 Ni(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Ni,"hasActiveArkRules");function Ti(e,t){return Ni(e,t)?K(D(cs({config:e,arkRules:t,warnings:[]}))):K(D(e))}i(Ti,"policyHashFor");function vn(e,t,n){let r=typeof e=="string"?Uo(e,t):sr(e,t),o=n?.arkRules??Ct();return{...r,arkRules:o,policyHash:Ti(r.config,o)}}i(vn,"loadContract");function Rs(e){let t=vn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=vn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=br(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=o.length>0,a=s&&Sr(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(Rs,"analyzePolicyDelta");function Pt(e){let t=e.files.map(h=>{let d=Pe(h.path);return{path:d,content:h.content,contentHash:K(h.content),layer:ne(d,e.contract.config.layers)??null}}).sort((h,d)=>h.path.localeCompare(d.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let d=gs(h,n);r.push(...d.edges),o.push(...d.capabilityUses)}let s=hs(r,e.contract.config),a=new Map(e.contract.config.layers.map(h=>[h.name,h])),c=new Map(e.contract.config.layers.map(h=>[h.name,new Set(qe(h))]));for(let h of o){let d=n.get(h.file)?.layer;if(!d)continue;let p=a.get(d),u=Ae(h.symbol,p?.forbiddenGlobals??[]);if(u){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${d} must not use module "${h.symbol}" because it is the import form of forbidden global "${u}".`,symbol:h.symbol,evidence:h.evidence});continue}c.get(d)?.has(h.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${d} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let l=t.length===0?"complete":"partial",m=l==="complete"?[]:[{..._i}],y={schemaVersion:kr,policyHash:e.contract.policyHash,compilerOptionsHash:K(D(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:l,completenessReasons:m,valid:l==="complete"&&s.length===0,ir:y}}i(Pt,"analyzeProject");function bn(e){let t=new Map(e.files.map(n=>[Pe(n.path),n]));for(let n of e.changes){let r=Pe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Pt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(bn,"analyzeChange");function As(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(As,"explainViolation");function Cr(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],c=i(l=>{n.set(l,t),r.set(l,t),t+=1,s.push(l),o.add(l);for(let h of[...e.get(l)??[]].sort())e.has(h)&&(n.has(h)?o.has(h)&&r.set(l,Math.min(r.get(l)??0,n.get(h)??0)):(c(h),r.set(l,Math.min(r.get(l)??0,r.get(h)??0))));if(r.get(l)!==n.get(l))return;let m=[],y;do{if(y=s.pop(),y===void 0)break;o.delete(y),m.push(y)}while(y!==l);m.length>1&&a.push(m.sort())},"connect");for(let l of[...e.keys()].sort())n.has(l)||c(l);return a.sort((l,m)=>l[0]<m[0]?-1:l[0]>m[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(Cr,"detectArchitectureCycles");function Xe(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=re(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let c=!!a.peerIsolation,l=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=a.message??(c?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}). Extract shared code or use events/ports across slices.`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:l?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...l?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Cr(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(Xe,"evaluateArchitectureGraph");var Di=["no-anemic-model"];function ks(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ks,"escapeGlobLiteral");function Li(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+=ks(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ks(o)}return new RegExp(`^${n}$`)}i(Li,"globToRegExp");function Ot(e,t){return!t||t.length===0?!0:t.some(n=>Li(n).test(e))}i(Ot,"matchesAppliesTo");function Fi(e){return Di.includes(e)}i(Fi,"isTier2");function Is(e){return e.mode==="enforced"&&!Fi(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Is,"severityFor");function et(e,t,n,r=1){let{severity:o,failsStrict:s}=Is(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 wr(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(wr,"isInRuleLayer");function Sn(e,t,n){return t.filter(r=>!(!r.exported||!Ot(r.file,e.appliesTo)||!wr(r.file,e,n)))}i(Sn,"shapesForRule");function $i(e,t,n){let r=[];for(let o of Sn(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($i,"evaluateAggregatePrivateState");function Mi(e,t,n){let r=[];for(let o of Sn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(et(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Mi,"evaluateAlwaysValidFactory");function Hi(e,t,n){let r=[];for(let o of Sn(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(Hi,"evaluateDomainEventOnMutation");function Ki(e,t){let n=[];for(let r of t.files)Ot(r,e.appliesTo)&&wr(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(Ki,"evaluateOrchestrationOnly");function Gi(e,t){let n=[];for(let r of t.files)Ot(r,e.appliesTo)&&wr(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(Gi,"evaluateThinAdapter");function Ui(e,t,n){let r=[];for(let o of Sn(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(Ui,"evaluateNoAnemicModel");function Es(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(...$i(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Mi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Hi(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Ki(n,e));break;case"thin-adapter":t.push(...Gi(n,e));break;case"no-anemic-model":t.push(...Ui(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(Es,"evaluateArkRuleSensors");function vs(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>Ot(l,o.appliesTo)))continue;let{severity:a,failsStrict:c}=Is(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:c})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>Ot(c,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(vs,"collectEmptyAppliesToFindings");var Vi=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,ji=/\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*=)/,Bi=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,qi=/\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*=/,zi=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Wi(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(qi.source,"g"))??[],r=t.match(new RegExp(zi.source,"g"))??[],o=(t.match(/\bif\s*\(/g)??[]).length,s=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&o+s>=6,c=Vi.test(t),l=ji.test(t)||Bi.test(t),m=n.length>=1||r.length>=2,y=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=c&&m||l&&m||c&&y&&(o>=4||n.length>=1)||l&&c;return!a&&!h?null:{...a?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{}}}i(Wi,"deriveArkRuleFileHints");function bs(e){let t={};for(let[n,r]of Object.entries(e)){let o=Wi(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}i(bs,"buildArkRuleFileHints");function Yi(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(Yi,"normalizeExtraMergeTeethClassification");function Cn(e){let t=Yi(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(Cn,"extraMergeTeethAllowed");function Ss(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(Ss,"classifyResolvedLayerCoverage");var Zi=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Qu=new Set(Zi);function Cs(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Cs,"isArkRunKernelModuleSpecifier");var Ji=["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"],xr=new Set(Ji);function ws(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(xr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(xr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:xr.has(e.slice(0,r))}i(ws,"isArkRunTransportBypassSpecifier");var Qi=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],lf=new Set(Qi);var xs={"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"},Xi="ARKRUN_INTERACTION_NAME_INCOMPLETE";function _s(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(_s,"isDomainRoleLayer");function ec(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(ec,"compareFindings");function me(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:xs[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ce({ruleId:xs[t],fromLayer:s?.fromLayer,target:s?.target})}}i(me,"finding");function tc(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(tc,"bagForFile");function Ps(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Ps,"emitKinds");function Os(e){return e==="subscribe"||e==="register-handler"}i(Os,"handleKinds");function nc(e){return e==="resolve"||e==="resolve-singleton"}i(nc,"dependKinds");function rc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(me(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let c=s.get(a.matchedRoot)??[];c.push(a),s.set(a.matchedRoot,c)}for(let a of o){let c=[...s.get(a)??[]].sort((m,y)=>m.file.localeCompare(y.file));if(c.length===0){r.push(me(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(c.some(m=>m.hasKernelFactory))continue;let l=c[0];r.push(me(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(rc,"evaluateMissingRoot");function oc(e,t,n,r,o){let s=new Map(t.map(c=>[c.name,c.intentPrefixes??[]])),a=[];for(let c of n){let l=c.specifier;if(!l||!Cs(l))continue;let m=r(c.from);m&&_s(m,s.get(m)??[])&&a.push(me(e,"arkrun-kernel-in-domain",c.from,c.line,`${m} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:m,target:l},o))}return a}i(oc,"evaluateKernelInDomain");function sc(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let c=new Map(t.map(y=>[y.name,y.intentPrefixes??[]])),l=new Set(r.filter(y=>y.hasKernelFactory).map(y=>y.file)),m=[];for(let y of n){if(l.has(y.file))continue;let h=y.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let d=o(y.file);!d||!a.has(d)||_s(d,c.get(d)??[])||m.push(me(e,"arkrun-direct-new",y.file,y.line,`${d} must not construct ${y.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:d,target:y.typeName},s))}return m}i(sc,"evaluateDirectNew");function ac(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let c=new Set(e.managedLayers);if(c.size===0)return{findings:s,completenessReasons:a};for(let l of t){if(!Ps(l.kind)&&!Os(l.kind)&&!nc(l.kind))continue;let m=r(l.file);if(!m||!c.has(m))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:Xi,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let y=tc(n,l.file);if(Ps(l.kind)){if(y.raises.has(l.nameLiteral)||y.sends.has(l.nameLiteral))continue;s.push(me(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:m,target:l.nameLiteral},o));continue}if(Os(l.kind)){if(y.reactsTo.has(l.nameLiteral))continue;s.push(me(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:m,target:l.nameLiteral},o));continue}y.uses.has(l.nameLiteral)||s.push(me(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:m,target:l.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(ac,"evaluateUndeclared");function ic(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let c=a.specifier;if(!c||!ws(c))continue;let l=n(a.from);!l||!o.has(l)||s.push(me(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(c)}; use the ArkRun kernel transport.`,{fromLayer:l,target:c},r))}return s}i(ic,"evaluateTransportBypass");function Ns(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=ac(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...rc(t,e.compositionRootHits,n),...oc(t,e.layers,e.dependencies,e.layerForFile,n),...sc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...ic(t,e.dependencies,e.layerForFile,n)].sort(ec),s=[...r.completenessReasons].sort((a,c)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,m=`${c.code}\0${c.file??""}\0${c.message}`;return l<m?-1:l>m?1:0});return{findings:o,completenessReasons:s}}i(Ns,"evaluateArkRunSensors");function Ts(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Ts,"isArkOrderModuleSpecifier");var Ds={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI"};function cc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(cc,"isDomainRoleLayer");function _t(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Ds[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ce({ruleId:Ds[t],fromLayer:s?.fromLayer,target:s?.target})}}i(_t,"finding");function Ls(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(_t(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let a=new Map;for(let c of e.planeRootHits){let l=a.get(c.matchedRoot)??[];l.push(c),a.set(c.matchedRoot,l)}for(let c of o){let l=a.get(c)??[];if(l.length===0){r.push(_t(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(c)} matched no governed files and has no createOrderPlane factory.`,{target:c},n));continue}l.some(m=>m.hasPlaneFactory)||r.push(_t(t,"arkorder-missing-plane",l[0].file,1,`ArkOrder plane root ${JSON.stringify(c)} has no createOrderPlane factory.`,{target:c},n))}}let s=new Map(e.layers.map(a=>[a.name,a.intentPrefixes??[]]));for(let a of e.dependencies){let c=a.specifier;if(!c||!Ts(c))continue;let l=e.layerForFile(a.from);l&&cc(l,s.get(l)??[])&&r.push(_t(t,"arkorder-kernel-in-domain",a.from,a.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:l,target:c},n))}for(let a of e.genericUpdates)r.push(_t(t,"arkorder-generic-update",a.file,a.line,`Generic ${a.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:a.method},n));return r.sort((a,c)=>a.file.localeCompare(c.file)||a.ruleId.localeCompare(c.ruleId)||a.line-c.line),{findings:r,completenessReasons:[]}}i(Ls,"evaluateArkOrderSensors");function z(e,t,n={}){return{ruleId:e,message:t,...n}}i(z,"configWarning");function wn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(p=>typeof p!="string"))&&s.push(z("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(z("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let p of["maxTsSuppressions","maxAnyCasts"]){let u=t.safety[p];u!==void 0&&(!Number.isInteger(u)||u<0)&&s.push(z("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${p} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],l=new Set([...a.map(p=>p.name).filter(Boolean),...c.map(p=>p.name).filter(p=>!!p)]);a.length===0&&s.push(z("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let m=new Set,y=new Set;for(let p of a){if(!p.name){s.push(z("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}m.has(p.name)&&y.add(p.name),m.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(f=>typeof f!="string"))&&s.push(z("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${p.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:p.name}));let u=Array.isArray(p.patterns)?p.patterns:[];if(u.length===0){s.push(z("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let f of u){let v;try{v=Se(f)}catch(I){s.push(z("CONFIG_INVALID_LAYER_PATTERN",`Layer "${p.name}" has an invalid pattern "${f}": ${I instanceof Error?I.message:String(I)}`,{layer:p.name,pattern:f}));continue}let b=p.optional===!0||p.reserved===!0||p.allowEmpty===!0;!r.some(I=>v.test(I))&&!b&&s.push(z("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${p.name}" pattern "${f}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:p.name,pattern:f,failsStrict:!1,reserved:!1}))}}for(let p of y)s.push(z("CONFIG_DUPLICATE_LAYER",`Layer "${p}" is configured more than once.`,{layer:p}));if(l.size>0)for(let p of n??[])p.from&&!l.has(p.from)&&s.push(z("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${p.from}".`,{fromLayer:p.from,toLayer:p.to})),p.to&&!l.has(p.to)&&s.push(z("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${p.to}".`,{fromLayer:p.from,toLayer:p.to}));let h=new Set;if(a.length>1)for(let p of r){let u=-1,f=[];for(let v of a)for(let b of v.patterns??[]){if(!Se(b).test(p))continue;let I=tr(b,p);I>u?(u=I,f=[v.name]):I===u&&!f.includes(v.name)&&f.push(v.name)}f.length>1&&h.add([...f].sort().join(" + "))}h.size>0&&s.push(z("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let d=r.filter(p=>!ne(p,a));return d.length>0&&s.push(z("CONFIG_UNCLASSIFIED_FILES",`${d.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:d.length,samples:d.slice(0,5)})),s}i(wn,"collectAnalysisConfigWarnings");function lc(e,t){return t.some(n=>{try{return Se(n).test(e)}catch{return!1}})}i(lc,"matchesAny");function dc(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(f=>f.kind==="ts-suppression").map(({file:f,line:v})=>({file:f,line:v})),c=t.safetyUses.filter(f=>f.kind==="any-cast").map(({file:f,line:v})=>({file:f,line:v})),l=t.safetyUses.filter(f=>(f.kind==="dynamic-import"||f.kind==="dynamic-require")&&!lc(f.file,s)).map(f=>({file:f.file,line:f.line,kind:f.kind==="dynamic-require"?"require":"import"})),m=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(f=>f.kind==="in-memory-store").map(f=>({file:f.file,line:f.line,store:f.symbol??"in-memory store"})),y=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(f=>f.peerIsolation===!1||f.allowed===!1&&!!f.from&&f.from===f.to&&f.peerIsolation!==!0).map(f=>({from:f.from,to:f.to})),h={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:l,inMemoryProductionStores:m,disabledPeerIsolationRules:y,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},d=[],p=l.filter(f=>f.kind==="import");if(p.length>0){let f=p[0];d.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let u=l.filter(f=>f.kind==="require");if(u.length>0){let f=u[0];d.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:f.file,line:f.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let f=a[0];d.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(c.length>o){let f=c[0];d.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:f.file,line:f.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(m.length>0){let f=m[0];d.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:f.file,line:f.line,message:`${m.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return y.length>0&&d.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${y.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:d}}i(dc,"evaluateSafety");function pc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(pc,"ambientForbiddenGlobal");function Fs(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return hr(e,n.length>0?n:gr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Fs,"intentLayer");function uc(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!pc(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let c=o.get(a),l=c?.forbiddenGlobals??[],m=s.source==="import-based"?t.dependencies.find(y=>y.from===s.file&&y.line===s.line&&y.specifier===s.symbol&&!y.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&At(s.symbol,l))){if(s.source==="import-based"){let y=Ae(s.symbol,l);if(y){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...m?{edgeKind:m}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${y}".`});continue}}qe(c).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...m?{edgeKind:m}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let l of kt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:l.ruleId,file:s.file,line:s.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!s.sourceIntent)continue;let c=Fs(s.sourceIntent,e.contract);!c||c===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let c=Fs(s.intent,e.contract);if(!c)continue;let l=re(e.contract.config.rules,a,c);l&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,message:l.message??`${a} must not reference ${c} intent ${s.intent}.`})}return r}i(uc,"contentViolations");function fc(e){let{facts:t}=e,n=bt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((g,ie)=>{let it=`${g.code}\0${g.file??""}\0${g.message}`,ct=`${ie.code}\0${ie.file??""}\0${ie.message}`;return it<ct?-1:it>ct?1:0}),a=t.files.map(g=>({...g,layer:ne(g.path,e.contract.config.layers)??null})),c=new Map(a.map(g=>[g.path,g.layer])),l=t.dependencies.map(g=>{let ie=g.target?c.get(g.target)??ne(g.target,e.contract.config.layers):void 0;return{from:g.from,fromLayer:c.get(g.from)??null,...g.resolution==="resolved-project"&&g.target?{to:g.target,...ie?{toLayer:ie}:{}}:{},line:g.line,kind:g.kind,typeOnly:g.typeOnly,...g.targetTypeOnlyExports?{targetTypeOnlyExports:g.targetTypeOnlyExports}:{},...g.sourcePureTypeModule?{sourcePureTypeModule:g.sourcePureTypeModule}:{},...g.namedBindingsTypeOnly?{namedBindingsTypeOnly:g.namedBindingsTypeOnly}:{},...g.portProofEligible?{portProofEligible:g.portProofEligible}:{}}}),m=wn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(g=>g.path)}),y=dc(e,t),h=e.contract.arkRules??Ct(),d=a.map(g=>g.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?bs(e.coverageInputs.fileContents):{},...e.fileHints??{}},f=[...Es({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:d,layerForFile:i(g=>c.get(g)??ne(g,e.contract.config.layers),"layerForFile"),fileHints:u}),...vs(h,d)],v=f.filter(g=>g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,nextAction:g.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${g.arkruleId} in ${g.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${g.arkruleId} (declared in ${g.arkruleSource}), then preflight again.`})),b=f.filter(g=>!g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,failsStrict:!1,nextAction:g.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${g.arkruleId} in ${g.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${g.arkruleId} in ${g.arkruleSource} (advisory).`})),k=(h.invariants?.length??0)>0?ls({arkRules:h,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0}):{coverage:[],violations:[],partial:!1},C=k.violations.filter(g=>g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,nextAction:`Add a test title or declared symbol covering ${g.arkruleId} (declared in ${g.arkruleSource}), then preflight again.`})),Y=k.violations.filter(g=>!g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${g.arkruleId} in ${g.arkruleSource} (advisory / partial).`})),_=Ss(a),j=Ns({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(g=>c.get(g)??ne(g,e.contract.config.layers),"layerForFile"),classification:_}),Ie=e.contract.config.arkRun?.mode,_e=j.findings.filter(()=>Ie==="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:g.failsStrict,...g.severity?{severity:g.severity}:{}})),Ne=j.findings.filter(()=>Ie!=="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:!1})),Te=Ls({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,dependencies:t.dependencies,layerForFile:i(g=>c.get(g)??ne(g,e.contract.config.layers),"layerForFile"),classification:_}),zn=e.contract.config.arkOrder?.mode,Wn=Te.findings.filter(()=>zn==="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:g.failsStrict,...g.severity?{severity:g.severity}:{}})),S=Te.findings.filter(()=>zn!=="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:!1})),R=[...k.partial&&k.coverage.some(g=>g.mode==="enforced"&&g.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...j.completenessReasons,...Te.completenessReasons],A=Xe({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(g=>g.layer).map(g=>g.path),contentViolations:[...uc(e,t,c),...v,...C,..._e,...Wn],edges:l,warnings:[...m,...y.warnings,...b,...Y,...Ne,...S],safety:y.report}),N=o==="complete"&&R.length>0?"partial":o,H=N==="complete"?s:[...s,...R].sort((g,ie)=>{let it=`${g.code}\0${g.file??""}\0${g.message}`,ct=`${ie.code}\0${ie.file??""}\0${ie.message}`;return it<ct?-1:it>ct?1:0}),ge=A.violations.filter(g=>g.failsStrict!==!1),Ee=N==="complete"&&ge.length===0,at=Ee&&A.warnings.every(g=>g.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:N,completenessReasons:H,valid:Ee,strictValid:at,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:y.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(g=>g.name),edges:l,capabilityUses:t.capabilityUses,violations:A.violations,warnings:A.warnings}}}i(fc,"analyzeCanonicalResolvedProject");function Nt(e){return fc({contract:e.contract,facts:ke(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(Nt,"analyzeResolvedProject");function $s(e){return K(D(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i($s,"analysisTreeHash");function Ms(e){let t=Pt(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],o=new Set,s=[];for(let u of e.changes){let f=u.path.replace(/\\/g,"/"),v=Pe(u.path);if(!v||v===".."||v.startsWith("../")||f.startsWith("/")||/^[A-Za-z]:\//.test(f)||f.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(v)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}o.add(v),"delete"in u&&u.delete&&!n.has(v)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:v,delete:!0}:{path:v,content:"content"in u?u.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=bn({...e,changes:r}),c=new Map(a.ir.files.map(u=>[u.path,u])),l=a.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let f=c.get(u.evidence.file)?.layer;return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...f?{fromLayer:f}:{},edgeKind:"import",message:u.message}}),m=Xe({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(u=>u.path),contentViolations:l,edges:a.ir.edges.filter(u=>!!u.fromLayer).map(u=>({from:u.from,fromLayer:u.fromLayer,...u.to?{to:u.to}:{},...u.toLayer?{toLayer:u.toLayer}:{},line:u.evidence.line,kind:"import",...u.typeOnly?{typeOnly:!0}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),y=r.map(u=>{let f=Pe(u.path),v=n.get(f),b=c.get(f);return{path:f,operation:"delete"in u&&u.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},...b?{candidateContentHash:b.contentHash}:{}}}).sort((u,f)=>u.path.localeCompare(f.path)),h=[...s,...m.violations].map(u=>({...u,nextAction:ce(u)})),d=h.filter(u=>u.failsStrict!==!1),p=e.changeMap?Qe({changeMap:e.changeMap,changes:y,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:a.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&d.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:$s(t.ir.files),candidateTreeHash:$s(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:y,violations:h,warnings:m.warnings}}i(Ms,"preflightChange");function mc(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(mc,"canonicalChangePath");function yc(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(yc,"identityViolations");function gc(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(gc,"preparedChange");function Hs(e){let t=ke(e.baseFacts),n=ke(e.candidateFacts),r=Nt({contract:e.contract,facts:t}),o=Nt({contract:e.contract,facts:n}),s=new Map(t.files.map(p=>[p.path,p])),a=new Map(n.files.map(p=>[p.path,p])),c=yc(t,n),l=new Map,m=[];for(let p of e.changes){let u=mc(p.path);if(!u){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(u)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:u,line:1,message:`The atomic change set contains more than one operation for ${u}.`});continue}l.set(u,p);let f=s.get(u),v=a.get(u);if("delete"in p&&p.delete)f||c.push({ruleId:"DELETE_TARGET_MISSING",file:u,line:1,message:`Cannot delete ${u} because it is not present in the supplied base facts.`}),v&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:u,line:1,message:`Candidate facts still contain deleted file ${u}.`});else{let b="content"in p?p.content:"",I=K(b);v?v.contentHash!==I&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:u,line:1,expectedContentHash:I,candidateContentHash:v.contentHash,message:`Candidate facts for ${u} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:u,line:1,message:`Candidate facts do not contain changed file ${u}.`})}m.push(gc(p,u,s,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...s.keys(),...a.keys()])){if(l.has(p))continue;let u=s.get(p),f=a.get(p);u&&f&&D(u)===D(f)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let y=e.changeMap?Qe({changeMap:e.changeMap,changes:m,baseDependencies:r.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:o.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,h=[...c,...o.ir.violations].map(p=>({...p,nextAction:ce(p)})),d=h.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&d.length===0&&(y?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...y?{convergence:y}:{},changes:m.sort((p,u)=>p.path<u.path?-1:p.path>u.path?1:0),violations:h,warnings:o.ir.warnings}}i(Hs,"preflightResolvedChange");var Pr="docs/diagnostics.md",hc="1.0";function E(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var xn=Object.freeze([E("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),E("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),E("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),E("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),E("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),E("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),E("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),E("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),E("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),E("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),E("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),E("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),E("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),E("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),E("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),E("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),E("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),E("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),E("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),E("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green."),E("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),E("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),E("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),E("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),E("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),E("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),E("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),E("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe."),E("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),E("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe."),E("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),E("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),E("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),E("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),E("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),E("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),E("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),E("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),E("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),E("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),E("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),E("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),E("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),E("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),E("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),E("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),E("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),E("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),E("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),E("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),E("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),E("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),E("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),E("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),E("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),E("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),E("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),E("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),E("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Or=new Map(xn.map(e=>[e.ruleId,e])),Rc=Object.freeze(xn.map(e=>e.ruleId));function Ac(e){return typeof e=="string"&&e.length>0&&Or.has(e)}i(Ac,"isKnownDiagnosticCode");function kc(e){return typeof e!="string"||e.length===0?!1:Or.has(e)?!0:e.startsWith("ARKRULE_")}i(kc,"isCataloguedOrArkRuleFamily");function Pn(e){if(!(typeof e!="string"||e.length===0))return Or.get(e)}i(Pn,"getDiagnosticCatalogEntry");function Ks(e){return`#${Pn(e)?.docsAnchor??e}`}i(Ks,"diagnosticDocsFragment");function Ic(e){return`${Pr}${Ks(e)}`}i(Ic,"diagnosticDocsPath");function Ec(){return{schemaVersion:"1.0",docsPath:Pr,codes:xn}}i(Ec,"serializeDiagnosticCatalog");function vc(e){return Pn(e)?.fix}i(vc,"catalogFixForRuleId");function bc(e){return Pn(e)?.why}i(bc,"catalogWhyForRuleId");var Sc="1.1";var Cc="1.0";var Tt=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 wc(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(wc,"initialState");var On=class{static{i(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new Tt,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)??wc(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 _n(e){return new On(e)}i(_n,"createProjectionRegistry");var Nn="1.0";function xc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(xc,"policyId");var _r=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Tn(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,a=e.projections,c=e.eventContracts,l=e.observability,m=t?t.list().map(b=>({name:b.name,dependencies:t.getDependencies(b.name),productions:t.getProductions(b.name)})):[],y=t?t.getAllRelationships():[],h=n?n.getPolicies().map(b=>({id:xc(b.name),name:b.name,severity:b.severity,tags:b.tags?[...b.tags]:void 0,owner:b.owner,version:b.version,rationale:b.rationale,enforcementMode:b.enforcementMode,deprecated:b.deprecated,replacedBy:b.replacedBy,description:b.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],d=r?r.toJSON():[],p=o?o.toJSON():{nodes:[],edges:[]},u=d.filter(b=>(b.emits?.length??0)>0||(b.consumes?.length??0)>0).map(b=>({entity:b.name,emits:b.emits,consumes:b.consumes})),f=a?a.list().map(b=>({name:b.name,sourceIntents:b.sourceIntents,checkpoint:a.getCheckpoint(b.name)})):[],v={schemaVersion:"1.0",version:Yn,exportedAt:new Date().toISOString(),intents:m,relationships:y,policies:h,entities:d,graph:p,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:f,eventContracts:c?.list()??[],observability:l?.report(),links:{entityIntents:u}};return new _r(v)}i(Tn,"createArkManifest");var Gs=0;function Us(e){return Gs+=1,`${e}-${Date.now()}-${Gs}`}i(Us,"createWorkflowId");function Nr(e){return e instanceof Error?e.message:String(e)}i(Nr,"errorMessage");function Pc(e){return new Promise(t=>{setTimeout(t,e)})}i(Pc,"sleep");async function Oc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((a,c)=>{o=setTimeout(()=>{let l=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(l),c(l)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}i(Oc,"withTimeout");var Dt=class{static{i(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let a=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||a){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let c=(s.version??0)+1;return s.version=c,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},Tr=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new Dt}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??Us(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=Nr(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=s;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let c;try{c=await Oc(l=>Promise.resolve(n.execute(t.context,this.bus,l)),n.timeoutMs,n.name)}catch(l){if(a<s){o.delayMs&&await Pc(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:Nr(l)}),l}c&&Object.assign(t.context,c),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(a=>t.completedSteps.includes(a.name));for(let a=s.length-1;a>=0;a-=1){let c=s[a];if(c.compensate)try{await Promise.resolve(c.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:c.name})}catch(l){await this.audit("workflow.step.failed",t,{step:c.name,compensation:!0,error:Nr(l)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Lt(e,t){return new Tr(e,t)}i(Lt,"createWorkflowEngine");function Vs(e,t,n={}){let r=Lt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??Us(e.name),a="idle",c=[];return{id:s,definition:e,get status(){return a},get completedSteps(){return[...c]},async run(l){a="running",c=[];try{let m=await r.start(e.name,l,{id:s});a=m.status==="waiting"?"idle":m.status,c=[...m.completedSteps]}catch(m){let y=await r.get(s);throw a=y?.status==="waiting"?"idle":y?.status??"failed",c=y?.completedSteps??[],m}}}}i(Vs,"createSaga");tt();Kn();Ut();Wt();Wt();async function qn(e,t={}){let n=qt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(ra(),na));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(qn,"startArkRunInspector");Kn();Wt();tt();Ut();tt();var sl=new Set(["singleton","transient"]);function oa(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(oa,"cloneComponent");function al(e){if(e===void 0)return"singleton";if(typeof e=="string"&&sl.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(al,"closedLifetime");function sa(){let e=new Map,t=new Map,n=new Set;function r(a){let c=e.get(a);if(!c)throw new Error(`ArkRun component "${a}" is not registered.`);return c}i(r,"mustRecord");function o(a,c){if(!c.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return c.factory()}finally{n.delete(a)}}i(o,"instantiate");function s(a,c){if(t.has(a))return t.get(a);let l=o(a,c);return t.set(a,l),l}return i(s,"singleton"),{register(a){let c=typeof a?.id=="string"?a.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let l=al(a.lifetime),m=Fr({id:c,lifetime:l,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!m)throw new Error("ArkRun component id must be a non-empty string.");let y=typeof a.factory=="function"?a.factory:void 0;return e.set(c,{component:m,factory:y}),oa(m)},resolve(a){let c=r(a);return c.component.lifetime==="transient"?o(a,c):s(a,c)},resolveSingleton(a){let c=r(a);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return s(a,c)},snapshotComponents(){return[...e.values()].map(a=>oa(a.component))}}}i(sa,"createComponentRegistry");Ut();function il(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(il,"stampMetadata");function cl(){}i(cl,"ignoreDetachedFailure");async function Yr(e,t,n,r={}){let o=Gn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=il(r),a=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let c=Promise.resolve(e.broker.send(a));o.awaitHandoff?await c:c.then(void 0,cl)}return o}i(Yr,"sendOnArkRunTransport");var Zr=1e3,aa=0;function ll(){return aa+=1,`ark-kernel-${Date.now()}-${aa}`}i(ll,"nextKernelInstanceId");function Yt(e={}){let t=e.strict??!0,n=e.instanceId??ll(),r=e.profile??Be,o=e.maxHistorySize??Zr,s=Zt(),a=dn(),c=e.metadata??Rn(),l=e.auditTrail??cn({maxRecords:o}),m=e.eventContracts??on(),y=e.eventBuffer??e.outbox??new Ce,h=e.projections??_n({auditTrail:l}),d=new ve([en(r),...e.policies??[]]),p=i(()=>{pn(s,a,{requireRegisteredTargets:!0})},"syncGraph"),u=e.ephemeral??!0,f=e.broker,v=new Ve({intentRegistry:s,dependencyGraph:a,policyEngine:d,strictRegistry:!0,validateIntentNaming:!0,auditTrail:l,eventContracts:m,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:y,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async _=>{await h.apply(_)}}),b=Lt(v,{auditTrail:l}),I=sn({registry:s,eventBus:v,graph:a}),k=sa(),C=typeof f?.send=="function",Y={instanceId:n,profile:r,registry:s,graph:a,metadata:c,auditTrail:l,eventContracts:m,eventBuffer:y,outbox:y,projections:h,policyEngine:d,eventBus:v,workflowEngine:b,observability:I,publisher(_){let j=v.createPublisher(_);return{source:j.source,publish:j.publish,send(Ie,_e,Ne={}){return Yr({eventBus:v,broker:f,defaultEphemeral:u},Ie,_e,{...Ne,source:j.source})}}},send(_,j,Ie={}){return Yr({eventBus:v,broker:f,defaultEphemeral:u},_,j,Ie)},register(_){return k.register(_)},resolve(_){return k.resolve(_)},resolveSingleton(_){return k.resolveSingleton(_)},getDependencyInformationPackage(){return ye({kernelInstanceId:n,components:k.snapshotComponents()})},requestGraph(_){return Hn({kernelInstanceId:n,components:k.snapshotComponents()},_)},getInspectorSnapshot(_){return jn({kernelInstanceId:n,host:_?.host,port:_?.port,package:{kernelInstanceId:n,components:k.snapshotComponents()},observability:I.report(),ephemeralDefault:u,brokerBound:C})},startInspector(_){return qn(Y,_)},syncGraph:p,manifest(){return p(),Tn({registry:s,policyEngine:d,metadata:c,graph:a,profile:r,projections:h,eventContracts:m,observability:I})}};return Y}i(Yt,"createArkKernel");function Jr(e={}){return Yt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Jr,"createStrictArkKernel");function Qr(e,t={}){let{profileName:n,...r}=t;return{...r,profile:gn(e,{name:n})}}i(Qr,"createOptionsFromConfig");function ia(e,t={}){return Yt(Qr(e,t))}i(ia,"createArkKernelFromConfig");function ca(e,t={}){return Jr(Qr(e,t))}i(ca,"createStrictArkKernelFromConfig");function la(e,t={}){return Xr(Qr(e,t))}i(la,"createLenientArkKernelFromConfig");function Xr(e={}){return Yt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(Xr,"createLenientArkKernel");export{kr as ANALYSIS_IR_SCHEMA_VERSION,va as ARK_ANALYSIS_RESULT_SCHEMA,Jn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Cc as ARK_DESIGN_DELTA_SCHEMA_VERSION,Sc as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Dr as ARK_RUN_COMPONENT_LIFETIMES,rt as ARK_RUN_EPHEMERAL_DEFAULT,Kr as ARK_RUN_GRAPH_DEFAULT_SLICE,Ws as ARK_RUN_GRAPH_NODE_KINDS,Ys as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,Hr as ARK_RUN_GRAPH_SCHEMA_VERSION,Gr as ARK_RUN_GRAPH_SLICES,Zs as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,Dn as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,Un as ARK_RUN_INSPECTOR_DEFAULT_HOST,qr as ARK_RUN_INSPECTOR_DEFAULT_PORT,jt as ARK_RUN_INSPECTOR_EVENTS_PATH,Bt as ARK_RUN_INSPECTOR_GRAPH_PATH,Br as ARK_RUN_INSPECTOR_SCHEMA_VERSION,Vt as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,zr as ARK_RUN_INSPECTOR_SSE_EVENT,Wr as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,Gt as ARK_RUN_TRANSPORT_KINDS,te as ArkRunInspectorBindError,ot as ArkRunInspectorProductionError,Zr as DEFAULT_MAX_HISTORY_SIZE,xn as DIAGNOSTIC_CATALOG,hc as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Pr as DIAGNOSTIC_DOCS_RELATIVE_PATH,Rc as DIAGNOSTIC_RULE_IDS,ft as EventContractRegistryImpl,He as EventContractViolationError,mt as InMemoryAuditStore,Ce as InMemoryEventBuffer,wo as InMemoryOutboxStore,Tt as InMemoryReadModelStore,Dt as InMemoryWorkflowStore,De as IntentRegistry,W as InvalidArkRunGraphQueryError,nt as InvalidArkRunSendOptionError,$e as InvalidIntentNameError,Me as LayerPolicyContextError,Nn as MANIFEST_SCHEMA_VERSION,Ke as ObservedLayerFlowViolationError,vr as POLICY_DELTA_SCHEMA_VERSION,ve as PolicyEngine,he as PolicyViolationError,Ar as RESOLVED_CANDIDATE_FACTS_SCHEMA,xe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Re as SourceMetadataOverrideError,be as UnknownEventSourceError,Fe as UnregisteredIntentError,Qe as analyzeArchitectureConvergence,bn as analyzeChange,Rs as analyzePolicyDelta,Pt as analyzeProject,Nt as analyzeResolvedProject,Qn as architecturalPolicies,Mn as arkRunGraphQueryFromSearchParams,Oe as arkRunInspectorUrl,jn as buildArkRunInspectorSnapshot,ye as buildDependencyInformationPackage,tn as buildPublishPolicyContext,vc as catalogFixForRuleId,bc as catalogWhyForRuleId,ar as checkAdapterGovernance,zo as checkContract,br as classifyArkPolicyDelta,$n as closeArkRunGraphQuery,jr as closedArkRunEphemeral,Vr as closedArkRunTransportKind,wn as collectAnalysisConfigWarnings,Ye as collectForbiddenCapabilityUses,ts as createAICodeGate,qo as createAdapter,Ea as createAdapterResult,yn as createArchitectureProfile,gn as createArchitectureProfileFromArkConfig,Yt as createArkKernel,ia as createArkKernelFromConfig,Tn as createArkManifest,Oo as createArkTestHarness,cn as createAuditTrail,dn as createDependencyGraph,jo as createElevenLayerArkConfig,Eo as createEventBus,on as createEventContractRegistry,Zt as createIntentRegistry,Xr as createLenientArkKernel,la as createLenientArkKernelFromConfig,Rn as createMetadataRegistry,sn as createObservabilityReporter,_n as createProjectionRegistry,Rr as createResolvedCandidateFacts,Vs as createSaga,Jr as createStrictArkKernel,ca as createStrictArkKernelFromConfig,Lt as createWorkflowEngine,ao as defaultIntentRegistry,en as defineArchitectureProfilePolicy,so as defineIntent,Qt as defineLayerPolicy,Le as definePolicy,Bo as definePort,lo as definePublishPolicy,Cr as detectArchitectureCycles,K as deterministicHash,Ks as diagnosticDocsFragment,Ic as diagnosticDocsPath,Be as elevenLayerProfile,Xe as evaluateArchitectureGraph,As as explainViolation,We as extractSemanticDependencies,Ur as formatArkRunGraphMermaid,zt as formatArkRunInspectorSseEvent,Pn as getDiagnosticCatalogEntry,st as isArkRunInspectorLoopbackHost,Vn as isArkRunInspectorProductionEnv,kc as isCataloguedOrArkRuleFamily,Ac as isKnownDiagnosticCode,Xt as isLayerPolicy,vn as loadContract,ke as loadResolvedCandidateFacts,Sr as policyDeltaAcknowledgementMatches,Ms as preflightChange,Hs as preflightResolvedChange,Hn as requestArkRunGraph,qt as resolveArkRunInspectorBind,Gn as resolveArkRunSendPlan,bt as resolvedFactsEvidenceRequirementsHash,Ec as serializeDiagnosticCatalog,D as stableSerialize,qn as startArkRunInspector,pn as syncRegistryToGraph,Zn as toAdapterDiagnostic,Jt as validateIntentName,Yn as version};
20
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Yo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Yo,"isObject");function pn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(pn,"propertyPath");function je(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(je,"valueType");function na(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(na,"resolveSchemaRef");function gt(e,t,n,r,o){if(t.$ref){let s=na(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}gt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Yo(e)){o.push({path:n,message:`must be an object; received ${je(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:pn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:pn(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in s||gt(e[l],a,pn(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&gt(e[a],l,pn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${je(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(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)=>gt(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 ${je(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${je(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${je(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(gt,"validateNode");function ra(e){let t={...e,$schema:e.$schema===void 0?un:e.$schema,schemaVersion:e.schemaVersion===void 0?re:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?fn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Vo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=jo(e.arkOrder)),t}i(ra,"defaultedConfig");function oa(e){return e===re?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(oa,"migratedFromOf");function sa(){let e=new Set([re]);for(let t of ar)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(sa,"knownInputVersions");function ia(e,t="ark.config.json"){if(!Yo(e))throw new fe(t,[{path:"$",message:`must be an object; received ${je(e)}`}]);let n=sa(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${re}`}]);if(r!=="unversioned"&&!n.has(r))throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);let o=r,s={...e},a=0;for(;o!==re&&a<ar.length+1;){a+=1;let l=ar.find(c=>c.from===o);if(!l)throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${re}`}]);o=l.to,s.schemaVersion=o}if(o!==re)throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);return{candidate:ra(s),migratedFrom:oa(r)}}i(ia,"migrateArkConfig");function lr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ia(e,t),o=[];if(gt(n,zo,"$",zo,o),Bo(n,o),Wo(n,o),o.length>0)throw new fe(t,o);return{config:n,migratedFrom:r}}i(lr,"loadArkConfigContract");function Xo(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new fe(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return lr(n,t)}i(Xo,"parseArkConfigJson");function Zo(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:un,schemaVersion:re};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Zo,"withArkConfigMetadata");function aa(e){return e.endsWith(".")?e:`${e}.`}i(aa,"normalizePrefix");function la(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(la,"byLongestPrefix");function gn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(aa)})),n=[...t].sort(la),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(gn,"createArchitectureProfile");function mn(e,t={}){return gn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}i(mn,"createArchitectureProfileFromArkConfig");var ca=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Be=gn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:ca,rules:fn.map(e=>({...e}))}),da={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 Jo(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Zo({include:e.include??[t],layers:Be.layers.map(o=>({name:o.name,patterns:(da[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Be.rules]})}i(Jo,"createElevenLayerArkConfig");var yn=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 hn(){return new yn}i(hn,"createMetadataRegistry");function Qo(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}i(Qo,"definePort");function es(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=>!ns(t,g));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let a={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=cr(a);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
21
+ `));return a}i(es,"createAdapter");function ts(e,t=[]){let n=t.filter(r=>!ns(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(ts,"checkContract");function cr(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}i(cr,"checkAdapterGovernance");function ns(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(ns,"hasMember");var pr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),fr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),gr=Object.freeze(Object.keys(fr).sort()),dr=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),ur=Object.freeze({process:Object.freeze(["process","node:process"])});function mt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=dr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=dr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:dr[e.slice(0,s)]??null}i(mt,"capabilityForModuleSpecifier");function Ie(e,t){for(let n of t)if(ur[n]?.includes(e))return n;return null}i(Ie,"forbiddenGlobalForModuleSpecifier");function Rn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=fr[r];if(o)return o}return null}i(Rn,"capabilityForAmbientName");function We(e){if(e?.pure===!0)return[...pr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>pr.includes(r));return[...new Set(n)].sort()}i(We,"effectiveCapabilityDeny");function yt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(yt,"ambientCoveredByForbiddenGlobals");function An(e){let t=new Set,n=new Set,r=Object.keys(fr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of ur[o]??[])t.add(`import-exact:${a}`)}for(let o of We(e)){if(t.add(`import:${o}`),o==="process")for(let s of ur.process)t.add(`import-exact:${s}`);for(let s of r)Rn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(An,"loweredLayerCoverage");function qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(qe,"literalText");function ss(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(ss,"lineOf");function rs(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(rs,"isTypeOnlyReference");function is(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(is,"singleFileChecker");function mr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(mr,"symbolAt");function yr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):mr(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(yr,"localDeclaration");function ze(e,t){let n,r=[],o=i((a,l,c,g=!1)=>r.push({specifier:c,kind:l,line:ss(t,a),typeOnly:g,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",qe(e,a.moduleSpecifier),rs(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",qe(e,a.moduleSpecifier),rs(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",qe(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!yr(e,n??(n=is(e,t)),t,a.expression);(l||g)&&o(a,g?"require":"dynamic-import",qe(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(ze,"extractSemanticDependencies");function pa(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=qe(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(pa,"staticAccessPath");function ua(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(ua,"runtimeIdentifierReference");function os(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(os,"bestForbiddenMatch");function Ye(e,t,n){if(n.length===0)return[];let r=new Set(n),o=is(e,t),s=new Map,a=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations)e.isIdentifier(f.name)&&a.add(f.name.text);let l=i(p=>{let f=pa(e,p);if(!f)return;let u=mr(o,f.root),y=u?s.get(u):void 0;return y?[...y,...f.segments.slice(1)]:yr(e,o,t,f.root)||a.has(f.root.text)?void 0:f.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations){if(!f.initializer||!e.isIdentifier(f.name))continue;let u=l(f.initializer),y=mr(o,f.name);!u||!y||s.set(y,u)}let c=[],g=new Set,m=i((p,f)=>{let u=ss(t,f),y=`${p}:${f.getStart(t)}`;g.has(y)||(g.add(y),c.push({name:p,line:u,node:f}))},"flag"),h=i(p=>{let f=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!f){let u=l(p),y=u?os(r,u):void 0;y&&m(y,p)}else e.isIdentifier(p)&&r.has(p.text)&&ua(e,p)&&!yr(e,o,t,p)&&m(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let u=l(p.initializer);if(u)for(let y of p.name.elements){if(!e.isIdentifier(y.name))continue;let b=y.propertyName?qe(e,y.propertyName)??y.propertyName.text:y.name.text,E=os(r,[...u,b]);E&&m(E,p.initializer)}}e.forEachChild(p,h)},"visit");return h(t),c}i(Ye,"collectForbiddenCapabilityUses");function hr(e,t,n){let r=[];for(let o of n?.dependencies??ze(e,t)){if(o.typeOnly||!o.specifier)continue;let s=mt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ye(e,t,gr)){let s=Rn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(hr,"collectCapabilityUses");var Rr={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Ar=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function kr(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(kr,"resolveIntentLayer");function we(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(we,"looksLikeArkIntent");function ht(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&we(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Rr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Rr.PUBLISH_MISSING_SOURCE}),t}i(ht,"classifyPublishFacts");function U(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(U,"violation");function Xe(e,t){return e.slice(0,t).split(`
22
+ `).length}i(Xe,"lineOf");function fa(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(fa,"extractQuotedStrings");function ga(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(ga,"extractModuleSpecifiers");function ma(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(ma,"extractQuotedStringsAst");function ya(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(ya,"hasInfrastructureToken");function ha(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(ha,"isKnownInfrastructurePackage");function Ra(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Ra,"layerHasInfrastructureRole");function At(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(At,"tsStringLiteralText");function Aa(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Aa,"tsPropertyName");function as(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Aa(e,r.name)===n)}i(as,"tsObjectProperty");function kt(e,t,n){return as(e,t,n)!==void 0}i(kt,"tsObjectHasProperty");function Rt(e,t,n){let r=as(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Rt,"tsObjectPropertyValue");function ka(e,t){let n=Rt(e,t,"metadata");return kt(e,n,"source")}i(ka,"tsObjectHasMetadataSource");function ls(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?ls(e,t.name):!1:!1}i(ls,"tsLooksLikeIntentCreatorExpression");function Ia(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(Ia,"tsIsPublishCall");function va(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=At(e,n);return r!==void 0&&we(r)||kt(e,n,"intent")||ls(e,n)}i(va,"tsIsArkPublishCandidate");function ba(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return ka(e,n)||kt(e,r,"source")||kt(e,o,"source")}i(ba,"tsPublishHasSource");function Ea(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Rt(e,n,"metadata");return At(e,Rt(e,s,"source"))??At(e,Rt(e,r,"source"))??At(e,Rt(e,o,"source"))}i(Ea,"tsPublishSourceLiteral");function Sa(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],g=i(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),m=i(h=>{if(Ia(e,h)){let p=h.arguments[0],f=At(e,p);for(let y of ht({publishCall:!0,rawIntentName:f,objectHasIntent:kt(e,p,"intent"),arkPublishCandidate:va(e,h),hasSource:ba(e,h)}))c.push(U(y.ruleId,y.message,{line:g(h),filePath:a}));let u=Ea(e,h);if(r&&l&&u&&we(u)){let y=r.resolveLayer(u);y&&y!==l&&c.push(U("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${y}, but the target file is classified as ${l}.`,{line:g(h),filePath:a,target:u,fromLayer:l,toLayer:y}))}}e.forEachChild(h,m)},"visit");return m(o),c}i(Sa,"analyzePublishAst");function cs(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let l=[],c=a,g=c?.filePath,m=c?.layer,h=e.typescript,p=h?h.createSourceFile(g??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,f=p?ze(e.typescript,p):void 0,u=f?f.filter(A=>A.specifier!==void 0).map(A=>({value:A.specifier,index:A.node.getStart(p),kind:A.kind,typeOnly:A.typeOnly})):ga(s),y=e.typescript?ma(e.typescript,s):fa(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(g))for(let A of f?.filter(({unresolved:v})=>v)??[]){let v=A.kind==="require";l.push(U(v?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${v?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:g}))}let b=m!==void 0&&(r.has(m)||Ra(m)),E=m!==void 0?` If "${m}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let A of n)if(A instanceof RegExp){A.lastIndex=0;let v=A.exec(s);A.lastIndex=0,v&&l.push(U("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:v.index===void 0?void 0:Xe(s,v.index),filePath:g,suggestion:"Remove infrastructure imports from domain/application layers."+E}))}else s.includes(A)&&l.push(U("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:Xe(s,s.indexOf(A)),filePath:g}));for(let A of u){let v=e.resolveImportTarget?.(A.value,g)??(e.resolveImportLayer?{layer:e.resolveImportLayer(A.value,g)}:void 0),P=typeof g=="string"?e.resolveImportTarget?.(g)??(e.resolveImportLayer?{layer:m,relPath:void 0}:void 0):void 0,j=v?.layer;if(j&&m){let k=ue(e.architectureProfile?.rules,m,j,{fromPath:P?.relPath,toPath:v?.relPath,layers:e.architectureLayers});if(k){if(A.typeOnly&&!k.peerIsolation)continue;let _=!!k.peerIsolation;l.push(U("LAYER_IMPORT_VIOLATION",k.message??(_?`Layer "${m}" must not import across slices into "${j}".`:`Layer "${m}" must not import "${j}".`),{line:Xe(s,A.index),source:A.value,target:A.value,filePath:g,fromLayer:m,toLayer:j,suggestion:_?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:A.kind,peerIsolation:_,...A.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||A.typeOnly||!ya(A.value)&&!ha(A.value)||l.push(U("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:Xe(s,A.index),source:A.value,target:A.value,filePath:g,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+E,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let v=A.check({source:s,context:a});if(v!==!0)if(Array.isArray(v))for(let P of v)l.push(U("POLICY_VIOLATION",P.message,{filePath:g,suggestion:`Fix violation of policy "${A.name}".`}));else v===!1?l.push(U("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(U("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let A of y)we(A.value)&&!t.has(A.value)&&l.push(U("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:Xe(s,A.index),filePath:g,target:A.value,suggestion:`Register intent "${A.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let A of y){if(!we(A.value))continue;let v=e.architectureProfile.resolveLayer(A.value);if(!v)continue;let P=ue(e.architectureProfile.rules,m,v);P&&l.push(U("LAYER_REFERENCE_VIOLATION",P.message??`Layer "${m}" must not reference "${v}" through "${A.value}".`,{line:Xe(s,A.index),filePath:g,target:A.value,fromLayer:m,toLayer:v,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:P}}))}if(e.extensions)for(let A of e.extensions)try{let v=A.analyze(s,a);l.push(...v)}catch(v){l.push(U("EXTENSION_ERROR",`Extension "${A.name}" failed: ${v instanceof Error?v.message:String(v)}`))}if(e.typescript&&p&&m&&e.forbiddenGlobals?.[m]?.length)try{let A=e.forbiddenGlobals[m];l.push(...Ye(e.typescript,p,A).map(v=>U("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${v.name}".`,{line:v.line,filePath:g,target:v.name,fromLayer:m,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let v of f??[]){if(v.typeOnly||!v.specifier)continue;let P=Ie(v.specifier,A);P&&l.push(U("FORBIDDEN_GLOBAL",`${m} must not use module "${v.specifier}" because it is the import form of forbidden global "${P}".`,{line:v.line,filePath:g,source:v.specifier,target:v.specifier,fromLayer:m,details:{importKind:v.kind,forbiddenGlobal:P},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript&&p&&m&&e.capabilityWalls?.[m]?.length)try{let A=new Set(e.capabilityWalls[m]),v=e.forbiddenGlobals?.[m]??[];for(let P of hr(e.typescript,p))A.has(P.capability)&&(P.source==="ambient-global"&&yt(P.symbol,v)||P.source==="import-based"&&Ie(P.symbol,v)||l.push(U("CAPABILITY_VIOLATION",P.source==="import-based"?`${m} denies the ${P.capability} capability; found import of "${P.symbol}".`:`${m} denies the ${P.capability} capability; found ambient "${P.symbol}".`,{line:P.line,filePath:g,target:P.symbol,capability:P.capability,fromLayer:m,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript)try{l.push(...Sa(e.typescript,s,a,e.architectureProfile))}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(cs,"createAICodeGate");function B(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(B,"deterministicHash");function 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 xe="1.2";var ds=["network","filesystem","clock","randomness","environment","process","persistence"];function V(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}i(V,"compareCanonical");function W(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(W,"sortedUnique");function It(e){let t={schemaVersion:"1.2",include:W(e.include??[]),exclude:W(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:W(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:W(n.patterns??[]),exclude:W(n.exclude??[]),forbiddenGlobals:W(n.forbiddenGlobals??[]),intentPrefixes:W(n.intentPrefixes??[]),capabilityDeny:W(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(V),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:W(e.arkRun.compositionRoots),managedLayers:W(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return B(F(t))}i(It,"resolvedFactsEvidenceRequirementsHash");function Ca(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(V),n=e.files.map(k=>({...k,typeOnlyExportNames:W(k.typeOnlyExportNames)})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:W(k.namedBindings)}:{}})).sort(V),o=e.capabilityUses.map(k=>({...k})).sort(V),s=e.ambientUses.map(k=>({...k})).sort(V),a=e.publishCalls.map(k=>({...k})).sort(V),l=e.intentReferences.map(k=>({...k})).sort(V),c=e.safetyUses.map(k=>({...k})).sort(V),g=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(_=>({..._}))})).sort(V),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(V),h=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(V),p=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(V),f=(e.arkRunDeclarations??[]).map(k=>({...k,uses:W(k.uses),reactsTo:W(k.reactsTo),raises:W(k.raises),sends:W(k.sends)})).sort(V),u=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(V),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(V),b=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(V),E=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(V),A=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(V),v=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(V),P=e.files.map(({path:k,contentHash:_})=>({path:k,contentHash:_})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),j=B(F(P));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:j,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:g,arkRunKernelCalls:m,arkRunManagedNews:h,arkRunCompositionRootHits:p,arkRunDeclarations:f,arkOrderPlaneCalls:u,arkOrderGenericUpdates:y,arkOrderRootHits:b,arkOrderXiFieldWrites:E,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:v}}i(Ca,"canonicalResolvedFactsInput");function ps(e){let t=Ca(e);return{...t,factsHash:B(F(t))}}i(ps,"createCanonicalResolvedCandidateFacts");function Ir(e){return ps(fs(D(e,"$"),!1))}i(Ir,"createResolvedCandidateFacts");function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(D,"asRecord");function $(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i($,"assertOnlyKeys");function T(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(T,"requiredText");function ge(e,t,n){if(e[t]!==void 0)return T(e,t,n)}i(ge,"optionalText");function M(e,t,n){let r=T(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(M,"requiredProjectPath");function H(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(H,"requiredBoolean");function us(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(us,"requiredInteger");function Y(e,t,n){let r=us(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Y,"requiredPositiveInteger");function K(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(K,"requiredArray");function me(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(me,"enumValue");function Ze(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(Ze,"parseStringArray");function wa(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(wa,"assertUnique");function fs(e,t){$(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=me(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=me(e,"completeness",["complete","partial","unavailable"],"$"),o=K(e,"completenessReasons","$").map((S,C)=>{let R=`$.completenessReasons[${C}]`,d=D(S,R);$(d,["code","message","file"],R);let N=d.file===void 0?void 0:M(d,"file",R);return{code:T(d,"code",R),message:T(d,"message",R),...N?{file:N}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=K(e,"files","$").map((S,C)=>{let R=`$.files[${C}]`,d=D(S,R);return $(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:M(d,"path",R),contentHash:T(d,"contentHash",R),parseStatus:me(d,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:us(d,"parseDiagnosticCount",R),exportsOnlyTypes:H(d,"exportsOnlyTypes",R),typeOnlyExportNames:Ze(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:H(d,"hasTopLevelSideEffects",R)}}),a=K(e,"dependencies","$").map((S,C)=>{let R=`$.dependencies[${C}]`,d=D(S,R);$(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let N=ge(d,"specifier",R),L=ge(d,"target",R),te=me(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(te==="resolved-project"&&!L)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(te!=="resolved-project"&&L)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(te!=="dynamic"&&!N)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:M(d,"from",R),...N?{specifier:N}:{},kind:me(d,"kind",["import","export","dynamic-import","require"],R),typeOnly:H(d,"typeOnly",R),line:Y(d,"line",R),resolution:te,...L?{target:M(d,"target",R)}:{},...d.namedBindings!==void 0?{namedBindings:Ze(d.namedBindings,`${R}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:H(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:H(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:H(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:H(d,"portProofEligible",R)}:{}}}),l=K(e,"capabilityUses","$").map((S,C)=>{let R=`$.capabilityUses[${C}]`,d=D(S,R);return $(d,["file","line","symbol","capability","source"],R),{file:M(d,"file",R),line:Y(d,"line",R),symbol:T(d,"symbol",R),capability:me(d,"capability",ds,R),source:me(d,"source",["ambient-global","import-based"],R)}}),c=K(e,"ambientUses","$").map((S,C)=>{let R=`$.ambientUses[${C}]`,d=D(S,R);return $(d,["file","line","symbol"],R),{file:M(d,"file",R),line:Y(d,"line",R),symbol:T(d,"symbol",R)}}),g=K(e,"publishCalls","$").map((S,C)=>{let R=`$.publishCalls[${C}]`,d=D(S,R);$(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let N=ge(d,"rawIntentName",R),L=ge(d,"sourceIntent",R);return{file:M(d,"file",R),line:Y(d,"line",R),...N?{rawIntentName:N}:{},objectHasIntent:H(d,"objectHasIntent",R),arkPublishCandidate:H(d,"arkPublishCandidate",R),hasSource:H(d,"hasSource",R),...L?{sourceIntent:L}:{}}}),m=K(e,"intentReferences","$").map((S,C)=>{let R=`$.intentReferences[${C}]`,d=D(S,R);return $(d,["file","line","intent"],R),{file:M(d,"file",R),line:Y(d,"line",R),intent:T(d,"intent",R)}}),h=K(e,"safetyUses","$").map((S,C)=>{let R=`$.safetyUses[${C}]`,d=D(S,R);$(d,["file","line","kind","symbol"],R);let N=ge(d,"symbol",R),L=me(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if(L==="in-memory-store"&&!N)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if(L!=="in-memory-store"&&N)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:M(d,"file",R),line:Y(d,"line",R),kind:L,...N?{symbol:N}:{}}});wa(s,S=>S.path,"$.files");let p=new Set(s.map(S=>S.path));for(let S of s){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!p.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:K(e,"arkRunKernelCalls","$")).map((S,C)=>{let R=`$.arkRunKernelCalls[${C}]`,d=D(S,R);$(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let N=ge(d,"receiver",R),L=ge(d,"nameLiteral",R);return{file:M(d,"file",R),line:Y(d,"line",R),kind:me(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:T(d,"callee",R),viaImport:H(d,"viaImport",R),...N?{receiver:N}:{},...L?{nameLiteral:L}:{}}}),b=(e.arkRunManagedNews===void 0?[]:K(e,"arkRunManagedNews","$")).map((S,C)=>{let R=`$.arkRunManagedNews[${C}]`,d=D(S,R);$(d,["file","line","typeName","importedFrom"],R);let N=ge(d,"importedFrom",R);return{file:M(d,"file",R),line:Y(d,"line",R),typeName:T(d,"typeName",R),...N?{importedFrom:N}:{}}}),A=(e.arkRunCompositionRootHits===void 0?[]:K(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let R=`$.arkRunCompositionRootHits[${C}]`,d=D(S,R);return $(d,["file","matchedRoot","hasKernelFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasKernelFactory:H(d,"hasKernelFactory",R)}}),v=e.arkRunDeclarations===void 0?[]:K(e,"arkRunDeclarations","$"),j=(e.arkOrderPlaneCalls===void 0?[]:K(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let R=`$.arkOrderPlaneCalls[${C}]`,d=D(S,R);return $(d,["file","line","callee"],R),{file:M(d,"file",R),line:Y(d,"line",R),callee:T(d,"callee",R)}}),_=(e.arkOrderGenericUpdates===void 0?[]:K(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let R=`$.arkOrderGenericUpdates[${C}]`,d=D(S,R);return $(d,["file","line","method"],R),{file:M(d,"file",R),line:Y(d,"line",R),method:T(d,"method",R)}}),de=(e.arkOrderRootHits===void 0?[]:K(e,"arkOrderRootHits","$")).map((S,C)=>{let R=`$.arkOrderRootHits[${C}]`,d=D(S,R);return $(d,["file","matchedRoot","hasPlaneFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasPlaneFactory:H(d,"hasPlaneFactory",R)}}),Ne=(e.arkOrderXiFieldWrites===void 0?[]:K(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let R=`$.arkOrderXiFieldWrites[${C}]`,d=D(S,R);return $(d,["file","line","key"],R),{file:M(d,"file",R),line:Y(d,"line",R),key:T(d,"key",R)}}),Wt=(e.arkOrderIngestWritesXi===void 0?[]:K(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let R=`$.arkOrderIngestWritesXi[${C}]`,d=D(S,R);return $(d,["file","line"],R),{file:M(d,"file",R),line:Y(d,"line",R)}}),zn=(e.arkOrderReleaseKeyCounts===void 0?[]:K(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let R=`$.arkOrderReleaseKeyCounts[${C}]`,d=D(S,R);return $(d,["file","line","keyCount"],R),{file:M(d,"file",R),line:Y(d,"line",R),keyCount:Y(d,"keyCount",R)}}),it=v.map((S,C)=>{let R=`$.arkRunDeclarations[${C}]`,d=D(S,R);return $(d,["file","line","uses","reactsTo","raises","sends"],R),{file:M(d,"file",R),line:Y(d,"line",R),uses:Ze(d.uses,`${R}.uses`),reactsTo:Ze(d.reactsTo,`${R}.reactsTo`),raises:Ze(d.raises,`${R}.raises`),sends:Ze(d.sends,`${R}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",g],["$.intentReferences",m],["$.safetyUses",h],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",it],["$.arkOrderPlaneCalls",j],["$.arkOrderGenericUpdates",_],["$.arkOrderRootHits",de],["$.arkOrderXiFieldWrites",Ne],["$.arkOrderIngestWritesXi",Wt],["$.arkOrderReleaseKeyCounts",zn]])for(let R of C)if(!p.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let be=ge(e,"projectPackageName","$"),Yn=(e.classShapes===void 0?[]:K(e,"classShapes","$")).map((S,C)=>{let R=`$.classShapes[${C}]`,d=D(S,R);$(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let N=K(d,"mutatingMethods",R).map((L,te)=>{let zt=`${R}.mutatingMethods[${te}]`,Xn=D(L,zt);return $(Xn,["name","referencesGuardOrPublish"],zt),{name:T(Xn,"name",zt),referencesGuardOrPublish:H(Xn,"referencesGuardOrPublish",zt)}});return{file:M(d,"file",R),className:T(d,"className",R),exported:H(d,"exported",R),hasPublicMutableFields:H(d,"hasPublicMutableFields",R),hasPublicSetters:H(d,"hasPublicSetters",R),hasPublicConstructor:H(d,"hasPublicConstructor",R),hasStaticFactory:H(d,"hasStaticFactory",R),mutatingMethods:N,...d.dataOnly===void 0?{}:{dataOnly:H(d,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:T(e,"resolverIdentity","$"),compilerIdentity:T(e,"compilerIdentity","$"),compilerOptionsHash:T(e,"compilerOptionsHash","$"),tsconfigHash:T(e,"tsconfigHash","$"),evidenceRequirementsHash:T(e,"evidenceRequirementsHash","$"),...be?{projectPackageName:be}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:g,intentReferences:m,safetyUses:h,classShapes:Yn,arkRunKernelCalls:u,arkRunManagedNews:b,arkRunCompositionRootHits:A,arkRunDeclarations:it,arkOrderPlaneCalls:j,arkOrderGenericUpdates:_,arkOrderRootHits:de,arkOrderXiFieldWrites:Ne,arkOrderIngestWritesXi:Wt,arkOrderReleaseKeyCounts:zn}}i(fs,"parseResolvedFactsInput");function ve(e){let t=D(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=ps(fs(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 xa=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},X={type:"integer",minimum:1},G={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},vr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:x,message:x,file:G}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:G,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:G,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:X,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:G,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:G,line:X,symbol:x,capability:{enum:xa},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:G,line:X,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:G,line:X,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:G,line:X,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:G,line:X,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:G,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:G,line:X,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:G,line:X,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:G,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:G,line:X,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:G,line:X,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:G,line:X,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:G,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:G,line:X,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:G,line:X}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:G,line:X,keyCount:{type:"integer",minimum:1}}}},factsHash:x},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var br="1.0";function Q(e){return`${e.from}->${e.to}`}i(Q,"dependencyKey");function vt(e,t,n,r="dependency"){return{id:`${e}:${r}:${Q(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Q(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Q(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Q(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Q(t)} from the candidate, then preflight again.`}:{}}}i(vt,"dependencyFinding");function Je(e){let t=[],n=new Map(e.changeMap.map.files.map(p=>[p.path,p])),r=new Map(e.changes.map(p=>[p.path,p])),o=new Map(e.changeMap.map.dependencies.map(p=>[Q(p),p])),s=new Map(e.baseDependencies.map(p=>[Q(p),p])),a=new Map(e.candidateDependencies.map(p=>[Q(p),p]));for(let p of[...n.values()].sort((f,u)=>f.path.localeCompare(u.path))){let f=r.get(p.path);f?f.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${f.operation}.`,nextAction:`Change ${p.path} to the planned ${p.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${p.path}`,classification:"satisfied",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} matches the planned ${p.operation} operation.`}):t.push({id:`missing:file:${p.path}`,classification:"missing",subject:"file",path:p.path,expectedOperation:p.operation,message:`${p.path} was planned as ${p.operation} but is absent from the actual change.`,nextAction:`${p.operation[0].toUpperCase()}${p.operation.slice(1)} ${p.path} in the complete change set, then preflight again.`})}for(let p of[...r.values()].sort((f,u)=>f.path.localeCompare(u.path)))n.has(p.path)||t.push({id:`unplanned:file:${p.path}`,classification:"unplanned",subject:"file",path:p.path,actualOperation:p.operation,message:`${p.path} has an unplanned ${p.operation} operation.`,nextAction:`Remove ${p.path} from the change set, then preflight again.`});let l=new Set;for(let p of[...o.values()].sort((f,u)=>Q(f).localeCompare(Q(u)))){if(a.has(Q(p))){t.push(vt("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let f={from:p.to,to:p.from};a.has(Q(f))?(l.add(Q(f)),t.push(vt("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(vt("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,f]of[...a].sort(([u],[y])=>u.localeCompare(y)))s.has(p)||o.has(p)||l.has(p)||!c.has(f.from)&&!c.has(f.to)||t.push({...vt("unplanned",f,`${f.from} -> ${f.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let g=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,f]of[...s].sort(([u],[y])=>u.localeCompare(y)))a.has(p)||g.has(f.from)||g.has(f.to)||!c.has(f.from)&&!c.has(f.to)||t.push({...vt("unplanned",f,`${f.from} -> ${f.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let m={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((p,f)=>m[p.classification]-m[f.classification]||(p.subject===f.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(f.id));let h={satisfied:t.filter(p=>p.classification==="satisfied").length,missing:t.filter(p=>p.classification==="missing").length,contradictory:t.filter(p=>p.classification==="contradictory").length,unplanned:t.filter(p=>p.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}i(Je,"analyzeArchitectureConvergence");var gs="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Oa=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var ms={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Tu={$schema:"https://json-schema.org/draft/2020-12/schema",$id:gs,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:gs},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:[...Oa]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ms,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:ms}}}};function bt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(bt,"emptyEffectiveArkRules");function ys(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(ys,"effectiveContractPolicyPayload");function hs(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(hs,"formatCoverageDiscards");function Pa(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(Pa,"isUnderCoverageRoot");function _a(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(_a,"titleMatchesInvariant");function Na(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(Na,"symbolPresent");function Rs(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=hs(s),l=hs(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",g=(e.coverageRoots??[]).filter(u=>typeof u=="string"&&u.length>0),m=g.length>0,h=g.join(", "),p=[],f=[];for(let u of t){let y=[],b=u.coverage?.test!==!1,E=u.coverage?.symbol,A,v;if(!r&&b){let _;for(let z of n){let de=e.fileContents[z];if(!(!de||!_a(de,u.id))){if(!m||Pa(z,g)){A=z,v=m?!1:void 0;break}_??=z}}A===void 0&&_!==void 0&&(A=_,v=!0),A!==void 0&&y.push("test-title")}E&&Na(e.fileContents,E)&&y.push("symbol");let j=(u.coverage?.test===!0||!!E||u.coverage===void 0)&&y.length>0||u.coverage?.test===!1&&!E?!0:y.length>0,k=r&&b&&y.length===0;if(p.push({invariantId:u.id,layer:u.provenance.layer,sourceFile:u.provenance.sourceFile,mode:u.mode,covered:j&&!k,evidence:y,partial:k,description:u.description,...A!==void 0?{testEvidenceFile:A}:{},...v!==void 0?{outsideDeclaredRoots:v}:{}}),v===!0&&A!==void 0&&f.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${u.id} is covered only by ${A}, which is outside the declared coverage roots (${h}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:A,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:"warning",failsStrict:!1}),!j||k){let _=u.mode==="enforced"&&!k,z=r||n.length===0?"never-had-tests":"tests-disappeared";f.push({ruleId:"INVARIANT_UNCOVERED",message:(k?o?`Invariant ${u.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${u.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:z==="tests-disappeared"?`Invariant ${u.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${u.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(k&&o?l:a),file:u.provenance.sourceFile,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:_?"error":"warning",failsStrict:_,kind:z})}}return{coverage:p,violations:f,partial:p.some(u=>u.partial)}}i(Rs,"evaluateInvariantCoverage");function As(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(As,"canPromoteInvariant");var Cr="1.0";function O(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(O,"addFinding");function q(e){return[...new Set(e??[])].sort()}i(q,"sortedUnique");function ae(e,t,n,r,o){let s=q(n),a=q(r),l=new Set(s),c=new Set(a),g=a.filter(h=>!l.has(h)),m=s.filter(h=>!c.has(h));g.length===0&&m.length===0||(g.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),m.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(ae,"compareStringSets");function Et(e,t,n,r,o,s,a){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(Et,"compareBoolean");function kn(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(kn,"keyed");function Ta(e,t,n){let r=kn(t,s=>s.name),o=kn(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&O(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!a&&l){O(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){O(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;ae(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ae(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=An(a),m=An(l);ae(e,`${c}.forbiddenGlobals`,g.rawGlobals,m.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ae(e,`${c}.capabilities`,g.atoms,m.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),q(a.intentPrefixes).join("\0")!==q(l.intentPrefixes).join("\0")&&O(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:q(a.intentPrefixes),after:q(l.intentPrefixes)}),Et(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."),Et(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(Ta,"compareLayers");function Da(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=kn(t,r),s=kn(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&O(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(a),c=s.values.get(a),g=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&O(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&O(e,{kind:"deny-removed",path:g,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&O(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${g}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let m=l.peerIsolation===!0,h=c.peerIsolation===!0;if(m!==h){let p=l.from===l.to&&c.from===c.to;O(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${g}.peerIsolation`,classification:p?h?"strengthening":"weakening":"judgment-required",message:p?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:m,after:h})}q(l.sliceFolders).join("\0")!==q(c.sliceFolders).join("\0")&&O(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:q(l.sliceFolders),after:q(c.sliceFolders)}),!(!m&&!h)&&(Is(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."),Is(e,`${g}.allowedCrossSlice`,"cross-slice-allowance",q((l.allowedCrossSlice??[]).map(ks)),q((c.allowedCrossSlice??[]).map(ks)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Da,"compareRules");function ks(e){return JSON.stringify([e.from,e.to])}i(ks,"crossSliceKey");function Is(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(m=>!r.includes(m)),c=r.filter(m=>!o.includes(m)),g=l.length>0&&c.length>0;O(e,{kind:g?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:g?"judgment-required":l.length>0?"weakening":"strengthening",message:g?`${s} Entries were added and removed in the same change.`:l.length>0?s:a,before:r,after:o})}i(Is,"compareDeclaredExceptions");function La(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,l=o[s]??0;a!==l&&O(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Et(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(La,"compareSafety");function Er(e){return e.mode==="enforced"?"enforced":"advisory"}i(Er,"arkRunMode");function Sr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Sr,"arkOrderMode");function Fa(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Sr(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=Sr(r),l=Sr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";O(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}ae(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Fa,"compareArkOrder");function $a(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 (${Er(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=Er(r),l=Er(o);if(a!==l){let c=a==="advisory"&&l==="enforced";O(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}ae(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Et(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i($a,"compareArkRun");function Ma(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(Ma,"overallClassification");function vs(e,t){return`${e}::${t}`}i(vs,"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(vs(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(vs(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(bs,"indexEffectiveRules");function Ha(e,t,n,r,o,s){let a=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},g=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of g){let f=l[p],u=c[p],y=`$.arkRules[${p}]`;if(f===void 0&&u!==void 0){O(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:u});continue}if(f!==void 0&&u===void 0){O(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:f});continue}f!==u&&O(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:f,after:u})}let m=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 b=f.mode==="advisory"&&u.mode==="enforced";O(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}f.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:f.sensor,after:u.sensor})}}for(let p of[...new Set([...m.invariants.keys(),...h.invariants.keys()])].sort()){let f=m.invariants.get(p),u=h.invariants.get(p),y=`$.arkRules.invariants[${p}]`;if(!f&&u){O(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(f&&!u){O(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${f.id} was removed.`,before:f});continue}if(!(!f||!u)&&f.mode!==u.mode)if(f.mode==="advisory"&&u.mode==="enforced"){let E=a?.get(u.id),A=As(E);A.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:f.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${A.reason}`,before:f.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}}i(Ha,"compareArkRules");function wr(e,t,n){let r=[];ae(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ae(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ae(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Et(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&O(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Ta(r,e.layers,t.layers),Da(r,e.rules,t.rules),La(r,e,t),Ha(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),$a(r,e,t),Fa(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Cr,classification:Ma(r),findings:r}}i(wr,"classifyArkPolicyDelta");function xr(e,t){if(!e||e.schemaVersion!==Cr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=q(e.findingIds),r=q(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(xr,"policyDeltaAcknowledgementMatches");function Oe(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Oe,"normalizePath");function Es(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Es,"isIdentifierStart");function In(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(In,"isIdentifierCharacter");function ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ee,"skipWhitespace");function St(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(St,"readString");function oe(e,t,n){return e.startsWith(t,n)&&!In(e[n-1])&&!In(e[n+t.length])}i(oe,"isWordAt");function Ss(e,t){let n=ee(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ee(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!oe(e,"type",n))return!1;let o=ee(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||oe(e,"as",o)||!Es(e[o]))return!1;for(n=o;n<e.length&&In(e[n]);)n+=1;if(n=ee(e,n),oe(e,"as",n)){if(n=ee(e,n+2),!Es(e[n]))return!1;for(;n<e.length&&In(e[n]);)n+=1}r=!0}return!1}i(Ss,"bracedNamedBindingsAreTypeOnly");function Ka(e,t){if(t=ee(e,t+6),e[t]==="(")return St(e,ee(e,t+1));let n=!1;if(oe(e,"type",t)){let o=ee(e,t+4);e[o]!==","&&!oe(e,"from",o)&&(n=!0)}else Ss(e,t)&&(n=!0);let r=Cs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Ka,"specifierAfterImport");function Ga(e,t){t=t+6;let n=ee(e,t),r=!1;if(oe(e,"type",n)){let s=ee(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Ss(e,n)&&(r=!0);let o=Cs(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(Ga,"specifierAfterExport");function Cs(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(oe(e,"from",t))return St(e,ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return St(e,t);if(t>0&&(oe(e,"import",t)||oe(e,"export",t)))return}}i(Cs,"specifierInStaticStatement");function Ua(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(Ua,"skipTemplateLiteral");function Va(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ee(e,t+7);if(e[r]!=="(")return;r=ee(e,r+1);let o=St(e,r);return o?{...o,requireCall:!0}:void 0}i(Va,"specifierAfterRequire");function ja(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=Ua(e,n);continue}if(r==="'"||r==='"'){let s=St(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&oe(e,"import",n)?Ka(e,n):r==="e"&&oe(e,"export",n)?Ga(e,n):r==="r"&&oe(e,"require",n)?Va(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(ja,"moduleSpecifiers");function ws(e,t){let n=[],r=[];for(let o of ja(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let g=mt(s);if(!g)continue;let m=e.content.slice(0,o.offset).split(`
24
+ `).length;r.push({file:e.path,symbol:s,capability:g,evidence:{kind:"import",file:e.path,line:m,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
25
+ `).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=Ba(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(ws,"moduleFactsFor");function Ba(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(Ba,"resolveSpecifier");function xs(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ue(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(xs,"violationsFor");var Wa={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 qa(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(qa,"hasActiveArkRules");function za(e,t){return qa(e,t)?B(F(ys({config:e,arkRules:t,warnings:[]}))):B(F(e))}i(za,"policyHashFor");function vn(e,t,n){let r=typeof e=="string"?Xo(e,t):lr(e,t),o=n?.arkRules??bt();return{...r,arkRules:o,policyHash:za(r.config,o)}}i(vn,"loadContract");function Os(e){let t=vn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=vn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=wr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,a=s&&xr(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(Os,"analyzePolicyDelta");function Ct(e){let t=e.files.map(h=>{let p=Oe(h.path);return{path:p,content:h.content,contentHash:B(h.content),layer:ie(p,e.contract.config.layers)??null}}).sort((h,p)=>h.path.localeCompare(p.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let p=ws(h,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=xs(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(We(h))]));for(let h of o){let p=n.get(h.file)?.layer;if(!p)continue;let f=a.get(p),u=Ie(h.symbol,f?.forbiddenGlobals??[]);if(u){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${h.symbol}" because it is the import form of forbidden global "${u}".`,symbol:h.symbol,evidence:h.evidence});continue}l.get(p)?.has(h.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let c=t.length===0?"complete":"partial",g=c==="complete"?[]:[{...Wa}],m={schemaVersion:br,policyHash:e.contract.policyHash,compilerOptionsHash:B(F(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:g,valid:c==="complete"&&s.length===0,ir:m}}i(Ct,"analyzeProject");function bn(e){let t=new Map(e.files.map(n=>[Oe(n.path),n]));for(let n of e.changes){let r=Oe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Ct({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(bn,"analyzeChange");function Ps(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(Ps,"explainViolation");function Or(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let h of[...e.get(c)??[]].sort())e.has(h)&&(n.has(h)?o.has(h)&&r.set(c,Math.min(r.get(c)??0,n.get(h)??0)):(l(h),r.set(c,Math.min(r.get(c)??0,r.get(h)??0))));if(r.get(c)!==n.get(c))return;let g=[],m;do{if(m=s.pop(),m===void 0)break;o.delete(m),g.push(m)}while(m!==c);g.length>1&&a.push(g.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,g)=>c[0]<g[0]?-1:c[0]>g[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(Or,"detectArchitectureCycles");function Qe(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=or(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,g=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=c?Eo(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,h=l.message?m?`${l.message} (${m})`:l.message:m?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${m}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:g?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...g?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Or(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 Ya=["no-anemic-model"];function _s(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(_s,"escapeGlobLiteral");function Xa(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+=_s(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=_s(o)}return new RegExp(`^${n}$`)}i(Xa,"globToRegExp");function et(e,t){return!t||t.length===0?!0:t.some(n=>Xa(n).test(e))}i(et,"matchesAppliesTo");function Za(e){return Ya.includes(e)}i(Za,"isTier2");function Ns(e){return e.mode==="enforced"&&!Za(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Ns,"severityFor");function Pe(e,t,n,r=1){let{severity:o,failsStrict:s}=Ns(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(Pe,"baseViolation");function En(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(En,"isInRuleLayer");function Sn(e,t,n){return t.filter(r=>!(!r.exported||!et(r.file,e.appliesTo)||!En(r.file,e,n)))}i(Sn,"shapesForRule");function Ja(e,t,n){let r=[];for(let o of Sn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Pe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Ja,"evaluateAggregatePrivateState");function Qa(e,t,n){let r=[];for(let o of Sn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Pe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Qa,"evaluateAlwaysValidFactory");function el(e,t,n){let r=[];for(let o of Sn(e,t,n))for(let s of o.mutatingMethods)s.referencesGuardOrPublish||r.push(Pe(e,o.file,`Mutating method ${o.className}.${s.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(el,"evaluateDomainEventOnMutation");function tl(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&En(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Pe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(tl,"evaluateOrchestrationOnly");function nl(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&En(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Pe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(nl,"evaluateThinAdapter");function rl(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&En(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Pe(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(rl,"evaluateWritesViaAggregate");function ol(e,t,n){let r=[];for(let o of Sn(e,t,n))if(o.dataOnly===!0){let s=Pe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(ol,"evaluateNoAnemicModel");function Ts(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(...Ja(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Qa(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...el(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...tl(n,e));break;case"thin-adapter":t.push(...nl(n,e));break;case"writes-via-aggregate":t.push(...rl(n,e));break;case"no-anemic-model":t.push(...ol(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(Ts,"evaluateArkRuleSensors");function Ds(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>et(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=Ns(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=>et(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(Ds,"collectEmptyAppliesToFindings");var sl=/\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)/,il=/\.(?: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,al=/\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)?['"]/,cl=/\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*=/,dl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function pl(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(cl.source,"g"))??[],r=t.match(new RegExp(dl.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=sl.test(t),c=al.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&&il.test(t);return!a&&!h&&!p?null:{...a?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{},...p?{persistenceWrite:!0}:{}}}i(pl,"deriveArkRuleFileHints");function Ls(e){let t={};for(let[n,r]of Object.entries(e)){let o=pl(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}i(Ls,"buildArkRuleFileHints");function ul(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(ul,"normalizeExtraMergeTeethClassification");function Cn(e){let t=ul(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(Cn,"extraMergeTeethAllowed");function Fs(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(Fs,"classifyResolvedLayerCoverage");var fl=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var yf=new Set(fl);function $s(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i($s,"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"],Pr=new Set(gl);function Ms(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Pr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Pr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Pr.has(e.slice(0,r))}i(Ms,"isArkRunTransportBypassSpecifier");var ml=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Cf=new Set(ml);var Hs={"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"},yl="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Us(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(Us,"isDomainRoleLayer");function hl(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(hl,"compareFindings");function ye(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Hs[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:Hs[t],fromLayer:s?.fromLayer,target:s?.target})}}i(ye,"finding");function Rl(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(Rl,"bagForFile");function Ks(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Ks,"emitKinds");function Gs(e){return e==="subscribe"||e==="register-handler"}i(Gs,"handleKinds");function Al(e){return e==="resolve"||e==="resolve-singleton"}i(Al,"dependKinds");function kl(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ye(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let l=s.get(a.matchedRoot)??[];l.push(a),s.set(a.matchedRoot,l)}for(let a of o){let l=[...s.get(a)??[]].sort((g,m)=>g.file.localeCompare(m.file));if(l.length===0){r.push(ye(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(g=>g.hasKernelFactory))continue;let c=l[0];r.push(ye(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(kl,"evaluateMissingRoot");function Il(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||!$s(c))continue;let g=r(l.from);g&&Us(g,s.get(g)??[])&&a.push(ye(e,"arkrun-kernel-in-domain",l.from,l.line,`${g} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:g,target:c},o))}return a}i(Il,"evaluateKernelInDomain");function vl(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(m=>[m.name,m.intentPrefixes??[]])),c=new Set(r.filter(m=>m.hasKernelFactory).map(m=>m.file)),g=[];for(let m of n){if(c.has(m.file))continue;let h=m.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let p=o(m.file);!p||!a.has(p)||Us(p,l.get(p)??[])||g.push(ye(e,"arkrun-direct-new",m.file,m.line,`${p} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:m.typeName},s))}return g}i(vl,"evaluateDirectNew");function bl(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(!Ks(c.kind)&&!Gs(c.kind)&&!Al(c.kind))continue;let g=r(c.file);if(!g||!l.has(g))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:yl,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=Rl(n,c.file);if(Ks(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;s.push(ye(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:g,target:c.nameLiteral},o));continue}if(Gs(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;s.push(ye(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:g,target:c.nameLiteral},o));continue}m.uses.has(c.nameLiteral)||s.push(ye(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:g,target:c.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(bl,"evaluateUndeclared");function El(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||!Ms(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(ye(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(El,"evaluateTransportBypass");function Vs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=bl(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...kl(t,e.compositionRootHits,n),...Il(t,e.layers,e.dependencies,e.layerForFile,n),...vl(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...El(t,e.dependencies,e.layerForFile,n)].sort(hl),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,g=`${l.code}\0${l.file??""}\0${l.message}`;return c<g?-1:c>g?1:0});return{findings:o,completenessReasons:s}}i(Vs,"evaluateArkRunSensors");function js(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(js,"isArkOrderModuleSpecifier");var Bs={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE"};function Sl(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(Sl,"isDomainRoleLayer");function he(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Bs[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:Bs[t],fromLayer:s?.fromLayer,target:s?.target})}}i(he,"finding");function Ws(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(he(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let g of e.planeRootHits){let m=c.get(g.matchedRoot)??[];m.push(g),c.set(g.matchedRoot,m)}for(let g of o){let m=c.get(g)??[];if(m.length===0){r.push(he(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(g)} matched no governed files and has no createOrderPlane factory.`,{target:g},n));continue}m.some(h=>h.hasPlaneFactory)||r.push(he(t,"arkorder-missing-plane",m[0].file,1,`ArkOrder plane root ${JSON.stringify(g)} has no createOrderPlane factory.`,{target:g},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let g=c.specifier;if(!g||!js(g))continue;let m=e.layerForFile(c.from);m&&Sl(m,s.get(m)??[])&&r.push(he(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:m,target:g},n))}for(let c of e.genericUpdates)r.push(he(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];a.length>t.maxXiKeys&&r.push(he(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(he(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(he(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let g=e.layerForFile(c.file);!g||!l.has(g)||r.push(he(t,"arkorder-xi-field-write",c.file,c.line,`File writes slow key ${JSON.stringify(c.key)} through a persistence driver; route the field through ingest or a pattern change through proposeRelease.`,{fromLayer:g,target:c.key},n))}return r.sort((c,g)=>c.file.localeCompare(g.file)||c.ruleId.localeCompare(g.ruleId)||c.line-g.line),{findings:r,completenessReasons:[]}}i(Ws,"evaluateArkOrderSensors");function Z(e,t,n={}){return{ruleId:e,message:t,...n}}i(Z,"configWarning");function wn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(f=>typeof f!="string"))&&s.push(Z("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(Z("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let f of["maxTsSuppressions","maxAnyCasts"]){let u=t.safety[f];u!==void 0&&(!Number.isInteger(u)||u<0)&&s.push(Z("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${f} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...a.map(f=>f.name).filter(Boolean),...l.map(f=>f.name).filter(f=>!!f)]);a.length===0&&s.push(Z("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let g=new Set,m=new Set;for(let f of a){if(!f.name){s.push(Z("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}g.has(f.name)&&m.add(f.name),g.add(f.name),f.forbiddenGlobals!==void 0&&(!Array.isArray(f.forbiddenGlobals)||f.forbiddenGlobals.some(y=>typeof y!="string"))&&s.push(Z("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${f.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:f.name}));let u=Array.isArray(f.patterns)?f.patterns:[];if(u.length===0){s.push(Z("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${f.name}" has no file patterns and will never classify files.`,{layer:f.name}));continue}for(let y of u){let b;try{b=pe(y)}catch(A){s.push(Z("CONFIG_INVALID_LAYER_PATTERN",`Layer "${f.name}" has an invalid pattern "${y}": ${A instanceof Error?A.message:String(A)}`,{layer:f.name,pattern:y}));continue}let E=f.optional===!0||f.reserved===!0||f.allowEmpty===!0;!r.some(A=>b.test(A))&&!E&&s.push(Z("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${f.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:f.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let f of m)s.push(Z("CONFIG_DUPLICATE_LAYER",`Layer "${f}" is configured more than once.`,{layer:f}));if(c.size>0)for(let f of n??[])f.from&&!c.has(f.from)&&s.push(Z("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${f.from}".`,{fromLayer:f.from,toLayer:f.to})),f.to&&!c.has(f.to)&&s.push(Z("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${f.to}".`,{fromLayer:f.from,toLayer:f.to}));let h=new Set;if(a.length>1)for(let f of r){let u=-1,y=[];for(let b of a)for(let E of b.patterns??[]){if(!pe(E).test(f))continue;let A=rr(E,f);A>u?(u=A,y=[b.name]):A===u&&!y.includes(b.name)&&y.push(b.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&s.push(Z("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let p=r.filter(f=>!ie(f,a));return p.length>0&&s.push(Z("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)})),s}i(wn,"collectAnalysisConfigWarnings");function Cl(e,t){return t.some(n=>{try{return pe(n).test(e)}catch{return!1}})}i(Cl,"matchesAny");function wl(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:b})=>({file:y,line:b})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:b})=>({file:y,line:b})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Cl(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),g=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),m=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),h={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:g,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],f=c.filter(y=>y.kind==="import");if(f.length>0){let y=f[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${f.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let u=c.filter(y=>y.kind==="require");if(u.length>0){let y=u[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(g.length>0){let y=g[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${g.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return m.length>0&&p.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${m.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:p}}i(wl,"evaluateSafety");function xl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(xl,"ambientForbiddenGlobal");function qs(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return kr(e,n.length>0?n:Ar.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(qs,"intentLayer");function Ol(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||!xl(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let l=o.get(a),c=l?.forbiddenGlobals??[],g=s.source==="import-based"?t.dependencies.find(m=>m.from===s.file&&m.line===s.line&&m.specifier===s.symbol&&!m.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&yt(s.symbol,c))){if(s.source==="import-based"){let m=Ie(s.symbol,c);if(m){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...g?{edgeKind:g}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${m}".`});continue}}We(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...g?{edgeKind:g}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let c of ht({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!s.sourceIntent)continue;let l=qs(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=qs(s.intent,e.contract);if(!l)continue;let c=ue(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(Ol,"contentViolations");function Pl(e){let{facts:t}=e,n=It(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,N)=>{let L=`${d.code}\0${d.file??""}\0${d.message}`,te=`${N.code}\0${N.file??""}\0${N.message}`;return L<te?-1:L>te?1:0}),a=t.files.map(d=>({...d,layer:ie(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let N=d.target?l.get(d.target)??ie(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...N?{toLayer:N}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),g=wn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),m=wl(e,t),h=e.contract.arkRules??bt(),p=a.map(d=>d.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Ls(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Ts({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:i(d=>l.get(d)??ie(d,e.contract.config.layers),"layerForFile"),fileHints:u}),...Ds(h,p)],b=y.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),E=y.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),v=(h.invariants?.length??0)>0?Rs({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=Fs(a),_=Vs({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ie(d,e.contract.config.layers),"layerForFile"),classification:k}),z=e.contract.config.arkRun?.mode,de=_.findings.filter(()=>z==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Bt=_.findings.filter(()=>z!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),Ne=Ws({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ie(d,e.contract.config.layers),"layerForFile"),classification:k}),qn=e.contract.config.arkOrder?.mode,Wt=Ne.findings.filter(()=>qn==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),no=Ne.findings.filter(()=>qn!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),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,...Ne.completenessReasons],be=Qe({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Ol(e,t,l),...b,...P,...de,...Wt],edges:c,warnings:[...g,...m.warnings,...E,...j,...Bt,...no],safety:m.report}),qt=o==="complete"&&it.length>0?"partial":o,Yn=qt==="complete"?s:[...s,...it].sort((d,N)=>{let L=`${d.code}\0${d.file??""}\0${d.message}`,te=`${N.code}\0${N.file??""}\0${N.message}`;return L<te?-1:L>te?1:0}),S=be.violations.filter(d=>d.failsStrict!==!1),C=qt==="complete"&&S.length===0,R=C&&be.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:qt,completenessReasons:Yn,valid:C,strictValid:R,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:m.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:be.violations,warnings:be.warnings}}}i(Pl,"analyzeCanonicalResolvedProject");function wt(e){return Pl({contract:e.contract,facts:ve(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(wt,"analyzeResolvedProject");function zs(e){return B(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(zs,"analysisTreeHash");function Ys(e){let t=Ct(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],o=new Set,s=[];for(let u of e.changes){let y=u.path.replace(/\\/g,"/"),b=Oe(u.path);if(!b||b===".."||b.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in u&&u.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:b,delete:!0}:{path:b,content:"content"in u?u.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=bn({...e,changes:r}),l=new Map(a.ir.files.map(u=>[u.path,u])),c=a.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let y=l.get(u.evidence.file)?.layer;return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:u.message}}),g=Qe({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(u=>u.path),contentViolations:c,edges:a.ir.edges.filter(u=>!!u.fromLayer).map(u=>({from:u.from,fromLayer:u.fromLayer,...u.to?{to:u.to}:{},...u.toLayer?{toLayer:u.toLayer}:{},line:u.evidence.line,kind:"import",...u.typeOnly?{typeOnly:!0}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(u=>{let y=Oe(u.path),b=n.get(y),E=l.get(y);return{path:y,operation:"delete"in u&&u.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...E?{candidateContentHash:E.contentHash}:{}}}).sort((u,y)=>u.path.localeCompare(y.path)),h=[...s,...g.violations].map(u=>({...u,nextAction:le(u)})),p=h.filter(u=>u.failsStrict!==!1),f=e.changeMap?Je({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:a.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&p.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:zs(t.ir.files),candidateTreeHash:zs(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:m,violations:h,warnings:g.warnings}}i(Ys,"preflightChange");function _l(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(_l,"canonicalChangePath");function Nl(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(Nl,"identityViolations");function Tl(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(Tl,"preparedChange");function Xs(e){let t=ve(e.baseFacts),n=ve(e.candidateFacts),r=wt({contract:e.contract,facts:t}),o=wt({contract:e.contract,facts:n}),s=new Map(t.files.map(f=>[f.path,f])),a=new Map(n.files.map(f=>[f.path,f])),l=Nl(t,n),c=new Map,g=[];for(let f of e.changes){let u=_l(f.path);if(!u){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(u)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:u,line:1,message:`The atomic change set contains more than one operation for ${u}.`});continue}c.set(u,f);let y=s.get(u),b=a.get(u);if("delete"in f&&f.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:u,line:1,message:`Cannot delete ${u} because it is not present in the supplied base facts.`}),b&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:u,line:1,message:`Candidate facts still contain deleted file ${u}.`});else{let E="content"in f?f.content:"",A=B(E);b?b.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:u,line:1,expectedContentHash:A,candidateContentHash:b.contentHash,message:`Candidate facts for ${u} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:u,line:1,message:`Candidate facts do not contain changed file ${u}.`})}g.push(Tl(f,u,s,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let f of new Set([...s.keys(),...a.keys()])){if(c.has(f))continue;let u=s.get(f),y=a.get(f);u&&y&&F(u)===F(y)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:f,line:1,message:`Candidate facts change ${f}, but the atomic change set does not declare it.`})}let m=e.changeMap?Je({changeMap:e.changeMap,changes:g,baseDependencies:r.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:o.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0,h=[...l,...o.ir.violations].map(f=>({...f,nextAction:le(f)})),p=h.filter(f=>f.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:g.sort((f,u)=>f.path<u.path?-1:f.path>u.path?1:0),violations:h,warnings:o.ir.warnings}}i(Xs,"preflightResolvedChange");var _r="docs/diagnostics.md",Dl="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(I,"entry");var xn=Object.freeze([I("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),I("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),I("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),I("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),I("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),I("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),I("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),I("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),I("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),I("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),I("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),I("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),I("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),I("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),I("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),I("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),I("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),I("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),I("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),I("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),I("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),I("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),I("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),I("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),I("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),I("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),I("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),I("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),I("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),I("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),I("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe."),I("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),I("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease + release, then preflight again. Never mechanical-safe."),I("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),I("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),I("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),I("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),I("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),I("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),I("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),I("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),I("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),I("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),I("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),I("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),I("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),I("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),I("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),I("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),I("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),I("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),I("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),I("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),I("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),I("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),I("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),I("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),I("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),I("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),I("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),I("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),I("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),I("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Nr=new Map(xn.map(e=>[e.ruleId,e])),Ll=Object.freeze(xn.map(e=>e.ruleId));function Fl(e){return typeof e=="string"&&e.length>0&&Nr.has(e)}i(Fl,"isKnownDiagnosticCode");function $l(e){return typeof e!="string"||e.length===0?!1:Nr.has(e)?!0:e.startsWith("ARKRULE_")}i($l,"isCataloguedOrArkRuleFamily");function On(e){if(!(typeof e!="string"||e.length===0))return Nr.get(e)}i(On,"getDiagnosticCatalogEntry");function Zs(e){return`#${On(e)?.docsAnchor??e}`}i(Zs,"diagnosticDocsFragment");function Ml(e){return`${_r}${Zs(e)}`}i(Ml,"diagnosticDocsPath");function Hl(){return{schemaVersion:"1.0",docsPath:_r,codes:xn}}i(Hl,"serializeDiagnosticCatalog");function Kl(e){return On(e)?.fix}i(Kl,"catalogFixForRuleId");function Gl(e){return On(e)?.why}i(Gl,"catalogWhyForRuleId");var Ul="1.1";var Vl="1.0";var xt=class{static{i(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function jl(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(jl,"initialState");var Pn=class{static{i(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new xt,this.auditTrail=t.auditTrail}register(t){if(this.definitions.has(t.name))throw new Error(`Projection "${t.name}" is already registered.`);this.definitions.set(t.name,t),this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(t){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(t.intent))continue;let o=await this.store.load(r.name)??jl(r),s=await r.project(t,o);await this.store.save(r.name,s);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function _n(e){return new Pn(e)}i(_n,"createProjectionRegistry");var Nn="1.0";function Bl(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i(Bl,"policyId");var Tr=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Tn(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,a=e.projections,l=e.eventContracts,c=e.observability,g=t?t.list().map(E=>({name:E.name,dependencies:t.getDependencies(E.name),productions:t.getProductions(E.name)})):[],m=t?t.getAllRelationships():[],h=n?n.getPolicies().map(E=>({id:Bl(E.name),name:E.name,severity:E.severity,tags:E.tags?[...E.tags]:void 0,owner:E.owner,version:E.version,rationale:E.rationale,enforcementMode:E.enforcementMode,deprecated:E.deprecated,replacedBy:E.replacedBy,description:E.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],f=o?o.toJSON():{nodes:[],edges:[]},u=p.filter(E=>(E.emits?.length??0)>0||(E.consumes?.length??0)>0).map(E=>({entity:E.name,emits:E.emits,consumes:E.consumes})),y=a?a.list().map(E=>({name:E.name,sourceIntents:E.sourceIntents,checkpoint:a.getCheckpoint(E.name)})):[],b={schemaVersion:"1.0",version:Zn,exportedAt:new Date().toISOString(),intents:g,relationships:m,policies:h,entities:p,graph:f,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:y,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:u}};return new Tr(b)}i(Tn,"createArkManifest");var Js=0;function Qs(e){return Js+=1,`${e}-${Date.now()}-${Js}`}i(Qs,"createWorkflowId");function Dr(e){return e instanceof Error?e.message:String(e)}i(Dr,"errorMessage");function Wl(e){return new Promise(t=>{setTimeout(t,e)})}i(Wl,"sleep");async function ql(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(ql,"withTimeout");var Ot=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()}},Lr=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new Ot}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??Qs(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=Dr(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=s;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let l;try{l=await ql(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<s){o.delayMs&&await Wl(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:Dr(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt: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:Dr(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Pt(e,t){return new Lr(e,t)}i(Pt,"createWorkflowEngine");function ei(e,t,n={}){let r=Pt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??Qs(e.name),a="idle",l=[];return{id:s,definition:e,get status(){return a},get completedSteps(){return[...l]},async run(c){a="running",l=[];try{let g=await r.start(e.name,c,{id:s});a=g.status==="waiting"?"idle":g.status,l=[...g.completedSteps]}catch(g){let m=await r.get(s);throw a=m?.status==="waiting"?"idle":m?.status??"failed",l=m?.completedSteps??[],g}}}}i(ei,"createSaga");tt();Kn();$t();Vt();Vt();async function Wn(e,t={}){let n=Gt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(gi(),fi));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(Wn,"startArkRunInspector");Kn();Vt();tt();$t();tt();var vc=new Set(["singleton","transient"]);function mi(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(mi,"cloneComponent");function bc(e){if(e===void 0)return"singleton";if(typeof e=="string"&&vc.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(bc,"closedLifetime");function yi(){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=bc(a.lifetime),g=Mr({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!g)throw new Error("ArkRun component id must be a non-empty string.");let m=typeof a.factory=="function"?a.factory:void 0;return e.set(l,{component:g,factory:m}),mi(g)},resolve(a){let l=r(a);return l.component.lifetime==="transient"?o(a,l):s(a,l)},resolveSingleton(a){let l=r(a);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return s(a,l)},snapshotComponents(){return[...e.values()].map(a=>mi(a.component))}}}i(yi,"createComponentRegistry");$t();function Ec(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new ke(e.source,t.source);return t.source=e.source,t}i(Ec,"stampMetadata");function Sc(){}i(Sc,"ignoreDetachedFailure");async function Zr(e,t,n,r={}){let o=Gn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Ec(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,Sc)}return o}i(Zr,"sendOnArkRunTransport");var Jr=1e3,hi=0;function Cc(){return hi+=1,`ark-kernel-${Date.now()}-${hi}`}i(Cc,"nextKernelInstanceId");function jt(e={}){let t=e.strict??!0,n=e.instanceId??Cc(),r=e.profile??Be,o=e.maxHistorySize??Jr,s=Yt(),a=cn(),l=e.metadata??hn(),c=e.auditTrail??an({maxRecords:o}),g=e.eventContracts??rn(),m=e.eventBuffer??e.outbox??new Ce,h=e.projections??_n({auditTrail:c}),p=new Ee([Qt(r),...e.policies??[]]),f=i(()=>{dn(s,a,{requireRegisteredTargets:!0})},"syncGraph"),u=e.ephemeral??!0,y=e.broker,b=new Ue({intentRegistry:s,dependencyGraph:a,policyEngine:p,strictRegistry:!0,validateIntentNaming:!0,auditTrail:c,eventContracts:g,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:m,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async k=>{await h.apply(k)}}),E=Pt(b,{auditTrail:c}),A=on({registry:s,eventBus:b,graph:a}),v=yi(),P=typeof y?.send=="function",j={instanceId:n,profile:r,registry:s,graph:a,metadata:l,auditTrail:c,eventContracts:g,eventBuffer:m,outbox:m,projections:h,policyEngine:p,eventBus:b,workflowEngine:E,observability:A,publisher(k){let _=b.createPublisher(k);return{source:_.source,publish:_.publish,send(z,de,Bt={}){return Zr({eventBus:b,broker:y,defaultEphemeral:u},z,de,{...Bt,source:_.source})}}},send(k,_,z={}){return Zr({eventBus:b,broker:y,defaultEphemeral:u},k,_,z)},register(k){return v.register(k)},resolve(k){return v.resolve(k)},resolveSingleton(k){return v.resolveSingleton(k)},getDependencyInformationPackage(){return Re({kernelInstanceId:n,components:v.snapshotComponents()})},requestGraph(k){return Hn({kernelInstanceId:n,components:v.snapshotComponents()},k)},getInspectorSnapshot(k){return jn({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:v.snapshotComponents()},observability:A.report(),ephemeralDefault:u,brokerBound:P})},startInspector(k){return Wn(j,k)},syncGraph:f,manifest(){return f(),Tn({registry:s,policyEngine:p,metadata:l,graph:a,profile:r,projections:h,eventContracts:g,observability:A})}};return j}i(jt,"createArkKernel");function Qr(e={}){return jt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Qr,"createStrictArkKernel");function eo(e,t={}){let{profileName:n,...r}=t;return{...r,profile:mn(e,{name:n})}}i(eo,"createOptionsFromConfig");function Ri(e,t={}){return jt(eo(e,t))}i(Ri,"createArkKernelFromConfig");function Ai(e,t={}){return Qr(eo(e,t))}i(Ai,"createStrictArkKernelFromConfig");function ki(e,t={}){return to(eo(e,t))}i(ki,"createLenientArkKernelFromConfig");function to(e={}){return jt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(to,"createLenientArkKernel");export{br as ANALYSIS_IR_SCHEMA_VERSION,Di as ARK_ANALYSIS_RESULT_SCHEMA,Qn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Vl as ARK_DESIGN_DELTA_SCHEMA_VERSION,Ul as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Fr as ARK_RUN_COMPONENT_LIFETIMES,rt as ARK_RUN_EPHEMERAL_DEFAULT,Ur as ARK_RUN_GRAPH_DEFAULT_SLICE,si as ARK_RUN_GRAPH_NODE_KINDS,ii as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,Gr as ARK_RUN_GRAPH_SCHEMA_VERSION,Vr as ARK_RUN_GRAPH_SLICES,ai as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,Dn as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,Un as ARK_RUN_INSPECTOR_DEFAULT_HOST,zr as ARK_RUN_INSPECTOR_DEFAULT_PORT,Ht as ARK_RUN_INSPECTOR_EVENTS_PATH,Kt as ARK_RUN_INSPECTOR_GRAPH_PATH,qr as ARK_RUN_INSPECTOR_SCHEMA_VERSION,Mt as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,Yr as ARK_RUN_INSPECTOR_SSE_EVENT,Xr as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,Ft as ARK_RUN_TRANSPORT_KINDS,se as ArkRunInspectorBindError,ot as ArkRunInspectorProductionError,Jr as DEFAULT_MAX_HISTORY_SIZE,xn as DIAGNOSTIC_CATALOG,Dl as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,_r as DIAGNOSTIC_DOCS_RELATIVE_PATH,Ll as DIAGNOSTIC_RULE_IDS,pt as EventContractRegistryImpl,Me as EventContractViolationError,ut as InMemoryAuditStore,Ce as InMemoryEventBuffer,Lo as InMemoryOutboxStore,xt as InMemoryReadModelStore,Ot as InMemoryWorkflowStore,Te as IntentRegistry,J as InvalidArkRunGraphQueryError,nt as InvalidArkRunSendOptionError,Fe as InvalidIntentNameError,$e as LayerPolicyContextError,Nn as MANIFEST_SCHEMA_VERSION,He as ObservedLayerFlowViolationError,Cr as POLICY_DELTA_SCHEMA_VERSION,Ee as PolicyEngine,Ae as PolicyViolationError,vr as RESOLVED_CANDIDATE_FACTS_SCHEMA,xe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ke as SourceMetadataOverrideError,Se as UnknownEventSourceError,Le as UnregisteredIntentError,Je as analyzeArchitectureConvergence,bn as analyzeChange,Os as analyzePolicyDelta,Ct as analyzeProject,wt as analyzeResolvedProject,er as architecturalPolicies,Mn as arkRunGraphQueryFromSearchParams,_e as arkRunInspectorUrl,jn as buildArkRunInspectorSnapshot,Re as buildDependencyInformationPackage,en as buildPublishPolicyContext,Kl as catalogFixForRuleId,Gl as catalogWhyForRuleId,cr as checkAdapterGovernance,ts as checkContract,wr as classifyArkPolicyDelta,$n as closeArkRunGraphQuery,Wr as closedArkRunEphemeral,Br as closedArkRunTransportKind,wn as collectAnalysisConfigWarnings,Ye as collectForbiddenCapabilityUses,cs as createAICodeGate,es as createAdapter,Ti as createAdapterResult,gn as createArchitectureProfile,mn as createArchitectureProfileFromArkConfig,jt as createArkKernel,Ri as createArkKernelFromConfig,Tn as createArkManifest,Mo as createArkTestHarness,an as createAuditTrail,cn as createDependencyGraph,Jo as createElevenLayerArkConfig,Po as createEventBus,rn as createEventContractRegistry,Yt as createIntentRegistry,to as createLenientArkKernel,ki as createLenientArkKernelFromConfig,hn as createMetadataRegistry,on as createObservabilityReporter,_n as createProjectionRegistry,Ir as createResolvedCandidateFacts,ei as createSaga,Qr as createStrictArkKernel,Ai as createStrictArkKernelFromConfig,Pt as createWorkflowEngine,co as defaultIntentRegistry,Qt as defineArchitectureProfilePolicy,lo as defineIntent,Zt as defineLayerPolicy,De as definePolicy,Qo as definePort,fo as definePublishPolicy,Or as detectArchitectureCycles,B as deterministicHash,Zs as diagnosticDocsFragment,Ml as diagnosticDocsPath,Be as elevenLayerProfile,Qe as evaluateArchitectureGraph,Ps as explainViolation,ze as extractSemanticDependencies,jr as formatArkRunGraphMermaid,Ut as formatArkRunInspectorSseEvent,On as getDiagnosticCatalogEntry,st as isArkRunInspectorLoopbackHost,Vn as isArkRunInspectorProductionEnv,$l as isCataloguedOrArkRuleFamily,Fl as isKnownDiagnosticCode,Jt as isLayerPolicy,vn as loadContract,ve as loadResolvedCandidateFacts,xr as policyDeltaAcknowledgementMatches,Ys as preflightChange,Xs as preflightResolvedChange,Hn as requestArkRunGraph,Gt as resolveArkRunInspectorBind,Gn as resolveArkRunSendPlan,It as resolvedFactsEvidenceRequirementsHash,Hl as serializeDiagnosticCatalog,F as stableSerialize,Wn as startArkRunInspector,dn as syncRegistryToGraph,Jn as toAdapterDiagnostic,Xt as validateIntentName,Zn as version};