arkgate 4.8.22 → 4.8.24

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 (136) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +7 -5
  3. package/bin/ark-check-runtime.mjs +27 -78
  4. package/bin/ark-dashboard.mjs +56 -53
  5. package/bin/ark-layer-match.mjs +1117 -38
  6. package/bin/ark-mcp-runtime.mjs +412 -138
  7. package/bin/ark-mcp.mjs +68 -4
  8. package/bin/ark-shared.mjs +39 -0
  9. package/bin/ark.mjs +65 -97
  10. package/bin/lib/adapter-contract-types.mjs +5 -0
  11. package/bin/lib/adapter-contract.mjs +15 -0
  12. package/bin/lib/agent-projection-command.mjs +5 -1
  13. package/bin/lib/analysis-engine.mjs +15 -11
  14. package/bin/lib/architecture-scan.mjs +50 -6
  15. package/bin/lib/ark-order-doctor.mjs +1 -1
  16. package/bin/lib/ark-order-facts.mjs +410 -15
  17. package/bin/lib/ark-order-invariants.mjs +51 -9
  18. package/bin/lib/ark-order-sensors.mjs +28 -101
  19. package/bin/lib/ark-order-types.mjs +2 -0
  20. package/bin/lib/ark-run-doctor.mjs +14 -0
  21. package/bin/lib/ark-run-facts.mjs +434 -11
  22. package/bin/lib/ark-run-sensors.mjs +5 -3
  23. package/bin/lib/arkgate-pins.mjs +91 -0
  24. package/bin/lib/arkrules-sensors.mjs +50 -249
  25. package/bin/lib/check-args.mjs +23 -1
  26. package/bin/lib/ci-and-commands.mjs +16 -6
  27. package/bin/lib/class-source-scan.mjs +479 -0
  28. package/bin/lib/codex-home.mjs +4 -2
  29. package/bin/lib/config-contract-slices.mjs +701 -0
  30. package/bin/lib/config-contract.mjs +5 -2
  31. package/bin/lib/config-warnings.mjs +32 -0
  32. package/bin/lib/dashboard-cli.mjs +62 -0
  33. package/bin/lib/design-delta.mjs +1 -1
  34. package/bin/lib/diagnostic-catalog.mjs +45 -6
  35. package/bin/lib/doctor-advisories.mjs +84 -1
  36. package/bin/lib/doctor-next-actions.mjs +17 -2
  37. package/bin/lib/doctor-plan.mjs +7 -9
  38. package/bin/lib/effective-contract-load.mjs +121 -59
  39. package/bin/lib/enforcement-honesty.mjs +22 -0
  40. package/bin/lib/enforcement-profiles.mjs +40 -4
  41. package/bin/lib/first-run-help.mjs +3 -2
  42. package/bin/lib/flat-parent-importers.mjs +137 -0
  43. package/bin/lib/flat-parent-pilot.mjs +192 -0
  44. package/bin/lib/gate-files.mjs +29 -2
  45. package/bin/lib/git-change-scope.mjs +109 -0
  46. package/bin/lib/github-enforcement.mjs +1 -1
  47. package/bin/lib/hook-templates.mjs +18 -16
  48. package/bin/lib/host-support-matrix.mjs +3 -1
  49. package/bin/lib/html-report-advisories.mjs +2 -0
  50. package/bin/lib/html-report-depth.mjs +3 -1
  51. package/bin/lib/import-resolve.mjs +13 -1
  52. package/bin/lib/install-migrate.mjs +50 -73
  53. package/bin/lib/invariant-coverage.mjs +59 -11
  54. package/bin/lib/mcp-adoption.mjs +9 -1
  55. package/bin/lib/mcp-hook-payload.mjs +401 -61
  56. package/bin/lib/package-manager.mjs +59 -1
  57. package/bin/lib/passthrough-commands.mjs +83 -0
  58. package/bin/lib/persistence-write-hint.mjs +81 -0
  59. package/bin/lib/physical-cohesion.mjs +16 -18
  60. package/bin/lib/pilot-loop.mjs +21 -8
  61. package/bin/lib/pin-dependent-gates.mjs +117 -0
  62. package/bin/lib/policy-delta-io.mjs +168 -10
  63. package/bin/lib/prepare-change.mjs +120 -6
  64. package/bin/lib/prepare-write.mjs +1 -0
  65. package/bin/lib/presets.mjs +3 -5
  66. package/bin/lib/remediation.mjs +23 -4
  67. package/bin/lib/resolved-candidate-facts.mjs +315 -55
  68. package/bin/lib/rules-inventory.mjs +22 -3
  69. package/bin/lib/rules-under-contract.mjs +179 -5
  70. package/bin/lib/scan-files.mjs +32 -0
  71. package/bin/lib/snippet-analysis.mjs +140 -6
  72. package/bin/lib/source-policy.mjs +34 -0
  73. package/bin/lib/stable-hash.mjs +90 -0
  74. package/bin/lib/start-install-recovery.mjs +71 -1
  75. package/bin/lib/start-preview.mjs +30 -0
  76. package/bin/lib/status-command.mjs +33 -4
  77. package/bin/lib/status-manifest.mjs +32 -4
  78. package/bin/lib/team-parliament-io.mjs +79 -75
  79. package/bin/lib/team-parliament.mjs +6 -1
  80. package/bin/lib/write-path-capabilities.mjs +4 -2
  81. package/dist/chunk-A5EIY3HI.cjs +5 -0
  82. package/dist/chunk-MBXCFLO4.js +16 -0
  83. package/dist/chunk-RNQHRDCQ.cjs +16 -0
  84. package/dist/chunk-SVSQVGFJ.js +5 -0
  85. package/dist/{configTypes-CTELo87-.d.ts → configTypes-BJbaeoj4.d.cts} +53 -4
  86. package/dist/configTypes-BJbaeoj4.d.ts +246 -0
  87. package/dist/eslint/index.cjs +17 -4
  88. package/dist/eslint/index.d.cts +359 -0
  89. package/dist/eslint/index.d.ts +178 -158
  90. package/dist/eslint/index.js +10 -4
  91. package/dist/index.cjs +38 -37
  92. package/dist/index.d.cts +5475 -0
  93. package/dist/index.d.ts +3408 -296
  94. package/dist/index.js +38 -37
  95. package/dist/inspectorListen-6DQVJ4DC.js +1 -0
  96. package/dist/inspectorListen-KGMIQ2TF.cjs +1 -0
  97. package/dist/nestjs/index.cjs +1 -18
  98. package/dist/nestjs/index.d.cts +22 -0
  99. package/dist/nestjs/index.d.ts +1 -3
  100. package/dist/nestjs/index.js +1 -18
  101. package/dist/order/index.cjs +1 -1
  102. package/dist/order/index.d.cts +155 -0
  103. package/dist/order/index.d.ts +15 -3
  104. package/dist/order/index.js +1 -1
  105. package/dist/runtime/index.cjs +13 -30
  106. package/dist/{diagnosticCatalog-WD2TPSwZ.d.ts → runtime/index.d.cts} +814 -290
  107. package/dist/runtime/index.d.ts +2678 -108
  108. package/dist/runtime/index.js +13 -30
  109. package/dist/{types-yDNEQ603.d.ts → types-DRinG-vT.d.cts} +576 -140
  110. package/dist/types-DRinG-vT.d.ts +1792 -0
  111. package/docs/README.md +3 -1
  112. package/docs/agent-guide.md +92 -15
  113. package/docs/ai-gates.md +160 -26
  114. package/docs/arkorder.md +32 -15
  115. package/docs/brownfield-adoption.md +5 -1
  116. package/docs/configuration.md +273 -12
  117. package/docs/develop.md +2 -1
  118. package/docs/diagnostics.md +122 -13
  119. package/docs/package-surface.md +31 -8
  120. package/docs/product-voice.md +1 -1
  121. package/package.json +59 -18
  122. package/schemas/ark.analysis-result.schema.json +15 -0
  123. package/schemas/ark.config.schema.json +163 -4
  124. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  125. package/schemas/ark.status-manifest.schema.json +22 -0
  126. package/server.json +3 -9
  127. package/templates/agent-skills/README.md +1 -1
  128. package/templates/agent-skills/ark-adopt/SKILL.md +4 -1
  129. package/templates/agent-skills/ark-order/SKILL.md +4 -2
  130. package/templates/agent-skills/ark-runtime/SKILL.md +6 -1
  131. package/templates/arkrules/PersistenceAdapters.json +1 -1
  132. package/templates/arkrules/PresentationAdapters.json +1 -1
  133. package/templates/skills/ark-adopt.md +4 -1
  134. package/templates/skills/ark-order.md +4 -2
  135. package/templates/skills/ark-runtime.md +6 -1
  136. package/dist/types-fQ9-KrBj.d.ts +0 -183
@@ -1,32 +1,15 @@
1
- "use strict";var qa=Object.create;var jt=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Xa=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,Ja=Object.prototype.hasOwnProperty;var a=(e,t)=>jt(e,"name",{value:t,configurable:!0});var Bt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var ms=(e,t)=>{for(var n in t)jt(e,n,{get:t[n],enumerable:!0})},ys=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xa(t))!Ja.call(e,o)&&o!==n&&jt(e,o,{get:()=>t[o],enumerable:!(r=Ya(t,o))||r.enumerable});return e};var Qa=(e,t,n)=>(n=e!=null?qa(Za(e)):{},ys(t||!e||!e.__esModule?jt(n,"default",{value:e,enumerable:!0}):n,e)),el=e=>ys(jt({},"__esModule",{value:!0}),e);function Xo(e,t){return e<t?-1:e>t?1:0}function nu(e){return[...new Set(e)].sort(Xo)}function _n(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return nu(t)}function ru(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function ou(e){return typeof e=="string"&&tu.has(e)?e:"singleton"}function _a(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(Xo)){if(n.length===0)continue;let r=ru(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function su(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=_n(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=_a(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Zo(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:ou(t.lifetime),uses:_n(t.uses),reactsTo:_n(t.reactsTo),raises:_n(t.raises),sends:_n(t.sends)},o=su(t.extendedInfo);return o&&(r.extendedInfo=o),r}function au(e){return _a(e)}function Jo(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.xiHash=="string"?t.xiHash.trim():"";if(!n)return;let r=t.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,s=typeof o.kind=="string"?o.kind.trim():"";if(!s)return;let i=t.residual;if(i===null||typeof i!="object"||Array.isArray(i))return;let l=i,c=typeof l.kind=="string"&&iu.has(l.kind)?l.kind:void 0;if(!c)return;let u={kind:s},f=au(o.payload);f&&(u.payload=f);let y={kind:c};return typeof l.reasonCode=="string"&&l.reasonCode.length>0&&(y.reasonCode=l.reasonCode),typeof l.eventId=="string"&&l.eventId.length>0&&(y.eventId=l.eventId),typeof l.target=="string"&&l.target.length>0&&(y.target=l.target),{xiHash:n,event:u,residual:y}}function lu(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=Jo(n);r&&t.push(r)}return t}function fe(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let i of n){let l=Zo(i);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((i,l)=>Xo(i.id,l.id));let s=lu(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function Qo(e,t){let n=Jo(t),r=e.decisionTape??[],o=n?[...r,n]:[...r];return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components,...o.length>0?{decisionTape:o}:{}}}var Tn,wr,Pa,tu,iu,Pt=Bt(()=>{"use strict";Tn="1.0",wr=["singleton","transient"],Pa=["absorb","escalate_up","hold"],tu=new Set(wr);a(Xo,"compare");a(nu,"uniqueSorted");a(_n,"nameList");a(ru,"jsonPrimitive");a(ou,"closedLifetime");a(_a,"sanitizeMetadata");a(su,"sanitizeArkRunExtendedInfo");a(Zo,"sanitizeArkRunComponent");iu=new Set(Pa);a(au,"sanitizeTapePayload");a(Jo,"sanitizeDecisionTapeRecord");a(lu,"sanitizeDecisionTape");a(fe,"buildDependencyInformationPackage");a(Qo,"appendDecisionTape")});function Ln(e,t){return e<t?-1:e>t?1:0}function rs(e){return[...new Set(e)].sort(Ln)}function Na(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function os(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function ge(e,t){if(e==null||e==="")return[];if(typeof e=="string")return rs(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new ee(t);let n=[];for(let r of e){if(typeof r!="string")throw new ee(t);let o=r.trim();o.length>0&&n.push(o)}return rs(n)}function $a(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 Nn(e,t){return e?t.some(n=>$a(e,n)):!1}function Ma(e){if(e==null||e==="")return _r;if(typeof e=="string"&&cu.has(e))return e;throw new ee("slice")}function Ha(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 ee("degreesOfSeparation")}function Da(e,t){if(e==null||e==="")return Na();if(typeof e=="string"||Array.isArray(e))return{...Na(),tokens:ge(e,t)};if(typeof e!="object")throw new ee(t);let n=e;for(let r of Object.keys(n))if(!uu.has(r))throw new ee(t);return{tokens:[],ids:ge(n.ids,t),labels:ge(n.labels,t),tags:ge(n.tags,t),groups:ge(n.groups,t),architectureKinds:ge(n.architectureKinds,t)}}function $n(e={}){if(e==null||e==="")return $n({});if(typeof e!="object"||Array.isArray(e))throw new ee("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!du.has(n))throw new ee("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Ma(t.slice),nodeIds:ge(t.nodeIds,"nodeIds"),degreesOfSeparation:Ha(t.degreesOfSeparation),include:Da(t.include,"include"),exclude:Da(t.exclude,"exclude")}}function Mn(e){let t={};e.slice&&(t.slice=Ma(e.slice));let n=ge(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=Ha(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=ge(e.include??void 0,"include");o.length>0&&(t.include=o);let s=ge(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function pu(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 La(e,t){if(!os(t))return!0;let n=pu(e);return t.tokens.some(r=>n.some(o=>$a(o,r)))||Nn(e.id,t.ids)||Nn(e.label,t.labels)||e.tags?.some(r=>Nn(r,t.tags))||Nn(e.group,t.groups)?!0:Nn(e.architectureKind,t.architectureKinds)}function fu(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return fe({kernelInstanceId:t.kernelInstanceId,components:t.components})}return fe({})}function gu(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 xr(e){return{id:e,kind:"interaction"}}function Dn(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function Or(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 mu(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Dn(n,gu(s)),t==="technical"){for(let i of s.uses)Dn(n,n.get(i)??xr(i)),Or(r,o,s.id,i,"uses");continue}for(let i of s.raises)Dn(n,n.get(i)??xr(i)),Or(r,o,s.id,i,"raises");for(let i of s.reactsTo)Dn(n,n.get(i)??xr(i)),Or(r,o,i,s.id,"reactsTo");for(let i of s.sends)Dn(n,n.get(i)??xr(i)),Or(r,o,s.id,i,"sends")}return{nodes:n,edges:r}}function yu(e){let t=new Map,n=a((r,o)=>{let s=t.get(r);s?s.push(o):t.set(r,[o])},"push");for(let r of e)n(r.from,r.to),n(r.to,r.from);return t}function hu(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let s=new Set,i=o.map(l=>({id:l,depth:0}));for(;i.length>0;){let l=i.shift();if(!(!l||s.has(l.id))&&(s.add(l.id),!(n!==null&&l.depth>=n)))for(let c of r.get(l.id)??[])!s.has(c)&&e.has(c)&&i.push({id:c,depth:l.depth+1})}return s}function Fn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function Fa(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Ru(e){let t=new Set,n=new Map;for(let r of e){let o=Fn(r),s=o,i=2;for(;t.has(s);)s=`${o}_${i}`,i+=1;t.add(s),n.set(r,s)}return n}function Nr(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=Ru(n),o=rs(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],i=a((l,c)=>{let u=r.get(l.id)??Fn(l.id),f=Fa(l.label??l.id);s.push(`${c}${u}["${f}"]`)},"emitNode");for(let l of o){let c=Fn(`group_${l}`);s.push(` subgraph ${c}["${Fa(l)}"]`);for(let u of e.nodes)u.group===l&&i(u," ");s.push(" end")}for(let l of e.nodes)l.group||i(l," ");for(let l of e.edges){let c=r.get(l.from)??Fn(l.from),u=r.get(l.to)??Fn(l.to);s.push(` ${c} -->|${l.kind}| ${u}`)}return s.join(`
2
- `)}function Au(e,t,n){let r=new Set(e.keys());if(os(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&La(c,n.include)}))),os(n.exclude))for(let l of[...r]){let c=e.get(l);c&&La(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=hu(r,n.nodeIds,n.degreesOfSeparation,yu(o)));let s=[...r].sort(Ln).map(l=>e.get(l)).filter(l=>!!l),i=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Ln(l.from,c.from)||Ln(l.kind,c.kind)||Ln(l.to,c.to));return{nodes:s,edges:i}}function Hn(e={},t={}){let n=fu(e),r=$n(t),o=mu(n.components,r.slice),s=Au(o.nodes,o.edges,r),i={schemaVersion:Pr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return i.mermaid=Nr(i),i}var Pr,_r,Tr,ss,is,as,ee,cu,du,uu,Dr=Bt(()=>{"use strict";Pt();Pr="1.0",_r="process",Tr=["process","technical"],ss=["component","interaction"],is=["raises","reactsTo","sends"],as=["uses"],ee=class extends Error{static{a(this,"InvalidArkRunGraphQueryError")}option;constructor(t,n){super(n??(t==="slice"?'ArkRun graph slice must be "process" or "technical".':t==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${t} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=t}},cu=new Set(Tr),du=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),uu=new Set(["ids","labels","tags","groups","architectureKinds"]);a(Ln,"compare");a(rs,"uniqueSorted");a(Na,"emptyMatch");a(os,"matchHasCriteria");a(ge,"nameList");a($a,"globMatch");a(Nn,"anyGlob");a(Ma,"closedSlice");a(Ha,"closedDegrees");a(Da,"closedMatch");a($n,"closeArkRunGraphQuery");a(Mn,"arkRunGraphQueryFromSearchParams");a(pu,"nodeFields");a(La,"nodeMatches");a(fu,"asPackage");a(gu,"componentNode");a(xr,"interactionNode");a(Dn,"addNode");a(Or,"addEdge");a(mu,"buildSlice");a(yu,"adjacency");a(hu,"neighborhood");a(Fn,"mermaidSafeId");a(Fa,"mermaidLabel");a(Ru,"uniqueMermaidIds");a(Nr,"formatArkRunGraphMermaid");a(Au,"filterGraph");a(Hn,"requestArkRunGraph")});function Lr(e){if(e===void 0)return"local";if(typeof e=="string"&&ku.has(e))return e;throw new it("transport")}function Fr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new it("ephemeral")}function Kn(e){let t=Lr(e.transport),n=Fr(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",s=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:s,awaitHandoff:n||s}}var _t,at,ku,it,Gn=Bt(()=>{"use strict";_t=["local","localBlocking","broker"],at=!0,ku=new Set(_t),it=class extends Error{static{a(this,"InvalidArkRunSendOptionError")}option;constructor(t){super(t==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=t}};a(Lr,"closedArkRunTransportKind");a(Fr,"closedArkRunEphemeral");a(Kn,"resolveArkRunSendPlan")});function Vn(e){return e==="production"}function bu(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 Ka(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function ct(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=Ka(t);if(n)return ct(n);let r=bu(t);return r!==void 0&&r[0]===127}function Ga(e){if(e===void 0)return Un;if(typeof e!="string")throw new ae(String(e));let t=e.trim();if(Iu.has(t.toLowerCase())||!ct(t))throw new ae(t);let n=t.toLowerCase();if(n==="localhost")return Un;if(n==="[::1]")return"::1";let r=Ka(n);return r?Ga(r):n}function vu(e){if(e===void 0)return Mr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new ae(`port:${String(e)}`);return e}function $t(e={}){if(Vn(e.nodeEnv)||Vn(e.processNodeEnv))throw new lt;return{host:Ga(e.host),port:vu(e.port)}}function me(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function Eu(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function Su(e){return{kinds:[..._t],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:Kr}}function Fe(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function wu(e){let t=Fe(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=Fe(t.event),o=r&&typeof r.intent=="string"?r.intent:typeof t.intent=="string"?t.intent:void 0,s={id:t.id,status:n,attempts:typeof t.attempts=="number"&&Number.isFinite(t.attempts)?t.attempts:0};return o&&(s.intent=o),typeof t.error=="string"&&t.error.length>0&&(s.error=t.error),typeof t.updatedAt=="string"&&(s.updatedAt=t.updatedAt),s}function Gr(e){if(typeof e!="number"||!Number.isFinite(e))return re;let t=Math.trunc(e);return t<0?0:t>re?re:t}function He(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function Mt(e={}){let t=Fe(e),n=Fe(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let s of r){let i=Fe(s);if(!i)continue;let l=i.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof i.id=="string"?i.id:typeof i.name=="string"?i.name:void 0;if(!c)continue;let u=i.kind==="memory"||i.kind==="durable"?i.kind:He(c,l).kind;o.push({role:l,id:c,kind:u})}return{durability:{stores:o}}}function Ke(e=[],t={}){let n=Gr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=[];for(let i of r){let l=wu(i);l&&(l.status==="pending"?o.push(l):s.push(l))}return{available:!0,pendingCount:o.length,failedCount:s.length,pending:o.slice(0,n),failed:s.slice(0,n),sampleLimit:n}}function $e(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:re}}function Cu(e){let t=Fe(e);if(!t||typeof t.id!="string")return;let n=typeof t.workflowName=="string"?t.workflowName:typeof t.name=="string"?t.name:void 0;if(!n)return;let r={id:t.id,name:n,status:typeof t.status=="string"?t.status:"unknown"};return typeof t.currentStep=="string"&&(r.currentStep=t.currentStep),typeof t.error=="string"&&t.error.length>0&&(r.error=t.error),r}function xu(e){return e==="idle"||e==="waiting"}function Ge(e=[],t={}){let n=Gr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],s=0,i=0,l=0,c=0;for(let u of r){let f=Cu(u);f&&(o.push(f),f.status==="running"?s+=1:f.status==="compensating"?i+=1:f.status==="failed"?l+=1:xu(f.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:s,compensatingCount:i,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function Me(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:re}}function Ou(e){if(e===void 0)return;let t=Fe(e);if(!t||t.available===!1)return $e();let n=Gr(t.sampleLimit);if(Array.isArray(t.pending)||Array.isArray(t.failed)||Array.isArray(t.records)){let r=[...Array.isArray(t.pending)?t.pending:[],...Array.isArray(t.failed)?t.failed:[],...Array.isArray(t.records)?t.records:[]],o=Ke(r,{sampleLimit:n}),s=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,i=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:s,failedCount:i,sampleLimit:n}}return $e()}function Pu(e){if(e===void 0)return;let t=Fe(e);if(!t||t.available===!1)return Me();let n=Gr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=Ge(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,s=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,i=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:s,compensatingCount:i,failedCount:l,pendingCount:c,sampleLimit:n}}return Me()}function jn(e={}){let t=$t({host:e.host,port:e.port}),n=fe({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=Ou(e.outbox),o=Pu(e.workflows),s={schemaVersion:$r,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Su(e),observability:Eu(e.observability)??{},hardening:Mt(e.hardening)};return r&&(s.outbox=r),o&&(s.workflows=o),s}function Ht(e){return`event: ${Hr}
3
- data: ${JSON.stringify(e)}
4
-
5
- `}var $r,Un,Mr,Tt,Nt,Dt,Lt,Ft,Hr,Kr,re,lt,ae,Iu,Bn=Bt(()=>{"use strict";Pt();Gn();$r="1.0",Un="127.0.0.1",Mr=0,Tt="/snapshot",Nt="/events",Dt="/graph",Lt="/outbox",Ft="/workflows",Hr="snapshot",Kr="in-process-local",re=32,lt=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},ae=class extends Error{static{a(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},Iu=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a(Vn,"isArkRunInspectorProductionEnv");a(bu,"ipv4Octets");a(Ka,"unwrapIpv4Mapped");a(ct,"isArkRunInspectorLoopbackHost");a(Ga,"closedHost");a(vu,"closedPort");a($t,"resolveArkRunInspectorBind");a(me,"arkRunInspectorUrl");a(Eu,"jsonClone");a(Su,"closedTransportFacts");a(Fe,"asRecord");a(wu,"closedOutboxSummary");a(Gr,"closedSampleLimit");a(He,"classifyArkRunInspectorStoreDurability");a(Mt,"buildArkRunInspectorHardening");a(Ke,"buildArkRunInspectorOutboxMonitor");a($e,"unavailableArkRunInspectorOutboxMonitor");a(Cu,"closedWorkflowSummary");a(xu,"isPendingWorkflowStatus");a(Ge,"buildArkRunInspectorWorkflowsMonitor");a(Me,"unavailableArkRunInspectorWorkflowsMonitor");a(Ou,"closedOutboxMonitor");a(Pu,"closedWorkflowsMonitor");a(jn,"buildArkRunInspectorSnapshot");a(Ht,"formatArkRunInspectorSseEvent")});var Ua={};ms(Ua,{listenArkRunInspector:()=>$u});function _u(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Tu(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Nu(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Ue(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,_u()),e.end(JSON.stringify(n))}catch{}}function Du(e,t){let n=e.address();if(n===null||typeof n=="string")throw new ae(t.host);if(!ct(n.address))throw new ae(n.address);return{host:t.host,port:n.port}}async function Lu(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return $e();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Ke([...n??[],...r??[]],{sampleLimit:re})}async function Fu(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?Me():Ge(await e.workflowEngine.list(),{sampleLimit:re})}async function $u(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,i=t.bind,l=a(()=>e.getInspectorSnapshot(i),"snapshot"),c=n.createServer((u,f)=>{let y=Nu(u.url),p=y.pathname;if(u.method==="GET"&&(p==="/"||p===Tt)){Ue(f,200,l());return}if(u.method==="GET"&&p===Dt){try{Ue(f,200,e.requestGraph(Mn({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof ee){Ue(f,400,{error:g.message,option:g.option});return}throw g}return}if(u.method==="GET"&&p===Lt){Lu(e).then(g=>Ue(f,200,g)).catch(g=>{Ue(f,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(u.method==="GET"&&p===Ft){Fu(e).then(g=>Ue(f,200,g)).catch(g=>{Ue(f,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(u.method==="GET"&&p===Nt){f.writeHead(200,Tu()),f.flushHeaders(),f.write(Ht(l())),r.add(f);let g=s>0?setInterval(()=>{f.write(Ht(l()))},s):void 0;g&&o.add(g);let d=a(()=>{r.delete(f),g&&(clearInterval(g),o.delete(g))},"drop");u.on("close",d),f.on("close",d);return}Ue(f,404,{error:"not found"})});try{await new Promise((u,f)=>{let y=a(p=>f(p),"onError");c.once("error",y),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",y);try{i=Du(c,t.bind),u()}catch(p){f(p instanceof Error?p:new ae(t.bind.host))}})})}catch(u){throw await new Promise(f=>{c.close(()=>f())}),u}return{host:i.host,port:i.port,url:me(i.host,i.port,"/"),snapshotUrl:me(i.host,i.port,Tt),eventsUrl:me(i.host,i.port,Nt),graphUrl:me(i.host,i.port,Dt),outboxUrl:me(i.host,i.port,Lt),workflowsUrl:me(i.host,i.port,Ft),close(){for(let u of o)clearInterval(u);o.clear();for(let u of r)u.end();return r.clear(),new Promise((u,f)=>{c.close(y=>{y?f(y):u()})})}}}var Va=Bt(()=>{"use strict";Dr();Bn();a(_u,"jsonHeaders");a(Tu,"sseHeaders");a(Nu,"requestUrl");a(Ue,"writeJson");a(Du,"boundAddress");a(Lu,"resolveOutboxMonitor");a(Fu,"resolveWorkflowsMonitor");a($u,"listenArkRunInspector")});var Vu={};ms(Vu,{ANALYSIS_IR_SCHEMA_VERSION:()=>gr,ARK_ANALYSIS_RESULT_SCHEMA:()=>Wr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Wt,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Ca,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>wa,ARK_RUN_COMPONENT_LIFETIMES:()=>wr,ARK_RUN_EPHEMERAL_DEFAULT:()=>at,ARK_RUN_GRAPH_DEFAULT_SLICE:()=>_r,ARK_RUN_GRAPH_NODE_KINDS:()=>ss,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS:()=>is,ARK_RUN_GRAPH_SCHEMA_VERSION:()=>Pr,ARK_RUN_GRAPH_SLICES:()=>Tr,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS:()=>as,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION:()=>Tn,ARK_RUN_INSPECTOR_DEFAULT_HOST:()=>Un,ARK_RUN_INSPECTOR_DEFAULT_PORT:()=>Mr,ARK_RUN_INSPECTOR_EVENTS_PATH:()=>Nt,ARK_RUN_INSPECTOR_GRAPH_PATH:()=>Dt,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT:()=>re,ARK_RUN_INSPECTOR_OUTBOX_PATH:()=>Lt,ARK_RUN_INSPECTOR_SCHEMA_VERSION:()=>$r,ARK_RUN_INSPECTOR_SNAPSHOT_PATH:()=>Tt,ARK_RUN_INSPECTOR_SSE_EVENT:()=>Hr,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK:()=>Kr,ARK_RUN_INSPECTOR_WORKFLOWS_PATH:()=>Ft,ARK_RUN_TRANSPORT_KINDS:()=>_t,ArkRunInspectorBindError:()=>ae,ArkRunInspectorProductionError:()=>lt,DEFAULT_MAX_HISTORY_SIZE:()=>Ur,DIAGNOSTIC_CATALOG:()=>wn,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ra,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Er,DIAGNOSTIC_RULE_IDS:()=>Aa,EventContractRegistryImpl:()=>mt,EventContractViolationError:()=>Ye,InMemoryAuditStore:()=>yt,InMemoryEventBuffer:()=>_e,InMemoryOutboxStore:()=>oo,InMemoryReadModelStore:()=>Ct,InMemoryWorkflowStore:()=>xt,IntentRegistry:()=>je,InvalidArkRunGraphQueryError:()=>ee,InvalidArkRunSendOptionError:()=>it,InvalidIntentNameError:()=>ze,LayerPolicyContextError:()=>qe,MANIFEST_SCHEMA_VERSION:()=>On,ObservedLayerFlowViolationError:()=>Xe,POLICY_DELTA_SCHEMA_VERSION:()=>yr,PolicyEngine:()=>Oe,PolicyViolationError:()=>Re,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>fr,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Ne,SourceMetadataOverrideError:()=>Ae,UnknownEventSourceError:()=>Pe,UnregisteredIntentError:()=>We,analyzeArchitectureConvergence:()=>rt,analyzeChange:()=>En,analyzePolicyDelta:()=>Mo,analyzeProject:()=>Et,analyzeResolvedProject:()=>wt,appendDecisionTape:()=>Qo,architecturalPolicies:()=>Jn,arkRunGraphQueryFromSearchParams:()=>Mn,arkRunInspectorUrl:()=>me,buildArkRunInspectorHardening:()=>Mt,buildArkRunInspectorOutboxMonitor:()=>Ke,buildArkRunInspectorSnapshot:()=>jn,buildArkRunInspectorWorkflowsMonitor:()=>Ge,buildDependencyInformationPackage:()=>fe,buildPublishPolicyContext:()=>Jt,catalogFixForRuleId:()=>Ea,catalogWhyForRuleId:()=>Sa,checkAdapterGovernance:()=>cr,checkContract:()=>go,classifyArkPolicyDelta:()=>hr,classifyArkRunInspectorStoreDurability:()=>He,closeArkRunGraphQuery:()=>$n,closedArkRunEphemeral:()=>Fr,closedArkRunTransportKind:()=>Lr,collectAnalysisConfigWarnings:()=>Sn,collectForbiddenCapabilityUses:()=>tt,compareInformationPackages:()=>Cr,createAICodeGate:()=>Oo,createAdapter:()=>fo,createAdapterResult:()=>Rs,createArchitectureProfile:()=>dn,createArchitectureProfileFromArkConfig:()=>un,createArkKernel:()=>Kt,createArkKernelFromConfig:()=>ds,createArkManifest:()=>Pn,createArkTestHarness:()=>io,createAuditTrail:()=>on,createDependencyGraph:()=>sn,createElevenLayerArkConfig:()=>uo,createEventBus:()=>ro,createEventContractRegistry:()=>nn,createIntentRegistry:()=>zt,createLenientArkKernel:()=>jr,createLenientArkKernelFromConfig:()=>ps,createMetadataRegistry:()=>pn,createObservabilityReporter:()=>rn,createProjectionRegistry:()=>xn,createResolvedCandidateFacts:()=>pr,createSaga:()=>Yo,createStrictArkKernel:()=>Vr,createStrictArkKernelFromConfig:()=>us,createWorkflowEngine:()=>Ot,defaultIntentRegistry:()=>Xr,defineArchitectureProfilePolicy:()=>Zt,defineIntent:()=>Yr,defineLayerPolicy:()=>Yt,definePolicy:()=>Be,definePort:()=>po,definePublishPolicy:()=>Zr,detectArchitectureCycles:()=>kr,deterministicHash:()=>z,diagnosticDocsFragment:()=>Bo,diagnosticDocsPath:()=>ba,elevenLayerProfile:()=>Qe,evaluateArchitectureGraph:()=>st,explainViolation:()=>Ho,extractSemanticDependencies:()=>et,formatArkRunGraphMermaid:()=>Nr,formatArkRunInspectorSseEvent:()=>Ht,getDiagnosticCatalogEntry:()=>Cn,isArkRunInspectorLoopbackHost:()=>ct,isArkRunInspectorProductionEnv:()=>Vn,isCataloguedOrArkRuleFamily:()=>Ia,isKnownDiagnosticCode:()=>ka,isLayerPolicy:()=>Xt,loadContract:()=>vn,loadResolvedCandidateFacts:()=>Ee,policyDeltaAcknowledgementMatches:()=>Rr,preflightChange:()=>Uo,preflightResolvedChange:()=>Vo,replayInformationPackages:()=>ns,requestArkRunGraph:()=>Hn,resolveArkRunInspectorBind:()=>$t,resolveArkRunSendPlan:()=>Kn,resolvedFactsEvidenceRequirementsHash:()=>bt,serializeDiagnosticCatalog:()=>va,shadowInformationPackage:()=>ts,stableSerialize:()=>$,startArkRunInspector:()=>Wn,syncRegistryToGraph:()=>an,toAdapterDiagnostic:()=>Zn,unavailableArkRunInspectorOutboxMonitor:()=>$e,unavailableArkRunInspectorWorkflowsMonitor:()=>Me,validateIntentName:()=>qt,version:()=>qn});module.exports=el(Vu);var qn="4.8.22";var tl=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,nl=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,rl=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ol(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return tl.test(n)?"pure-shared":r==="PersistenceAdapters"&&(nl.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":rl.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(ol,"classifyLayerImportKind");function sl(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=ol(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}a(sl,"layerImportNextAction");function il(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(il,"arkRunCallSiteName");function al(e){let t=il(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(al,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return sl(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"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";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 al(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(pe,"deterministicNextAction");var Wt="1.5",Br="docs/diagnostics.md",Wr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function Yn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}a(Yn,"adapterFindingTargetKey");function Xn(e){let t=new Map;return e.map(n=>{let r=Yn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(Xn,"adapterFindingOccurrenceTargetKeys");function zr(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(zr,"adapterFindingRefFromTargetKey");function qr(e){return`${Br}#${e}`}a(qr,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}a(O,"text");function hs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(hs,"positiveInteger");function ll(e,t,n){return pe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(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:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}a(ll,"nextActionForDiagnostic");function Zn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(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}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},i=n??Yn(e),l=zr(i);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:hs(e.line,1),column:hs(e.column,1)},evidence:s,nextAction:O(e.nextAction)??ll(r,s,e),findingRef:l,targetKey:i,docsCodePath:qr(r)}}a(Zn,"toAdapterDiagnostic");function Rs(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(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],i=e.warnings??[],l=Xn(s),c=Xn(i),u=[...s.map((y,p)=>Zn(y,"error",l[p])),...i.map((y,p)=>Zn(y,"warning",c[p]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...o};let y={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...o}:{...f,mode:n,valid:!1,completeness:t,...o}}a(Rs,"createAdapterResult");var je=class{static{a(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=a(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var As=new je;function Yr(e,t){return As.define(e,t)}a(Yr,"defineIntent");function zt(){return new je}a(zt,"createIntentRegistry");var Xr=As;var ks=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function qt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!ks.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${ks.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}a(qt,"validateIntentName");var Re=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
6
- `);super(`Hard policy violation(s) detected:
7
- ${n}`),this.name="PolicyViolationError",this.violations=t}};var Oe=class{static{a(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let i=s.check(t);if(i!==!0){if(i===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(i))for(let l of i)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:i.message,details:i.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new Re(n.hardViolations);return n}clear(){this.policies.length=0}};function Be(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}a(Be,"definePolicy");function cl(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}a(cl,"defaultLayerOf");function Is(e,t){return t.resolveLayer?.(e)??cl(e)}a(Is,"resolveLayer");function dl(e,t,n){return e===n.from&&t===n.to}a(dl,"matchesRule");function Yt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return Be({name:t,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(i=>i.kind==="declared"||i.kind==="produces").map(i=>({from:i.from,to:i.to})),...(r.relationships??[]).filter(i=>i.kind==="dependsOn").map(i=>({from:i.from,to:i.to}))],s=[];for(let i of o){let l=Is(i.from,e),c=Is(i.to,e);for(let u of e.rules)!u.allowed&&dl(l,c,u)&&s.push({policyName:t,severity:n,message:u.message??`Layer violation: ${i.from} (${l}) must not relate to ${i.to} (${c})`})}return s.length>0?s:!0},"check")})}a(Yt,"defineLayerPolicy");function Xt(e){return e.tags?.includes("layer")??!1}a(Xt,"isLayerPolicy");var Jn={layerIsolation(){return Jn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return Yt({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 Zt(e,t={}){return Yt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}a(Zt,"defineArchitectureProfilePolicy");function Jt(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}a(Jt,"buildPublishPolicyContext");function Zr(e){return Be(e)}a(Zr,"definePublishPolicy");var We=class extends Error{static{a(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},ze=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},qe=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},Ye=class extends Error{static{a(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Pe=class extends Error{static{a(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},Ae=class extends Error{static{a(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},Xe=class extends Error{static{a(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function Qt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=qt(e);if(!n.valid)throw new ze(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new We(e)}}a(Qt,"assertIntentAllowed");function bs(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Pe(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Pe(e.intent,e.metadata.source)}}a(bs,"assertSourceAllowed");function en(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Ye(e.intent,n.issues)}a(en,"assertContractAllowed");function dt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(dt,"isPlainRecord");function ut(e){return Array.isArray(e)?e.map(ut):dt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ut(n)])):e}a(ut,"clonePatchValue");function Jr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let i=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=ut(s);continue}if(dt(r[o])&&dt(s)){r[o]=Jr(r[o],s,i);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=Qr(r[o],s,i);continue}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}return r}a(Jr,"mergeRecordPatch");function Qr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let i=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=ut(o);return}if(dt(r[s])&&dt(o)){r[s]=Jr(r[s],o,i);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=Qr(r[s],o,i);return}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}),r}a(Qr,"mergeArrayPatch");function vs(e,t){if(Array.isArray(t)){if(e===void 0)return ut(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return Qr(e,t)}if(e===void 0)return ut(t);if(!dt(e))throw new Error("Object interceptor patch requires an object payload.");return Jr(e,t)}a(vs,"applyPayloadPatch");async function Es(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:a(c=>{s.push(c)},"intercept")})),s.length===0)continue;let i=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:i}]}};for(let c of s)l={...l,payload:vs(l.payload,c),metadata:{...l.metadata}};en(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=i,t.appendTrace({type:"event.intercepted",timestamp:i,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(i){await ul(o,r,i,t)}}return r}a(Es,"applyInterceptors");async function ul(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}a(ul,"recordInterceptorError");var Ss=new Map;function ws(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(ws,"escapeLiteral");function er(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}a(er,"normalizeGlobSeparators");function pl(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(pl,"bracesBalanced");function ke(e){let t=Ss.get(e);if(t)return t;let n=er(e),r=pl(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=ws(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+=ws(c)}let i=new RegExp(`^${o}$`);return Ss.set(e,i),i}a(ke,"globToRegExp");function fl(e){return er(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(fl,"concreteGlobSegments");function to(e,t){let n=er(String(e)),r=fl(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let u of r){let f=-1;for(let y=l;y<i.length;y+=1)if(i[y]===u){f=y;break}if(f<0)return s;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}a(to,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>ke(i).test(n))){for(let i of s.patterns??[])if(ke(i).test(n)){let l=to(i,n);l>o&&(o=l,r=s.name)}}return r}a(de,"layerForRelativePath");function Qn(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",o=String(e).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let s=new Set;for(let i of t)if(!(typeof i!="string"||i.length===0)){if(Os(i)){let l=gl(o,i,r);if(l)return l;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&s.add(i.toLowerCase())}return Rl(o,s)}a(Qn,"sliceIdForPath");function Os(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Os,"isAnchoredSliceEntry");function gl(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=Ns(e,r[0]??"");for(let s of o){let i=ml(e,r,s,n);if(i)return i}}a(gl,"anchoredSliceId");function ml(e,t,n,r="path"){let o=[],s=-1,i=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(i>=e.length-1){for(let u=l;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[i].toLowerCase()),i+=1;continue}if(c==="**"||i>=e.length||e[i].toLowerCase()!==c)return;o.push(e[i].toLowerCase()),s=o.length-1,i+=1}if(o.length!==0)return r==="stars"?s<0?void 0:o.slice(s).join("/"):o.join("/")}a(ml,"bindAnchoredSlice");function Ps(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let s of n.sliceFolders??[]){if(typeof s!="string"||s.length===0)continue;let i=yl(s);if(!i)continue;let l=s.split(/[/\\]/).filter(f=>f.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let u=r.get(i)??[];u.push(s),r.set(i,u)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:hl(n.from,n.to,i,s)})}return t}a(Ps,"sliceIdentityCollisions");function yl(e){if(!Os(e))return;let t=e.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),n=-1;for(let o=0;o<t.length;o+=1){let s=t[o]??"";if(s==="**")return;s!=="*"&&(n=o)}if(n<0)return;let r=t.slice(n);if(!r.some((o,s)=>s>0&&o!=="*"))return r.join("/")}a(yl,"starsIdentityStem");function hl(e,t,n,r){let o=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${o}. They bind as ${r}.`}a(hl,"formatSliceIdentityCollision");function Rl(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}a(Rl,"bareSliceId");function Al(e){let t=new Set;for(let n of e??[]){let o=er(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let i=o[s];if((i==="**"||i==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(Al,"inferSliceFoldersFromPatterns");function _s(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 Al(r?.patterns)}a(_s,"resolveSliceFolders");function Cs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(Cs,"normalizeSegments");function Ts(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Ts,"trimTrailingSlashes");var kl=["src","app"];function Ns(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return kl.includes(n)&&r!==n?[0,1]:[0]}a(Ns,"anchorOffsets");function Il(e){let t=Ts(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Il,"isBlanketRoot");function eo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Cs(n);for(let s of t){if(typeof s!="string"||s.length===0||Il(s))continue;if(s.includes("*")){let c=Ts(s.toLowerCase());if(ke(c).test(r)||ke(`${c}/**`).test(r))return!0;continue}let i=Cs(s);if(i.length===0)continue;let l=Ns(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let u=!0;for(let f=0;f<i.length;f+=1)if(o[c+f]!==i[f]){u=!1;break}if(u)return!0}}return!1}a(eo,"pathUnderSharedRoot");function xs(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(xs,"sliceMatchesDeclaration");function bl(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&xs(r.from,t)&&xs(r.to,n))}a(bl,"crossSliceEdgeAllowed");function vl(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(vl,"peerIsolationDecision");function pt(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"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(pt,"peerIsolationDenyExplanation");function ft(e,t,n,r){return Ze(e,t,n,r)?.rule}a(ft,"findDeniedEdgeRule");function Ze(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,i=r?.toPath,l=_s(o,t,r?.layers),c=s?Qn(s,l,o.sliceIdentity):void 0,u=i?Qn(i,l,o.sliceIdentity):void 0,f=vl({fromPath:s,toPath:i,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&eo(s,o.sharedRoots),toShared:!u&&eo(i,o.sharedRoots),crossSliceAllowed:bl(o.allowedCrossSlice,c,u),sharedImportsSlice:o.sharedImportsSlice});if(f.denied)return{rule:o,peerIsolationReason:f.reason,fromSlice:c,toSlice:u};continue}if(t!==n)return{rule:o}}}a(Ze,"findDeniedEdgeDecision");function Ds(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let i of e??[]){if(i.from!==t||i.to!==n||i.allowed!==!1||!i.peerIsolation||i.sharedImportsSlice==="deny")continue;let l=_s(i,t,r?.layers),c=Qn(o,l,i.sliceIdentity),u=Qn(s,l,i.sliceIdentity);if(!(c||!u)&&eo(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}a(Ds,"findSharedImportsSliceBridge");async function Ls(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let i=ft(r.rules,o,s);if(!i)return;let l=t.mode,c=i.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,u={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:i};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:u}),await t.recordAudit("layer.observedViolation",e,u),l==="hard")throw new Xe(n,e.intent,o,s,c)}a(Ls,"assertObservedLayerFlowAllowed");async function Fs(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Re&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}a(Fs,"enforcePublishPolicy");function El(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}a(El,"appendHistory");function tn(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}a(tn,"appendTrace");async function tr(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){tn(e,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}a(tr,"recordAudit");async function $s(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."};tn(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 tr(e,"event.rawPublish",t,n)}a($s,"recordRawPublishDiagnostic");async function Ms(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return El(e,o),await e.eventBuffer?.enqueue(t,r),tn(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 tr(e,"event.published",t,{subscribersNotified:n}),o}a(Ms,"recordSuccessfulPublish");function no(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}a(no,"enrichMetadata");var Hs=0;function Sl(){return Hs+=1,`interceptor-${Date.now()}-${Hs}`}a(Sl,"nextInterceptorRegistrationId");var gt=class{static{a(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new Oe(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Xt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new qe;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=Jt({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,i=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,u=typeof t!="function";if(u){let p=t,g=r??n??{};c={...p,metadata:no(p.metadata,g,this.recording.instanceId)}}else{let p=t,g=n,d=r??{},m=p(g);c={...m,metadata:no(m.metadata,d,this.recording.instanceId)}}u&&this.strictRegistry&&await $s(this.recording,c),Qt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),bs(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),en(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Es(c,{interceptorsForIntent:a(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,g,d)=>this.recordAudit(p,g,d),"recordAudit")}),en(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Ls(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,g,d)=>this.recordAudit(p,g,d),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await Fs(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,g,d)=>this.recordAudit(p,g,d),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((p,g,d)=>this.safeHook(p,g,d),"safeHook")}),await Ms(this.recording,c,s?f.length:0,o.tx);let y=(async()=>{s&&await Promise.all(f.map(p=>this.invokeHandler(p,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return i?await y:y.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return Qt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,s={},i)=>{if(s.source&&s.source!==n)throw new Ae(n,s.source);await this.publish(r,o,{...s,source:n},i)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Qt(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let i=this.subscriptions.indexOf(o);i>=0&&this.subscriptions.splice(i,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Qt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:Sl(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let i=this.interceptorsByIntent.get(o)??[];return i.push(s),this.interceptorsByIntent.set(o,i),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(t){tn(this.recording,t)}async recordAudit(t,n,r){await tr(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 ro(e){return new gt(e)}a(ro,"createEventBus");function wl(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}a(wl,"formatStandardSchemaPath");function Cl(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}a(Cl,"actualType");function xl(e,t){return e?`${e}.${t}`:t}a(xl,"formatPath");function Ks(e,t,n,r,o){let s=Cl(e);if(t.type!=="unknown"&&s!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${s}.`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}Gs(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((i,l)=>{Ks(i,t.items,`${n}[${l}]`,r,o)})}a(Ks,"validateSchemaField");function Gs(e,t,n,r,o){for(let[s,i]of Object.entries(t)){let l=xl(o,s),c=e[s];if(c===void 0){i.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}Ks(c,i,l,n,r)}}a(Gs,"validateObjectSchema");var mt=class{static{a(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Gs(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let i of Object.keys(s))r.schema[i]||o.push({intent:t.intent,version:r.version,field:i,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let i=r.standardSchema["~standard"].validate(t.payload);if(i instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(i.issues)for(let l of i.issues)o.push({intent:t.intent,version:r.version,field:wl(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 nn(){return new mt}a(nn,"createEventContractRegistry");var Us=0;function Ol(){return Us+=1,`outbox-${Date.now()}-${Us}`}a(Ol,"nextOutboxId");function Vs(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}a(Vs,"cloneRecord");var _e=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Ol(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Vs(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(Vs)}async clear(){this.records.clear()}},oo=_e;function so(e){return`${e.from}->${e.to}`}a(so,"flowKey");function js(e){let t=new Set,n=[];for(let r of e){let o=so(r);t.has(o)||(t.add(o),n.push(r))}return n}a(js,"uniqueFlows");function Bs(e,t){let n=new Set(t.map(so));return e.filter(r=>!n.has(so(r)))}a(Bs,"difference");function rn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="produces").map(m=>({from:m.from,to:m.to})),i=n?.getHistory().map(m=>({from:m.event.metadata.source,to:m.event.intent}))??[],l=i.length>0||!r?[]:r.getEdges().filter(m=>m.kind==="observed").map(m=>({from:m.from,to:m.to})),c=js([...o,...s]),u=js([...i,...l]),f=u.filter(m=>!m.from||m.from==="unknown"),y=t?Array.from(new Set(u.map(m=>m.from).filter(m=>m&&m!=="unknown"&&!t.has(m)))):[],p=t?Array.from(new Set(u.map(m=>m.to).filter(m=>!t.has(m)))):[],g=new Set(u.flatMap(m=>[m.from,m.to])),d=t?t.list().map(m=>m.name).filter(m=>!g.has(m)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:u,declaredButUnobserved:Bs(c,u),observedButUndeclared:Bs(u.filter(m=>m.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:p,registeredButNeverObserved:d}}}}a(rn,"createObservabilityReporter");function io(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}a(io,"createArkTestHarness");var Ws=0;function Pl(){return Ws+=1,`audit-${Date.now()}-${Ws}`}a(Pl,"createAuditId");function _l(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}a(_l,"matchesQuery");var yt=class{constructor(t){this.maxRecords=t}maxRecords;static{a(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>_l(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},nr=class{constructor(t){this.store=t}store;static{a(this,"AuditTrailImpl")}async record(t){let n={id:Pl(),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 on(e={}){return new nr(e.store??new yt(e.maxRecords))}a(on,"createAuditTrail");var rr=class{static{a(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let t=`flowchart TD
8
- `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";t+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
9
- `}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(t+=` ${this.safeId(r)}
10
- `);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let i=t.resolveLayer(s)??"Unclassified",l=n.get(i)??[];l.push(s),n.set(i,l)}let r=`flowchart TD
11
- `;for(let s of t.layers){let i=n.get(s.name)??[];if(i.length!==0){r+=` subgraph ${this.safeId(s.name)}[${s.name}]
12
- `;for(let l of i)r+=` ${this.safeId(l)}[${l}]
13
- `;r+=` end
14
- `}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
15
- `;for(let s of o)r+=` ${this.safeId(s)}[${s}]
16
- `;r+=` end
17
- `}for(let s of this.edges){let i=s.kind?`|${s.kind}|`:"";r+=` ${this.safeId(s.from)} -->${i} ${this.safeId(s.to)}
18
- `}return r.trim()}detectViolations(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.message}`)}return n}ensureNode(t){this.nodes.has(t)||this.nodes.set(t,{id:t})}addEdge(t){this.edges.some(r=>r.from===t.from&&r.to===t.to&&r.kind===t.kind)||this.edges.push(t)}findSimpleCycles(){let t=new Map;for(let l of this.edges)t.has(l.from)||t.set(l.from,[]),t.get(l.from).push(l.to);let n=[],r=new Set,o=[],s=a(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))s(c);else if(o.includes(c)){let u=o.indexOf(c),f=o.slice(u).concat(c);n.push(f)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||s(l);let i=new Set(n.map(l=>l.join("->")));return Array.from(i).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function sn(){return new rr}a(sn,"createDependencyGraph");function an(e,t,n={}){let r=n.requireRegisteredTargets??!1;for(let o of e.getAllRelationships())r&&!e.has(o.to)||(o.kind==="dependsOn"?t.registerDependency(o.from,o.to,"declared"):t.registerDependency(o.from,o.to,"produces"))}a(an,"syncRegistryToGraph");var Je={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},zs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Je,default:[]},kernelRoots:{...Je},managedLayers:{...Je,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},qs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Je,default:[]},managedLayers:{...Je,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Je,default:[]},appliesTo:{...Je,default:[]}}};function ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ln,"isObject");function Ys(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)ln(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Ys,"declaredLayerNames");function Xs(e){if(!ln(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}a(Xs,"defaultedArkRun");function Zs(e){if(!ln(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}a(Zs,"defaultedArkOrder");function Js(e,t){let n=e.arkRun;if(n===void 0||!ln(n))return;let r=Ys(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Js,"validateArkRunExtra");function Qs(e,t){let n=e.arkOrder;if(n===void 0||!ln(n))return;let r=Ys(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Qs,"validateArkOrderExtra");function or(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(or,"normalizeStewardId");function ei(e){let t=or(e);return!t||ao(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(ei,"isGitHubHandle");function Tl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||ao(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}a(Tl,"isGitHubEmail");function Nl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&ei(t[1])?or(t[1]):null}a(Nl,"githubHandleFromEmail");function ti(e){let t=Nl(e);if(t)return t;let n=or(e);return!n||ao(n)?null:ei(n)||Tl(n)?n:null}a(ti,"canonicalStewardId");var Dl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function ao(e){let t=or(e);return!t||Dl.test(t)}a(ao,"isAutomationAuthor");var le="1.3",Ll=["public","auth","admin","internal"];function Fl(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(Fl,"isFutureHouseLayer");function $l(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a($l,"layerOwnersList");function oi(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Fl(t)&&!$l(t)).map(t=>t.name)}a(oi,"layersMissingRequiredOwners");function si(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(si,"missingLayerOwnersNextAction");var ir="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",ni=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ml=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Hl(){let e=[];for(let t of ni)for(let n of ni)t===n||Ml.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Hl,"createDefaultRules");var ar=Hl(),lo=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],oe={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ri={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ir,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:ir,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:le,default:le},name:{type:"string",minLength:1},include:{...oe,minItems:1,default:["src"]},exclude:{...oe,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ar,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...oe,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:{...oe,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...oe,minItems:1},exclude:oe,intentPrefixes:oe,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Ll]},owners:{...oe,minItems:1},forbiddenGlobals:oe,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:{...oe,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...oe,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}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...oe,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...oe,minItems:1}}},arkRun:zs,arkOrder:qs}},Ie=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
19
- ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
20
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ii(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ii,"isObject");function sr(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(sr,"propertyPath");function ht(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(ht,"valueType");function Kl(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Kl,"resolveSchemaRef");function cn(e,t,n,r,o){if(t.$ref){let s=Kl(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}cn(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(!ii(e)){o.push({path:n,message:`must be an object; received ${ht(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:sr(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:sr(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||cn(e[l],i,sr(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&cn(e[i],l,sr(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${ht(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>cn(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${ht(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 ${ht(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${ht(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(cn,"validateNode");function Gl(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((i,l)=>{typeof i=="string"&&(ti(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Gl,"validateLayerOwners");function Ul(e){let t={...e,$schema:e.$schema===void 0?ir:e.$schema,schemaVersion:e.schemaVersion===void 0?le:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?ar.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Xs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Zs(e.arkOrder)),t}a(Ul,"defaultedConfig");function Vl(e){return e===le?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Vl,"migratedFromOf");function jl(){let e=new Set([le]);for(let t of lo)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(jl,"knownInputVersions");function Bl(e,t="ark.config.json"){if(!ii(e))throw new Ie(t,[{path:"$",message:`must be an object; received ${ht(e)}`}]);let n=jl(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${le}`}]);if(r!=="unversioned"&&!n.has(r))throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);let o=r,s={...e},i=0;for(;o!==le&&i<lo.length+1;){i+=1;let l=lo.find(c=>c.from===o);if(!l)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${le}`}]);o=l.to,s.schemaVersion=o}if(o!==le)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);return{candidate:Ul(s),migratedFrom:Vl(r)}}a(Bl,"migrateArkConfig");function co(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Bl(e,t),o=[];if(cn(n,ri,"$",ri,o),Js(n,o),Qs(n,o),Gl(n,o),o.length>0)throw new Ie(t,o);return{config:n,migratedFrom:r}}a(co,"loadArkConfigContract");function ai(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Ie(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return co(n,t)}a(ai,"parseArkConfigJson");function li(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:ir,schemaVersion:le};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(li,"withArkConfigMetadata");function Wl(e){return e.endsWith(".")?e:`${e}.`}a(Wl,"normalizePrefix");function zl(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}a(zl,"byLongestPrefix");function dn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Wl)})),n=[...t].sort(zl),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(i=>o.startsWith(i)))?.name}}}a(dn,"createArchitectureProfile");function un(e,t={}){return dn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(un,"createArchitectureProfileFromArkConfig");var ql=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Qe=dn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:ql,rules:ar.map(e=>({...e}))}),Yl={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 uo(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return li({include:e.include??[t],layers:Qe.layers.map(o=>({name:o.name,patterns:(Yl[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Qe.rules]})}a(uo,"createElevenLayerArkConfig");var lr=class{static{a(this,"MetadataRegistryImpl")}entities=new Map;entity(t,n,r={}){if(this.entities.has(t)&&!r.allowOverwrite)throw new Error(`Entity metadata "${t}" is already registered.`);let o={name:t,fields:{},...n};return this.entities.set(t,o),o}getEntity(t){return this.entities.get(t)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(t){return this.listEntities().filter(n=>n.emits?.includes(t)||n.consumes?.includes(t))}validate(){let t=[];for(let n of this.entities.values()){n.name.trim()||t.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||t.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&t.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&t.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:t.length===0,issues:t}}toJSON(){return this.listEntities()}};function pn(){return new lr}a(pn,"createMetadataRegistry");function po(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}a(po,"definePort");function fo(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(u=>!ci(t,u));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let i={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=cr(i);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
21
- `));return i}a(fo,"createAdapter");function go(e,t=[]){let n=t.filter(r=>!ci(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}a(go,"checkContract");function cr(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}a(cr,"checkAdapterGovernance");function ci(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}a(ci,"hasMember");var yo=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ro=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ao=Object.freeze(Object.keys(Ro).sort()),mo=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"}),ho=Object.freeze({process:Object.freeze(["process","node:process"])});function fn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=mo[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=mo[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:mo[e.slice(0,s)]??null}a(fn,"capabilityForModuleSpecifier");function Te(e,t){for(let n of t)if(ho[n]?.includes(e))return n;return null}a(Te,"forbiddenGlobalForModuleSpecifier");function dr(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Ro[r];if(o)return o}return null}a(dr,"capabilityForAmbientName");function Rt(e){if(e?.pure===!0)return[...yo].sort();let n=(e?.capabilities?.deny??[]).filter(r=>yo.includes(r));return[...new Set(n)].sort()}a(Rt,"effectiveCapabilityDeny");function gn(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}a(gn,"ambientCoveredByForbiddenGlobals");function ur(e){let t=new Set,n=new Set,r=Object.keys(Ro);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(i=>i===o||i.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let i of s)t.add(`ambient:${i}`);for(let i of ho[o]??[])t.add(`import-exact:${i}`)}for(let o of Rt(e)){if(t.add(`import:${o}`),o==="process")for(let s of ho.process)t.add(`import-exact:${s}`);for(let s of r)dr(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(ur,"loweredLayerCoverage");function At(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(At,"literalText");function pi(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(pi,"lineOf");function di(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}a(di,"isTypeOnlyReference");function fi(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}a(fi,"singleFileChecker");function ko(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(ko,"symbolAt");function Io(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):ko(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Io,"localDeclaration");function et(e,t){let n,r=[],o=a((i,l,c,u=!1)=>r.push({specifier:c,kind:l,line:pi(t,i),typeOnly:u,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",At(e,i.moduleSpecifier),di(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",At(e,i.moduleSpecifier),di(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",At(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Io(e,n??(n=fi(e,t)),t,i.expression);(l||u)&&o(i,u?"require":"dynamic-import",At(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(et,"extractSemanticDependencies");function Xl(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=At(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}a(Xl,"staticAccessPath");function Zl(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}a(Zl,"runtimeIdentifierReference");function ui(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}a(ui,"bestForbiddenMatch");function tt(e,t,n){if(n.length===0)return[];let r=new Set(n),o=fi(e,t),s=new Map,i=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let g of p.declarationList.declarations)e.isIdentifier(g.name)&&i.add(g.name.text);let l=a(p=>{let g=Xl(e,p);if(!g)return;let d=ko(o,g.root),m=d?s.get(d):void 0;return m?[...m,...g.segments.slice(1)]:Io(e,o,t,g.root)||i.has(g.root.text)?void 0:g.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let g of p.declarationList.declarations){if(!g.initializer||!e.isIdentifier(g.name))continue;let d=l(g.initializer),m=ko(o,g.name);!d||!m||s.set(m,d)}let c=[],u=new Set,f=a((p,g)=>{let d=pi(t,g),m=`${p}:${g.getStart(t)}`;u.has(m)||(u.add(m),c.push({name:p,line:d,node:g}))},"flag"),y=a(p=>{let g=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!g){let d=l(p),m=d?ui(r,d):void 0;m&&f(m,p)}else e.isIdentifier(p)&&r.has(p.text)&&Zl(e,p)&&!Io(e,o,t,p)&&f(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let d=l(p.initializer);if(d)for(let m of p.name.elements){if(!e.isIdentifier(m.name))continue;let E=m.propertyName?At(e,m.propertyName)??m.propertyName.text:m.name.text,S=ui(r,[...d,E]);S&&f(S,p.initializer)}}e.forEachChild(p,y)},"visit");return y(t),c}a(tt,"collectForbiddenCapabilityUses");function bo(e,t,n){let r=[];for(let o of n?.dependencies??et(e,t)){if(o.typeOnly||!o.specifier)continue;let s=fn(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??tt(e,t,Ao)){let s=dr(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}a(bo,"collectCapabilityUses");var vo={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."},Eo=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 So(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}a(So,"resolveIntentLayer");function nt(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(nt,"looksLikeArkIntent");function mn(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&nt(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:vo.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:vo.PUBLISH_MISSING_SOURCE}),t}a(mn,"classifyPublishFacts");function j(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(j,"violation");function kt(e,t){return e.slice(0,t).split(`
22
- `).length}a(kt,"lineOf");var Jl=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ql(e,t){return e.index+e[0].indexOf(t)}a(Ql,"captureIndex");function ec(e){let t=[],n=new Set,r=a((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=a(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,Ql(c,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,i;for(;(i=s.exec(e))!==null;){let l=i[1]??"",c=i.index+i[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=u.exec(l))!==null;){let y=f[1];y&&r(y,c+f.index+f[0].indexOf(y))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}a(ec,"extractQuotedStrings");function tc(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),i=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(i)||r.kind==="export"&&/\bexport\s+type\b/.test(i);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}a(tc,"extractModuleSpecifiers");function nc(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}a(nc,"isSyntaxWrapper");function wo(e,t){let n=t;for(;n?.parent&&nc(e,n.parent);)n=n.parent;return n}a(wo,"unwrapWrappers");function Co(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}a(Co,"callCalleeName");function rc(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=wo(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Co(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&xo(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=wo(e,s).parent;return!!(l&&e.isCallExpression(l)&&Co(e,l)==="publish")}return!1}a(rc,"isPublishMetadataSource");function gi(e,t){let n=wo(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Co(e,r);if(o&&Jl.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return gi(e,r);if(e.isPropertyAssignment(r)){let o=xo(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&rc(e,r))return!0}return!1}a(gi,"isDeclaredIntentSite");function oc(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&gi(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(oc,"extractQuotedStringsAst");function sc(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}a(sc,"hasInfrastructureToken");function ic(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(ic,"isKnownInfrastructurePackage");function ac(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(ac,"layerHasInfrastructureRole");function hn(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(hn,"tsStringLiteralText");function xo(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(xo,"tsPropertyName");function mi(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:xo(e,r.name)===n)}a(mi,"tsObjectProperty");function Rn(e,t,n){return mi(e,t,n)!==void 0}a(Rn,"tsObjectHasProperty");function yn(e,t,n){let r=mi(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(yn,"tsObjectPropertyValue");function lc(e,t){let n=yn(e,t,"metadata");return Rn(e,n,"source")}a(lc,"tsObjectHasMetadataSource");function yi(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?yi(e,t.name):!1:!1}a(yi,"tsLooksLikeIntentCreatorExpression");function cc(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}a(cc,"tsIsPublishCall");function dc(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=hn(e,n);return r!==void 0&&nt(r)||Rn(e,n,"intent")||yi(e,n)}a(dc,"tsIsArkPublishCandidate");function uc(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return lc(e,n)||Rn(e,r,"source")||Rn(e,o,"source")}a(uc,"tsPublishHasSource");function pc(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=yn(e,n,"metadata");return hn(e,yn(e,s,"source"))??hn(e,yn(e,r,"source"))??hn(e,yn(e,o,"source"))}a(pc,"tsPublishSourceLiteral");function fc(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],u=a(y=>o.getLineAndCharacterOfPosition(y.getStart(o)).line+1,"lineForNode"),f=a(y=>{if(cc(e,y)){let p=y.arguments[0],g=hn(e,p);for(let m of mn({publishCall:!0,rawIntentName:g,objectHasIntent:Rn(e,p,"intent"),arkPublishCandidate:dc(e,y),hasSource:uc(e,y)}))c.push(j(m.ruleId,m.message,{line:u(y),filePath:i}));let d=pc(e,y);if(r&&l&&d&&nt(d)){let m=r.resolveLayer(d);m&&m!==l&&c.push(j("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${m}, but the target file is classified as ${l}.`,{line:u(y),filePath:i,target:d,fromLayer:l,toLayer:m}))}}e.forEachChild(y,f)},"visit");return f(o),c}a(fc,"analyzePublishAst");function Oo(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,u=c?.filePath,f=c?.layer,y=e.typescript,p=y?y.createSourceFile(u??"generated.ts",s,y.ScriptTarget.Latest,!0):void 0,g=p?et(e.typescript,p):void 0,d=g?g.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(p),kind:k.kind,typeOnly:k.typeOnly})):tc(s),m=e.typescript?oc(e.typescript,s):ec(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of g?.filter(({unresolved:v})=>v)??[]){let v=k.kind==="require";l.push(j(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:k.line,filePath:u}))}let E=f!==void 0&&(r.has(f)||ac(f)),S=f!==void 0?` If "${f}" 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 k of n)if(k instanceof RegExp){k.lastIndex=0;let v=k.exec(s);k.lastIndex=0,v&&l.push(j("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:v.index===void 0?void 0:kt(s,v.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+S}))}else s.includes(k)&&l.push(j("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:kt(s,s.indexOf(k)),filePath:u}));for(let k of d){let v=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,N=v?.layer;if(N&&f){let b=ft(e.architectureProfile?.rules,f,N,{fromPath:C?.relPath,toPath:v?.relPath,layers:e.architectureLayers});if(b){if(k.typeOnly&&!b.peerIsolation)continue;let T=!!b.peerIsolation;l.push(j("LAYER_IMPORT_VIOLATION",b.message??(T?`Layer "${f}" must not import across slices into "${N}".`:`Layer "${f}" must not import "${N}".`),{line:kt(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:f,toLayer:N,suggestion:T?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:k.kind,peerIsolation:T,...k.typeOnly?{typeOnly:!0}:{}}}));continue}continue}E||k.typeOnly||!sc(k.value)&&!ic(k.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:kt(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+S,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let v=k.check({source:s,context:i});if(v!==!0)if(Array.isArray(v))for(let C of v)l.push(j("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else v===!1?l.push(j("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):l.push(j("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let k of m)nt(k.value)&&!t.has(k.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:kt(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let k of m){if(!nt(k.value))continue;let v=e.architectureProfile.resolveLayer(k.value);if(!v)continue;let C=Ze(e.architectureProfile.rules,f,v,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let N=C.rule.peerIsolation?pt(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,b=`Layer "${f}" must not reference "${v}" through "${k.value}".`,T=N&&C.peerIsolationReason!=="cross-slice"?`${b} ${N}`:C.rule.message?N?`${C.rule.message} (${N})`:C.rule.message:b;l.push(j("LAYER_REFERENCE_VIOLATION",T,{line:kt(s,k.index),filePath:u,target:k.value,fromLayer:f,toLayer:v,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let k of e.extensions)try{let v=k.analyze(s,i);l.push(...v)}catch(v){l.push(j("EXTENSION_ERROR",`Extension "${k.name}" failed: ${v instanceof Error?v.message:String(v)}`))}if(e.typescript&&p&&f&&e.forbiddenGlobals?.[f]?.length)try{let k=e.forbiddenGlobals[f];l.push(...tt(e.typescript,p,k).map(v=>j("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${v.name}".`,{line:v.line,filePath:u,target:v.name,fromLayer:f,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 g??[]){if(v.typeOnly||!v.specifier)continue;let C=Te(v.specifier,k);C&&l.push(j("FORBIDDEN_GLOBAL",`${f} must not use module "${v.specifier}" because it is the import form of forbidden global "${C}".`,{line:v.line,filePath:u,source:v.specifier,target:v.specifier,fromLayer:f,details:{importKind:v.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&p&&f&&e.capabilityWalls?.[f]?.length)try{let k=new Set(e.capabilityWalls[f]),v=e.forbiddenGlobals?.[f]??[];for(let C of bo(e.typescript,p))k.has(C.capability)&&(C.source==="ambient-global"&&gn(C.symbol,v)||C.source==="import-based"&&Te(C.symbol,v)||l.push(j("CAPABILITY_VIOLATION",C.source==="import-based"?`${f} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${f} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{l.push(...fc(e.typescript,s,i,e.architectureProfile))}catch(k){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}a(Oo,"createAICodeGate");function z(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(z,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$(t[n])}`).join(",")}}`}a($,"stableSerialize");var Ne="1.2";var hi=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=$(e),r=$(t);return n<r?-1:n>r?1:0}a(B,"compareCanonical");function X(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(X,"sortedUnique");function bt(e){let t={schemaVersion:"1.2",include:X(e.include??[]),exclude:X(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:X(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:X(n.patterns??[]),exclude:X(n.exclude??[]),forbiddenGlobals:X(n.forbiddenGlobals??[]),intentPrefixes:X(n.intentPrefixes??[]),capabilityDeny:X(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:X(e.arkRun.compositionRoots),managedLayers:X(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return z($(t))}a(bt,"resolvedFactsEvidenceRequirementsHash");function gc(e){let t=e.completenessReasons.map(b=>({code:b.code,message:b.message,...b.file?{file:b.file}:{}})).sort(B),n=e.files.map(b=>({...b,typeOnlyExportNames:X(b.typeOnlyExportNames)})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),r=e.dependencies.map(b=>({...b,...b.namedBindings?{namedBindings:X(b.namedBindings)}:{}})).sort(B),o=e.capabilityUses.map(b=>({...b})).sort(B),s=e.ambientUses.map(b=>({...b})).sort(B),i=e.publishCalls.map(b=>({...b})).sort(B),l=e.intentReferences.map(b=>({...b})).sort(B),c=e.safetyUses.map(b=>({...b})).sort(B),u=(e.classShapes??[]).map(b=>({...b,mutatingMethods:[...b.mutatingMethods??[]].map(T=>({...T}))})).sort(B),f=(e.arkRunKernelCalls??[]).map(b=>({...b})).sort(B),y=(e.arkRunManagedNews??[]).map(b=>({...b})).sort(B),p=(e.arkRunCompositionRootHits??[]).map(b=>({...b})).sort(B),g=(e.arkRunDeclarations??[]).map(b=>({...b,uses:X(b.uses),reactsTo:X(b.reactsTo),raises:X(b.raises),sends:X(b.sends)})).sort(B),d=(e.arkOrderPlaneCalls??[]).map(b=>({...b})).sort(B),m=(e.arkOrderGenericUpdates??[]).map(b=>({...b})).sort(B),E=(e.arkOrderRootHits??[]).map(b=>({...b})).sort(B),S=(e.arkOrderXiFieldWrites??[]).map(b=>({...b})).sort(B),k=(e.arkOrderIngestWritesXi??[]).map(b=>({...b})).sort(B),v=(e.arkOrderReleaseKeyCounts??[]).map(b=>({...b})).sort(B),C=e.files.map(({path:b,contentHash:T})=>({path:b,contentHash:T})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),N=z($(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:N,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:p,arkRunDeclarations:g,arkOrderPlaneCalls:d,arkOrderGenericUpdates:m,arkOrderRootHits:E,arkOrderXiFieldWrites:S,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:v}}a(gc,"canonicalResolvedFactsInput");function Ri(e){let t=gc(e);return{...t,factsHash:z($(t))}}a(Ri,"createCanonicalResolvedCandidateFacts");function pr(e){return Ri(ki(M(e,"$"),!1))}a(pr,"createResolvedCandidateFacts");function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(M,"asRecord");function H(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}a(H,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}a(F,"requiredText");function be(e,t,n){if(e[t]!==void 0)return F(e,t,n)}a(be,"optionalText");function K(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(K,"requiredProjectPath");function G(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(G,"requiredBoolean");function Ai(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}a(Ai,"requiredInteger");function Q(e,t,n){let r=Ai(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(Q,"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}a(U,"requiredArray");function ve(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}a(ve,"enumValue");function It(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}a(It,"parseStringArray");function mc(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}a(mc,"assertUnique");function ki(e,t){H(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ve(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ve(e,"completeness",["complete","partial","unavailable"],"$"),o=U(e,"completenessReasons","$").map((w,x)=>{let h=`$.completenessReasons[${x}]`,A=M(w,h);H(A,["code","message","file"],h);let L=A.file===void 0?void 0:K(A,"file",h);return{code:F(A,"code",h),message:F(A,"message",h),...L?{file:L}:{}}});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((w,x)=>{let h=`$.files[${x}]`,A=M(w,h);return H(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:K(A,"path",h),contentHash:F(A,"contentHash",h),parseStatus:ve(A,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Ai(A,"parseDiagnosticCount",h),exportsOnlyTypes:G(A,"exportsOnlyTypes",h),typeOnlyExportNames:It(A.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:G(A,"hasTopLevelSideEffects",h)}}),i=U(e,"dependencies","$").map((w,x)=>{let h=`$.dependencies[${x}]`,A=M(w,h);H(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let L=be(A,"specifier",h),W=be(A,"target",h),xe=ve(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(xe==="resolved-project"&&!W)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(xe!=="resolved-project"&&W)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(xe!=="dynamic"&&!L)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:K(A,"from",h),...L?{specifier:L}:{},kind:ve(A,"kind",["import","export","dynamic-import","require"],h),typeOnly:G(A,"typeOnly",h),line:Q(A,"line",h),resolution:xe,...W?{target:K(A,"target",h)}:{},...A.namedBindings!==void 0?{namedBindings:It(A.namedBindings,`${h}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(A,"targetTypeOnlyExports",h)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(A,"sourcePureTypeModule",h)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(A,"namedBindingsTypeOnly",h)}:{},...A.portProofEligible!==void 0?{portProofEligible:G(A,"portProofEligible",h)}:{}}}),l=U(e,"capabilityUses","$").map((w,x)=>{let h=`$.capabilityUses[${x}]`,A=M(w,h);return H(A,["file","line","symbol","capability","source"],h),{file:K(A,"file",h),line:Q(A,"line",h),symbol:F(A,"symbol",h),capability:ve(A,"capability",hi,h),source:ve(A,"source",["ambient-global","import-based"],h)}}),c=U(e,"ambientUses","$").map((w,x)=>{let h=`$.ambientUses[${x}]`,A=M(w,h);return H(A,["file","line","symbol"],h),{file:K(A,"file",h),line:Q(A,"line",h),symbol:F(A,"symbol",h)}}),u=U(e,"publishCalls","$").map((w,x)=>{let h=`$.publishCalls[${x}]`,A=M(w,h);H(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let L=be(A,"rawIntentName",h),W=be(A,"sourceIntent",h);return{file:K(A,"file",h),line:Q(A,"line",h),...L?{rawIntentName:L}:{},objectHasIntent:G(A,"objectHasIntent",h),arkPublishCandidate:G(A,"arkPublishCandidate",h),hasSource:G(A,"hasSource",h),...W?{sourceIntent:W}:{}}}),f=U(e,"intentReferences","$").map((w,x)=>{let h=`$.intentReferences[${x}]`,A=M(w,h);return H(A,["file","line","intent"],h),{file:K(A,"file",h),line:Q(A,"line",h),intent:F(A,"intent",h)}}),y=U(e,"safetyUses","$").map((w,x)=>{let h=`$.safetyUses[${x}]`,A=M(w,h);H(A,["file","line","kind","symbol"],h);let L=be(A,"symbol",h),W=ve(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(W==="in-memory-store"&&!L)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(W!=="in-memory-store"&&L)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:K(A,"file",h),line:Q(A,"line",h),kind:W,...L?{symbol:L}:{}}});mc(s,w=>w.path,"$.files");let p=new Set(s.map(w=>w.path));for(let w of s){if(w.parseStatus==="parsed"&&w.parseDiagnosticCount!==0)throw new Error(`$.files[${w.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(w.parseStatus==="invalid"&&w.parseDiagnosticCount===0)throw new Error(`$.files[${w.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(w=>w.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let w of i)if(!p.has(w.from))throw new Error(`$.dependencies references missing source file ${w.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:U(e,"arkRunKernelCalls","$")).map((w,x)=>{let h=`$.arkRunKernelCalls[${x}]`,A=M(w,h);H(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let L=be(A,"receiver",h),W=be(A,"nameLiteral",h);return{file:K(A,"file",h),line:Q(A,"line",h),kind:ve(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(A,"callee",h),viaImport:G(A,"viaImport",h),...L?{receiver:L}:{},...W?{nameLiteral:W}:{}}}),E=(e.arkRunManagedNews===void 0?[]:U(e,"arkRunManagedNews","$")).map((w,x)=>{let h=`$.arkRunManagedNews[${x}]`,A=M(w,h);H(A,["file","line","typeName","importedFrom"],h);let L=be(A,"importedFrom",h);return{file:K(A,"file",h),line:Q(A,"line",h),typeName:F(A,"typeName",h),...L?{importedFrom:L}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:U(e,"arkRunCompositionRootHits","$")).map((w,x)=>{let h=`$.arkRunCompositionRootHits[${x}]`,A=M(w,h);return H(A,["file","matchedRoot","hasKernelFactory"],h),{file:K(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasKernelFactory:G(A,"hasKernelFactory",h)}}),v=e.arkRunDeclarations===void 0?[]:U(e,"arkRunDeclarations","$"),N=(e.arkOrderPlaneCalls===void 0?[]:U(e,"arkOrderPlaneCalls","$")).map((w,x)=>{let h=`$.arkOrderPlaneCalls[${x}]`,A=M(w,h);return H(A,["file","line","callee"],h),{file:K(A,"file",h),line:Q(A,"line",h),callee:F(A,"callee",h)}}),T=(e.arkOrderGenericUpdates===void 0?[]:U(e,"arkOrderGenericUpdates","$")).map((w,x)=>{let h=`$.arkOrderGenericUpdates[${x}]`,A=M(w,h);return H(A,["file","line","method"],h),{file:K(A,"file",h),line:Q(A,"line",h),method:F(A,"method",h)}}),ye=(e.arkOrderRootHits===void 0?[]:U(e,"arkOrderRootHits","$")).map((w,x)=>{let h=`$.arkOrderRootHits[${x}]`,A=M(w,h);return H(A,["file","matchedRoot","hasPlaneFactory"],h),{file:K(A,"file",h),matchedRoot:F(A,"matchedRoot",h),hasPlaneFactory:G(A,"hasPlaneFactory",h)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:U(e,"arkOrderXiFieldWrites","$")).map((w,x)=>{let h=`$.arkOrderXiFieldWrites[${x}]`,A=M(w,h);return H(A,["file","line","key"],h),{file:K(A,"file",h),line:Q(A,"line",h),key:F(A,"key",h)}}),Y=(e.arkOrderIngestWritesXi===void 0?[]:U(e,"arkOrderIngestWritesXi","$")).map((w,x)=>{let h=`$.arkOrderIngestWritesXi[${x}]`,A=M(w,h);return H(A,["file","line"],h),{file:K(A,"file",h),line:Q(A,"line",h)}}),Ce=(e.arkOrderReleaseKeyCounts===void 0?[]:U(e,"arkOrderReleaseKeyCounts","$")).map((w,x)=>{let h=`$.arkOrderReleaseKeyCounts[${x}]`,A=M(w,h);return H(A,["file","line","keyCount"],h),{file:K(A,"file",h),line:Q(A,"line",h),keyCount:Q(A,"keyCount",h)}}),Gt=v.map((w,x)=>{let h=`$.arkRunDeclarations[${x}]`,A=M(w,h);return H(A,["file","line","uses","reactsTo","raises","sends"],h),{file:K(A,"file",h),line:Q(A,"line",h),uses:It(A.uses,`${h}.uses`),reactsTo:It(A.reactsTo,`${h}.reactsTo`),raises:It(A.raises,`${h}.raises`),sends:It(A.sends,`${h}.sends`)}});for(let[w,x]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",Gt],["$.arkOrderPlaneCalls",N],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",ye],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",Y],["$.arkOrderReleaseKeyCounts",Ce]])for(let h of x)if(!p.has(h.file))throw new Error(`${w} references missing file ${h.file}.`);let zn=be(e,"projectPackageName","$"),gs=(e.classShapes===void 0?[]:U(e,"classShapes","$")).map((w,x)=>{let h=`$.classShapes[${x}]`,A=M(w,h);H(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let L=U(A,"mutatingMethods",h).map((W,xe)=>{let R=`${h}.mutatingMethods[${xe}]`,te=M(W,R);return H(te,["name","referencesGuardOrPublish"],R),{name:F(te,"name",R),referencesGuardOrPublish:G(te,"referencesGuardOrPublish",R)}});return{file:K(A,"file",h),className:F(A,"className",h),exported:G(A,"exported",h),hasPublicMutableFields:G(A,"hasPublicMutableFields",h),hasPublicSetters:G(A,"hasPublicSetters",h),hasPublicConstructor:G(A,"hasPublicConstructor",h),hasStaticFactory:G(A,"hasStaticFactory",h),mutatingMethods:L,...A.dataOnly===void 0?{}:{dataOnly:G(A,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...zn?{projectPackageName:zn}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:gs,arkRunKernelCalls:d,arkRunManagedNews:E,arkRunCompositionRootHits:k,arkRunDeclarations:Gt,arkOrderPlaneCalls:N,arkOrderGenericUpdates:T,arkOrderRootHits:ye,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:Y,arkOrderReleaseKeyCounts:Ce}}a(ki,"parseResolvedFactsInput");function Ee(e){let t=M(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Ri(ki(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}a(Ee,"loadResolvedCandidateFacts");var yc=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},ne={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},fr={$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:_,message:_,file:V}}},resolverIdentity:_,compilerIdentity:_,compilerOptionsHash:_,tsconfigHash:_,candidateTreeHash:_,evidenceRequirementsHash:_,projectPackageName:_,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:_,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:_},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:_,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ne,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:_},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:ne,symbol:_,capability:{enum:yc},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:ne,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:ne,rawIntentName:_,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:_}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:ne,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:ne,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:_},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:_,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:_,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:V,line:ne,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:_,viaImport:{type:"boolean"},receiver:_,nameLiteral:_}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:V,line:ne,typeName:_,importedFrom:_}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:_,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:ne,uses:{type:"array",items:_},reactsTo:{type:"array",items:_},raises:{type:"array",items:_},sends:{type:"array",items:_}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:V,line:ne,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:ne,method:_}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:_,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:V,line:ne,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:ne}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:ne,keyCount:{type:"integer",minimum:1}}}},factsHash:_},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 gr="1.0";function se(e){return`${e.from}->${e.to}`}a(se,"dependencyKey");function An(e,t,n,r="dependency"){return{id:`${e}:${r}:${se(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${se(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${se(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${se(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${se(t)} from the candidate, then preflight again.`}:{}}}a(An,"dependencyFinding");function rt(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=>[se(p),p])),s=new Map(e.baseDependencies.map(p=>[se(p),p])),i=new Map(e.candidateDependencies.map(p=>[se(p),p]));for(let p of[...n.values()].sort((g,d)=>g.path.localeCompare(d.path))){let g=r.get(p.path);g?g.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:g.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${g.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:g.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((g,d)=>g.path.localeCompare(d.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((g,d)=>se(g).localeCompare(se(d)))){if(i.has(se(p))){t.push(An("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let g={from:p.to,to:p.from};i.has(se(g))?(l.add(se(g)),t.push(An("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(An("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,g]of[...i].sort(([d],[m])=>d.localeCompare(m)))s.has(p)||o.has(p)||l.has(p)||!c.has(g.from)&&!c.has(g.to)||t.push({...An("unplanned",g,`${g.from} -> ${g.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,g]of[...s].sort(([d],[m])=>d.localeCompare(m)))i.has(p)||u.has(g.from)||u.has(g.to)||!c.has(g.from)&&!c.has(g.to)||t.push({...An("unplanned",g,`${g.from} -> ${g.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((p,g)=>f[p.classification]-f[g.classification]||(p.subject===g.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(g.id));let y={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:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}a(rt,"analyzeArchitectureConvergence");var Ii="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",hc=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var bi={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},lm={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ii,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:Ii},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:[...hc]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:bi,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:bi}}}};function kn(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(kn,"emptyEffectiveArkRules");function Po(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(Po,"omitLayerDescriptions");function vi(e){let{stewards:t,...n}=Po(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}a(vi,"effectiveContractPolicyPayload");var Rc="INVARIANT_TESTS_PATH_MISSING",Ac="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",kc="INVARIANT_COVERAGE_ROOTS_MISSING",Ic="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Ei(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}a(Ei,"formatCoverageDiscards");function Ci(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}a(Ci,"isUnderCoverageRoot");function To(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(To,"escapeRegExp");function vt(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(vt,"normalizePath");function No(e,t){let n=[],r=0,o=e.length;for(;r<o;){let s=e[r],i=e[r+1];if(s==="/"&&i==="/"){for(;r<o&&e[r]!==`
23
- `;)n.push(" "),r+=1;continue}if(s==="/"&&i==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkRNQHRDCQcjs = require('../chunk-RNQHRDCQ.cjs');var _chunkA5EIY3HIcjs = require('../chunk-A5EIY3HI.cjs');var Mt="docs/diagnostics.md",wo= exports.DIAGNOSTIC_CATALOG_SCHEMA_VERSION ="1.0";function k(e,t,n,r,a,s){return{ruleId:e,title:n,why:r,fix:a,docsAnchor:e,category:t,..._optionalChain([s, 'optionalAccess', _2 => _2.oftenAdvisory])?{oftenAdvisory:!0}:{}}}_chunkA5EIY3HIcjs.a.call(void 0, k,"entry");var dt=Object.freeze([k("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),k("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),k("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),k("SHARED_IMPORTS_SLICE","layer","A shared root imports a slice",'A declared shared root imports a slice directly. That hop is allowed while sharedImportsSlice is unset or "deny-cross-parent", so this is advisory: the universe wall is direct-only.','Move the code the shared root needs into the shared root, or invert the dependency. Set sharedImportsSlice: "deny" to make these edges errors. With "deny-cross-parent", a slice that reaches another universe through a shared root is reported as LAYER_IMPORT_VIOLATION with reasonId CROSS_PARENT_VIA_SHARED. This warning does not fail the check.',{oftenAdvisory:!0}),k("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),k("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),k("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),k("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),k("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),k("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),k("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),k("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),k("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),k("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),k("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),k("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),k("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),k("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),k("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),k("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),k("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),k("ARKRULE_FILE_UNREFERENCED","arkrules","ArkRules file not referenced","A JSON file under arkrules/ is not referenced by the arkRules map in ark.config.json (or no map exists), so none of its rules are enforced or reported. Drift looks like governance until someone notices.",'Reference the file from arkRules ("<Layer>": "arkrules/<file>.json"), or delete it. Advisory only: it never fails the check.',{oftenAdvisory:!0}),k("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),k("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),k("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),k("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),k("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),k("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel, their *FromConfig variants, or ArkModule.forRoot / forRootAsync imported from arkgate/nestjs) was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, arkgate/nestjs, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),k("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),k("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),k("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),k("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call on a receiver traced to the kernel names a component that is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),k("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),k("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),k("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),k("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),k("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),k("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),k("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),k("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),k("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),k("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),k("ARKORDER_STALE_PROPOSAL","arkorder","Proposal is not bound to the current Release","apply() got a ProposeResult computed against another Release (another apply landed first), one missing its base binding, or one whose reviewed blast radius is not the transition that would commit. The binding is data, not a capability: a proposal that states the current base and the exact transition applies whoever built it.","Run proposeRelease again against the current Release, review the new blast radius, then apply that proposal. Never mechanical-safe."),k("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),k("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),k("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),k("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),k("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),k("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),k("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),k("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),k("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),k("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),k("WRITE_GATE_UNAVAILABLE","preflight","Write gate could not run","The write gate could not load its own inputs (ark.config.json missing, unreadable, or invalid; a referenced ArkRules file missing or invalid; or the built library missing), so it cannot judge this governed source write (existing files included), or a write would leave ark.config.json or a referenced ArkRules file unloadable. No checker, no write: the hook blocks instead of letting the write through unchecked.","Fix the reported input (repair ark.config.json or the ArkRules file, or run `npm run build` / reinstall arkgate from npm), then retry the same write. Do not remove the hook to get past it."),k("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),k("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),k("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","For a complete verdict, run `npx arkgate-check --root . --config ark.config.json` (or ark_prepare_change over MCP with the full candidate batch). Read lexicalValid for the one-file result."),k("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),k("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),k("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),k("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),k("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),k("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),k("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),k("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),k("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),k("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),k("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),k("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),k("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),k("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),k("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),k("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),k("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),k("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICES_VERSION","config","Config needs a newer arkgate than a pinned copy",'ark.config.json uses a slice key (childSlices, sharedImportsSlice "deny-cross-parent" or its object form, sliceIdentity, sharedImportsSlice, childSlices.message, siblings.ratchet) that an arkgate pinned in this repo rejects at config load. Emitted only with evidence of that pin: an exact package.json dependency, the installed node_modules/arkgate, package-lock.json, a scripts/*hook* or host hook command, or a CI workflow. Silent otherwise.',"Bump the named file to the version the finding gives (or newer), then run Ark again. This warning does not fail the check.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICE_EXTENDS","config","Child slice id does not extend its universe","A path resolved a child id that is not the universe id plus a further segment. The child wall does not treat that id as a child, so the edge is universe common until the folders line up.","Point childSlices.sliceFolders at children under the same universe id the outer sliceFolders already names. Doctor names the path.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICE_CROSS_UNIVERSE","config","Child slice allowance cannot cross the universe wall","childSlices.allowedCrossSlice names a pattern that can match two universes. That list clears only a sibling crossing inside one universe. The universe wall still denies the edge.","Narrow the pattern so both sides share one universe prefix (features/projects/* to features/projects/d2d-item), or remove the entry. This warning does not fail the check.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICES_INERT","config","childSlices on a rule that cannot run it","A rule sets childSlices without peerIsolation: true and allowed: false. The child wall runs only inside a universe wall, so on this rule childSlices enforces nothing. Config load still accepts it (arkgate 4.8.23 did too).",'Add "peerIsolation": true and "allowed": false to the same rule so the child wall runs, or remove childSlices. This warning does not fail the check.',{oftenAdvisory:!0}),k("CONFIG_SLICE_LEGACY_STARS_ID","config","Slice id written in the 4.8.23 stars form",'Under sliceIdentity "stars", a sliceAliases target or an allowedCrossSlice entry names the 4.8.23 stars id, which dropped a star binding before the last literal (modules/*/api/* bound api/v1). The id now keeps that binding (orders/api/v1). For one release the entry keeps its 4.8.23 meaning, so verdicts do not change.',"Rewrite the entry with the new id the warning names (for example orders/api/v1/x instead of api/v1/x). A sliceAliases target that maps to more than one universe shape is rejected at config load. This warning does not fail the check.",{oftenAdvisory:!0}),k("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),k("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),k("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Ht=new Map(dt.map(e=>[e.ruleId,e])),To= exports.DIAGNOSTIC_RULE_IDS =Object.freeze(dt.map(e=>e.ruleId));function No(e){return typeof e=="string"&&e.length>0&&Ht.has(e)}_chunkA5EIY3HIcjs.a.call(void 0, No,"isKnownDiagnosticCode");function Po(e){return typeof e!="string"||e.length===0?!1:Ht.has(e)?!0:e.startsWith("ARKRULE_")}_chunkA5EIY3HIcjs.a.call(void 0, Po,"isCataloguedOrArkRuleFamily");function ut(e){if(!(typeof e!="string"||e.length===0))return Ht.get(e)}_chunkA5EIY3HIcjs.a.call(void 0, ut,"getDiagnosticCatalogEntry");function Wr(e){return`#${_nullishCoalesce(_optionalChain([ut, 'call', _3 => _3(e), 'optionalAccess', _4 => _4.docsAnchor]), () => (e))}`}_chunkA5EIY3HIcjs.a.call(void 0, Wr,"diagnosticDocsFragment");function Lo(e){return`${Mt}${Wr(e)}`}_chunkA5EIY3HIcjs.a.call(void 0, Lo,"diagnosticDocsPath");function Do(){return{schemaVersion:"1.0",docsPath:Mt,codes:dt}}_chunkA5EIY3HIcjs.a.call(void 0, Do,"serializeDiagnosticCatalog");function Fo(e){return _optionalChain([ut, 'call', _5 => _5(e), 'optionalAccess', _6 => _6.fix])}_chunkA5EIY3HIcjs.a.call(void 0, Fo,"catalogFixForRuleId");function $o(e){return _optionalChain([ut, 'call', _7 => _7(e), 'optionalAccess', _8 => _8.why])}_chunkA5EIY3HIcjs.a.call(void 0, $o,"catalogWhyForRuleId");var Mo=Object.freeze([Object.freeze({reasonId:"CROSS_PARENT_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe slice",why:"This import crosses two universe slices. The child wall cannot allow another universe.",fix:"Keep the import inside one universe, or move the shared code into a folder both universes may use."}),Object.freeze({reasonId:"CROSS_SIBLING_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-sibling slice",why:"This import crosses two feature slices inside one universe.",fix:"Import universe-common code, or move the shared piece into the feature that owns it.",advisoryNote:"This crossing is a warning (siblings advisory). With a baseline in use, a new one fails only when the baseline already records an advisory crossing of this rule and the count grows, or when siblings.ratchet is true; ratchet false measures only."}),Object.freeze({reasonId:"CROSS_PARENT_VIA_SHARED",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe through a shared root",why:"A slice reaches another universe only through a shared root. ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.",fix:"Stop the shared root from importing the other universe, or move that import into the universe that owns it. A shared hop that stays inside one universe is allowed. If the shared hop is a composition root (bootstrap, DI registrations), list it in sharedImportsSlice.stopAt; a path through a stop is not a crossing."})]),Ho=new Map(Mo.map(e=>[e.reasonId,e]));function qr(e){if(!(typeof e!="string"||e.length===0))return Ho.get(e)}_chunkA5EIY3HIcjs.a.call(void 0, qr,"sliceReasonHint");var Ko=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Uo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Vo=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Go(e,t){let n=String(_nullishCoalesce(e, () => (""))).replace(/\\/g,"/").trim(),r=String(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _9 => _9.fromLayer]), () => (""))),a=String(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _10 => _10.toLayer]), () => ("")));return Ko.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Uo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${a} ${n}`))?"kernel-emit":Vo.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&a==="PersistenceAdapters"?"use-case":"unknown"}_chunkA5EIY3HIcjs.a.call(void 0, Go,"classifyLayerImportKind");function jo(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}_chunkA5EIY3HIcjs.a.call(void 0, jo,"sliceHintAction");function Bo(e){let t=qr(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${jo(t,e)} Then preflight again.`;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 n=Go(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 n==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":n==="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.":n==="use-case"||e.portProofEligible?`Define a port in ${_nullishCoalesce(e.fromLayer, () => ("the source layer"))}, inject the ${_nullishCoalesce(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."}_chunkA5EIY3HIcjs.a.call(void 0, Bo,"layerImportNextAction");function zo(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}_chunkA5EIY3HIcjs.a.call(void 0, zo,"arkRunCallSiteName");function Wo(e){let t=zo(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 ${_nullishCoalesce(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.`}}_chunkA5EIY3HIcjs.a.call(void 0, Wo,"arkRunNextAction");function le(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Bo(e);case"CONFIG_CHILD_SLICES_VERSION":return typeof e.nextAction=="string"&&e.nextAction.length>0?e.nextAction:"Bump the pinned arkgate named in the finding to the version it gives, then run Ark again.";case"FORBIDDEN_GLOBAL":return`Inject ${_nullishCoalesce(e.target, () => ("the capability"))} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(_nullishCoalesce(e.capability, () => ("capability")))} port in ${_nullishCoalesce(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"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";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 Wo(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}_chunkA5EIY3HIcjs.a.call(void 0, le,"deterministicNextAction");var pt="1.5",Kt="docs/diagnostics.md",Yr= exports.ARK_ANALYSIS_RESULT_SCHEMA ={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1},reasonId:{enum:["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]},universeFrom:{type:"string",minLength:1},universeTo:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function ft(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,a=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,_nullishCoalesce(r, () => ("")),_nullishCoalesce(a, () => ("")),_nullishCoalesce(s, () => (""))].join("|")}_chunkA5EIY3HIcjs.a.call(void 0, ft,"adapterFindingTargetKey");function gt(e){let t=new Map;return e.map(n=>{let r=ft(n),a=(_nullishCoalesce(t.get(r), () => (0)))+1;return t.set(r,a),a===1?r:`${r}#${a}`})}_chunkA5EIY3HIcjs.a.call(void 0, gt,"adapterFindingOccurrenceTargetKeys");function Ut(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")}`}_chunkA5EIY3HIcjs.a.call(void 0, Ut,"adapterFindingRefFromTargetKey");function Vt(e){return`${Kt}#${e}`}_chunkA5EIY3HIcjs.a.call(void 0, Vt,"adapterDocsCodePath");function S(e){return typeof e=="string"&&e.length>0?e:void 0}_chunkA5EIY3HIcjs.a.call(void 0, S,"text");function Xr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}_chunkA5EIY3HIcjs.a.call(void 0, Xr,"positiveInteger");function qo(e,t,n){return le({ruleId:e,target:_nullishCoalesce(_nullishCoalesce(S(t.target), () => (S(n.target))), () => (void 0)),fromLayer:_nullishCoalesce(S(t.fromLayer), () => (void 0)),toLayer:_nullishCoalesce(S(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:_nullishCoalesce(S(t.edgeKind), () => (void 0)),capability:_nullishCoalesce(_nullishCoalesce(S(t.capability), () => (S(n.capability))), () => (void 0)),arkruleId:_nullishCoalesce(S(t.arkruleId), () => (void 0)),arkruleSource:_nullishCoalesce(S(t.arkruleSource), () => (void 0)),reasonId:_nullishCoalesce(S(t.reasonId), () => (void 0))})}_chunkA5EIY3HIcjs.a.call(void 0, qo,"nextActionForDiagnostic");var Yo=new Set(["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]);function Xo(e){let t=e.details,n=t!==null&&typeof t=="object"?t.reasonId:void 0,r=_nullishCoalesce(S(e.reasonId), () => (S(n)));return r&&Yo.has(r)?r:void 0}_chunkA5EIY3HIcjs.a.call(void 0, Xo,"sliceReasonOf");function Gt(e,t="error",n){let r=_nullishCoalesce(_nullishCoalesce(S(e.ruleId), () => (S(e.code))), () => ("ARK_UNKNOWN")),a=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s=Xo(e),o={...S(e.target)?{target:S(e.target)}:{},...S(e.fromLayer)?{fromLayer:S(e.fromLayer)}:{},...S(e.toLayer)?{toLayer:S(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}:{},...S(e.capability)?{capability:S(e.capability)}:{},...S(e.edgeKind)?{edgeKind:S(e.edgeKind)}:{},...S(e.arkruleId)?{arkruleId:S(e.arkruleId)}:{},...S(e.arkruleSource)?{arkruleSource:S(e.arkruleSource)}:{},...s?{reasonId:s}:{},...s&&S(e.universeFrom)?{universeFrom:S(e.universeFrom)}:{},...s&&S(e.universeTo)?{universeTo:S(e.universeTo)}:{}},l=_nullishCoalesce(n, () => (ft(e))),c=Ut(l);return{ruleId:r,severity:a,message:_nullishCoalesce(S(e.message), () => (r)),location:{file:_nullishCoalesce(S(e.file), () => ("<unknown>")),line:Xr(e.line,1),column:Xr(e.column,1)},evidence:o,nextAction:_nullishCoalesce(S(e.nextAction), () => (qo(r,o,e))),findingRef:c,targetKey:l,docsCodePath:Vt(r)}}_chunkA5EIY3HIcjs.a.call(void 0, Gt,"toAdapterDiagnostic");function Zo(e){let t=_nullishCoalesce(e.completeness, () => ("complete")),n=_nullishCoalesce(e.mode, () => ("lexical-compatibility"));if(t==="complete"&&(_nullishCoalesce(_optionalChain([e, 'access', _11 => _11.completenessReasons, 'optionalAccess', _12 => _12.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:_nullishCoalesce(S(h.code), () => ("ANALYSIS_EVIDENCE_INCOMPLETE")),message:_nullishCoalesce(S(h.message), () => (`Analysis ${t}: required evidence is incomplete.`)),...S(h.file)?{file:S(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],a={...S(e.policyHash)?{policyHash:S(e.policyHash)}:{},...S(e.resolverIdentity)?{resolverIdentity:S(e.resolverIdentity)}:{},...S(e.factsHash)?{factsHash:S(e.factsHash)}:{},...S(e.candidateTreeHash)?{candidateTreeHash:S(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!a[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=_nullishCoalesce(e.violations, () => ([])),o=_nullishCoalesce(e.warnings, () => ([])),l=gt(s),c=gt(o),f=[...s.map((h,p)=>Gt(h,"error",l[p])),...o.map((h,p)=>Gt(h,"warning",c[p]))],g={schemaVersion:"1.5",completenessReasons:r,diagnostics:f};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...a};let h={policyHash:a.policyHash,resolverIdentity:a.resolverIdentity,factsHash:a.factsHash,candidateTreeHash:a.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...h}:{...g,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...a}:{...g,mode:n,valid:!1,completeness:t,...a}}_chunkA5EIY3HIcjs.a.call(void 0, Zo,"createAdapterResult");function Zr(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()}}}_chunkA5EIY3HIcjs.a.call(void 0, Zr,"createArkTestHarness");function Jr(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}_chunkA5EIY3HIcjs.a.call(void 0, Jr,"definePort");function Qr(e,t,n,r={}){let a=Array.isArray(n)?{...r,requiredKeys:n}:{..._nullishCoalesce(n, () => ({}))},s=a.requiredKeys;if(s&&s.length>0){let c=s.filter(f=>!ts(t,f));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let o={name:a.name,layer:a.layer,intent:a.intent,port:e,impl:t},l=jt(o);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
2
+ `));return o}_chunkA5EIY3HIcjs.a.call(void 0, Qr,"createAdapter");function es(e,t=[]){let n=t.filter(r=>!ts(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}_chunkA5EIY3HIcjs.a.call(void 0, es,"checkContract");function jt(e){let t=_nullishCoalesce(e.port.allowedAdapters, () => ([]));return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(a=>typeof a=="string"&&a.length>0).some(a=>t.includes(a))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:_nullishCoalesce(e.name, () => (e.intent)),message:`Adapter "${_nullishCoalesce(_nullishCoalesce(e.name, () => (e.intent)), () => ("unknown"))}" is not allowed for port "${e.port.name}".`}]}}_chunkA5EIY3HIcjs.a.call(void 0, jt,"checkAdapterGovernance");function ts(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}_chunkA5EIY3HIcjs.a.call(void 0, ts,"hasMember");var zt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),qt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Yt=Object.freeze(Object.keys(qt).sort()),Bt=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"}),Wt=Object.freeze({process:Object.freeze(["process","node:process"])});function Be(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Bt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),a=Bt[r];if(a)return a;let s=e.indexOf("/",n+1);return s<0?null:_nullishCoalesce(Bt[e.slice(0,s)], () => (null))}_chunkA5EIY3HIcjs.a.call(void 0, Be,"capabilityForModuleSpecifier");function Re(e,t){for(let n of t)if(_optionalChain([Wt, 'access', _13 => _13[n], 'optionalAccess', _14 => _14.includes, 'call', _15 => _15(e)]))return n;return null}_chunkA5EIY3HIcjs.a.call(void 0, Re,"forbiddenGlobalForModuleSpecifier");function mt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),a=qt[r];if(a)return a}return null}_chunkA5EIY3HIcjs.a.call(void 0, mt,"capabilityForAmbientName");function we(e){if(_optionalChain([e, 'optionalAccess', _16 => _16.pure])===!0)return[...zt].sort();let n=(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _17 => _17.capabilities, 'optionalAccess', _18 => _18.deny]), () => ([]))).filter(r=>zt.includes(r));return[...new Set(n)].sort()}_chunkA5EIY3HIcjs.a.call(void 0, we,"effectiveCapabilityDeny");function ze(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let a=r.length;a>=1;a-=1)if(n.has(r.slice(0,a).join(".")))return!0;return!1}_chunkA5EIY3HIcjs.a.call(void 0, ze,"ambientCoveredByForbiddenGlobals");function yt(e){let t=new Set,n=new Set,r=Object.keys(qt);for(let a of _nullishCoalesce(_optionalChain([e, 'optionalAccess', _19 => _19.forbiddenGlobals]), () => ([]))){let s=r.filter(o=>o===a||o.startsWith(`${a}.`));if(s.length===0)n.add(a);else for(let o of s)t.add(`ambient:${o}`);for(let o of _nullishCoalesce(Wt[a], () => ([])))t.add(`import-exact:${o}`)}for(let a of we(e)){if(t.add(`import:${a}`),a==="process")for(let s of Wt.process)t.add(`import-exact:${s}`);for(let s of r)mt(s)===a&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}_chunkA5EIY3HIcjs.a.call(void 0, yt,"loweredLayerCoverage");function Te(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}_chunkA5EIY3HIcjs.a.call(void 0, Te,"literalText");function ss(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}_chunkA5EIY3HIcjs.a.call(void 0, ss,"lineOf");function ns(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let a=r.namedBindings;return!!(a&&e.isNamedImports(a)&&a.elements.length>0&&a.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))}_chunkA5EIY3HIcjs.a.call(void 0, ns,"isTypeOnlyReference");function as(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=a=>a===t.fileName?t:void 0,r.fileExists=a=>a===t.fileName,r.readFile=a=>a===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}_chunkA5EIY3HIcjs.a.call(void 0, as,"singleFileChecker");function Xt(e,t){try{return e.getSymbolAtLocation(t)}catch (e2){return}}_chunkA5EIY3HIcjs.a.call(void 0, Xt,"symbolAt");function Zt(e,t,n,r){let a=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=a?t.getShorthandAssignmentValueSymbol(r.parent):Xt(t,r)}catch (e3){s=void 0}return!!_optionalChain([s, 'optionalAccess', _20 => _20.declarations, 'optionalAccess', _21 => _21.some, 'call', _22 => _22(o=>o.getSourceFile().fileName===n.fileName)])}_chunkA5EIY3HIcjs.a.call(void 0, Zt,"localDeclaration");function Ne(e,t){let n,r=[],a=_chunkA5EIY3HIcjs.a.call(void 0, (o,l,c,f=!1)=>r.push({specifier:c,kind:l,line:ss(t,o),typeOnly:f,unresolved:c===void 0,node:o}),"add"),s=_chunkA5EIY3HIcjs.a.call(void 0, o=>{if(e.isImportDeclaration(o))a(o,"import",Te(e,o.moduleSpecifier),ns(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)a(o,"export",Te(e,o.moduleSpecifier),ns(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))a(o,"require",Te(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let l=o.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Zt(e,_nullishCoalesce(n, () => ((n=as(e,t)))),t,o.expression);(l||f)&&a(o,f?"require":"dynamic-import",Te(e,o.arguments[0]))}e.forEachChild(o,s)},"visit");return s(t),r}_chunkA5EIY3HIcjs.a.call(void 0, Ne,"extractSemanticDependencies");function Jo(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let a=Te(e,r.argumentExpression);if(a===void 0)return;n.unshift(a)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}_chunkA5EIY3HIcjs.a.call(void 0, Jo,"staticAccessPath");function Qo(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}_chunkA5EIY3HIcjs.a.call(void 0, Qo,"runtimeIdentifierReference");function rs(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let a=n.slice(0,r).join(".");if(e.has(a))return a}}_chunkA5EIY3HIcjs.a.call(void 0, rs,"bestForbiddenMatch");function Pe(e,t,n){if(n.length===0)return[];let r=new Set(n),a=as(e,t),s=new Map,o=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let R of p.declarationList.declarations)e.isIdentifier(R.name)&&o.add(R.name.text);let l=_chunkA5EIY3HIcjs.a.call(void 0, p=>{let R=Jo(e,p);if(!R)return;let u=Xt(a,R.root),m=u?s.get(u):void 0;return m?[...m,...R.segments.slice(1)]:Zt(e,a,t,R.root)||o.has(R.root.text)?void 0:R.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let R of p.declarationList.declarations){if(!R.initializer||!e.isIdentifier(R.name))continue;let u=l(R.initializer),m=Xt(a,R.name);!u||!m||s.set(m,u)}let c=[],f=new Set,g=_chunkA5EIY3HIcjs.a.call(void 0, (p,R)=>{let u=ss(t,R),m=`${p}:${R.getStart(t)}`;f.has(m)||(f.add(m),c.push({name:p,line:u,node:R}))},"flag"),h=_chunkA5EIY3HIcjs.a.call(void 0, p=>{let R=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!R){let u=l(p),m=u?rs(r,u):void 0;m&&g(m,p)}else e.isIdentifier(p)&&r.has(p.text)&&Qo(e,p)&&!Zt(e,a,t,p)&&g(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let u=l(p.initializer);if(u)for(let m of p.name.elements){if(!e.isIdentifier(m.name))continue;let v=m.propertyName?_nullishCoalesce(Te(e,m.propertyName), () => (m.propertyName.text)):m.name.text,w=rs(r,[...u,v]);w&&g(w,p.initializer)}}e.forEachChild(p,h)},"visit");return h(t),c}_chunkA5EIY3HIcjs.a.call(void 0, Pe,"collectForbiddenCapabilityUses");function Jt(e,t,n){let r=[];for(let a of _nullishCoalesce(_optionalChain([n, 'optionalAccess', _23 => _23.dependencies]), () => (Ne(e,t)))){if(a.typeOnly||!a.specifier)continue;let s=Be(a.specifier);s&&r.push({capability:s,symbol:a.specifier,line:a.line,source:"import-based"})}for(let a of _nullishCoalesce(_optionalChain([n, 'optionalAccess', _24 => _24.ambientUses]), () => (Pe(e,t,Yt)))){let s=mt(a.name);s&&r.push({capability:s,symbol:a.name,line:a.line,source:"ambient-global"})}return r.sort((a,s)=>a.line-s.line||a.capability.localeCompare(s.capability)||a.symbol.localeCompare(s.symbol))}_chunkA5EIY3HIcjs.a.call(void 0, Jt,"collectCapabilityUses");function z(e,t,n){return{ruleId:e,code:e,message:t,...n}}_chunkA5EIY3HIcjs.a.call(void 0, z,"violation");function ei(e,t){return e?t==="unclassifiable-path"||t==="missing-path"?"Move the file into a slice, or declare its root in the rule's sharedRoots.":t==="no-slice-folders"?"Set sliceFolders on the peerIsolation rule.":t==="shared-imports-slice"?"Move the code the shared root needs into the shared root, or invert the dependency.":"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."}_chunkA5EIY3HIcjs.a.call(void 0, ei,"peerSuggestion");function Le(e,t){return e.slice(0,t).split(`
3
+ `).length}_chunkA5EIY3HIcjs.a.call(void 0, Le,"lineOf");var ti=new Set(["publish","subscribe","defineIntent","registerHandler"]);function ni(e,t){return e.index+e[0].indexOf(t)}_chunkA5EIY3HIcjs.a.call(void 0, ni,"captureIndex");function ri(e){let t=[],n=new Set,r=_chunkA5EIY3HIcjs.a.call(void 0, (l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),a=_chunkA5EIY3HIcjs.a.call(void 0, l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let f=c[1];f&&r(f,ni(c,f))}},"pushFrom");a(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),a(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,o;for(;(o=s.exec(e))!==null;){let l=_nullishCoalesce(o[1], () => ("")),c=o.index+o[0].indexOf(l),f=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,g;for(;(g=f.exec(l))!==null;){let h=g[1];h&&r(h,c+g.index+g[0].indexOf(h))}}return a(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),a(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}_chunkA5EIY3HIcjs.a.call(void 0, ri,"extractQuotedStrings");function si(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 a;for(;(a=r.re.exec(e))!==null;){let s=a.index+a[0].indexOf(a[1]),o=a[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:a[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,a)=>r.index-a.index)}_chunkA5EIY3HIcjs.a.call(void 0, si,"extractModuleSpecifiers");function ai(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}_chunkA5EIY3HIcjs.a.call(void 0, ai,"isSyntaxWrapper");function Qt(e,t){let n=t;for(;_optionalChain([n, 'optionalAccess', _25 => _25.parent])&&ai(e,n.parent);)n=n.parent;return n}_chunkA5EIY3HIcjs.a.call(void 0, Qt,"unwrapWrappers");function en(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}_chunkA5EIY3HIcjs.a.call(void 0, en,"callCalleeName");function oi(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Qt(e,n),a=r.parent;if(!a)return!1;if(e.isCallExpression(a)&&en(e,a)==="publish"){let s=a.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(a)&&tn(e,a.name)==="metadata"){let s=a.parent;if(!s)return!1;let l=Qt(e,s).parent;return!!(l&&e.isCallExpression(l)&&en(e,l)==="publish")}return!1}_chunkA5EIY3HIcjs.a.call(void 0, oi,"isPublishMetadataSource");function os(e,t){let n=Qt(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let a=en(e,r);if(a&&ti.has(a)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return os(e,r);if(e.isPropertyAssignment(r)){let a=tn(e,r.name);if(a==="intent"||a==="onEvent"||a==="reactsTo"||a==="source"&&oi(e,r))return!0}return!1}_chunkA5EIY3HIcjs.a.call(void 0, os,"isDeclaredIntentSite");function ii(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],a=_chunkA5EIY3HIcjs.a.call(void 0, s=>{e.isStringLiteralLike(s)&&os(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,a)},"visit");return a(n),r}_chunkA5EIY3HIcjs.a.call(void 0, ii,"extractQuotedStringsAst");function li(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))}_chunkA5EIY3HIcjs.a.call(void 0, li,"hasInfrastructureToken");function ci(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}_chunkA5EIY3HIcjs.a.call(void 0, ci,"isKnownInfrastructurePackage");function di(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}_chunkA5EIY3HIcjs.a.call(void 0, di,"layerHasInfrastructureRole");function qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}_chunkA5EIY3HIcjs.a.call(void 0, qe,"tsStringLiteralText");function tn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}_chunkA5EIY3HIcjs.a.call(void 0, tn,"tsPropertyName");function is(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:tn(e,r.name)===n)}_chunkA5EIY3HIcjs.a.call(void 0, is,"tsObjectProperty");function Ye(e,t,n){return is(e,t,n)!==void 0}_chunkA5EIY3HIcjs.a.call(void 0, Ye,"tsObjectHasProperty");function We(e,t,n){let r=is(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}_chunkA5EIY3HIcjs.a.call(void 0, We,"tsObjectPropertyValue");function ui(e,t){let n=We(e,t,"metadata");return Ye(e,n,"source")}_chunkA5EIY3HIcjs.a.call(void 0, ui,"tsObjectHasMetadataSource");function ls(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?ls(e,t.name):!1:!1}_chunkA5EIY3HIcjs.a.call(void 0, ls,"tsLooksLikeIntentCreatorExpression");function pi(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}_chunkA5EIY3HIcjs.a.call(void 0, pi,"tsIsPublishCall");function fi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=qe(e,n);return r!==void 0&&_chunkRNQHRDCQcjs.fa.call(void 0, r)||Ye(e,n,"intent")||ls(e,n)}_chunkA5EIY3HIcjs.a.call(void 0, fi,"tsIsArkPublishCandidate");function gi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,a]=t.arguments;return ui(e,n)||Ye(e,r,"source")||Ye(e,a,"source")}_chunkA5EIY3HIcjs.a.call(void 0, gi,"tsPublishHasSource");function mi(e,t){if(!e.isCallExpression(t))return;let[n,r,a]=t.arguments,s=We(e,n,"metadata");return _nullishCoalesce(_nullishCoalesce(qe(e,We(e,s,"source")), () => (qe(e,We(e,r,"source")))), () => (qe(e,We(e,a,"source"))))}_chunkA5EIY3HIcjs.a.call(void 0, mi,"tsPublishSourceLiteral");function yi(e,t,n,r){let a=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,o=_optionalChain([s, 'optionalAccess', _26 => _26.filePath]),l=_optionalChain([s, 'optionalAccess', _27 => _27.layer]),c=[],f=_chunkA5EIY3HIcjs.a.call(void 0, h=>a.getLineAndCharacterOfPosition(h.getStart(a)).line+1,"lineForNode"),g=_chunkA5EIY3HIcjs.a.call(void 0, h=>{if(pi(e,h)){let p=h.arguments[0],R=qe(e,p);for(let m of _chunkRNQHRDCQcjs.ga.call(void 0, {publishCall:!0,rawIntentName:R,objectHasIntent:Ye(e,p,"intent"),arkPublishCandidate:fi(e,h),hasSource:gi(e,h)}))c.push(z(m.ruleId,m.message,{line:f(h),filePath:o}));let u=mi(e,h);if(r&&l&&u&&_chunkRNQHRDCQcjs.fa.call(void 0, u)){let m=r.resolveLayer(u);m&&m!==l&&c.push(z("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${m}, but the target file is classified as ${l}.`,{line:f(h),filePath:o,target:u,fromLayer:l,toLayer:m}))}}e.forEachChild(h,g)},"visit");return g(a),c}_chunkA5EIY3HIcjs.a.call(void 0, yi,"analyzePublishAst");function cs(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(_nullishCoalesce(e.infrastructureLayers, () => ([]))),a=_nullishCoalesce(e.enforceIntentAllowlist, () => (t.size>0));return{validate(s,o){let l=[],c=o,f=_optionalChain([c, 'optionalAccess', _28 => _28.filePath]),g=_optionalChain([c, 'optionalAccess', _29 => _29.layer]),h=e.typescript,p=h?h.createSourceFile(_nullishCoalesce(f, () => ("generated.ts")),s,h.ScriptTarget.Latest,!0):void 0,R=p?Ne(e.typescript,p):void 0,u=R?R.filter(A=>A.specifier!==void 0).map(A=>({value:A.specifier,index:A.node.getStart(p),kind:A.kind,typeOnly:A.typeOnly})):si(s),m=e.typescript?ii(e.typescript,s):ri(s);if(e.typescript&&!_optionalChain([e, 'access', _30 => _30.allowNonLiteralDynamicImport, 'optionalCall', _31 => _31(f)]))for(let A of _nullishCoalesce(_optionalChain([R, 'optionalAccess', _32 => _32.filter, 'call', _33 => _33(({unresolved:b})=>b)]), () => ([]))){let b=A.kind==="require";l.push(z(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:f}))}let v=g!==void 0&&(r.has(g)||di(g)),w=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let A of n)if(A instanceof RegExp){A.lastIndex=0;let b=A.exec(s);A.lastIndex=0,b&&l.push(z("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:b.index===void 0?void 0:Le(s,b.index),filePath:f,suggestion:"Remove infrastructure imports from domain/application layers."+w}))}else s.includes(A)&&l.push(z("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:Le(s,s.indexOf(A)),filePath:f}));for(let A of u){let b=_nullishCoalesce(_optionalChain([e, 'access', _34 => _34.resolveImportTarget, 'optionalCall', _35 => _35(A.value,f)]), () => ((e.resolveImportLayer?{layer:e.resolveImportLayer(A.value,f)}:void 0))),O=typeof f=="string"?_nullishCoalesce(_optionalChain([e, 'access', _36 => _36.resolveImportTarget, 'optionalCall', _37 => _37(f)]), () => ((e.resolveImportLayer?{layer:g,relPath:void 0}:void 0))):void 0,G=_optionalChain([b, 'optionalAccess', _38 => _38.layer]);if(G&&g){let K=_chunkRNQHRDCQcjs.O.call(void 0, _optionalChain([e, 'access', _39 => _39.architectureProfile, 'optionalAccess', _40 => _40.rules]),g,G,{fromPath:_optionalChain([O, 'optionalAccess', _41 => _41.relPath]),toPath:_optionalChain([b, 'optionalAccess', _42 => _42.relPath]),layers:e.architectureLayers});if(K){let j=K.rule;if(A.typeOnly&&!j.peerIsolation)continue;let I=!!j.peerIsolation,D=K.sliceVerdict,X=_chunkRNQHRDCQcjs.L.call(void 0, D),ne=_nullishCoalesce(_chunkRNQHRDCQcjs.J.call(void 0, j,D), () => ((I?`Layer "${g}" must not import across slices into "${G}".`:`Layer "${g}" must not import "${G}".`))),ue=I&&_optionalChain([D, 'optionalAccess', _43 => _43.explanation])&&(X.reasonId||K.peerIsolationReason!=="cross-slice")?D.explanation:void 0;l.push(z("LAYER_IMPORT_VIOLATION",ue?`${ne} ${ue}`:ne,{line:Le(s,A.index),source:A.value,target:A.value,filePath:f,fromLayer:g,toLayer:G,...I?{peerIsolation:!0}:{},...X.reasonId?{reasonId:X.reasonId}:{},...X.universeFrom?{universeFrom:X.universeFrom}:{},...X.universeTo?{universeTo:X.universeTo}:{},...X.failsStrict===!1?{failsStrict:!1}:{},suggestion:ei(I,K.peerIsolationReason),details:{importKind:A.kind,peerIsolation:I,...A.typeOnly?{typeOnly:!0}:{},...X.reasonId?{reasonId:X.reasonId}:{}}}));continue}continue}v||A.typeOnly||!li(A.value)&&!ci(A.value)||l.push(z("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:Le(s,A.index),source:A.value,target:A.value,filePath:f,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+w,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let b=A.check({source:s,context:o});if(b!==!0)if(Array.isArray(b))for(let O of b)l.push(z("POLICY_VIOLATION",O.message,{filePath:f,suggestion:`Fix violation of policy "${A.name}".`}));else b===!1?l.push(z("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(z("POLICY_VIOLATION",b.message))}if(a&&t.size>0)for(let A of m)_chunkRNQHRDCQcjs.fa.call(void 0, A.value)&&!t.has(A.value)&&l.push(z("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:Le(s,A.index),filePath:f,target:A.value,suggestion:`Register intent "${A.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let A of m){if(!_chunkRNQHRDCQcjs.fa.call(void 0, A.value))continue;let b=e.architectureProfile.resolveLayer(A.value);if(!b)continue;let O=_chunkRNQHRDCQcjs.O.call(void 0, e.architectureProfile.rules,g,b,{fromPath:typeof f=="string"?f:void 0,layers:e.architectureLayers});if(O){let G=O.sliceVerdict,K=`Layer "${g}" must not reference "${b}" through "${A.value}".`,j=G?_chunkRNQHRDCQcjs.K.call(void 0, {surface:"intent",verdict:G,fromLayer:g,toLayer:b,fromPath:typeof f=="string"?f:void 0,ruleMessage:O.rule.message,childMessage:_optionalChain([O, 'access', _44 => _44.rule, 'access', _45 => _45.childSlices, 'optionalAccess', _46 => _46.message]),defaultMessage:K}):_nullishCoalesce(O.rule.message, () => (K)),I=_chunkRNQHRDCQcjs.L.call(void 0, G);l.push(z("LAYER_REFERENCE_VIOLATION",j,{line:Le(s,A.index),filePath:f,target:A.value,fromLayer:g,toLayer:b,...I.reasonId?{reasonId:I.reasonId}:{},...I.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O.rule,peerIsolationReason:O.peerIsolationReason,...I.reasonId?{reasonId:I.reasonId}:{}}}))}}if(e.extensions)for(let A of e.extensions)try{let b=A.analyze(s,o);l.push(...b)}catch(b){l.push(z("EXTENSION_ERROR",`Extension "${A.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&p&&g&&_optionalChain([e, 'access', _47 => _47.forbiddenGlobals, 'optionalAccess', _48 => _48[g], 'optionalAccess', _49 => _49.length]))try{let A=e.forbiddenGlobals[g];l.push(...Pe(e.typescript,p,A).map(b=>z("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:f,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of _nullishCoalesce(R, () => ([]))){if(b.typeOnly||!b.specifier)continue;let O=Re(b.specifier,A);O&&l.push(z("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${O}".`,{line:b.line,filePath:f,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:O},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(A){l.push(z("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript&&p&&g&&_optionalChain([e, 'access', _50 => _50.capabilityWalls, 'optionalAccess', _51 => _51[g], 'optionalAccess', _52 => _52.length]))try{let A=new Set(e.capabilityWalls[g]),b=_nullishCoalesce(_optionalChain([e, 'access', _53 => _53.forbiddenGlobals, 'optionalAccess', _54 => _54[g]]), () => ([]));for(let O of Jt(e.typescript,p))A.has(O.capability)&&(O.source==="ambient-global"&&ze(O.symbol,b)||O.source==="import-based"&&Re(O.symbol,b)||l.push(z("CAPABILITY_VIOLATION",O.source==="import-based"?`${g} denies the ${O.capability} capability; found import of "${O.symbol}".`:`${g} denies the ${O.capability} capability; found ambient "${O.symbol}".`,{line:O.line,filePath:f,target:O.symbol,capability:O.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(A){l.push(z("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript)try{l.push(...yi(e.typescript,s,o,e.architectureProfile))}catch(A){l.push(z("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.some(A=>A.failsStrict!==!1),violations:l}}}}_chunkA5EIY3HIcjs.a.call(void 0, cs,"createAICodeGate");function Z(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")}`}_chunkA5EIY3HIcjs.a.call(void 0, Z,"deterministicHash");function W(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(W).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${W(t[n])}`).join(",")}}`}_chunkA5EIY3HIcjs.a.call(void 0, W,"stableSerialize");function ge(e,t){let n=t.hash;for(let r=0;r<e.length;r+=1)n^=e.charCodeAt(r),n=Math.imul(n,16777619);t.hash=n}_chunkA5EIY3HIcjs.a.call(void 0, ge,"feedText");function nn(e,t){if(Array.isArray(e)){ge("[",t);for(let a=0;a<e.length;a+=1){if(a>0&&ge(",",t),!(a in e))continue;let s=e[a];if(s!==null&&typeof s=="object")nn(s,t);else{let o=JSON.stringify(s);o!==void 0&&ge(o,t)}}ge("]",t);return}let n=e,r=Object.keys(n).sort();ge("{",t);for(let a=0;a<r.length;a+=1){a>0&&ge(",",t);let s=r[a];ge(`${JSON.stringify(s)}:`,t);let o=n[s];o!==null&&typeof o=="object"?nn(o,t):ge(`${JSON.stringify(o)}`,t)}ge("}",t)}_chunkA5EIY3HIcjs.a.call(void 0, nn,"feedStable");function rn(e){if(e===null||typeof e!="object")return Z(W(e));let t={hash:2166136261};return nn(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}_chunkA5EIY3HIcjs.a.call(void 0, rn,"stableHash");var Se="1.2";var ds=["network","filesystem","clock","randomness","environment","process","persistence"];function V(e){let t=e.map((n,r)=>({key:W(n),index:r}));return t.sort((n,r)=>n.key<r.key?-1:n.key>r.key?1:n.index-r.index),t.map(({index:n})=>e[n])}_chunkA5EIY3HIcjs.a.call(void 0, V,"sortCanonical");function J(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}_chunkA5EIY3HIcjs.a.call(void 0, J,"sortedUnique");function Xe(e){let t={schemaVersion:"1.2",include:J(_nullishCoalesce(e.include, () => ([]))),exclude:J(_nullishCoalesce(e.exclude, () => ([]))),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:J(_nullishCoalesce(e.dynamicImportAllowlist, () => ([]))),layers:V(e.layers.map(n=>({name:n.name,patterns:J(_nullishCoalesce(n.patterns, () => ([]))),exclude:J(_nullishCoalesce(n.exclude, () => ([]))),forbiddenGlobals:J(_nullishCoalesce(n.forbiddenGlobals, () => ([]))),intentPrefixes:J(_nullishCoalesce(n.intentPrefixes, () => ([]))),capabilityDeny:J(_nullishCoalesce(_optionalChain([n, 'access', _55 => _55.capabilities, 'optionalAccess', _56 => _56.deny]), () => ([]))),pure:n.pure===!0}))),safety:{maxTsSuppressions:_nullishCoalesce(_optionalChain([e, 'access', _57 => _57.safety, 'optionalAccess', _58 => _58.maxTsSuppressions]), () => (0)),maxAnyCasts:_nullishCoalesce(_optionalChain([e, 'access', _59 => _59.safety, 'optionalAccess', _60 => _60.maxAnyCasts]), () => (0)),allowInMemory:_optionalChain([e, 'access', _61 => _61.safety, 'optionalAccess', _62 => _62.allowInMemory])===!0,allowDisabledPeerIsolation:_optionalChain([e, 'access', _63 => _63.safety, 'optionalAccess', _64 => _64.allowDisabledPeerIsolation])===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:J(e.arkRun.compositionRoots),managedLayers:J(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return Z(W(t))}_chunkA5EIY3HIcjs.a.call(void 0, Xe,"resolvedFactsEvidenceRequirementsHash");function hi(e){let t=V(e.completenessReasons.map(I=>({code:I.code,message:I.message,...I.file?{file:I.file}:{}}))),n=e.files.map(I=>({...I,typeOnlyExportNames:J(I.typeOnlyExportNames)})).sort((I,D)=>I.path<D.path?-1:I.path>D.path?1:0),r=V(e.dependencies.map(I=>({...I,...I.namedBindings?{namedBindings:J(I.namedBindings)}:{}}))),a=V(e.capabilityUses.map(I=>({...I}))),s=V(e.ambientUses.map(I=>({...I}))),o=V(e.publishCalls.map(I=>({...I}))),l=V(e.intentReferences.map(I=>({...I}))),c=V(e.safetyUses.map(I=>({...I}))),f=V((_nullishCoalesce(e.classShapes, () => ([]))).map(I=>({...I,mutatingMethods:[..._nullishCoalesce(I.mutatingMethods, () => ([]))].map(D=>({...D}))}))),g=V((_nullishCoalesce(e.arkRunKernelCalls, () => ([]))).map(I=>({...I}))),h=V((_nullishCoalesce(e.arkRunManagedNews, () => ([]))).map(I=>({...I}))),p=V((_nullishCoalesce(e.arkRunCompositionRootHits, () => ([]))).map(I=>({...I}))),R=V((_nullishCoalesce(e.arkRunDeclarations, () => ([]))).map(I=>({...I,uses:J(I.uses),reactsTo:J(I.reactsTo),raises:J(I.raises),sends:J(I.sends)}))),u=V((_nullishCoalesce(e.arkOrderPlaneCalls, () => ([]))).map(I=>({...I}))),m=V((_nullishCoalesce(e.arkOrderGenericUpdates, () => ([]))).map(I=>({...I}))),v=V((_nullishCoalesce(e.arkOrderRootHits, () => ([]))).map(I=>({...I}))),w=V((_nullishCoalesce(e.arkOrderXiFieldWrites, () => ([]))).map(I=>({...I}))),A=V((_nullishCoalesce(e.arkOrderIngestWritesXi, () => ([]))).map(I=>({...I}))),b=V((_nullishCoalesce(e.arkOrderReleaseKeyCounts, () => ([]))).map(I=>({...I}))),O=V((_nullishCoalesce(e.arkOrderXiTtlKeys, () => ([]))).map(I=>({...I}))),G=V((_nullishCoalesce(e.arkOrderBudgetLeaks, () => ([]))).map(I=>({...I}))),K=e.files.map(({path:I,contentHash:D})=>({path:I,contentHash:D})).sort((I,D)=>I.path<D.path?-1:I.path>D.path?1:0),j=rn(K);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:a,ambientUses:s,publishCalls:o,intentReferences:l,safetyUses:c,classShapes:f,arkRunKernelCalls:g,arkRunManagedNews:h,arkRunCompositionRootHits:p,arkRunDeclarations:R,arkOrderPlaneCalls:u,arkOrderGenericUpdates:m,arkOrderRootHits:v,arkOrderXiFieldWrites:w,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:b,arkOrderXiTtlKeys:O,arkOrderBudgetLeaks:G}}_chunkA5EIY3HIcjs.a.call(void 0, hi,"canonicalResolvedFactsInput");function us(e){let t=hi(e);return{...t,factsHash:rn(t)}}_chunkA5EIY3HIcjs.a.call(void 0, us,"createCanonicalResolvedCandidateFacts");function an(e){return us(ps(P(e,"$"),!1))}_chunkA5EIY3HIcjs.a.call(void 0, an,"createResolvedCandidateFacts");function P(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}_chunkA5EIY3HIcjs.a.call(void 0, P,"asRecord");function L(e,t,n){let r=Object.keys(e).find(a=>!t.includes(a));if(r)throw new Error(`${n}.${r} is not part of schema ${"1.2"}.`)}_chunkA5EIY3HIcjs.a.call(void 0, L,"assertOnlyKeys");function N(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}_chunkA5EIY3HIcjs.a.call(void 0, N,"requiredText");function me(e,t,n){if(e[t]!==void 0)return N(e,t,n)}_chunkA5EIY3HIcjs.a.call(void 0, me,"optionalText");function F(e,t,n){let r=N(e,t,n),a=r.replace(/\\/g,"/");if(!a||a.startsWith("/")||/^[A-Za-z]:\//.test(a)||/[\u0000-\u001f\u007f]/.test(a))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of a.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 o=s.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}_chunkA5EIY3HIcjs.a.call(void 0, F,"requiredProjectPath");function B(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}_chunkA5EIY3HIcjs.a.call(void 0, B,"requiredBoolean");function sn(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)}_chunkA5EIY3HIcjs.a.call(void 0, sn,"requiredInteger");function Y(e,t,n){let r=sn(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}_chunkA5EIY3HIcjs.a.call(void 0, Y,"requiredPositiveInteger");function $(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}_chunkA5EIY3HIcjs.a.call(void 0, $,"requiredArray");function ye(e,t,n,r){let a=e[t];if(typeof a!="string"||!n.includes(a))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return a}_chunkA5EIY3HIcjs.a.call(void 0, ye,"enumValue");function De(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]}_chunkA5EIY3HIcjs.a.call(void 0, De,"parseStringArray");function Ri(e,t,n){let r=new Set;for(let a of e){let s=t(a);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}_chunkA5EIY3HIcjs.a.call(void 0, Ri,"assertUnique");function ps(e,t){L(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","arkOrderXiTtlKeys","arkOrderBudgetLeaks",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ye(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ye(e,"completeness",["complete","partial","unavailable"],"$"),a=$(e,"completenessReasons","$").map((E,_)=>{let y=`$.completenessReasons[${_}]`,d=P(E,y);L(d,["code","message","file"],y);let T=d.file===void 0?void 0:F(d,"file",y);return{code:N(d,"code",y),message:N(d,"message",y),...T?{file:T}:{}}});if(r==="complete"&&a.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&a.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=$(e,"files","$").map((E,_)=>{let y=`$.files[${_}]`,d=P(E,y);return L(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:F(d,"path",y),contentHash:N(d,"contentHash",y),parseStatus:ye(d,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:sn(d,"parseDiagnosticCount",y),exportsOnlyTypes:B(d,"exportsOnlyTypes",y),typeOnlyExportNames:De(d.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:B(d,"hasTopLevelSideEffects",y)}}),o=$(e,"dependencies","$").map((E,_)=>{let y=`$.dependencies[${_}]`,d=P(E,y);L(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let T=me(d,"specifier",y),U=me(d,"target",y),re=ye(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(re==="resolved-project"&&!U)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(re!=="resolved-project"&&U)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(re!=="dynamic"&&!T)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:F(d,"from",y),...T?{specifier:T}:{},kind:ye(d,"kind",["import","export","dynamic-import","require"],y),typeOnly:B(d,"typeOnly",y),line:Y(d,"line",y),resolution:re,...U?{target:F(d,"target",y)}:{},...d.namedBindings!==void 0?{namedBindings:De(d.namedBindings,`${y}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:B(d,"targetTypeOnlyExports",y)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:B(d,"sourcePureTypeModule",y)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:B(d,"namedBindingsTypeOnly",y)}:{},...d.portProofEligible!==void 0?{portProofEligible:B(d,"portProofEligible",y)}:{}}}),l=$(e,"capabilityUses","$").map((E,_)=>{let y=`$.capabilityUses[${_}]`,d=P(E,y);return L(d,["file","line","symbol","capability","source"],y),{file:F(d,"file",y),line:Y(d,"line",y),symbol:N(d,"symbol",y),capability:ye(d,"capability",ds,y),source:ye(d,"source",["ambient-global","import-based"],y)}}),c=$(e,"ambientUses","$").map((E,_)=>{let y=`$.ambientUses[${_}]`,d=P(E,y);return L(d,["file","line","symbol"],y),{file:F(d,"file",y),line:Y(d,"line",y),symbol:N(d,"symbol",y)}}),f=$(e,"publishCalls","$").map((E,_)=>{let y=`$.publishCalls[${_}]`,d=P(E,y);L(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let T=me(d,"rawIntentName",y),U=me(d,"sourceIntent",y);return{file:F(d,"file",y),line:Y(d,"line",y),...T?{rawIntentName:T}:{},objectHasIntent:B(d,"objectHasIntent",y),arkPublishCandidate:B(d,"arkPublishCandidate",y),hasSource:B(d,"hasSource",y),...U?{sourceIntent:U}:{}}}),g=$(e,"intentReferences","$").map((E,_)=>{let y=`$.intentReferences[${_}]`,d=P(E,y);return L(d,["file","line","intent"],y),{file:F(d,"file",y),line:Y(d,"line",y),intent:N(d,"intent",y)}}),h=$(e,"safetyUses","$").map((E,_)=>{let y=`$.safetyUses[${_}]`,d=P(E,y);L(d,["file","line","kind","symbol"],y);let T=me(d,"symbol",y),U=ye(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(U==="in-memory-store"&&!T)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(U!=="in-memory-store"&&T)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:F(d,"file",y),line:Y(d,"line",y),kind:U,...T?{symbol:T}:{}}});Ri(s,E=>E.path,"$.files");let p=new Set(s.map(E=>E.path));for(let E of s){if(E.parseStatus==="parsed"&&E.parseDiagnosticCount!==0)throw new Error(`$.files[${E.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(E.parseStatus==="invalid"&&E.parseDiagnosticCount===0)throw new Error(`$.files[${E.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(E=>E.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let E of o)if(!p.has(E.from))throw new Error(`$.dependencies references missing source file ${E.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:$(e,"arkRunKernelCalls","$")).map((E,_)=>{let y=`$.arkRunKernelCalls[${_}]`,d=P(E,y);L(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let T=me(d,"receiver",y),U=me(d,"nameLiteral",y);return{file:F(d,"file",y),line:Y(d,"line",y),kind:ye(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:N(d,"callee",y),viaImport:B(d,"viaImport",y),...T?{receiver:T}:{},...U?{nameLiteral:U}:{}}}),v=(e.arkRunManagedNews===void 0?[]:$(e,"arkRunManagedNews","$")).map((E,_)=>{let y=`$.arkRunManagedNews[${_}]`,d=P(E,y);L(d,["file","line","typeName","importedFrom"],y);let T=me(d,"importedFrom",y);return{file:F(d,"file",y),line:Y(d,"line",y),typeName:N(d,"typeName",y),...T?{importedFrom:T}:{}}}),A=(e.arkRunCompositionRootHits===void 0?[]:$(e,"arkRunCompositionRootHits","$")).map((E,_)=>{let y=`$.arkRunCompositionRootHits[${_}]`,d=P(E,y);return L(d,["file","matchedRoot","hasKernelFactory"],y),{file:F(d,"file",y),matchedRoot:N(d,"matchedRoot",y),hasKernelFactory:B(d,"hasKernelFactory",y)}}),b=e.arkRunDeclarations===void 0?[]:$(e,"arkRunDeclarations","$"),G=(e.arkOrderPlaneCalls===void 0?[]:$(e,"arkOrderPlaneCalls","$")).map((E,_)=>{let y=`$.arkOrderPlaneCalls[${_}]`,d=P(E,y);return L(d,["file","line","callee"],y),{file:F(d,"file",y),line:Y(d,"line",y),callee:N(d,"callee",y)}}),j=(e.arkOrderGenericUpdates===void 0?[]:$(e,"arkOrderGenericUpdates","$")).map((E,_)=>{let y=`$.arkOrderGenericUpdates[${_}]`,d=P(E,y);return L(d,["file","line","method"],y),{file:F(d,"file",y),line:Y(d,"line",y),method:N(d,"method",y)}}),D=(e.arkOrderRootHits===void 0?[]:$(e,"arkOrderRootHits","$")).map((E,_)=>{let y=`$.arkOrderRootHits[${_}]`,d=P(E,y);return L(d,["file","matchedRoot","hasPlaneFactory"],y),{file:F(d,"file",y),matchedRoot:N(d,"matchedRoot",y),hasPlaneFactory:B(d,"hasPlaneFactory",y)}}),ne=(e.arkOrderXiFieldWrites===void 0?[]:$(e,"arkOrderXiFieldWrites","$")).map((E,_)=>{let y=`$.arkOrderXiFieldWrites[${_}]`,d=P(E,y);return L(d,["file","line","key"],y),{file:F(d,"file",y),line:Y(d,"line",y),key:N(d,"key",y)}}),ae=(e.arkOrderIngestWritesXi===void 0?[]:$(e,"arkOrderIngestWritesXi","$")).map((E,_)=>{let y=`$.arkOrderIngestWritesXi[${_}]`,d=P(E,y);return L(d,["file","line"],y),{file:F(d,"file",y),line:Y(d,"line",y)}}),pe=(e.arkOrderReleaseKeyCounts===void 0?[]:$(e,"arkOrderReleaseKeyCounts","$")).map((E,_)=>{let y=`$.arkOrderReleaseKeyCounts[${_}]`,d=P(E,y);return L(d,["file","line","keyCount"],y),{file:F(d,"file",y),line:Y(d,"line",y),keyCount:Y(d,"keyCount",y)}}),st=(e.arkOrderXiTtlKeys===void 0?[]:$(e,"arkOrderXiTtlKeys","$")).map((E,_)=>{let y=`$.arkOrderXiTtlKeys[${_}]`,d=P(E,y);return L(d,["file","line","key"],y),{file:F(d,"file",y),line:Y(d,"line",y),key:N(d,"key",y)}}),Nt=(e.arkOrderBudgetLeaks===void 0?[]:$(e,"arkOrderBudgetLeaks","$")).map((E,_)=>{let y=`$.arkOrderBudgetLeaks[${_}]`,d=P(E,y);return L(d,["file","line","kind"],y),{file:F(d,"file",y),line:Y(d,"line",y),kind:N(d,"kind",y)}}),Ve=b.map((E,_)=>{let y=`$.arkRunDeclarations[${_}]`,d=P(E,y);return L(d,["file","line","uses","reactsTo","raises","sends"],y),{file:F(d,"file",y),line:Y(d,"line",y),uses:De(d.uses,`${y}.uses`),reactsTo:De(d.reactsTo,`${y}.reactsTo`),raises:De(d.raises,`${y}.raises`),sends:De(d.sends,`${y}.sends`)}});for(let[E,_]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",f],["$.intentReferences",g],["$.safetyUses",h],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",Ve],["$.arkOrderPlaneCalls",G],["$.arkOrderGenericUpdates",j],["$.arkOrderRootHits",D],["$.arkOrderXiFieldWrites",ne],["$.arkOrderIngestWritesXi",ae],["$.arkOrderReleaseKeyCounts",pe],["$.arkOrderXiTtlKeys",st],["$.arkOrderBudgetLeaks",Nt]])for(let y of _)if(!p.has(y.file))throw new Error(`${E} references missing file ${y.file}.`);let Ie=me(e,"projectPackageName","$"),Pt=(e.classShapes===void 0?[]:$(e,"classShapes","$")).map((E,_)=>{let y=`$.classShapes[${_}]`,d=P(E,y);L(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],y);let T=$(d,"mutatingMethods",y).map((U,re)=>{let ot=`${y}.mutatingMethods[${re}]`,Lt=P(U,ot);return L(Lt,["name","referencesGuardOrPublish"],ot),{name:N(Lt,"name",ot),referencesGuardOrPublish:B(Lt,"referencesGuardOrPublish",ot)}});return{file:F(d,"file",y),className:N(d,"className",y),exported:B(d,"exported",y),hasPublicMutableFields:B(d,"hasPublicMutableFields",y),hasPublicSetters:B(d,"hasPublicSetters",y),hasPublicConstructor:B(d,"hasPublicConstructor",y),hasStaticFactory:B(d,"hasStaticFactory",y),mutatingMethods:T,...d.dataOnly===void 0?{}:{dataOnly:B(d,"dataOnly",y)},...d.truncatedUntil===void 0?{}:{truncatedUntil:sn(d,"truncatedUntil",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:a,resolverIdentity:N(e,"resolverIdentity","$"),compilerIdentity:N(e,"compilerIdentity","$"),compilerOptionsHash:N(e,"compilerOptionsHash","$"),tsconfigHash:N(e,"tsconfigHash","$"),evidenceRequirementsHash:N(e,"evidenceRequirementsHash","$"),...Ie?{projectPackageName:Ie}:{},files:s,dependencies:o,capabilityUses:l,ambientUses:c,publishCalls:f,intentReferences:g,safetyUses:h,classShapes:Pt,arkRunKernelCalls:u,arkRunManagedNews:v,arkRunCompositionRootHits:A,arkRunDeclarations:Ve,arkOrderPlaneCalls:G,arkOrderGenericUpdates:j,arkOrderRootHits:D,arkOrderXiFieldWrites:ne,arkOrderIngestWritesXi:ae,arkOrderReleaseKeyCounts:pe,arkOrderXiTtlKeys:st,arkOrderBudgetLeaks:Nt}}_chunkA5EIY3HIcjs.a.call(void 0, ps,"parseResolvedFactsInput");function Ae(e){let t=P(e,"$"),n=N(t,"factsHash","$"),r=N(t,"candidateTreeHash","$"),a=us(ps(t,!0));if(a.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${a.factsHash}).`);if(r!==a.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${a.candidateTreeHash}).`);return a}_chunkA5EIY3HIcjs.a.call(void 0, Ae,"loadResolvedCandidateFacts");var Ai=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},Q={type:"integer",minimum:1},M={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},on= exports.RESOLVED_CANDIDATE_FACTS_SCHEMA ={$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:M}}},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:M,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:M,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Q,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:M,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:M,line:Q,symbol:x,capability:{enum:Ai},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:M,line:Q,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:M,line:Q,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:M,line:Q,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:M,line:Q,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:M,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},truncatedUntil:{type:"integer",minimum:0},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:M,line:Q,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:M,line:Q,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:M,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:M,line:Q,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:M,line:Q,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:M,line:Q,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:M,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:M,line:Q,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:M,line:Q}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:M,line:Q,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:M,line:Q,key:x}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:M,line:Q,kind:x}}},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 ln="1.0";function ee(e){return`${e.from}->${e.to}`}_chunkA5EIY3HIcjs.a.call(void 0, ee,"dependencyKey");function Ze(e,t,n,r="dependency"){return{id:`${e}:${r}:${ee(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ee(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ee(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ee(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ee(t)} from the candidate, then preflight again.`}:{}}}_chunkA5EIY3HIcjs.a.call(void 0, Ze,"dependencyFinding");function Fe(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])),a=new Map(e.changeMap.map.dependencies.map(p=>[ee(p),p])),s=new Map(e.baseDependencies.map(p=>[ee(p),p])),o=new Map(e.candidateDependencies.map(p=>[ee(p),p]));for(let p of[...n.values()].sort((R,u)=>R.path.localeCompare(u.path))){let R=r.get(p.path);R?R.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:R.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${R.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:R.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((R,u)=>R.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[...a.values()].sort((R,u)=>ee(R).localeCompare(ee(u)))){if(o.has(ee(p))){t.push(Ze("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let R={from:p.to,to:p.from};o.has(ee(R))?(l.add(ee(R)),t.push(Ze("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ze("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,R]of[...o].sort(([u],[m])=>u.localeCompare(m)))s.has(p)||a.has(p)||l.has(p)||!c.has(R.from)&&!c.has(R.to)||t.push({...Ze("unplanned",R,`${R.from} -> ${R.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,R]of[...s].sort(([u],[m])=>u.localeCompare(m)))o.has(p)||f.has(R.from)||f.has(R.to)||!c.has(R.from)&&!c.has(R.to)||t.push({...Ze("unplanned",R,`${R.from} -> ${R.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((p,R)=>g[p.classification]-g[R.classification]||(p.subject===R.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(R.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}}_chunkA5EIY3HIcjs.a.call(void 0, Fe,"analyzeArchitectureConvergence");var fs="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",ki=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var gs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Hd={$schema:"https://json-schema.org/draft/2020-12/schema",$id:fs,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:fs},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...ki]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:gs,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:gs}}}};function Je(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}_chunkA5EIY3HIcjs.a.call(void 0, Je,"emptyEffectiveArkRules");function cn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:a,...s}=t;return s})}}_chunkA5EIY3HIcjs.a.call(void 0, cn,"omitLayerDescriptions");function ms(e){let{stewards:t,...n}=cn(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:_nullishCoalesce(r.appliesTo, () => (null)),description:_nullishCoalesce(r.description, () => (null)),provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:_nullishCoalesce(r.aggregate, () => (null)),coverage:_nullishCoalesce(r.coverage, () => (null)),mode:r.mode,appliesTo:_nullishCoalesce(r.appliesTo, () => (null)),provenance:r.provenance}))}}}_chunkA5EIY3HIcjs.a.call(void 0, ms,"effectiveContractPolicyPayload");var vi=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Ii=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),bi=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function Ei(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(n<0)return!0;let r=e[n];if(/[A-Za-z0-9_$]/.test(r)){let a=n;for(;a>=0&&/[A-Za-z0-9_$]/.test(e[a]);)a-=1;return bi.has(e.slice(a+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:Ii.has(r)}_chunkA5EIY3HIcjs.a.call(void 0, Ei,"slashStartsRegex");function Si(e,t){if(!Ei(e,t))return t;let n=t+1,r=!1;for(;n<e.length;){let a=e[n];if(a===`
4
+ `||a==="\r")return t;if(a==="\\"){n+=2;continue}if(r)a==="]"&&(r=!1);else if(a==="[")r=!0;else if(a==="/"){for(n+=1;n<e.length&&/[A-Za-z]/.test(e[n]);)n+=1;return n}n+=1}return t}_chunkA5EIY3HIcjs.a.call(void 0, Si,"skipRegexLiteral");function Ce(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
5
+ `,t);return r===-1?e.length:r}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}if(n==="/")return Si(e,t);if(n==="'"||n==='"'||n==="`"){let r=t+1;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]===n)return r+1;r+=1}return e.length}return t}_chunkA5EIY3HIcjs.a.call(void 0, Ce,"skipStringOrComment");function ce(e,t){let n=t;for(;n<e.length;){if(/\s/.test(e[n])){n+=1;continue}if(e[n]==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=Ce(e,n);continue}break}return n}_chunkA5EIY3HIcjs.a.call(void 0, ce,"skipWsAndComments");function ht(e,t){let n=e[t];if(!n||!/[A-Za-z_$]/.test(n))return null;let r=t+1;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{ident:e.slice(t,r),end:r}}_chunkA5EIY3HIcjs.a.call(void 0, ht,"readIdent");function ke(e,t,n,r){if(e[t]!==n)return null;let a=1,s=t+1;for(;s<e.length&&a>0;){let o=Ce(e,s);if(o!==s){s=o;continue}let l=e[s];l===n?a+=1:l===r&&!(r===">"&&e[s-1]==="=")&&(a-=1),s+=1}return a===0?s:null}_chunkA5EIY3HIcjs.a.call(void 0, ke,"skipBalanced");function dn(e){let t=[],n=0,r;for(;n<e.length&&(n=ce(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let a=[],s=n;for(;;){let g=ht(e,s);if(!g||!vi.has(g.ident))break;a.push(g.ident),s=ce(e,g.end)}if(a.length===1&&a[0]==="static"&&e[s]==="{"){let g=ke(e,s,"{","}");if(g==null){r=e.length;break}n=g;continue}let o=ht(e,s);if(!o){n+=1;continue}if(s=ce(e,o.end),e[s]==="<"){let g=ke(e,s,"<",">");if(g==null){r=e.length;break}s=ce(e,g)}if(e[s]==="("){let g=ke(e,s,"(",")");if(g==null){r=e.length;break}if(s=ce(e,g),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let h=Ce(e,s);if(h!==s){s=h;continue}s+=1}if(e[s]==="{"){let h=ke(e,s,"{","}");if(h==null){r=e.length;break}t.push({name:o.ident,modifiers:a,kind:"method",body:e.slice(s+1,h-1)}),n=h;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,f=0;for(;s<e.length;){let g=Ce(e,s);if(g!==s){s=g;continue}let h=e[s];if(h==="{")l+=1;else if(h==="}"){if(l===0)break;l-=1}else if(h==="(")c+=1;else if(h===")")c-=1;else if(h==="[")f+=1;else if(h==="]")f-=1;else if(h===";"&&l===0&&c===0&&f===0){s+=1;break}s+=1}s>=e.length&&(l>0||c>0||f>0)&&(r=e.length),t.push({name:o.ident,modifiers:a,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}_chunkA5EIY3HIcjs.a.call(void 0, dn,"scanClassMembers");function ys(e,t){let n=t;for(;n<e.length;){let r=ce(e,n);if(r!==n){n=r;continue}let a=e[n];if(a==="{")return n;if(a===";")return null;if(a==="<"||a==="("||a==="["){let o=ke(e,n,a,a==="<"?">":a==="("?")":"]");if(o==null)return null;n=o;continue}if(a==='"'||a==="'"||a==="`"){n=Ce(e,n);continue}n+=1}return null}_chunkA5EIY3HIcjs.a.call(void 0, ys,"findClassBodyBrace");function un(e,t={}){let n=[],r=t.exportedOnly?/\bexport\s+(?:abstract\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*)/g:/(?:\b(export)\s+(?:default\s+)?)?(?:\babstract\s+)?\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,a=hs(e),s;for(;(s=r.exec(a))!==null;){let o=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=ys(e,s.index+s[0].length);if(c==null){n.push({name:o,start:s.index,exported:l,bodyStart:null,bodyEnd:null});continue}let f=ke(e,c,"{","}");n.push({name:o,start:s.index,exported:l,bodyStart:c+1,bodyEnd:f==null?null:f-1})}return n}_chunkA5EIY3HIcjs.a.call(void 0, un,"findClassDeclarations");function hs(e){let t="",n=0;for(;n<e.length;){let r=Ce(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}_chunkA5EIY3HIcjs.a.call(void 0, hs,"maskStringsAndComments");function Rs(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=hs(e),a=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),s=new RegExp(`\\b(?:(namespace|module)\\s+${a}\\s*\\{|(?:const|let|var)\\s+${a}\\s*(?::[^=;]+?)?=(?!=|>)\\s*(class\\b)?)`,"g"),o;for(;(o=s.exec(r))!==null;){let l,c;if(o[1])c="namespace",l=o.index+o[0].length-1;else if(o[2])c="class-expression",l=ys(e,o.index+o[0].length);else{c="object";let g=ce(e,o.index+o[0].length);l=e[g]==="{"?g:null}if(l==null)continue;let f=ke(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:f==null?e.length:f-1})}return n}_chunkA5EIY3HIcjs.a.call(void 0, Rs,"findMemberContainers");function As(e){let t=[],n=0,r=!0;for(;n<e.length;){let a=Ce(e,n);if(a!==n){n=a,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=_nullishCoalesce(ke(e,n,s,s==="{"?"}":s==="("?")":"]"), () => (e.length)),r=!1;continue}if(s===","){r=!0,n+=1;continue}if(r&&/[A-Za-z_$]/.test(s)){let o=ht(e,n);for(;o&&(o.ident==="async"||o.ident==="get"||o.ident==="set");){let l=ce(e,o.end);e[l]==="*"&&(l=ce(e,l+1));let c=ht(e,l);if(!c)break;o=c}if(o){let l=ce(e,o.end);("(:,<".includes(_nullishCoalesce(e[l], () => ("")))||l>=e.length)&&t.push(o.ident),n=o.end,r=!1;continue}}if(r&&s==="*"){n+=1;continue}/\s/.test(s)||(r=!1),n+=1}return t}_chunkA5EIY3HIcjs.a.call(void 0, As,"objectLiteralMemberNames");var Ci="INVARIANT_TESTS_PATH_MISSING",_i="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",Oi="INVARIANT_COVERAGE_ROOTS_MISSING",xi="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function ks(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let a=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${a}.`}_chunkA5EIY3HIcjs.a.call(void 0, ks,"formatCoverageDiscards");function bs(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let a=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return a===""||a==="."?!0:n===a||n.startsWith(`${a}/`)})}_chunkA5EIY3HIcjs.a.call(void 0, bs,"isUnderCoverageRoot");function fn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_chunkA5EIY3HIcjs.a.call(void 0, fn,"escapeRegExp");function $e(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}_chunkA5EIY3HIcjs.a.call(void 0, $e,"normalizePath");function gn(e,t){let n=[],r=0,a=e.length;for(;r<a;){let s=e[r],o=e[r+1];if(s==="/"&&o==="/"){for(;r<a&&e[r]!==`
6
+ `;)n.push(" "),r+=1;continue}if(s==="/"&&o==="*"){for(n.push(" "," "),r+=2;r<a&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
24
7
  `?`
25
- `:" "),r+=1;r<o&&(n.push(" "," "),r+=2);continue}if(s==='"'||s==="'"||s==="`"){let l=s;for(n.push(t?" ":s),r+=1;r<o;){let c=e[r];if(c==="\\"){let u=e[r+1];t?n.push(" ",u===void 0?"":" "):(n.push("\\"),u!==void 0&&n.push(u)),r+=u===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
26
- `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(No,"maskNonCode");function bc(e,t){if(!t)return;let n=To(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(No(e,!1))?.[2];return s===void 0?void 0:s}a(bc,"matchTestTitle");function vc(e,t){if(!t)return;let n=To(t),r=No(e,!0),o=[{shape:"function",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:declare\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${n}\\s*[(<]`},{shape:"class",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+${n}\\b`},{shape:"const",source:`(?:^|[\\s;{}])export\\s+(?:const|let|var)\\s+${n}(?:\\s*:(?:[^=]|=>)+?)?\\s*=(?!>)`},{shape:"type",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?type\\s+${n}\\b`},{shape:"interface",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?interface\\s+${n}\\b`},{shape:"enum",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?(?:const\\s+)?enum\\s+${n}\\b`},{shape:"method",source:`(?:^|[\\n;{}])\\s*(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set|declare)\\s+)*${n}\\s*(?:<[^>\\n]*>)?\\s*\\([^;{}]*\\)\\s*(?::\\s*[^;{]+)?\\s*\\{`}];for(let s of o)if(new RegExp(s.source).test(r))return s.shape}a(vc,"declarationShape");function Ec(e,t){let n=e.lastIndexOf(`
8
+ `:" "),r+=1;r<a&&(n.push(" "," "),r+=2);continue}if(s==='"'||s==="'"||s==="`"){let l=s;for(n.push(t?" ":s),r+=1;r<a;){let c=e[r];if(c==="\\"){let f=e[r+1];t?n.push(" ",f===void 0?"":" "):(n.push("\\"),f!==void 0&&n.push(f)),r+=f===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
9
+ `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}_chunkA5EIY3HIcjs.a.call(void 0, gn,"maskNonCode");function wi(e,t){if(!t)return;let n=fn(t),s=_optionalChain([new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i"), 'access', _65 => _65.exec, 'call', _66 => _66(gn(e,!1)), 'optionalAccess', _67 => _67[2]]);return s===void 0?void 0:s}_chunkA5EIY3HIcjs.a.call(void 0, wi,"matchTestTitle");function Es(e,t){if(!t)return;let n=fn(t),r=gn(e,!0),a=[{shape:"function",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:declare\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${n}\\s*[(<]`},{shape:"class",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+${n}\\b`},{shape:"const",source:`(?:^|[\\s;{}])export\\s+(?:const|let|var)\\s+${n}(?:\\s*:(?:[^=]|=>)+?)?\\s*=(?!>)`},{shape:"type",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?type\\s+${n}\\b`},{shape:"interface",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?interface\\s+${n}\\b`},{shape:"enum",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?(?:const\\s+)?enum\\s+${n}\\b`},{shape:"method",source:`(?:^|[\\n;{}])\\s*(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set|declare)\\s+)*${n}\\s*(?:<[^>\\n]*>)?\\s*\\([^;{}]*\\)\\s*(?::\\s*[^;{]+)?\\s*\\{`}];for(let s of a)if(new RegExp(s.source).test(r))return s.shape}_chunkA5EIY3HIcjs.a.call(void 0, Es,"declarationShape");function Ti(e,t,n){let r=_chunkA5EIY3HIcjs.a.call(void 0, a=>dn(a).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let a of un(e))if(!(a.name!==t||a.bodyStart==null)&&r(e.slice(a.bodyStart,_nullishCoalesce(a.bodyEnd, () => (e.length)))))return"method";for(let a of Rs(e,t)){let s=e.slice(a.bodyStart,a.bodyEnd);if(a.kind==="class-expression"&&r(s)||a.kind==="object"&&As(s).includes(n))return"method";if(a.kind==="namespace"){let o=Es(s,n);if(o==="function"||o==="const")return o}}}_chunkA5EIY3HIcjs.a.call(void 0, Ti,"classMemberShape");function Ni(e,t){let n=e.lastIndexOf(`
27
10
  `,t-1)+1,r=e.indexOf(`
28
- `,t);return e.slice(n,r===-1?e.length:r)}a(Ec,"lineAt");function Sc(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(Sc,"isImportLine");function Si(e,t,n){if(!t||!e.includes(t))return;let r=new Set,o=0,s=e.length,i=a((l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(Sc(Ec(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;o<s;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(;o<s&&e[o]!==`
29
- `;)i(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(i(o,"comment"),i(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)i(o,"comment"),o+=1;o<s&&(i(o,"comment"),i(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let u=l;for(i(o,"string"),o+=1;o<s;){let f=e[o];if(f==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(f===u){i(o,"string"),o+=1;break}i(o,"string"),o+=1}continue}i(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(Si,"mentionContext");function xi(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}a(xi,"symbolNeedle");function wc(e){return xi(e.coverage?.symbol)?.name??e.id}a(wc,"declaredLabel");function wi(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(wi,"sortedContentFiles");function Cc(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(g=>vt(g))),s=(t.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),i=e.coverage?.test!==!1&&n,l=xi(e.coverage?.symbol??void 0),c,u;if(i){for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=bc(d,e.id);if(m!==void 0){if(s.length===0||Ci(g,s)){c={file:g,title:m};break}u??={file:g,title:m}}}c??=u}let f;if(l)for(let g of wi(t.fileContents)){if(o.has(vt(g)))continue;let d=t.fileContents[g];if(!d||l.className&&!d.includes(l.className))continue;let m=vc(d,l.name);if(m){f={file:g,shape:m};break}}let y;if(!c&&!f){if(i)for(let g of r){let d=t.fileContents[g];if(!d)continue;let m=Si(d,e.id,!0);if(m){y={file:g,context:m};break}}if(!y&&l)for(let g of wi(t.fileContents)){if(o.has(vt(g)))continue;let d=t.fileContents[g];if(!d)continue;let m=Si(d,l.name,!1);if(m){y={file:g,context:m};break}}}let p=c?{kind:"test-title",file:c.file,title:c.title}:f?{kind:"declaration",file:f.file,shape:f.shape}:y?{kind:"mention-only",file:y.file,context:y.context}:{kind:"none"};return p.kind==="mention-only"&&p.context==="comment"&&l&&xc(t.fileContents,o,l.name,p.file)&&(p={kind:"declaration-miss",symbol:l.name}),{best:p,...c?{testTitle:c}:{},...f?{declaration:f}:{}}}a(Cc,"rankCoverage");function xc(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${To(n)}(?=$|[^A-Za-z0-9_$])`),s=vt(r);for(let i of Object.keys(e)){if(t.has(vt(i))||vt(i)===s)continue;let l=e[i];if(l&&o.test(No(l,!0)))return!0}return!1}a(xc,"symbolInCodeElsewhere");function Oc(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Oc,"countsAsCoverage");function Pc(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}a(Pc,"mentionWhere");function _c(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${wc(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Pc(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}a(_c,"describeCoverage");function Oi(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,i=Ei(s),l=Ei(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",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),f=u.length>0,y=u.join(", "),p=[],g=[];for(let d of t){let m=d.coverage?.test!==!1,E=d.coverage?.symbol,S=!r&&m,k=Cc(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},S),v=k.best,C=[];S&&k.testTitle&&C.push("test-title"),k.declaration&&C.push("symbol");let N=Oc(v),b,T;S&&k.testTitle&&(b=k.testTitle.file,f&&(T=!Ci(b,u)));let Ve=k.declaration?.file,ye=k.declaration?.shape,D=(d.coverage?.test===!0||!!E||d.coverage===void 0)&&N||d.coverage?.test===!1&&!E?!0:N,q=r&&m&&!N;if(p.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:D&&!q,evidence:C,partial:q,description:d.description,...b!==void 0?{testEvidenceFile:b}:{},...Ve!==void 0?{symbolEvidenceFile:Ve}:{},...ye!==void 0?{shape:ye}:{},...T!==void 0?{outsideDeclaredRoots:T}:{},coverageRootsDeclared:f}),T===!0&&b!==void 0&&g.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${b}, which is outside the declared coverage roots (${y}). 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:b,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!D||q){let Y=d.mode==="enforced"&&!q,he=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(q?o?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${_c(d,v)} (${he==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(q&&o?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:Y?"error":"warning",failsStrict:Y,kind:he})}}return{coverage:p,violations:g,partial:p.some(d=>d.partial)}}a(Oi,"evaluateInvariantCoverage");function Pi(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.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a(Pi,"canPromoteInvariant");function _o(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}a(_o,"nonEmptyPathStrings");function Tc(e){return!e||typeof e!="object"?[]:[..._o(e.testGlobs),..._o(e.coverageRoots)]}a(Tc,"configuredInvariantTestsPaths");function Nc(e){return Tc(e).length>0}a(Nc,"hasConfiguredInvariantTestsPath");function Do(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Do,"catalogDemandsInvariantTestsPath");function _i(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Do(e.invariants);return e.adopted!==!0||!t?[]:Nc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Rc,message:Ac,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(_i,"collectMissingInvariantTestsPathFindings");function Dc(e){return!e||typeof e!="object"?[]:_o(e.coverageRoots)}a(Dc,"configuredCoverageRoots");function Lc(e){return Dc(e).length>0}a(Lc,"hasConfiguredCoverageRoots");function Lo(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Lo,"catalogHasEnforcedInvariant");function Ti(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Lo(e.invariants)?Lc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:kc,message:Ic,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(Ti,"collectMissingCoverageRootsFindings");var yr="1.0",Fc="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function P(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Fc}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}a(P,"addFinding");function Z(e){return[...new Set(e??[])].sort()}a(Z,"sortedUnique");function ue(e,t,n,r,o){let s=Z(n),i=Z(r),l=new Set(s),c=new Set(i),u=i.filter(y=>!l.has(y)),f=s.filter(y=>!c.has(y));u.length===0&&f.length===0||(u.length>0&&P(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),f.length>0&&P(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(ue,"compareStringSets");function In(e,t,n,r,o,s,i){if(n===r)return;P(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(In,"compareBoolean");function mr(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}a(mr,"keyed");function $c(e,t,n){let r=mr(t,s=>s.name),o=mr(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&P(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){P(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){P(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;ue(e,`${c}.patterns`,i.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ue(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=ur(i),f=ur(l);ue(e,`${c}.forbiddenGlobals`,u.rawGlobals,f.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ue(e,`${c}.capabilities`,u.atoms,f.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Z(i.intentPrefixes).join("\0")!==Z(l.intentPrefixes).join("\0")&&P(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Z(i.intentPrefixes),after:Z(l.intentPrefixes)}),In(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),In(e,`${c}.optional`,i.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}a($c,"compareLayers");function Mc(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=mr(t,r),s=mr(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&P(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),u=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?P(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):P(e,{kind:"allow-added",path:u,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&P(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&P(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.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 f=l.peerIsolation===!0,y=c.peerIsolation===!0;if(f!==y){let d=l.from===l.to&&c.from===c.to;P(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?y?"strengthening":"weakening":"judgment-required",message:d?y?"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:f,after:y})}Z(l.sliceFolders).join("\0")!==Z(c.sliceFolders).join("\0")&&P(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Z(l.sliceFolders),after:Z(c.sliceFolders)});let p=l.sliceIdentity??"path",g=c.sliceIdentity??"path";if(p!==g&&P(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:p,after:g}),!(!f&&!y)&&(Di(e,`${u}.sharedRoots`,"shared-roots",Z(l.sharedRoots),Z(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Di(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(Ni)),Z((c.allowedCrossSlice??[]).map(Ni)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(l.sharedImportsSlice??null)!==(c.sharedImportsSlice??null))){let d=c.sharedImportsSlice==="deny";P(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:d?"strengthening":"weakening",message:d?"A shared root may no longer import a slice.":"A shared root may import a slice again.",before:l.sharedImportsSlice??null,after:c.sharedImportsSlice??null})}}}a(Mc,"compareRules");function Ni(e){return JSON.stringify([e.from,e.to])}a(Ni,"crossSliceKey");function Di(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(f=>!r.includes(f)),c=r.filter(f=>!o.includes(f)),u=l.length>0&&c.length>0;P(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(Di,"compareDeclaredExceptions");function Hc(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&P(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])In(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(Hc,"compareSafety");function Fo(e){return e.mode==="enforced"?"enforced":"advisory"}a(Fo,"arkRunMode");function $o(e){return e.mode==="enforced"?"enforced":"advisory"}a($o,"arkOrderMode");function Kc(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${$o(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=$o(r),l=$o(o);if(i!==l){let c=i==="advisory"&&l==="enforced";P(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}ue(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."}),ue(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(Kc,"compareArkOrder");function Gc(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Fo(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Fo(r),l=Fo(o);if(i!==l){let c=i==="advisory"&&l==="enforced";P(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}ue(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."}),ue(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."}),In(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Gc,"compareArkRun");function Uc(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}a(Uc,"overallClassification");function Li(e,t){return`${e}::${t}`}a(Li,"ruleKey");function Fi(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Li(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Li(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Fi,"indexEffectiveRules");function Vc(e,t,n,r,o,s){let i=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of u){let g=l[p],d=c[p],m=`$.arkRules[${p}]`;if(g===void 0&&d!==void 0){P(e,{kind:"arkrules-ref-added",path:m,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:d});continue}if(g!==void 0&&d===void 0){P(e,{kind:"arkrules-ref-removed",path:m,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:g});continue}g!==d&&P(e,{kind:"arkrules-ref-path-changed",path:m,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:g,after:d})}let f=Fi(r),y=Fi(o);for(let p of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let g=f.structure.get(p),d=y.structure.get(p),m=`$.arkRules.structure[${p}]`;if(!g&&d){P(e,{kind:"arkrule-structure-added",path:m,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){P(e,{kind:"arkrule-structure-removed",path:m,classification:"weakening",message:`Structure ArkRule ${g.id} was removed.`,before:g});continue}if(!(!g||!d)){if(g.mode!==d.mode){let E=g.mode==="advisory"&&d.mode==="enforced";P(e,{kind:E?"arkrule-promoted":"arkrule-demoted",path:`${m}.mode`,classification:E?"strengthening":"weakening",message:E?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}g.sensor!==d.sensor&&P(e,{kind:"arkrule-sensor-changed",path:`${m}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:g.sensor,after:d.sensor})}}for(let p of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let g=f.invariants.get(p),d=y.invariants.get(p),m=`$.arkRules.invariants[${p}]`;if(!g&&d){P(e,{kind:"arkrule-invariant-added",path:m,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){P(e,{kind:"arkrule-invariant-removed",path:m,classification:"weakening",message:`Invariant ${g.id} was removed.`,before:g});continue}if(!(!g||!d)&&g.mode!==d.mode)if(g.mode==="advisory"&&d.mode==="enforced"){let S=i?.get(d.id),k=Pi(S);k.ok?P(e,{kind:"arkrule-invariant-promoted",path:`${m}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:g.mode,after:d.mode}):P(e,{kind:"arkrule-invariant-promote-refused",path:`${m}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:g.mode,after:d.mode})}else P(e,{kind:"arkrule-invariant-demoted",path:`${m}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}}a(Vc,"compareArkRules");function hr(e,t,n){let r=[];ue(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ue(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."}),ue(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."}),In(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";P(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&P(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),$c(r,e.layers,t.layers),Mc(r,e.rules,t.rules),Hc(r,e,t),Vc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Gc(r,e,t),Kc(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:yr,classification:Uc(r),findings:r}}a(hr,"classifyArkPolicyDelta");function Rr(e,t){if(!e||e.schemaVersion!==yr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=Z(e.findingIds),r=Z(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}a(Rr,"policyDeltaAcknowledgementMatches");function ot(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(ot,"normalizePath");function $i(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a($i,"isIdentifierStart");function Ar(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(Ar,"isIdentifierCharacter");function ie(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ie,"skipWhitespace");function bn(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}a(bn,"readString");function ce(e,t,n){return e.startsWith(t,n)&&!Ar(e[n-1])&&!Ar(e[n+t.length])}a(ce,"isWordAt");function Mi(e,t){let n=ie(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ie(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ce(e,"type",n))return!1;let o=ie(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ce(e,"as",o)||!$i(e[o]))return!1;for(n=o;n<e.length&&Ar(e[n]);)n+=1;if(n=ie(e,n),ce(e,"as",n)){if(n=ie(e,n+2),!$i(e[n]))return!1;for(;n<e.length&&Ar(e[n]);)n+=1}r=!0}return!1}a(Mi,"bracedNamedBindingsAreTypeOnly");function jc(e,t){if(t=ie(e,t+6),e[t]==="(")return bn(e,ie(e,t+1));let n=!1;if(ce(e,"type",t)){let o=ie(e,t+4);e[o]!==","&&!ce(e,"from",o)&&(n=!0)}else Mi(e,t)&&(n=!0);let r=Hi(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(jc,"specifierAfterImport");function Bc(e,t){t=t+6;let n=ie(e,t),r=!1;if(ce(e,"type",n)){let s=ie(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Mi(e,n)&&(r=!0);let o=Hi(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(Bc,"specifierAfterExport");function Hi(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ce(e,"from",t))return bn(e,ie(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return bn(e,t);if(t>0&&(ce(e,"import",t)||ce(e,"export",t)))return}}a(Hi,"specifierInStaticStatement");function Wc(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}a(Wc,"skipTemplateLiteral");function zc(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ie(e,t+7);if(e[r]!=="(")return;r=ie(e,r+1);let o=bn(e,r);return o?{...o,requireCall:!0}:void 0}a(zc,"specifierAfterRequire");function qc(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(`
30
- `,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=Wc(e,n);continue}if(r==="'"||r==='"'){let s=bn(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&ce(e,"import",n)?jc(e,n):r==="e"&&ce(e,"export",n)?Bc(e,n):r==="r"&&ce(e,"require",n)?zc(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(qc,"moduleSpecifiers");function Ki(e,t){let n=[],r=[];for(let o of qc(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=fn(s);if(!u)continue;let f=e.content.slice(0,o.offset).split(`
31
- `).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
32
- `).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=Yc(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}a(Ki,"moduleFactsFor");function Yc(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let i=n.get(s);if(i)return i}}a(Yc,"resolveSpecifier");function Gi(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ft(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}a(Gi,"violationsFor");var Xc={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 Zc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(Zc,"hasActiveArkRules");function Jc(e,t){return Zc(e,t)?z($(vi({config:e,arkRules:t,warnings:[]}))):z($(Po(e)))}a(Jc,"policyHashFor");function vn(e,t,n){let r=typeof e=="string"?ai(e,t):co(e,t),o=n?.arkRules??kn();return{...r,arkRules:o,policyHash:Jc(r.config,o)}}a(vn,"loadContract");function Mo(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=hr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,i=s&&Rr(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:i,valid:!s||i}}a(Mo,"analyzePolicyDelta");function Et(e){let t=e.files.map(y=>{let p=ot(y.path);return{path:p,content:y.content,contentHash:z(y.content),layer:de(p,e.contract.config.layers)??null}}).sort((y,p)=>y.path.localeCompare(p.path)),n=new Map(t.map(y=>[y.path,y])),r=[],o=[];for(let y of t){let p=Ki(y,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=Gi(r,e.contract.config),i=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(Rt(y))]));for(let y of o){let p=n.get(y.file)?.layer;if(!p)continue;let g=i.get(p),d=Te(y.symbol,g?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${y.symbol}" because it is the import form of forbidden global "${d}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(p)?.has(y.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...Xc}],f={schemaVersion:gr,policyHash:e.contract.policyHash,compilerOptionsHash:z($(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&s.length===0,ir:f}}a(Et,"analyzeProject");function En(e){let t=new Map(e.files.map(n=>[ot(n.path),n]));for(let n of e.changes){let r=ot(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Et({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(En,"analyzeChange");function Ho(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}a(Ho,"explainViolation");function kr(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?o.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let u=[],f;do{if(f=s.pop(),f===void 0)break;o.delete(f),u.push(f)}while(f!==c);u.length>1&&i.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(kr,"detectArchitectureCycles");function st(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let i=Ze(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let p=Ds(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});p&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:p.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:p.toPath,toSlice:p.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${p.fromPath} \u2192 slice ${p.toSlice} (${p.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),f=c?pt(i.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:i.fromSlice,toSlice:i.toSlice}):void 0,y=l.message?f?`${l.message} (${f})`:l.message:f?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${f}`:`${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:u?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=kr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}a(st,"evaluateArchitectureGraph");function Ui(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}a(Ui,"structureFreezeTarget");var Qc=["no-anemic-model"],zi=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Um=new RegExp(`\\b(${zi.join("|")})\\b`),qi="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Vm=new RegExp(`\\bthis\\.${qi}\\.push\\s*\\(`),jm=new RegExp(`^this\\.${qi}\\s*=\\s*\\[\\s*\\]`);var ed="truncatedUntil";function td(){return`${zi.join(", ")}, or events-array .push(`}a(td,"expectedDomainInvariantWordsPhrase");function Ko(e){let t=Object.getOwnPropertyDescriptor(e,ed)?.value;return typeof t=="number"?t:void 0}a(Ko,"shapeTruncatedUntil");function nd(e){let t=Ko(e);return t==null?"":` shape analysed until character ${t}`}a(nd,"shapeTruncationSuffix");function Vi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Vi,"escapeGlobLiteral");function rd(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+=Vi(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Vi(o)}return new RegExp(`^${n}$`)}a(rd,"globToRegExp");function St(e,t){return!t||t.length===0?!0:t.some(n=>rd(n).test(e))}a(St,"matchesAppliesTo");function Yi(e){return Qc.includes(e)}a(Yi,"isTier2");function Xi(e){return e.mode==="enforced"&&!Yi(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Xi,"severityFor");function De(e,t,n,r=1){let{severity:o,failsStrict:s}=Xi(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}a(De,"baseViolation");function Ir(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(Ir,"isInRuleLayer");function br(e,t,n){return t.filter(r=>!(!r.exported||!St(r.file,e.appliesTo)||!Ir(r.file,e,n)))}a(br,"shapesForRule");function od(e,t,n){let r=[];for(let o of br(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(De(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(od,"evaluateAggregatePrivateState");function sd(e,t,n){let r=[];for(let o of br(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(De(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(sd,"evaluateAlwaysValidFactory");function id(e,t,n){let r=[],o=td();for(let s of br(e,t,n)){let i=nd(s);Ko(s)!=null&&r.push(De(e,s.file,`Exported class ${s.className} shape analysed until character ${Ko(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(De(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(id,"evaluateDomainEventOnMutation");function ad(e,t){let n=[];for(let r of t.files)St(r,e.appliesTo)&&Ir(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(De(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(ad,"evaluateOrchestrationOnly");function ld(e,t){let n=[];for(let r of t.files)St(r,e.appliesTo)&&Ir(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(De(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(ld,"evaluateThinAdapter");function cd(e,t){let n=[];for(let r of t.files)St(r,e.appliesTo)&&Ir(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(De(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}a(cd,"evaluateWritesViaAggregate");function dd(e,t,n){let r=[];for(let o of br(e,t,n))if(o.dataOnly===!0){let s=De(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}a(dd,"evaluateNoAnemicModel");function Zi(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(...od(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...sd(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...id(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...ad(n,e));break;case"thin-adapter":t.push(...ld(n,e));break;case"writes-via-aggregate":t.push(...cd(n,e));break;case"no-anemic-model":t.push(...dd(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}a(Zi,"evaluateArkRuleSensors");function Ji(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=>St(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=Xi(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>St(l,o.appliesTo)))continue;let i=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a(Ji,"collectEmptyAppliesToFindings");var ji=64;function ud(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}a(ud,"stripTrailingDots");function pd(e){let t=e.trim(),n=t.length>ji?t.slice(0,ji):t;return ud(n)}a(pd,"normalizeIntentPrefix");function fd(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(fd,"layerNameLooksDomain");function gd(e){return e.some(t=>{let n=pd(t);return n==="Domain"||n.startsWith("Domain.")})}a(gd,"ownsDomainIntent");function md(e,t=[]){return fd(e)||gd(t)}a(md,"isDomainRoleLayerName");function Qi(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>md(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=t.find(c=>e.arkRules.byLayer?.[c])??t[0],i=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!Yi(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${i}.`,file:i,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:i,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}a(Qi,"collectEmptyInvariantCatalogFindings");var Bi=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,Wi=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,yd=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function hd(e){return e==="PersistenceAdapters"}a(hd,"isPersistenceDriverLayer");function Rd(e,t){if(Bi.test(e)||Wi.test(e))return!0;if(!t)return!1;for(let n of t){if(hd(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Bi.test(o)||Wi.test(o))return!0}return!1}a(Rd,"sourceImportsPersistenceDriver");var Ad=/\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*=)/,kd=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Id=/\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*=/,bd=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function vd(e,t,n){if(!t)return null;let r=Rd(t,n),o=r&&yd.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Id.source,"g"))??[],i=t.match(new RegExp(bd.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,f=Ad.test(t)||kd.test(t),y=s.length>=1||i.length>=2,p=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=r&&y||f&&y||r&&p&&(l>=4||s.length>=1)||f&&r;return!u&&!g&&!o?null:{...u?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(vd,"deriveArkRuleFileHints");function ea(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=vd(r,o,t?.[s]);i&&(n[s]=i)}return n}a(ea,"buildArkRuleFileHints");function Ed(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}a(Ed,"normalizeExtraMergeTeethClassification");function vr(e){let t=Ed(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}a(vr,"extraMergeTeethAllowed");function ta(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(ta,"classifyResolvedLayerCoverage");var Sd=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Ym=new Set(Sd);function na(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(na,"isArkRunKernelModuleSpecifier");var wd=["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"],Go=new Set(wd);function ra(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Go.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Go.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Go.has(e.slice(0,r))}a(ra,"isArkRunTransportBypassSpecifier");var Cd=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],sy=new Set(Cd);var oa={"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"},xd="ARKRUN_INTERACTION_NAME_INCOMPLETE";function aa(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(aa,"isDomainRoleLayer");function Od(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Od,"compareFindings");function Se(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:oa[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:oa[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Se,"finding");function Pd(e,t){let n=[],r=[],o=[],s=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),o.push(...i.raises),s.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}a(Pd,"bagForFile");function sa(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(sa,"emitKinds");function ia(e){return e==="subscribe"||e==="register-handler"}a(ia,"handleKinds");function _d(e){return e==="resolve"||e==="resolve-singleton"}a(_d,"dependKinds");function Td(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Se(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((u,f)=>u.file.localeCompare(f.file));if(l.length===0){r.push(Se(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(Se(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(Td,"evaluateMissingRoot");function Nd(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!na(c))continue;let u=r(l.from);u&&aa(u,s.get(u)??[])&&i.push(Se(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return i}a(Nd,"evaluateKernelInDomain");function Dd(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(f=>[f.name,f.intentPrefixes??[]])),c=new Set(r.filter(f=>f.hasKernelFactory).map(f=>f.file)),u=[];for(let f of n){if(c.has(f.file))continue;let y=f.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let p=o(f.file);!p||!i.has(p)||aa(p,l.get(p)??[])||u.push(Se(e,"arkrun-direct-new",f.file,f.line,`${p} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:f.typeName},s))}return u}a(Dd,"evaluateDirectNew");function Ld(e,t,n,r,o){let s=[],i=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:i};for(let c of t){if(!sa(c.kind)&&!ia(c.kind)&&!_d(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:xd,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let f=Pd(n,c.file);if(sa(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;s.push(Se(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},o));continue}if(ia(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;s.push(Se(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},o));continue}f.uses.has(c.nameLiteral)||s.push(Se(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(Ld,"evaluateUndeclared");function Fd(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!ra(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(Se(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}a(Fd,"evaluateTransportBypass");function la(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=vr(e.classification),r=Ld(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Td(t,e.compositionRootHits,n),...Nd(t,e.layers,e.dependencies,e.layerForFile,n),...Dd(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Fd(t,e.dependencies,e.layerForFile,n)].sort(Od),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}a(la,"evaluateArkRunSensors");function ca(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(ca,"isArkOrderModuleSpecifier");var da=new Map;function ua(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(ua,"escapeAppliesToLiteral");function $d(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}a($d,"normalizeAppliesToGlob");function Md(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(Md,"appliesToBracesBalanced");function Hd(e){let t=da.get(e);if(t)return t;let n=$d(e),r=Md(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=ua(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+=ua(c)}let i=new RegExp(`^${o}$`);return da.set(e,i),i}a(Hd,"globToRegExp");var pa={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Kd(e,t){return!t||t.length===0?!0:t.some(n=>Hd(n).test(e))}a(Kd,"matchesArkOrderAppliesTo");function Gd(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(Gd,"isDomainRoleLayer");function Le(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:pa[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:pa[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Le,"finding");function fa(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=vr(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Le(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 u of e.planeRootHits){let f=c.get(u.matchedRoot)??[];f.push(u),c.set(u.matchedRoot,f)}for(let u of o){let f=c.get(u)??[];if(f.length===0){r.push(Le(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}f.some(y=>y.hasPlaneFactory)||r.push(Le(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!ca(u))continue;let f=e.layerForFile(c.from);f&&Gd(f,s.get(f)??[])&&r.push(Le(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:u},n))}for(let c of e.genericUpdates)r.push(Le(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Le(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(Le(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||Kd(c.file,t.appliesTo)&&r.push(Le(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}a(fa,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}a(J,"configWarning");function Sn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(J("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(J("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[d];m!==void 0&&(!Number.isInteger(m)||m<0)&&s.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);i.length===0&&s.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,f=new Set;for(let d of i){if(!d.name){s.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&f.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(E=>typeof E!="string"))&&s.push(J("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let m=Array.isArray(d.patterns)?d.patterns:[];if(m.length===0){s.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let E of m){let S;try{S=ke(E)}catch(v){s.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${E}": ${v instanceof Error?v.message:String(v)}`,{layer:d.name,pattern:E}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(v=>S.test(v))&&!k&&s.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${E}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:E,failsStrict:!1,reserved:!1}))}}for(let d of f)s.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&s.push(J("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&s.push(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let y=new Set;if(i.length>1)for(let d of r){let m=-1,E=[];for(let S of i)for(let k of S.patterns??[]){if(!ke(k).test(d))continue;let v=to(k,d);v>m?(m=v,E=[S.name]):v===m&&!E.includes(S.name)&&E.push(S.name)}E.length>1&&y.add([...E].sort().join(" + "))}y.size>0&&s.push(J("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let p=r.filter(d=>!de(d,i));p.length>0&&s.push(J("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)}));for(let d of Ps(n))s.push(J("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));let g=oi(t);if(g.length>0){let d=g[0]??"this layer";s.push(J("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:g,nextAction:si(d)}))}return s}a(Sn,"collectAnalysisConfigWarnings");function ga(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:Ui({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(ga,"toArkRuleEngineViolation");function Ud(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Ud,"arkRulesMapIsOn");function ma(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}a(ma,"arkRuleFindingNextAction");function Vd(e,t){return t.some(n=>{try{return ke(n).test(e)}catch{return!1}})}a(Vd,"matchesAny");function jd(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(m=>m.kind==="ts-suppression").map(({file:m,line:E})=>({file:m,line:E})),l=t.safetyUses.filter(m=>m.kind==="any-cast").map(({file:m,line:E})=>({file:m,line:E})),c=t.safetyUses.filter(m=>(m.kind==="dynamic-import"||m.kind==="dynamic-require")&&!Vd(m.file,s)).map(m=>({file:m.file,line:m.line,kind:m.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(m=>m.kind==="in-memory-store").map(m=>({file:m.file,line:m.line,store:m.symbol??"in-memory store"})),f=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(m=>m.peerIsolation===!1||m.allowed===!1&&!!m.from&&m.from===m.to&&m.peerIsolation!==!0).map(m=>({from:m.from,to:m.to})),y={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],g=c.filter(m=>m.kind==="import");if(g.length>0){let m=g[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${g.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(m=>m.kind==="require");if(d.length>0){let m=d[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let m=i[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let m=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let m=u[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:m.file,line:m.line,message:`${u.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 f.length>0&&p.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${f.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:p}}a(jd,"evaluateSafety");function Bd(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(Bd,"ambientForbiddenGlobal");function ya(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return So(e,n.length>0?n:Eo.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(ya,"intentLayer");function Wd(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let i=n.get(s.file);!i||!Bd(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(f=>f.from===s.file&&f.line===s.line&&f.specifier===s.symbol&&!f.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&gn(s.symbol,c))){if(s.source==="import-based"){let f=Te(s.symbol,c);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...u?{edgeKind:u}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${f}".`});continue}}Rt(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of mn({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=ya(s.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let s of t.intentReferences){let i=n.get(s.file);if(!i)continue;let l=ya(s.intent,e.contract);if(!l)continue;let c=Ze(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?pt(c.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,f=`${i} must not reference ${l} intent ${s.intent}.`,y=u&&c.peerIsolationReason!=="cross-slice"?`${f} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:f;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:y})}return r}a(Wd,"contentViolations");function zd(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((R,te)=>{let Ut=`${R.code}\0${R.file??""}\0${R.message}`,Vt=`${te.code}\0${te.file??""}\0${te.message}`;return Ut<Vt?-1:Ut>Vt?1:0}),i=t.files.map(R=>({...R,layer:de(R.path,e.contract.config.layers)??null})),l=new Map(i.map(R=>[R.path,R.layer])),c=t.dependencies.map(R=>{let te=R.target?l.get(R.target)??de(R.target,e.contract.config.layers):void 0;return{from:R.from,fromLayer:l.get(R.from)??null,...R.resolution==="resolved-project"&&R.target?{to:R.target,...te?{toLayer:te}:{}}:{},line:R.line,kind:R.kind,typeOnly:R.typeOnly,...R.targetTypeOnlyExports?{targetTypeOnlyExports:R.targetTypeOnlyExports}:{},...R.sourcePureTypeModule?{sourcePureTypeModule:R.sourcePureTypeModule}:{},...R.namedBindingsTypeOnly?{namedBindingsTypeOnly:R.namedBindingsTypeOnly}:{},...R.portProofEligible?{portProofEligible:R.portProofEligible}:{}}}),u=Sn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(R=>R.path)}),f=jd(e,t),y=e.contract.arkRules??kn(),p=i.map(R=>R.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?ea(e.coverageInputs.fileContents):{},...e.fileHints??{}},m=a(R=>l.get(R)??de(R,e.contract.config.layers),"resolveLayer"),E=[...Zi({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:m,fileHints:d}),...Ji(y,p),...Qi({arkRulesActive:Ud(e.contract.config),arkRules:y,layers:e.contract.config.layers??[],files:p.map(R=>({path:R,layer:m(R)}))})],S=(y.invariants?.length??0)>0,k=Ti({hasEnforcedInvariant:Lo(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),v=k.length>0?[]:_i({adopted:e.adopted===!0,hasDomainInvariants:Do(y.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),C=[...k.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...v.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],N=E.filter(R=>R.failsStrict).map(R=>ga(R,ma(R,!1))),b=E.filter(R=>!R.failsStrict).map(R=>({...ga(R,ma(R,!0)),failsStrict:!1})),T=S?Oi({arkRules:y,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},Ve=T.violations.filter(R=>R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,nextAction:`Add a test title or declared symbol covering ${R.arkruleId} (declared in ${R.arkruleSource}), then preflight again.`})),ye=T.violations.filter(R=>!R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,failsStrict:!1,nextAction:R.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${R.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${R.arkruleId} in ${R.arkruleSource} (advisory / partial).`})),we=ta(i),D=la({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:a(R=>l.get(R)??de(R,e.contract.config.layers),"layerForFile"),classification:we}),q=e.contract.config.arkRun?.mode,Y=D.findings.filter(()=>q==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),he=D.findings.filter(()=>q!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),Ce=fa({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:a(R=>l.get(R)??de(R,e.contract.config.layers),"layerForFile"),classification:we}),Gt=e.contract.config.arkOrder?.mode,zn=Ce.findings.filter(()=>Gt==="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:R.failsStrict,...R.severity?{severity:R.severity}:{}})),fs=Ce.findings.filter(()=>Gt!=="enforced").map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,target:R.target,nextAction:R.nextAction,sensor:R.sensor,failsStrict:!1})),w=[...T.partial&&T.coverage.some(R=>R.mode==="enforced"&&R.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."}]:[],...D.completenessReasons,...Ce.completenessReasons],x=st({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(R=>R.layer).map(R=>R.path),contentViolations:[...Wd(e,t,l),...N,...C,...Ve,...Y,...zn],edges:c,warnings:[...u,...f.warnings,...b,...ye,...he,...fs],safety:f.report}),h=o==="complete"&&w.length>0?"partial":o,A=h==="complete"?s:[...s,...w].sort((R,te)=>{let Ut=`${R.code}\0${R.file??""}\0${R.message}`,Vt=`${te.code}\0${te.file??""}\0${te.message}`;return Ut<Vt?-1:Ut>Vt?1:0}),L=x.violations.filter(R=>R.failsStrict!==!1),W=h==="complete"&&L.length===0,xe=W&&x.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:A,valid:W,strictValid:xe,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:f.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(R=>R.name),edges:c,capabilityUses:t.capabilityUses,violations:x.violations,warnings:x.warnings}}}a(zd,"analyzeCanonicalResolvedProject");function wt(e){return zd({contract:e.contract,facts:Ee(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}a(wt,"analyzeResolvedProject");function ha(e){return z($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(ha,"analysisTreeHash");function Uo(e){let t=Et(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let m=d.path.replace(/\\/g,"/"),E=ot(d.path);if(!E||E===".."||E.startsWith("../")||m.startsWith("/")||/^[A-Za-z]:\//.test(m)||m.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(E)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:E,line:1,message:`The atomic change set contains more than one operation for ${E}.`});continue}o.add(E),"delete"in d&&d.delete&&!n.has(E)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:E,line:1,message:`Cannot delete ${E} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:E,delete:!0}:{path:E,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=En({...e,changes:r}),l=new Map(i.ir.files.map(d=>[d.path,d])),c=i.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let m=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...m?{fromLayer:m}:{},edgeKind:"import",message:d.message}}),u=st({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(d=>d.path),contentViolations:c,edges:i.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(d=>{let m=ot(d.path),E=n.get(m),S=l.get(m);return{path:m,operation:"delete"in d&&d.delete?"delete":E?"update":"create",...E?{beforeContentHash:E.contentHash}:{},...S?{candidateContentHash:S.contentHash}:{}}}).sort((d,m)=>d.path.localeCompare(m.path)),y=[...s,...u.violations].map(d=>({...d,nextAction:pe(d)})),p=y.filter(d=>d.failsStrict!==!1),g=e.changeMap?rt({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:i.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&p.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:ha(t.ir.files),candidateTreeHash:ha(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:f,violations:y,warnings:u.warnings}}a(Uo,"preflightChange");function qd(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}a(qd,"canonicalChangePath");function Yd(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}a(Yd,"identityViolations");function Xd(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}a(Xd,"preparedChange");function Vo(e){let t=Ee(e.baseFacts),n=Ee(e.candidateFacts),r=wt({contract:e.contract,facts:t}),o=wt({contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),i=new Map(n.files.map(g=>[g.path,g])),l=Yd(t,n),c=new Map,u=[];for(let g of e.changes){let d=qd(g.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,g);let m=s.get(d),E=i.get(d);if("delete"in g&&g.delete)m||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let S="content"in g?g.content:"",k=z(S);E?E.contentHash!==k&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:E.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(Xd(g,d,s,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let g of new Set([...s.keys(),...i.keys()])){if(c.has(g))continue;let d=s.get(g),m=i.get(g);d&&m&&$(d)===$(m)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:g,line:1,message:`Candidate facts change ${g}, but the atomic change set does not declare it.`})}let f=e.changeMap?rt({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[]),candidateDependencies:o.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[])}):void 0,y=[...l,...o.ir.violations].map(g=>({...g,nextAction:pe(g)})),p=y.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.length===0&&(f?.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}:{},...f?{convergence:f}:{},changes:u.sort((g,d)=>g.path<d.path?-1:g.path>d.path?1:0),violations:y,warnings:o.ir.warnings}}a(Vo,"preflightResolvedChange");var Er="docs/diagnostics.md",Ra="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(I,"entry");var wn=Object.freeze([I("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","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("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),I("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{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("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),I("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),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 a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),I("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),I("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),I("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),I("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),I("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),I("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),I("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),I("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),I("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),I("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),I("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),I("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),I("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),I("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),I("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),I("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),I("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),I("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. 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("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),I("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{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.")]),jo=new Map(wn.map(e=>[e.ruleId,e])),Aa=Object.freeze(wn.map(e=>e.ruleId));function ka(e){return typeof e=="string"&&e.length>0&&jo.has(e)}a(ka,"isKnownDiagnosticCode");function Ia(e){return typeof e!="string"||e.length===0?!1:jo.has(e)?!0:e.startsWith("ARKRULE_")}a(Ia,"isCataloguedOrArkRuleFamily");function Cn(e){if(!(typeof e!="string"||e.length===0))return jo.get(e)}a(Cn,"getDiagnosticCatalogEntry");function Bo(e){return`#${Cn(e)?.docsAnchor??e}`}a(Bo,"diagnosticDocsFragment");function ba(e){return`${Er}${Bo(e)}`}a(ba,"diagnosticDocsPath");function va(){return{schemaVersion:"1.0",docsPath:Er,codes:wn}}a(va,"serializeDiagnosticCatalog");function Ea(e){return Cn(e)?.fix}a(Ea,"catalogFixForRuleId");function Sa(e){return Cn(e)?.why}a(Sa,"catalogWhyForRuleId");var wa="1.1";var Ca="1.0";var Ct=class{static{a(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function Zd(e){return typeof e.initialState=="function"?e.initialState():e.initialState}a(Zd,"initialState");var Sr=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new Ct,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)??Zd(r),s=await r.project(t,o);await this.store.save(r.name,s);let i=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(i?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function xn(e){return new Sr(e)}a(xn,"createProjectionRegistry");var On="1.0";function Jd(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(Jd,"policyId");var Wo=class{constructor(t){this.data=t}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Pn(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,i=e.projections,l=e.eventContracts,c=e.observability,u=t?t.list().map(S=>({name:S.name,dependencies:t.getDependencies(S.name),productions:t.getProductions(S.name)})):[],f=t?t.getAllRelationships():[],y=n?n.getPolicies().map(S=>({id:Jd(S.name),name:S.name,severity:S.severity,tags:S.tags?[...S.tags]:void 0,owner:S.owner,version:S.version,rationale:S.rationale,enforcementMode:S.enforcementMode,deprecated:S.deprecated,replacedBy:S.replacedBy,description:S.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},d=p.filter(S=>(S.emits?.length??0)>0||(S.consumes?.length??0)>0).map(S=>({entity:S.name,emits:S.emits,consumes:S.consumes})),m=i?i.list().map(S=>({name:S.name,sourceIntents:S.sourceIntents,checkpoint:i.getCheckpoint(S.name)})):[],E={schemaVersion:"1.0",version:qn,exportedAt:new Date().toISOString(),intents:u,relationships:f,policies:y,entities:p,graph:g,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:m,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:d}};return new Wo(E)}a(Pn,"createArkManifest");var xa=0;function Oa(e){return xa+=1,`${e}-${Date.now()}-${xa}`}a(Oa,"createWorkflowId");function zo(e){return e instanceof Error?e.message:String(e)}a(zo,"errorMessage");function Qd(e){return new Promise(t=>{setTimeout(t,e)})}a(Qd,"sleep");async function eu(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((i,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}a(eu,"withTimeout");var xt=class{static{a(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let i=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||i){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},qo=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new xt}bus;options;static{a(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),i={id:r.id??Oa(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(i,r.tx),await this.audit("workflow.started",i,{workflowName:t}),this.executeSnapshot(i,o,r.tx)}async resume(t,n={}){let r=await this.get(t,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(t,n,r){try{let o=n.steps.filter(s=>!t.completedSteps.includes(s.name));for(let s of o)await this.runStep(t,s,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=zo(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let i=1;i<=s;i+=1){t.attempts[n.name]=i,await this.store.save(t,r);let l;try{l=await eu(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(i<s){o.delayMs&&await Qd(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:i,error:zo(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:i});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(i=>t.completedSteps.includes(i.name));for(let i=s.length-1;i>=0;i-=1){let l=s[i];if(l.compensate)try{await Promise.resolve(l.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:l.name})}catch(c){await this.audit("workflow.step.failed",t,{step:l.name,compensation:!0,error:zo(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Ot(e,t){return new qo(e,t)}a(Ot,"createWorkflowEngine");function Yo(e,t,n={}){let r=Ot(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??Oa(e.name),i="idle",l=[];return{id:s,definition:e,get status(){return i},get completedSteps(){return[...l]},async run(c){i="running",l=[];try{let u=await r.start(e.name,c,{id:s});i=u.status==="waiting"?"idle":u.status,l=[...u.completedSteps]}catch(u){let f=await r.get(s);throw i=f?.status==="waiting"?"idle":f?.status??"failed",l=f?.completedSteps??[],u}}}}a(Yo,"createSaga");Pt();function Ta(e){return Object.keys(e).sort()}a(Ta,"sortedKeys");function es(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],u=Math.max(l.length,c.length);for(let f=0;f<u;f+=1)es(l[f],c[f],`${n}[${f}]`,r);return}let o=e,s=t,i=new Set([...Ta(o),...Ta(s)]);for(let l of[...i].sort())es(o[l],s[l],n?`${n}.${l}`:l,r)}a(es,"walk");function ts(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}a(ts,"shadowInformationPackage");function Cr(e,t){let n=[];return es(e,t,"",n),{equal:n.length===0,diffs:n}}a(Cr,"compareInformationPackages");function ns(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Cr(e[n-1],e[n]));return t}a(ns,"replayInformationPackages");Dr();Gn();Bn();Bn();async function Wn(e,t={}){let n=$t({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Va(),Ua));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}a(Wn,"startArkRunInspector");Dr();Bn();Pt();Gn();Pt();var Mu=new Set(["singleton","transient"]);function ja(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return t}a(ja,"cloneComponent");function Hu(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Mu.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(Hu,"closedLifetime");function Ba(){let e=new Map,t=new Map,n=new Set;function r(i){let l=e.get(i);if(!l)throw new Error(`ArkRun component "${i}" is not registered.`);return l}a(r,"mustRecord");function o(i,l){if(!l.factory)throw new Error(`ArkRun component "${i}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(i))throw new Error(`ArkRun component "${i}" has a circular resolve.`);n.add(i);try{return l.factory()}finally{n.delete(i)}}a(o,"instantiate");function s(i,l){if(t.has(i))return t.get(i);let c=o(i,l);return t.set(i,c),c}return a(s,"singleton"),{register(i){let l=typeof i?.id=="string"?i.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=Hu(i.lifetime),u=Zo({id:l,lifetime:c,uses:i.uses,reactsTo:i.reactsTo,raises:i.raises,sends:i.sends,extendedInfo:i.extendedInfo});if(!u)throw new Error("ArkRun component id must be a non-empty string.");let f=typeof i.factory=="function"?i.factory:void 0;return e.set(l,{component:u,factory:f}),ja(u)},resolve(i){let l=r(i);return l.component.lifetime==="transient"?o(i,l):s(i,l)},resolveSingleton(i){let l=r(i);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${i}" is transient; resolveSingleton requires lifetime "singleton".`);return s(i,l)},snapshotComponents(){return[...e.values()].map(i=>ja(i.component))}}}a(Ba,"createComponentRegistry");Gn();function Ku(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Ae(e.source,t.source);return t.source=e.source,t}a(Ku,"stampMetadata");function Gu(){}a(Gu,"ignoreDetachedFailure");async function ls(e,t,n,r={}){let o=Kn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Ku(r),i=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let l=Promise.resolve(e.broker.send(i));o.awaitHandoff?await l:l.then(void 0,Gu)}return o}a(ls,"sendOnArkRunTransport");var Ur=1e3,Wa=0;function Uu(){return Wa+=1,`ark-kernel-${Date.now()}-${Wa}`}a(Uu,"nextKernelInstanceId");function za(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}a(za,"portConstructorId");function Kt(e={}){let t=e.strict??!0,n=e.instanceId??Uu(),r=e.profile??Qe,o=e.maxHistorySize??Ur,s=zt(),i=sn(),l=e.metadata??pn(),c=e.auditTrail===void 0,u=e.auditTrail??on({maxRecords:o}),f=e.eventContracts??nn(),y=e.eventBuffer===void 0&&e.outbox===void 0,p=e.eventBuffer??e.outbox??new _e,g=e.projections??xn({auditTrail:u}),d=new Oe([Zt(r),...e.policies??[]]),m=a(()=>{an(s,i,{requireRegisteredTargets:!0})},"syncGraph"),E=e.ephemeral??!0,S=e.broker,k=new gt({intentRegistry:s,dependencyGraph:i,policyEngine:d,strictRegistry:!0,validateIntentNaming:!0,auditTrail:u,eventContracts:f,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:p,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async D=>{await g.apply(D)}}),v=Ot(k,{auditTrail:u}),C=rn({registry:s,eventBus:k,graph:i}),N=Ba(),b=typeof S?.send=="function",T=y?"InMemoryEventBuffer":za(p,"EventBufferStore"),Ve=c?"InMemoryAuditStore":za(u,"AuditTrail"),ye=Mt({stores:[He(T,"outbox"),He(Ve,"audit"),He("InMemoryWorkflowStore","workflow")]}),we={instanceId:n,profile:r,registry:s,graph:i,metadata:l,auditTrail:u,eventContracts:f,eventBuffer:p,outbox:p,projections:g,policyEngine:d,eventBus:k,workflowEngine:v,observability:C,publisher(D){let q=k.createPublisher(D);return{source:q.source,publish:q.publish,send(Y,he,Ce={}){return ls({eventBus:k,broker:S,defaultEphemeral:E},Y,he,{...Ce,source:q.source})}}},send(D,q,Y={}){return ls({eventBus:k,broker:S,defaultEphemeral:E},D,q,Y)},register(D){return N.register(D)},resolve(D){return N.resolve(D)},resolveSingleton(D){return N.resolveSingleton(D)},getDependencyInformationPackage(){return fe({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(D){return Hn({kernelInstanceId:n,components:N.snapshotComponents()},D)},getInspectorSnapshot(D){return jn({kernelInstanceId:n,host:D?.host,port:D?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:C.report(),ephemeralDefault:E,brokerBound:b,hardening:ye})},startInspector(D){return Wn({getInspectorSnapshot:a(Y=>we.getInspectorSnapshot(Y),"getInspectorSnapshot"),requestGraph:a(Y=>we.requestGraph(Y),"requestGraph"),async listInspectorOutbox(){let[Y,he]=await Promise.all([p.list("pending"),p.list("failed")]);return Ke([...Y,...he],{sampleLimit:re})},async listInspectorWorkflows(){return Ge(await v.list(),{sampleLimit:re})}},D)},syncGraph:m,manifest(){return m(),Pn({registry:s,policyEngine:d,metadata:l,graph:i,profile:r,projections:g,eventContracts:f,observability:C})}};return we}a(Kt,"createArkKernel");function Vr(e={}){return Kt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}a(Vr,"createStrictArkKernel");function cs(e,t={}){let{profileName:n,...r}=t;return{...r,profile:un(e,{name:n})}}a(cs,"createOptionsFromConfig");function ds(e,t={}){return Kt(cs(e,t))}a(ds,"createArkKernelFromConfig");function us(e,t={}){return Vr(cs(e,t))}a(us,"createStrictArkKernelFromConfig");function ps(e,t={}){return jr(cs(e,t))}a(ps,"createLenientArkKernelFromConfig");function jr(e={}){return Kt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}a(jr,"createLenientArkKernel");0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_RUN_COMPONENT_LIFETIMES,ARK_RUN_EPHEMERAL_DEFAULT,ARK_RUN_GRAPH_DEFAULT_SLICE,ARK_RUN_GRAPH_NODE_KINDS,ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,ARK_RUN_GRAPH_SCHEMA_VERSION,ARK_RUN_GRAPH_SLICES,ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,ARK_RUN_INSPECTOR_DEFAULT_HOST,ARK_RUN_INSPECTOR_DEFAULT_PORT,ARK_RUN_INSPECTOR_EVENTS_PATH,ARK_RUN_INSPECTOR_GRAPH_PATH,ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,ARK_RUN_INSPECTOR_OUTBOX_PATH,ARK_RUN_INSPECTOR_SCHEMA_VERSION,ARK_RUN_INSPECTOR_SNAPSHOT_PATH,ARK_RUN_INSPECTOR_SSE_EVENT,ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,ARK_RUN_INSPECTOR_WORKFLOWS_PATH,ARK_RUN_TRANSPORT_KINDS,ArkRunInspectorBindError,ArkRunInspectorProductionError,DEFAULT_MAX_HISTORY_SIZE,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EventContractRegistryImpl,EventContractViolationError,InMemoryAuditStore,InMemoryEventBuffer,InMemoryOutboxStore,InMemoryReadModelStore,InMemoryWorkflowStore,IntentRegistry,InvalidArkRunGraphQueryError,InvalidArkRunSendOptionError,InvalidIntentNameError,LayerPolicyContextError,MANIFEST_SCHEMA_VERSION,ObservedLayerFlowViolationError,POLICY_DELTA_SCHEMA_VERSION,PolicyEngine,PolicyViolationError,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,SourceMetadataOverrideError,UnknownEventSourceError,UnregisteredIntentError,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,appendDecisionTape,architecturalPolicies,arkRunGraphQueryFromSearchParams,arkRunInspectorUrl,buildArkRunInspectorHardening,buildArkRunInspectorOutboxMonitor,buildArkRunInspectorSnapshot,buildArkRunInspectorWorkflowsMonitor,buildDependencyInformationPackage,buildPublishPolicyContext,catalogFixForRuleId,catalogWhyForRuleId,checkAdapterGovernance,checkContract,classifyArkPolicyDelta,classifyArkRunInspectorStoreDurability,closeArkRunGraphQuery,closedArkRunEphemeral,closedArkRunTransportKind,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,compareInformationPackages,createAICodeGate,createAdapter,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createArkKernel,createArkKernelFromConfig,createArkManifest,createArkTestHarness,createAuditTrail,createDependencyGraph,createElevenLayerArkConfig,createEventBus,createEventContractRegistry,createIntentRegistry,createLenientArkKernel,createLenientArkKernelFromConfig,createMetadataRegistry,createObservabilityReporter,createProjectionRegistry,createResolvedCandidateFacts,createSaga,createStrictArkKernel,createStrictArkKernelFromConfig,createWorkflowEngine,defaultIntentRegistry,defineArchitectureProfilePolicy,defineIntent,defineLayerPolicy,definePolicy,definePort,definePublishPolicy,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,formatArkRunGraphMermaid,formatArkRunInspectorSseEvent,getDiagnosticCatalogEntry,isArkRunInspectorLoopbackHost,isArkRunInspectorProductionEnv,isCataloguedOrArkRuleFamily,isKnownDiagnosticCode,isLayerPolicy,loadContract,loadResolvedCandidateFacts,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,replayInformationPackages,requestArkRunGraph,resolveArkRunInspectorBind,resolveArkRunSendPlan,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,shadowInformationPackage,stableSerialize,startArkRunInspector,syncRegistryToGraph,toAdapterDiagnostic,unavailableArkRunInspectorOutboxMonitor,unavailableArkRunInspectorWorkflowsMonitor,validateIntentName,version});
11
+ `,t);return e.slice(n,r===-1?e.length:r)}_chunkA5EIY3HIcjs.a.call(void 0, Ni,"lineAt");function Pi(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}_chunkA5EIY3HIcjs.a.call(void 0, Pi,"isImportLine");function vs(e,t,n){if(!t||!e.includes(t))return;let r=new Set,a=0,s=e.length,o=_chunkA5EIY3HIcjs.a.call(void 0, (l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(Pi(Ni(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;a<s;){let l=e[a],c=e[a+1];if(l==="/"&&c==="/"){for(;a<s&&e[a]!==`
12
+ `;)o(a,"comment"),a+=1;continue}if(l==="/"&&c==="*"){for(o(a,"comment"),o(a+1,"comment"),a+=2;a<s&&!(e[a]==="*"&&e[a+1]==="/");)o(a,"comment"),a+=1;a<s&&(o(a,"comment"),o(a+1,"comment"),a+=2);continue}if(l==='"'||l==="'"||l==="`"){let f=l;for(o(a,"string"),a+=1;a<s;){let g=e[a];if(g==="\\"){o(a,"string"),e[a+1]!==void 0&&o(a+1,"string"),a+=e[a+1]===void 0?1:2;continue}if(g===f){o(a,"string"),a+=1;break}o(a,"string"),a+=1}continue}o(a,"code"),a+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}_chunkA5EIY3HIcjs.a.call(void 0, vs,"mentionContext");function Ss(e){if(!e)return;let t=e.split("."),n=_nullishCoalesce(t[t.length-1], () => (""));return n?{className:t.length>1&&t[t.length-2]||null,name:n}:void 0}_chunkA5EIY3HIcjs.a.call(void 0, Ss,"symbolNeedle");function Li(e){return _nullishCoalesce(_optionalChain([Ss, 'call', _68 => _68(_optionalChain([e, 'access', _69 => _69.coverage, 'optionalAccess', _70 => _70.symbol])), 'optionalAccess', _71 => _71.name]), () => (e.id))}_chunkA5EIY3HIcjs.a.call(void 0, Li,"declaredLabel");function Is(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}_chunkA5EIY3HIcjs.a.call(void 0, Is,"sortedContentFiles");function Di(e,t,n=!0){let r=_nullishCoalesce(t.testFiles, () => ([])),a=new Set(r.map(R=>$e(R))),s=(_nullishCoalesce(t.coverageRoots, () => ([]))).filter(R=>typeof R=="string"&&R.length>0),o=_optionalChain([e, 'access', _72 => _72.coverage, 'optionalAccess', _73 => _73.test])!==!1&&n,l=Ss(_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.coverage, 'optionalAccess', _75 => _75.symbol]), () => (void 0))),c,f;if(o){for(let R of r){let u=t.fileContents[R];if(!u)continue;let m=wi(u,e.id);if(m!==void 0){if(s.length===0||bs(R,s)){c={file:R,title:m};break}f??={file:R,title:m}}}c??=f}let g;if(l)for(let R of Is(t.fileContents)){if(a.has($e(R)))continue;let u=t.fileContents[R];if(!u)continue;let m=l.className?Ti(u,l.className,l.name):Es(u,l.name);if(m){g={file:R,shape:m};break}}let h;if(!c&&!g){if(o)for(let R of r){let u=t.fileContents[R];if(!u)continue;let m=vs(u,e.id,!0);if(m){h={file:R,context:m};break}}if(!h&&l)for(let R of Is(t.fileContents)){if(a.has($e(R)))continue;let u=t.fileContents[R];if(!u)continue;let m=vs(u,l.name,!1);if(m){h={file:R,context:m};break}}}let p=c?{kind:"test-title",file:c.file,title:c.title}:g?{kind:"declaration",file:g.file,shape:g.shape}:h?{kind:"mention-only",file:h.file,context:h.context}:{kind:"none"};return p.kind==="mention-only"&&p.context==="comment"&&l&&Fi(t.fileContents,a,l.name,p.file)&&(p={kind:"declaration-miss",symbol:l.name}),{best:p,...c?{testTitle:c}:{},...g?{declaration:g}:{}}}_chunkA5EIY3HIcjs.a.call(void 0, Di,"rankCoverage");function Fi(e,t,n,r){let a=new RegExp(`(?:^|[^A-Za-z0-9_$])${fn(n)}(?=$|[^A-Za-z0-9_$])`),s=$e(r);for(let o of Object.keys(e)){if(t.has($e(o))||$e(o)===s)continue;let l=e[o];if(l&&a.test(gn(l,!0)))return!0}return!1}_chunkA5EIY3HIcjs.a.call(void 0, Fi,"symbolInCodeElsewhere");function $i(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}_chunkA5EIY3HIcjs.a.call(void 0, $i,"countsAsCoverage");function Mi(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}_chunkA5EIY3HIcjs.a.call(void 0, Mi,"mentionWhere");function Hi(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${Li(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Mi(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}_chunkA5EIY3HIcjs.a.call(void 0, Hi,"describeCoverage");function Cs(e){let t=_nullishCoalesce(e.arkRules.invariants, () => ([]));if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=_nullishCoalesce(e.testFiles, () => ([])),r=e.testGlobsMissing===!0||n.length===0,a=e.coverageBudgetExhausted===!0,s=e.coverageStats,o=ks(s),l=ks(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",f=(_nullishCoalesce(e.coverageRoots, () => ([]))).filter(u=>typeof u=="string"&&u.length>0),g=f.length>0,h=f.join(", "),p=[],R=[];for(let u of t){let m=_optionalChain([u, 'access', _76 => _76.coverage, 'optionalAccess', _77 => _77.test])!==!1,v=_optionalChain([u, 'access', _78 => _78.coverage, 'optionalAccess', _79 => _79.symbol]),w=!r&&m,A=Di(u,{fileContents:e.fileContents,testFiles:n,coverageRoots:f},w),b=A.best,O=[];w&&A.testTitle&&O.push("test-title"),A.declaration&&O.push("symbol");let G=$i(b),K,j;w&&A.testTitle&&(K=A.testTitle.file,g&&(j=!bs(K,f)));let I=_optionalChain([A, 'access', _80 => _80.declaration, 'optionalAccess', _81 => _81.file]),D=_optionalChain([A, 'access', _82 => _82.declaration, 'optionalAccess', _83 => _83.shape]),X=_optionalChain([u, 'access', _84 => _84.coverage, 'optionalAccess', _85 => _85.test])===!0||!!v||u.coverage===void 0,ne=_optionalChain([u, 'access', _86 => _86.coverage, 'optionalAccess', _87 => _87.test])===!1&&!v,ue=X&&G||ne&&u.mode!=="enforced"?!0:G,ae=r&&m&&!G;if(p.push({invariantId:u.id,layer:u.provenance.layer,sourceFile:u.provenance.sourceFile,mode:u.mode,covered:ue&&!ae,evidence:O,partial:ae,description:u.description,...K!==void 0?{testEvidenceFile:K}:{},...I!==void 0?{symbolEvidenceFile:I}:{},...D!==void 0?{shape:D}:{},...j!==void 0?{outsideDeclaredRoots:j}:{},coverageRootsDeclared:g}),j===!0&&K!==void 0&&R.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${u.id} is covered only by ${K}, 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:K,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:"warning",failsStrict:!1}),!ue||ae){let Ue=u.mode==="enforced"&&!ae,pe=r||n.length===0?"never-had-tests":"tests-disappeared";R.push({ruleId:"INVARIANT_UNCOVERED",message:(ae?a?`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).`:ne?`Invariant ${u.id} is enforced but declares no evidence (coverage.test is false and no coverage.symbol); set coverage.symbol, drop test:false, or keep mode "advisory".`:`Invariant ${u.id}: ${Hi(u,b)} (${pe==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(ae&&a?l:o),file:u.provenance.sourceFile,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:Ue?"error":"warning",failsStrict:Ue,kind:pe})}}return{coverage:p,violations:R,partial:p.some(u=>u.partial)}}_chunkA5EIY3HIcjs.a.call(void 0, Cs,"evaluateInvariantCoverage");function _s(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?Array.isArray(e.evidence)&&e.evidence.length===0?{ok:!1,reason:`Invariant ${e.invariantId} declares no evidence (coverage.test:false and no symbol); add coverage.symbol or a test title before promoting to enforced.`}:e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${_nullishCoalesce(e.testEvidenceFile, () => ("a test"))}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{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."}}_chunkA5EIY3HIcjs.a.call(void 0, _s,"canPromoteInvariant");function pn(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}_chunkA5EIY3HIcjs.a.call(void 0, pn,"nonEmptyPathStrings");function Ki(e){return!e||typeof e!="object"?[]:[...pn(e.testGlobs),...pn(e.coverageRoots)]}_chunkA5EIY3HIcjs.a.call(void 0, Ki,"configuredInvariantTestsPaths");function Ui(e){return Ki(e).length>0}_chunkA5EIY3HIcjs.a.call(void 0, Ui,"hasConfiguredInvariantTestsPath");function mn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&_optionalChain([t, 'access', _88 => _88.coverage, 'optionalAccess', _89 => _89.test])!==!1)}_chunkA5EIY3HIcjs.a.call(void 0, mn,"catalogDemandsInvariantTestsPath");function Os(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&mn(e.invariants);return e.adopted!==!0||!t?[]:Ui(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Ci,message:_i,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}_chunkA5EIY3HIcjs.a.call(void 0, Os,"collectMissingInvariantTestsPathFindings");function Vi(e){return!e||typeof e!="object"?[]:pn(e.coverageRoots)}_chunkA5EIY3HIcjs.a.call(void 0, Vi,"configuredCoverageRoots");function Gi(e){return Vi(e).length>0}_chunkA5EIY3HIcjs.a.call(void 0, Gi,"hasConfiguredCoverageRoots");function yn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}_chunkA5EIY3HIcjs.a.call(void 0, yn,"catalogHasEnforcedInvariant");function xs(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&yn(e.invariants)?Gi(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Oi,message:xi,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}_chunkA5EIY3HIcjs.a.call(void 0, xs,"collectMissingCoverageRootsFindings");var kn="1.0",ji="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function C(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${ji}`:void 0,r=_nullishCoalesce(t.nextAction, () => (n));e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}_chunkA5EIY3HIcjs.a.call(void 0, C,"addFinding");function H(e){return[...new Set(_nullishCoalesce(e, () => ([])))].sort()}_chunkA5EIY3HIcjs.a.call(void 0, H,"sortedUnique");function ie(e,t,n,r,a){let s=H(n),o=H(r),l=new Set(s),c=new Set(o),f=o.filter(h=>!l.has(h)),g=s.filter(h=>!c.has(h));f.length===0&&g.length===0||(f.length>0&&C(e,{kind:"added",path:t,classification:a.added,message:a.addedMessage,before:s,after:o}),g.length>0&&C(e,{kind:"removed",path:t,classification:a.removed,message:a.removedMessage,before:s,after:o}))}_chunkA5EIY3HIcjs.a.call(void 0, ie,"compareStringSets");function Qe(e,t,n,r,a,s,o){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?a:a==="strengthening"?"weakening":"strengthening",message:r?s:o,before:n,after:r})}_chunkA5EIY3HIcjs.a.call(void 0, Qe,"compareBoolean");function At(e,t){let n=new Map,r=new Set;for(let a of e){let s=t(a);n.has(s)?r.add(s):n.set(s,a)}return{values:n,duplicates:[...r].sort()}}_chunkA5EIY3HIcjs.a.call(void 0, At,"keyed");function Bi(e,t,n){let r=At(t,s=>s.name),a=At(n,s=>s.name);(r.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:a.duplicates});for(let s of[...new Set([...r.values.keys(),...a.values.keys()])].sort()){let o=r.values.get(s),l=a.values.get(s),c=`$.layers[${s}]`;if(!o&&l){C(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(o&&!l){C(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!l)continue;ie(e,`${c}.patterns`,o.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ie(e,`${c}.exclude`,o.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=yt(o),g=yt(l);ie(e,`${c}.forbiddenGlobals`,f.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ie(e,`${c}.capabilities`,f.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),H(o.intentPrefixes).join("\0")!==H(l.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:H(o.intentPrefixes),after:H(l.intentPrefixes)}),Qe(e,`${c}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Qe(e,`${c}.optional`,o.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.")}}_chunkA5EIY3HIcjs.a.call(void 0, Bi,"compareLayers");function zi(e,t,n){let r=_chunkA5EIY3HIcjs.a.call(void 0, o=>`${o.from}->${o.to}`,"keyOf"),a=At(t,r),s=At(n,r);(a.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:a.duplicates,after:s.duplicates});for(let o of[...new Set([...a.values.keys(),...s.values.keys()])].sort()){let l=a.values.get(o),c=s.values.get(o),f=`$.rules[${o}]`;if(!l&&c){c.allowed===!1?C(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):C(e,{kind:"allow-added",path:f,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&C(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&C(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let g=l.peerIsolation===!0,h=c.peerIsolation===!0;if(g!==h){let v=l.from===l.to&&c.from===c.to;C(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.peerIsolation`,classification:v?h?"strengthening":"weakening":"judgment-required",message:v?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:h})}H(l.sliceFolders).join("\0")!==H(c.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:H(l.sliceFolders),after:H(c.sliceFolders)});let p=_nullishCoalesce(l.sliceIdentity, () => ("path")),R=_nullishCoalesce(c.sliceIdentity, () => ("path"));if(p!==R&&C(e,{kind:"slice-identity-changed",path:`${f}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:p,after:R}),!g&&!h)continue;Rt(e,`${f}.sharedRoots`,"shared-roots",H(l.sharedRoots),H(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."),Rt(e,`${f}.allowedCrossSlice`,"cross-slice-allowance",H((_nullishCoalesce(l.allowedCrossSlice, () => ([]))).map(An)),H((_nullishCoalesce(c.allowedCrossSlice, () => ([]))).map(An)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let u=_nullishCoalesce(_chunkRNQHRDCQcjs.x.call(void 0, l.sharedImportsSlice), () => (null)),m=_nullishCoalesce(_chunkRNQHRDCQcjs.x.call(void 0, c.sharedImportsSlice), () => (null));if(u!==m){let v=Hs(m)>Hs(u);C(e,{kind:"shared-imports-slice",path:`${f}.sharedImportsSlice`,classification:v?"strengthening":"weakening",message:al(u,m),before:u,after:m})}else m==="deny-cross-parent"&&Rt(e,`${f}.sharedImportsSlice.stopAt`,"shared-walk-stop",Ts(l.sharedImportsSlice),Ts(c.sharedImportsSlice),"Composition roots now stop the cross-parent walk. Paths through them are no longer reported.","Composition roots no longer stop the cross-parent walk. Paths through them are reported again.");qi(e,f,l,c)}}_chunkA5EIY3HIcjs.a.call(void 0, zi,"compareRules");function ws(e){let t=e.childSlices;return t?JSON.stringify([H(_nullishCoalesce(t.sliceFolders, () => ([]))),_nullishCoalesce(t.sliceIdentity, () => ("path")),H(_nullishCoalesce(t.commonFolders, () => ([])))]):""}_chunkA5EIY3HIcjs.a.call(void 0, ws,"childSliceFoldersKey");function Ts(e){return H(_chunkRNQHRDCQcjs.y.call(void 0, e).map(t=>et(t.trim().replace(/\\/g,"/")).toLowerCase()))}_chunkA5EIY3HIcjs.a.call(void 0, Ts,"stopAtKeys");function Ns(e){return e==="always"?2:e==="auto"?1:0}_chunkA5EIY3HIcjs.a.call(void 0, Ns,"siblingRatchetRank");function Wi(e){return H((_nullishCoalesce(e, () => ([]))).map(t=>et(t.trim().replace(/\\/g,"/")).toLowerCase()))}_chunkA5EIY3HIcjs.a.call(void 0, Wi,"enforceKeys");function Ps(e){if(!e.childSlices)return null;let t=e.childSlices.siblings;return t==null||t==="deny"?{mode:"deny",enforce:[],ratchet:"auto"}:t==="advisory"?{mode:"advisory",enforce:[],ratchet:"auto"}:t.default==="deny"?{mode:"deny",enforce:[],ratchet:"auto"}:{mode:"advisory",enforce:Wi(t.enforce),ratchet:_chunkRNQHRDCQcjs.N.call(void 0, t)}}_chunkA5EIY3HIcjs.a.call(void 0, Ps,"childSliceSiblingPolicy");function qi(e,t,n,r){let a=Ps(n),s=Ps(r);if(a===null&&s===null)return;if(a===null&&s!==null){C(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:s.mode==="advisory"?"judgment-required":"strengthening",message:s.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(a!==null&&s===null){C(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(ws(n)!==ws(r)){C(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(a===null||s===null)return;if(a.mode!==s.mode){let c=s.mode==="advisory";C(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?s.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:a.mode,after:s.mode})}else if(a.mode==="advisory"&&(Yi(e,`${t}.childSlices.siblings.enforce`,a.enforce,s.enforce),a.ratchet!==s.ratchet)){let c=Ns(s.ratchet)>Ns(a.ratchet);C(e,{kind:"child-slices-siblings-ratchet",path:`${t}.childSlices.siblings.ratchet`,classification:c?"strengthening":"weakening",message:c?"New advisory sibling crossings past the baseline fail in more cases.":s.ratchet==="never"?"Advisory sibling crossings are measured only and never fail.":"New advisory sibling crossings past the baseline fail in fewer cases.",before:a.ratchet,after:s.ratchet})}let o=_optionalChain([n, 'access', _90 => _90.childSlices, 'optionalAccess', _91 => _91.parentMayImportChild])===!0,l=_optionalChain([r, 'access', _92 => _92.childSlices, 'optionalAccess', _93 => _93.parentMayImportChild])===!0;o!==l&&C(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:o,after:l}),Qi(e,t,n,r),Ji(e,t,n,r)}_chunkA5EIY3HIcjs.a.call(void 0, qi,"compareChildSlices");function Yi(e,t,n,r){if(JSON.stringify(n)===JSON.stringify(r))return;let a=r.filter(l=>!n.includes(l)),s=n.filter(l=>!r.includes(l)),o=a.length>0&&s.length>0;C(e,{kind:o?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:o?"judgment-required":a.length>0?"strengthening":"weakening",message:o?"Enforced sibling subtrees were added and removed in the same change.":a.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}_chunkA5EIY3HIcjs.a.call(void 0, Yi,"compareSiblingEnforceList");function An(e){return JSON.stringify([e.from,e.to])}_chunkA5EIY3HIcjs.a.call(void 0, An,"crossSliceKey");function Ls(e){return H((_nullishCoalesce(_optionalChain([e, 'access', _94 => _94.childSlices, 'optionalAccess', _95 => _95.allowedCrossSlice]), () => ([]))).map(An))}_chunkA5EIY3HIcjs.a.call(void 0, Ls,"childCrossSliceKeys");function Me(e){return et(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}_chunkA5EIY3HIcjs.a.call(void 0, Me,"allowanceSegments");function Ds(e,t){let n=Me(e),r=Me(t);if(n.length===0||n.length!==r.length)return!1;let a=!1;for(let s=0;s<n.length;s+=1)if(n[s]!==r[s]){if(n[s]==="*"&&r[s]!=="*"){a=!0;continue}return!1}return a}_chunkA5EIY3HIcjs.a.call(void 0, Ds,"patternWidens");function Xi(e,t){let n=JSON.parse(e),r=JSON.parse(t),a=Me(n[0]).join("/")===Me(r[0]).join("/"),s=Me(n[1]).join("/")===Me(r[1]).join("/"),o=Ds(n[0],r[0]),l=Ds(n[1],r[1]);return!(a||o)||!(s||l)?!1:o||l}_chunkA5EIY3HIcjs.a.call(void 0, Xi,"allowanceWidens");function Zi(e){return JSON.stringify([et(e.from.trim().replace(/\\/g,"/")).toLowerCase(),et(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}_chunkA5EIY3HIcjs.a.call(void 0, Zi,"aliasEntryKey");function Fs(e){return H((_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.childSlices, 'optionalAccess', _97 => _97.sliceAliases]), () => ([]))).map(Zi))}_chunkA5EIY3HIcjs.a.call(void 0, Fs,"sliceAliasKeys");function Ji(e,t,n,r){let a=Fs(n),s=Fs(r);if(JSON.stringify(a)===JSON.stringify(s))return;let o=s.filter(f=>!a.includes(f)),l=a.filter(f=>!s.includes(f)),c=o.length>0&&l.length>0;C(e,{kind:c?"slice-aliases-changed":o.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":o.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":o.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:a,after:s})}_chunkA5EIY3HIcjs.a.call(void 0, Ji,"compareSliceAliases");function Qi(e,t,n,r){let a=Ls(n),s=Ls(r);if(JSON.stringify(a)===JSON.stringify(s))return;let o=s.filter(c=>!a.includes(c)),l=a.filter(c=>!s.includes(c));if(o.length>0&&l.length>0&&l.filter(f=>!o.some(g=>Xi(g,f))).length===0){C(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:a,after:s});return}Rt(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",a,s,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}_chunkA5EIY3HIcjs.a.call(void 0, Qi,"compareChildCrossSliceAllowances");function Rt(e,t,n,r,a,s,o){if(JSON.stringify(r)===JSON.stringify(a))return;let l=a.filter(g=>!r.includes(g)),c=r.filter(g=>!a.includes(g)),f=l.length>0&&c.length>0;C(e,{kind:f?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:f?"judgment-required":l.length>0?"weakening":"strengthening",message:f?`${s} Entries were added and removed in the same change.`:l.length>0?s:o,before:r,after:a})}_chunkA5EIY3HIcjs.a.call(void 0, Rt,"compareDeclaredExceptions");function el(e,t,n){let r=_nullishCoalesce(t.safety, () => ({})),a=_nullishCoalesce(n.safety, () => ({}));for(let s of["maxTsSuppressions","maxAnyCasts"]){let o=_nullishCoalesce(r[s], () => (0)),l=_nullishCoalesce(a[s], () => (0));o!==l&&C(e,{kind:l>o?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>o?"weakening":"strengthening",message:l>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Qe(e,`$.safety.${s}`,r[s]===!0,a[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}_chunkA5EIY3HIcjs.a.call(void 0, el,"compareSafety");function hn(e){return e.mode==="enforced"?"enforced":"advisory"}_chunkA5EIY3HIcjs.a.call(void 0, hn,"arkRunMode");function Rn(e){return e.mode==="enforced"?"enforced":"advisory"}_chunkA5EIY3HIcjs.a.call(void 0, Rn,"arkOrderMode");function tl(e,t,n){let r=t.arkOrder,a=n.arkOrder,s="$.arkOrder";if(!r&&!a)return;if(!r&&a){C(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Rn(a)}).`,after:a});return}if(r&&!a){C(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!a)return;let o=Rn(r),l=Rn(a);if(o!==l){let c=o==="advisory"&&l==="enforced";C(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:o,after:l})}ie(e,`${s}.planeRoots`,r.planeRoots,a.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ie(e,`${s}.managedLayers`,r.managedLayers,a.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}_chunkA5EIY3HIcjs.a.call(void 0, tl,"compareArkOrder");function nl(e,t,n){let r=t.arkRun,a=n.arkRun,s="$.arkRun";if(!r&&!a)return;if(!r&&a){C(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${hn(a)}).`,after:a});return}if(r&&!a){C(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!a)return;let o=hn(r),l=hn(a);if(o!==l){let c=o==="advisory"&&l==="enforced";C(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:o,after:l})}ie(e,`${s}.compositionRoots`,r.compositionRoots,a.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ie(e,`${s}.managedLayers`,r.managedLayers,a.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Qe(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,a.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}_chunkA5EIY3HIcjs.a.call(void 0, nl,"compareArkRun");function rl(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"}_chunkA5EIY3HIcjs.a.call(void 0, rl,"overallClassification");function $s(e,t){return`${e}::${t}`}_chunkA5EIY3HIcjs.a.call(void 0, $s,"ruleKey");function Ms(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set($s(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set($s(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}_chunkA5EIY3HIcjs.a.call(void 0, Ms,"indexEffectiveRules");function sl(e,t,n,r,a,s){let o=new Map((_nullishCoalesce(s, () => ([]))).map(p=>[p.invariantId,p])),l=_nullishCoalesce(t.arkRules, () => ({})),c=_nullishCoalesce(n.arkRules, () => ({})),f=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of f){let R=l[p],u=c[p],m=`$.arkRules[${p}]`;if(R===void 0&&u!==void 0){C(e,{kind:"arkrules-ref-added",path:m,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:u});continue}if(R!==void 0&&u===void 0){C(e,{kind:"arkrules-ref-removed",path:m,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:R});continue}R!==u&&C(e,{kind:"arkrules-ref-path-changed",path:m,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:R,after:u})}let g=Ms(r),h=Ms(a);for(let p of[...new Set([...g.structure.keys(),...h.structure.keys()])].sort()){let R=g.structure.get(p),u=h.structure.get(p),m=`$.arkRules.structure[${p}]`;if(!R&&u){C(e,{kind:"arkrule-structure-added",path:m,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(R&&!u){C(e,{kind:"arkrule-structure-removed",path:m,classification:"weakening",message:`Structure ArkRule ${R.id} was removed.`,before:R});continue}if(!(!R||!u)){if(R.mode!==u.mode){let v=R.mode==="advisory"&&u.mode==="enforced";C(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${m}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:R.mode,after:u.mode})}R.sensor!==u.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${m}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:R.sensor,after:u.sensor})}}for(let p of[...new Set([...g.invariants.keys(),...h.invariants.keys()])].sort()){let R=g.invariants.get(p),u=h.invariants.get(p),m=`$.arkRules.invariants[${p}]`;if(!R&&u){C(e,{kind:"arkrule-invariant-added",path:m,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(R&&!u){C(e,{kind:"arkrule-invariant-removed",path:m,classification:"weakening",message:`Invariant ${R.id} was removed.`,before:R});continue}if(!(!R||!u)&&R.mode!==u.mode)if(R.mode==="advisory"&&u.mode==="enforced"){let w=_optionalChain([o, 'optionalAccess', _98 => _98.get, 'call', _99 => _99(u.id)]),A=_s(w);A.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${m}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:R.mode,after:u.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${m}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${A.reason}`,before:R.mode,after:u.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${m}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:R.mode,after:u.mode})}}_chunkA5EIY3HIcjs.a.call(void 0, sl,"compareArkRules");function vn(e,t,n){let r=[];ie(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ie(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ie(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Qe(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let a={off:0,soft:1,"framework-soft":1,strict:2},s=_nullishCoalesce(e.cyclePolicy, () => ("strict")),o=_nullishCoalesce(t.cyclePolicy, () => ("strict"));if(s!==o){let l=a[o]===a[s]?"judgment-required":a[o]>a[s]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:o})}return(_nullishCoalesce(e.frameworkOverlay, () => (null)))!==(_nullishCoalesce(t.frameworkOverlay, () => (null)))&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:_nullishCoalesce(e.frameworkOverlay, () => (null)),after:_nullishCoalesce(t.frameworkOverlay, () => (null))}),Bi(r,e.layers,t.layers),zi(r,e.rules,t.rules),el(r,e,t),sl(r,e,t,_optionalChain([n, 'optionalAccess', _100 => _100.baseArkRules]),_optionalChain([n, 'optionalAccess', _101 => _101.candidateArkRules]),_optionalChain([n, 'optionalAccess', _102 => _102.candidateInvariantCoverage])),nl(r,e,t),tl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:kn,classification:rl(r),findings:r}}_chunkA5EIY3HIcjs.a.call(void 0, vn,"classifyArkPolicyDelta");function In(e,t){if(!e||e.schemaVersion!==kn||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(a=>typeof a!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=H(e.findingIds),r=H(t.findingIds);return n.length===r.length&&n.every((a,s)=>a===r[s])}_chunkA5EIY3HIcjs.a.call(void 0, In,"policyDeltaAcknowledgementMatches");function et(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}_chunkA5EIY3HIcjs.a.call(void 0, et,"trimTrailingSlashes");function Hs(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}_chunkA5EIY3HIcjs.a.call(void 0, Hs,"sharedImportsSliceRank");function al(e,t){return t==="deny"?"A shared root may no longer import a slice.":e==="deny"&&t==="deny-cross-parent"?"A shared root may import a slice again, except when that hop carries another universe.":e==="deny"?"A shared root may import a slice again.":t==="deny-cross-parent"?"A slice may no longer reach another universe through a shared root. ark-check and CI report that path. The write hook and ESLint see one edge at a time and do not block it.":"A slice may reach another universe through a shared root again."}_chunkA5EIY3HIcjs.a.call(void 0, al,"sharedImportsSliceMessage");function _e(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}_chunkA5EIY3HIcjs.a.call(void 0, _e,"normalizePath");function Ks(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}_chunkA5EIY3HIcjs.a.call(void 0, Ks,"isIdentifierStart");function kt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}_chunkA5EIY3HIcjs.a.call(void 0, kt,"isIdentifierCharacter");function te(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}_chunkA5EIY3HIcjs.a.call(void 0, te,"skipWhitespace");function tt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,a="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:a,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(a+=e[t+1],t+=1):a+=s}}_chunkA5EIY3HIcjs.a.call(void 0, tt,"readString");function se(e,t,n){return e.startsWith(t,n)&&!kt(e[n-1])&&!kt(e[n+t.length])}_chunkA5EIY3HIcjs.a.call(void 0, se,"isWordAt");function Us(e,t){let n=te(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=te(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!se(e,"type",n))return!1;let a=te(e,n+4);if(a>=e.length||e[a]===","||e[a]==="}"||se(e,"as",a)||!Ks(e[a]))return!1;for(n=a;n<e.length&&kt(e[n]);)n+=1;if(n=te(e,n),se(e,"as",n)){if(n=te(e,n+2),!Ks(e[n]))return!1;for(;n<e.length&&kt(e[n]);)n+=1}r=!0}return!1}_chunkA5EIY3HIcjs.a.call(void 0, Us,"bracedNamedBindingsAreTypeOnly");function ol(e,t){if(t=te(e,t+6),e[t]==="(")return tt(e,te(e,t+1));let n=!1;if(se(e,"type",t)){let a=te(e,t+4);e[a]!==","&&!se(e,"from",a)&&(n=!0)}else Us(e,t)&&(n=!0);let r=Vs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}_chunkA5EIY3HIcjs.a.call(void 0, ol,"specifierAfterImport");function il(e,t){t=t+6;let n=te(e,t),r=!1;if(se(e,"type",n)){let s=te(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Us(e,n)&&(r=!0);let a=Vs(e,t,!1);return a&&r?{...a,typeOnly:!0}:a}_chunkA5EIY3HIcjs.a.call(void 0, il,"specifierAfterExport");function Vs(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(se(e,"from",t))return tt(e,te(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return tt(e,t);if(t>0&&(se(e,"import",t)||se(e,"export",t)))return}}_chunkA5EIY3HIcjs.a.call(void 0, Vs,"specifierInStaticStatement");function ll(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}_chunkA5EIY3HIcjs.a.call(void 0, ll,"skipTemplateLiteral");function cl(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=te(e,t+7);if(e[r]!=="(")return;r=te(e,r+1);let a=tt(e,r);return a?{...a,requireCall:!0}:void 0}_chunkA5EIY3HIcjs.a.call(void 0, cl,"specifierAfterRequire");function dl(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(`
13
+ `,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=ll(e,n);continue}if(r==="'"||r==='"'){let s=tt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let a=r==="i"&&se(e,"import",n)?ol(e,n):r==="e"&&se(e,"export",n)?il(e,n):r==="r"&&se(e,"require",n)?cl(e,n):void 0;a&&(t.push(a),n=a.offset+a.excerpt.length-1)}return t}_chunkA5EIY3HIcjs.a.call(void 0, dl,"moduleSpecifiers");function Gs(e,t){let n=[],r=[];for(let a of dl(e.content)){let s=a.value;if(!s.startsWith(".")){if(a.typeOnly)continue;let f=Be(s);if(!f)continue;let g=e.content.slice(0,a.offset).split(`
14
+ `).length;r.push({file:e.path,symbol:s,capability:f,evidence:{kind:"import",file:e.path,line:g,excerpt:a.excerpt}});continue}let o=e.content.slice(0,a.offset).split(`
15
+ `).length,l={kind:"import",file:e.path,line:o,excerpt:a.excerpt},c=ul(e.path,s,t);n.push({from:e.path,specifier:s,to:_nullishCoalesce(_optionalChain([c, 'optionalAccess', _103 => _103.path]), () => (null)),resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:_nullishCoalesce(_optionalChain([c, 'optionalAccess', _104 => _104.layer]), () => (null)),evidence:l})}return{edges:n,capabilityUses:r}}_chunkA5EIY3HIcjs.a.call(void 0, Gs,"moduleFactsFor");function ul(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let a=r.join("/");for(let s of[a,`${a}.ts`,`${a}.tsx`,`${a}.mts`,`${a}.cts`,`${a}/index.ts`,`${a}/index.tsx`]){let o=n.get(s);if(o)return o}}_chunkA5EIY3HIcjs.a.call(void 0, ul,"resolveSpecifier");function js(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let a=_chunkRNQHRDCQcjs.O.call(void 0, t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});if(!a)continue;let s=a.rule;n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:_nullishCoalesce(_chunkRNQHRDCQcjs.J.call(void 0, s,a.sliceVerdict), () => (`${s.from} must not depend on ${s.to}.`)),edge:r,evidence:r.evidence})}return n}_chunkA5EIY3HIcjs.a.call(void 0, js,"violationsFor");var pl={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function fl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}_chunkA5EIY3HIcjs.a.call(void 0, fl,"hasActiveArkRules");function gl(e,t){return fl(e,t)?Z(W(ms({config:e,arkRules:t,warnings:[]}))):Z(W(cn(e)))}_chunkA5EIY3HIcjs.a.call(void 0, gl,"policyHashFor");function vt(e,t,n){let r=typeof e=="string"?_chunkRNQHRDCQcjs.ca.call(void 0, e,t):_chunkRNQHRDCQcjs.ba.call(void 0, e,t),a=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _105 => _105.arkRules]), () => (Je()));return{...r,arkRules:a,policyHash:gl(r.config,a)}}_chunkA5EIY3HIcjs.a.call(void 0, vt,"loadContract");function Bs(e){let t=vt(e.baseConfig,_nullishCoalesce(e.baseSource, () => ("base ark.config.json")),{arkRules:e.baseArkRules}),n=vt(e.candidateConfig,_nullishCoalesce(e.candidateSource, () => ("candidate ark.config.json")),{arkRules:e.candidateArkRules}),r=vn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),a=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=a.length>0,o=s&&In(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:a});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:a,requiresAcknowledgement:s,acknowledged:o,valid:!s||o}}_chunkA5EIY3HIcjs.a.call(void 0, Bs,"analyzePolicyDelta");function nt(e){let t=e.files.map(h=>{let p=_e(h.path);return{path:p,content:h.content,contentHash:Z(h.content),layer:_nullishCoalesce(_chunkRNQHRDCQcjs.B.call(void 0, p,e.contract.config.layers), () => (null))}}).sort((h,p)=>h.path.localeCompare(p.path)),n=new Map(t.map(h=>[h.path,h])),r=[],a=[];for(let h of t){let p=Gs(h,n);r.push(...p.edges),a.push(...p.capabilityUses)}let s=js(r,e.contract.config),o=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 a){let p=_optionalChain([n, 'access', _106 => _106.get, 'call', _107 => _107(h.file), 'optionalAccess', _108 => _108.layer]);if(!p)continue;let R=o.get(p),u=Re(h.symbol,_nullishCoalesce(_optionalChain([R, 'optionalAccess', _109 => _109.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}_optionalChain([l, 'access', _110 => _110.get, 'call', _111 => _111(p), 'optionalAccess', _112 => _112.has, 'call', _113 => _113(h.capability)])&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let c=t.length===0?"complete":"partial",f=c==="complete"?[]:[{...pl}],g={schemaVersion:ln,policyHash:e.contract.policyHash,compilerOptionsHash:Z(W(_nullishCoalesce(e.compilerOptions, () => ({})))),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:a,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:f,valid:c==="complete"&&s.length===0,ir:g}}_chunkA5EIY3HIcjs.a.call(void 0, nt,"analyzeProject");function It(e){let t=new Map(e.files.map(n=>[_e(n.path),n]));for(let n of e.changes){let r=_e(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return nt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}_chunkA5EIY3HIcjs.a.call(void 0, It,"analyzeChange");function zs(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=_nullishCoalesce(e.edge.to, () => (e.edge.specifier));return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}_chunkA5EIY3HIcjs.a.call(void 0, zs,"explainViolation");function En(e){let t=0,n=new Map,r=new Map,a=new Set,s=[],o=[],l=_chunkA5EIY3HIcjs.a.call(void 0, c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),a.add(c);for(let h of[..._nullishCoalesce(e.get(c), () => ([]))].sort())e.has(h)&&(n.has(h)?a.has(h)&&r.set(c,Math.min(_nullishCoalesce(r.get(c), () => (0)),_nullishCoalesce(n.get(h), () => (0)))):(l(h),r.set(c,Math.min(_nullishCoalesce(r.get(c), () => (0)),_nullishCoalesce(r.get(h), () => (0))))));if(r.get(c)!==n.get(c))return;let f=[],g;do{if(g=s.pop(),g===void 0)break;a.delete(g),f.push(g)}while(g!==c);f.length>1&&o.push(f.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return o.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}_chunkA5EIY3HIcjs.a.call(void 0, En,"detectArchitectureCycles");function He(e){let t=e.contentViolations.map(s=>({...s})),n=(_nullishCoalesce(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)&&_optionalChain([r, 'access', _114 => _114.get, 'call', _115 => _115(s.from), 'optionalAccess', _116 => _116.add, 'call', _117 => _117(s.to)]),!s.to||!s.fromLayer||!s.toLayer)continue;let o=_chunkRNQHRDCQcjs.O.call(void 0, e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!o){let p=_chunkRNQHRDCQcjs.P.call(void 0, e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});p&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:p.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:p.toPath,toSlice:p.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${p.fromPath} \u2192 slice ${p.toSlice} (${p.toPath}). The wall is direct-only.`});continue}let l=o.rule,c=!!l.peerIsolation,f=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),g=o.sliceVerdict,h=g?_chunkRNQHRDCQcjs.K.call(void 0, {surface:"import",verdict:g,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.message,childMessage:_optionalChain([l, 'access', _118 => _118.childSlices, 'optionalAccess', _119 => _119.message])}):_nullishCoalesce(l.message, () => (`${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}:{},..._chunkRNQHRDCQcjs.L.call(void 0, g),message:f?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...f?{failsStrict:!1,severity:"warning"}:{}})}t.push(...hl(e));let a=String(_nullishCoalesce(e.config.cyclePolicy, () => ("strict"))).toLowerCase();if(a!=="off"){let s=En(r);a==="soft"||a==="framework-soft"?n.push(...s.map(o=>({...o,message:`${o.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}}_chunkA5EIY3HIcjs.a.call(void 0, He,"evaluateArchitectureGraph");var ml="CROSS_PARENT_VIA_SHARED",yl="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function Ws(e,t,n){for(let r of _nullishCoalesce(e, () => ([])))if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&_chunkRNQHRDCQcjs.x.call(void 0, r.sharedImportsSlice)==="deny-cross-parent")return r}_chunkA5EIY3HIcjs.a.call(void 0, Ws,"denyingCrossParentRule");function bn(e,t,n,r){let a=_chunkRNQHRDCQcjs.G.call(void 0, n,e,_chunkRNQHRDCQcjs.Q.call(void 0, e,t,r)).universeId;return a?{kind:"slice",id:a}:_chunkRNQHRDCQcjs.D.call(void 0, n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}_chunkA5EIY3HIcjs.a.call(void 0, bn,"placeFile");function qs(e,t){return _chunkRNQHRDCQcjs.F.call(void 0, t,_chunkRNQHRDCQcjs.y.call(void 0, e.sharedImportsSlice))}_chunkA5EIY3HIcjs.a.call(void 0, qs,"isWalkStop");function hl(e){let t=_nullishCoalesce(e.rules, () => ([]));if(!t.some(s=>_chunkRNQHRDCQcjs.x.call(void 0, s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let o=Rl(s);if(!o)continue;let l=n.get(o.from);l?l.push(o):n.set(o.from,[o])}for(let s of n.values())s.sort((o,l)=>o.to<l.to?-1:o.to>l.to?1:o.line-l.line);let r=new Map,a=[...n.values()].flat();a.sort((s,o)=>s.from<o.from?-1:s.from>o.from?1:s.to<o.to?-1:s.to>o.to?1:0);for(let s of a){let o=Ws(t,s.fromLayer,s.toLayer);if(!o)continue;let l=bn(o,s.fromLayer,s.from,e.config.layers),c=bn(o,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||qs(o,s.to))continue;let f=[{file:s.to,path:[s.from,s.to]}],g=new Set([s.to]);for(;f.length>0;){let h=f.shift();if(!h)break;for(let p of _nullishCoalesce(n.get(h.file), () => ([]))){let R=Ws(t,p.fromLayer,p.toLayer);if(!R)continue;let u=bn(R,p.fromLayer,p.to,e.config.layers);if(u.kind==="shared"){if(g.has(p.to)||qs(R,p.to))continue;g.add(p.to),f.push({file:p.to,path:[...h.path,p.to]});continue}if(u.kind!=="slice"||u.id.toLowerCase()===l.id.toLowerCase()||_chunkRNQHRDCQcjs.E.call(void 0, o.allowedCrossSlice,l.id,u.id))continue;if(o.sliceIdentity==="stars"){let b=_chunkRNQHRDCQcjs.H.call(void 0, o,_chunkRNQHRDCQcjs.Q.call(void 0, o,s.fromLayer,e.config.layers),s.from,p.to);if(b.crossSliceAllowed||b.from.universeId&&b.from.universeId===b.to.universeId)continue}let m=[...h.path,p.to],v=`${s.from}\0${p.to}`,w={file:s.from,target:p.to,line:s.line,fromLayer:s.fromLayer,toLayer:p.toLayer,fromSlice:l.id,toSlice:u.id,path:m},A=r.get(v);(!A||m.length<A.path.length||m.length===A.path.length&&m.join("\0")<A.path.join("\0"))&&r.set(v,w)}}}return[...r.values()].sort((s,o)=>s.file<o.file?-1:s.file>o.file?1:s.target<o.target?-1:s.target>o.target?1:0).map(s=>{let o=_chunkRNQHRDCQcjs.I.call(void 0, s.fromSlice),l=_chunkRNQHRDCQcjs.I.call(void 0, s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:ml,file:s.file,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.target,peerIsolation:!0,...o&&l?{universeFrom:o,universeTo:l}:{},via:s.path.slice(1,-1),message:`${s.fromLayer} reaches ${s.toLayer} in another universe through a shared root (${s.path.join(" \u2192 ")}): cross-parent via shared ${s.fromSlice} \u2192 ${s.toSlice}. ${yl}`}})}_chunkA5EIY3HIcjs.a.call(void 0, hl,"crossParentViaSharedViolations");function Rl(e){if(!(!e.to||e.to===e.from||!e.fromLayer||!e.toLayer))return{from:e.from,to:e.to,line:e.line,fromLayer:e.fromLayer,toLayer:e.toLayer}}_chunkA5EIY3HIcjs.a.call(void 0, Rl,"valueHop");function Ys(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);_optionalChain([r, 'optionalAccess', _120 => _120[1]])&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}_chunkA5EIY3HIcjs.a.call(void 0, Ys,"structureFreezeTarget");var Al=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,kl=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,vl=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,Il=["db","tx","client","prisma","prismaClient","drizzle"],bl="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",El="\\bINSERT\\s+INTO\\b|\\bUPDATE\\s+[A-Za-z_][\\w.]*\\s+SET\\b|\\bDELETE\\s+FROM\\b",Xs="\\((?:[^()]|\\([^()]*\\))*\\)",Sl=`\\bnew\\s+PrismaClient\\s*${Xs}|\\bdrizzle\\s*${Xs}`,Cl=/(?<![\w$])([A-Za-z_$][\w$]*)\s*[?!]?\s*(?::[^=;\n]+)?=(?![=>])\s*(?:await\s+)?(?:new\s+(?:PrismaClient|Pool|Client|MongoClient|Sequelize|Kysely|Knex)\b|(?:drizzle|knex|Knex|postgres)\s*\()/g,_l=/(?<![\w$])([A-Za-z_$][\w$]*)\s*[?!]?\s*:\s*(?:Readonly\s*<\s*)?(?:Prisma\s*\.\s*TransactionClient|PrismaClient|Pool|PoolClient|MongoClient|Sequelize|Kysely|Knex|DataSource|EntityManager|NodePgDatabase|PostgresJsDatabase|BetterSQLite3Database|MySql2Database|LibSQLDatabase)\b/g;function Ol(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_chunkA5EIY3HIcjs.a.call(void 0, Ol,"escapeRegExp");function bt(e){return Al.test(e)||kl.test(e)}_chunkA5EIY3HIcjs.a.call(void 0, bt,"sourceImportsPersistenceDriverText");function Zs(e,t,n){let r=new RegExp(e.source,"g"),a;for(;(a=r.exec(t))!==null;)a[1]&&n.add(a[1])}_chunkA5EIY3HIcjs.a.call(void 0, Zs,"collectFirstGroup");function xl(e){let t=new Set;Zs(Cl,e,t),Zs(_l,e,t);let n=new RegExp(vl.source,"g"),r;for(;(r=n.exec(e))!==null;)for(let a of(_nullishCoalesce(r[1], () => (""))).split(",")){let s=a.trim().replace(/^type\s+/,"").split(/\s+as\s+/),o=(_nullishCoalesce(_nullishCoalesce(s[1], () => (s[0])), () => (""))).trim();/^[A-Za-z_$][\w$]*$/.test(o)&&t.add(o)}return[...t].sort()}_chunkA5EIY3HIcjs.a.call(void 0, xl,"persistenceClientBindings");function Sn(e){let t=[...Il,...xl(e)].map(Ol).join("|");return new RegExp(`(?:\\b(?:${t})(?![\\w$])|${Sl})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${bl}\\s*\\(|${El}`,"i").test(e)}_chunkA5EIY3HIcjs.a.call(void 0, Sn,"sourceHasPersistenceWrite");var wl=["no-anemic-model"],ea=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],_u=new RegExp(`\\b(${ea.join("|")})\\b`),ta="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Ou=new RegExp(`\\bthis\\.${ta}\\.push\\s*\\(`),xu=new RegExp(`^this\\.${ta}\\s*=\\s*\\[\\s*\\]`);function Tl(){return`${ea.join(", ")}, or events-array .push(`}_chunkA5EIY3HIcjs.a.call(void 0, Tl,"expectedDomainInvariantWordsPhrase");function na(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}_chunkA5EIY3HIcjs.a.call(void 0, na,"shapeTruncatedUntil");function Nl(e){let t=na(e);return t==null?"":` shape analysed until character ${t}`}_chunkA5EIY3HIcjs.a.call(void 0, Nl,"shapeTruncationSuffix");function Js(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}_chunkA5EIY3HIcjs.a.call(void 0, Js,"escapeGlobLiteral");function Pl(e){let t="";for(let r=0;r<e.length;r+=1){let a=e[r];if(a==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=a}let n="";for(let r=0;r<t.length;r+=1){let a=t[r];a==="\\"&&r+1<t.length?(n+=Js(t[r+1]),r+=1):a==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":a==="?"?n+="[^/]":n+=Js(a)}return new RegExp(`^${n}$`)}_chunkA5EIY3HIcjs.a.call(void 0, Pl,"globToRegExp");function Ke(e,t){return!t||t.length===0?!0:t.some(n=>Pl(n).test(e))}_chunkA5EIY3HIcjs.a.call(void 0, Ke,"matchesAppliesTo");function ra(e){return wl.includes(e)}_chunkA5EIY3HIcjs.a.call(void 0, ra,"isTier2");function sa(e){return e.mode==="enforced"&&!ra(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}_chunkA5EIY3HIcjs.a.call(void 0, sa,"severityFor");function ve(e,t,n,r=1){let{severity:a,failsStrict:s}=sa(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:a,sensor:e.sensor,failsStrict:s}}_chunkA5EIY3HIcjs.a.call(void 0, ve,"baseViolation");function Et(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}_chunkA5EIY3HIcjs.a.call(void 0, Et,"isInRuleLayer");function St(e,t,n){return t.filter(r=>!(!r.exported||!Ke(r.file,e.appliesTo)||!Et(r.file,e,n)))}_chunkA5EIY3HIcjs.a.call(void 0, St,"shapesForRule");function Cn(e,t,n){let r=na(t);if(r!=null)return ve(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}_chunkA5EIY3HIcjs.a.call(void 0, Cn,"truncatedShapeViolation");function Ll(e,t,n){let r=[];for(let a of St(e,t,n)){let s=Cn(e,a,"members");s&&r.push(s),(a.hasPublicSetters||a.hasPublicMutableFields)&&r.push(ve(e,a.file,`Exported class ${a.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}_chunkA5EIY3HIcjs.a.call(void 0, Ll,"evaluateAggregatePrivateState");function Dl(e,t,n){let r=[];for(let a of St(e,t,n)){let s=Cn(e,a,"constructors and factories");if(s&&r.push(s),a.hasPublicConstructor&&!a.hasStaticFactory){if(!(a.hasPublicMutableFields||a.hasPublicSetters||(_nullishCoalesce(_optionalChain([a, 'access', _121 => _121.mutatingMethods, 'optionalAccess', _122 => _122.length]), () => (0)))>0))continue;r.push(ve(e,a.file,`Exported class ${a.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}_chunkA5EIY3HIcjs.a.call(void 0, Dl,"evaluateAlwaysValidFactory");function Fl(e,t,n){let r=[],a=Tl();for(let s of St(e,t,n)){let o=Nl(s),l=Cn(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(ve(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${a} (sensor domain-event-on-mutation).${o}`))}return r}_chunkA5EIY3HIcjs.a.call(void 0, Fl,"evaluateDomainEventOnMutation");function $l(e,t){let n=[];for(let r of t.files)Ke(r,e.appliesTo)&&Et(r,e,t.layerForFile)&&_optionalChain([t, 'access', _123 => _123.fileHints, 'optionalAccess', _124 => _124[r], 'optionalAccess', _125 => _125.orchestrationHeavy])&&n.push(ve(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}_chunkA5EIY3HIcjs.a.call(void 0, $l,"evaluateOrchestrationOnly");function Ml(e,t){let n=[];for(let r of t.files)Ke(r,e.appliesTo)&&Et(r,e,t.layerForFile)&&_optionalChain([t, 'access', _126 => _126.fileHints, 'optionalAccess', _127 => _127[r], 'optionalAccess', _128 => _128.adapterThick])&&n.push(ve(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}_chunkA5EIY3HIcjs.a.call(void 0, Ml,"evaluateThinAdapter");function Hl(e,t){let n=[];for(let r of t.files)Ke(r,e.appliesTo)&&Et(r,e,t.layerForFile)&&_optionalChain([t, 'access', _129 => _129.fileHints, 'optionalAccess', _130 => _130[r], 'optionalAccess', _131 => _131.persistenceWrite])&&n.push(ve(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}_chunkA5EIY3HIcjs.a.call(void 0, Hl,"evaluateWritesViaAggregate");function Kl(e,t,n){let r=[];for(let a of St(e,t,n))if(a.dataOnly===!0){let s=ve(e,a.file,`Exported type ${a.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}_chunkA5EIY3HIcjs.a.call(void 0, Kl,"evaluateNoAnemicModel");function aa(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Ll(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Dl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Fl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...$l(n,e));break;case"thin-adapter":t.push(...Ml(n,e));break;case"writes-via-aggregate":t.push(...Hl(n,e));break;case"no-anemic-model":t.push(...Kl(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))}_chunkA5EIY3HIcjs.a.call(void 0, aa,"evaluateArkRuleSensors");function oa(e,t){let n=[],r=t.map(a=>a.replace(/\\/g,"/"));for(let a of e.structure){if(!a.appliesTo||a.appliesTo.length===0||r.some(c=>Ke(c,a.appliesTo)))continue;let{severity:o,failsStrict:l}=sa(a);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${a.id}" appliesTo matched zero governed files (patterns: ${a.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:a.provenance.sourceFile,line:1,fromLayer:a.provenance.layer,arkruleId:a.id,arkruleSource:a.provenance.sourceFile,severity:o,sensor:a.sensor,failsStrict:l})}for(let a of _nullishCoalesce(e.invariants, () => ([]))){if(!a.appliesTo||a.appliesTo.length===0||r.some(l=>Ke(l,a.appliesTo)))continue;let o=a.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${a.id}" appliesTo matched zero governed files (patterns: ${a.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:a.provenance.sourceFile,line:1,fromLayer:a.provenance.layer,arkruleId:a.id,arkruleSource:a.provenance.sourceFile,severity:o?"error":"warning",sensor:"invariant-coverage",failsStrict:o})}return n.sort((a,s)=>a.file.localeCompare(s.file)||a.arkruleId.localeCompare(s.arkruleId)||a.message.localeCompare(s.message))}_chunkA5EIY3HIcjs.a.call(void 0, oa,"collectEmptyAppliesToFindings");var Qs=64;function Ul(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}_chunkA5EIY3HIcjs.a.call(void 0, Ul,"stripTrailingDots");function Vl(e){let t=e.trim(),n=t.length>Qs?t.slice(0,Qs):t;return Ul(n)}_chunkA5EIY3HIcjs.a.call(void 0, Vl,"normalizeIntentPrefix");function Gl(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}_chunkA5EIY3HIcjs.a.call(void 0, Gl,"layerNameLooksDomain");function jl(e){return e.some(t=>{let n=Vl(t);return n==="Domain"||n.startsWith("Domain.")})}_chunkA5EIY3HIcjs.a.call(void 0, jl,"ownsDomainIntent");function Bl(e,t=[]){return Gl(e)||jl(t)}_chunkA5EIY3HIcjs.a.call(void 0, Bl,"isDomainRoleLayerName");function ia(e){if(e.arkRulesActive!==!0)return[];let t=(_nullishCoalesce(e.layers, () => ([]))).filter(c=>Bl(c.name,_nullishCoalesce(c.intentPrefixes, () => ([])))).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(_nullishCoalesce(e.files, () => ([]))).some(c=>{let f=typeof c.layer=="string"?c.layer:"";return f.length>0&&n.has(f)}))return[];if((_nullishCoalesce(e.arkRules.invariants, () => ([]))).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=_nullishCoalesce(t.find(c=>_optionalChain([e, 'access', _132 => _132.arkRules, 'access', _133 => _133.byLayer, 'optionalAccess', _134 => _134[c]])), () => (t[0])),o=_nullishCoalesce(_optionalChain([e, 'access', _135 => _135.arkRules, 'access', _136 => _136.byLayer, 'optionalAccess', _137 => _137[s], 'optionalAccess', _138 => _138.sourceFile]), () => (`arkrules/${s}.json`)),l=(_nullishCoalesce(e.arkRules.structure, () => ([]))).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!ra(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${o}.`,file:o,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:o,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}_chunkA5EIY3HIcjs.a.call(void 0, ia,"collectEmptyInvariantCatalogFindings");function zl(e){return e==="PersistenceAdapters"}_chunkA5EIY3HIcjs.a.call(void 0, zl,"isPersistenceDriverLayer");function Wl(e,t){if(bt(e))return!0;if(!t)return!1;for(let n of t){if(zl(n.layer))return!0;let r=n.specifier;if(!r)continue;let a=`from '${r}'`;if(bt(a))return!0}return!1}_chunkA5EIY3HIcjs.a.call(void 0, Wl,"sourceImportsPersistenceDriver");var ql=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,Yl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Xl=/\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*=/,Zl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Jl(e,t,n){if(!t)return null;let r=Wl(t,n),a=r&&Sn(t);if(t.length<40)return a?{persistenceWrite:!0}:null;let s=_nullishCoalesce(t.match(new RegExp(Xl.source,"g")), () => ([])),o=_nullishCoalesce(t.match(new RegExp(Zl.source,"g")), () => ([])),l=(_nullishCoalesce(t.match(/\bif\s*\(/g), () => ([]))).length,c=(_nullishCoalesce(t.match(/\bswitch\s*\(/g), () => ([]))).length,f=s.length>=2||s.length>=1&&o.length>=2||o.length>=3&&l+c>=6,g=ql.test(t)||Yl.test(t),h=s.length>=1||o.length>=2,p=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),R=r&&h||g&&h||r&&p&&(l>=4||s.length>=1)||g&&r;return!f&&!R&&!a?null:{...f?{orchestrationHeavy:!0}:{},...R?{adapterThick:!0}:{},...a?{persistenceWrite:!0}:{}}}_chunkA5EIY3HIcjs.a.call(void 0, Jl,"deriveArkRuleFileHints");function la(e,t){let n={};for(let[r,a]of Object.entries(e)){let s=r.replace(/\\/g,"/"),o=Jl(r,a,_optionalChain([t, 'optionalAccess', _139 => _139[s]]));o&&(n[s]=o)}return n}_chunkA5EIY3HIcjs.a.call(void 0, la,"buildArkRuleFileHints");function Ql(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}}_chunkA5EIY3HIcjs.a.call(void 0, Ql,"normalizeExtraMergeTeethClassification");function Ct(e){let t=Ql(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(_nullishCoalesce(n, () => (0)))>=50&&(_nullishCoalesce(r, () => (0)))>=1}_chunkA5EIY3HIcjs.a.call(void 0, Ct,"extraMergeTeethAllowed");function ca(e){let t=e.length,n=0,r=new Set;for(let a of e){let s=typeof a.layer=="string"&&a.layer.length>0?a.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}_chunkA5EIY3HIcjs.a.call(void 0, ca,"classifyResolvedLayerCoverage");var ec=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"];var tc=["forRoot","forRootAsync"],nc=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"];var Fu=new Set(tc),$u=new Set(nc);var Mu=new Set(ec);function da(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}_chunkA5EIY3HIcjs.a.call(void 0, da,"isArkRunKernelModuleSpecifier");var rc=["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"],_n=new Set(rc);function ua(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(_n.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(_n.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:_n.has(e.slice(0,r))}_chunkA5EIY3HIcjs.a.call(void 0, ua,"isArkRunTransportBypassSpecifier");var sc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],qu=new Set(sc);var pa={"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"},ac="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ma(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 a=r.trim().replace(/\.+$/,"");return a==="Domain"||a.startsWith("Domain.")})}_chunkA5EIY3HIcjs.a.call(void 0, ma,"isDomainRoleLayer");function oc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}_chunkA5EIY3HIcjs.a.call(void 0, oc,"compareFindings");function he(e,t,n,r,a,s,o){let l=e.mode==="enforced"&&o;return{ruleId:pa[t],sensor:t,message:a,file:n,line:r,..._optionalChain([s, 'optionalAccess', _140 => _140.fromLayer])?{fromLayer:s.fromLayer}:{},..._optionalChain([s, 'optionalAccess', _141 => _141.target])?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:le({ruleId:pa[t],fromLayer:_optionalChain([s, 'optionalAccess', _142 => _142.fromLayer]),target:_optionalChain([s, 'optionalAccess', _143 => _143.target])})}}_chunkA5EIY3HIcjs.a.call(void 0, he,"finding");function ic(e,t){let n=[],r=[],a=[],s=[];for(let o of e)o.file===t&&(n.push(...o.uses),r.push(...o.reactsTo),a.push(...o.raises),s.push(...o.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(a),sends:new Set(s)}}_chunkA5EIY3HIcjs.a.call(void 0, ic,"bagForFile");function fa(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}_chunkA5EIY3HIcjs.a.call(void 0, fa,"emitKinds");function ga(e){return e==="subscribe"||e==="register-handler"}_chunkA5EIY3HIcjs.a.call(void 0, ga,"handleKinds");function lc(e){return e==="resolve"||e==="resolve-singleton"}_chunkA5EIY3HIcjs.a.call(void 0, lc,"dependKinds");function cc(e,t,n){let r=[],a=_nullishCoalesce(e.kernelRoots, () => (e.compositionRoots));if(a.length===0)return r.push(he(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 o of t){let l=_nullishCoalesce(s.get(o.matchedRoot), () => ([]));l.push(o),s.set(o.matchedRoot,l)}for(let o of a){let l=[..._nullishCoalesce(s.get(o), () => ([]))].sort((f,g)=>f.file.localeCompare(g.file));if(l.length===0){r.push(he(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(o)} matched no governed files and has no createArkKernel factory.`,{target:o},n));continue}if(l.some(f=>f.hasKernelFactory))continue;let c=l[0];r.push(he(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(o)} has no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel / *FromConfig, or ArkModule.forRoot / forRootAsync from arkgate/nestjs).`,{target:o},n))}return r}_chunkA5EIY3HIcjs.a.call(void 0, cc,"evaluateMissingRoot");function dc(e,t,n,r,a){let s=new Map(t.map(l=>[l.name,_nullishCoalesce(l.intentPrefixes, () => ([]))])),o=[];for(let l of n){let c=l.specifier;if(!c||!da(c))continue;let f=r(l.from);f&&ma(f,_nullishCoalesce(s.get(f), () => ([])))&&o.push(he(e,"arkrun-kernel-in-domain",l.from,l.line,`${f} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:f,target:c},a))}return o}_chunkA5EIY3HIcjs.a.call(void 0, dc,"evaluateKernelInDomain");function uc(e,t,n,r,a,s){let o=new Set(e.managedLayers);if(o.size===0)return[];let l=new Map(t.map(g=>[g.name,_nullishCoalesce(g.intentPrefixes, () => ([]))])),c=new Set(r.filter(g=>g.hasKernelFactory).map(g=>g.file)),f=[];for(let g of n){if(c.has(g.file))continue;let h=g.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let p=a(g.file);!p||!o.has(p)||ma(p,_nullishCoalesce(l.get(p), () => ([])))||f.push(he(e,"arkrun-direct-new",g.file,g.line,`${p} must not construct ${g.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:g.typeName},s))}return f}_chunkA5EIY3HIcjs.a.call(void 0, uc,"evaluateDirectNew");function pc(e,t,n,r,a){let s=[],o=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:o};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:o};for(let c of t){if(!fa(c.kind)&&!ga(c.kind)&&!lc(c.kind))continue;let f=r(c.file);if(!f||!l.has(f))continue;if(!c.nameLiteral){e.mode==="enforced"&&c.kind!=="publisher"&&o.push({code:ac,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name or same-file define/defineIntent binding; enforced extra cannot prove the declaration.`});continue}let g=ic(n,c.file);if(fa(c.kind)){if(g.raises.has(c.nameLiteral)||g.sends.has(c.nameLiteral))continue;s.push(he(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:f,target:c.nameLiteral},a));continue}if(ga(c.kind)){if(g.reactsTo.has(c.nameLiteral))continue;s.push(he(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:f,target:c.nameLiteral},a));continue}g.uses.has(c.nameLiteral)||s.push(he(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:f,target:c.nameLiteral},a))}return{findings:s,completenessReasons:o}}_chunkA5EIY3HIcjs.a.call(void 0, pc,"evaluateUndeclared");function fc(e,t,n,r){let a=new Set(e.managedLayers);if(a.size===0)return[];let s=[];for(let o of t){if(o.typeOnly)continue;let l=o.specifier;if(!l||!ua(l))continue;let c=n(o.from);!c||!a.has(c)||s.push(he(e,"arkrun-transport-bypass",o.from,o.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}_chunkA5EIY3HIcjs.a.call(void 0, fc,"evaluateTransportBypass");function ya(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Ct(e.classification),r=pc(t,e.kernelCalls,e.declarations,e.layerForFile,n),a=[...cc(t,e.compositionRootHits,n),...dc(t,e.layers,e.dependencies,e.layerForFile,n),...uc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...fc(t,e.dependencies,e.layerForFile,n)].sort(oc),s=[...r.completenessReasons].sort((o,l)=>{let c=`${o.code}\0${_nullishCoalesce(o.file, () => (""))}\0${o.message}`,f=`${l.code}\0${_nullishCoalesce(l.file, () => (""))}\0${l.message}`;return c<f?-1:c>f?1:0});return{findings:a,completenessReasons:s}}_chunkA5EIY3HIcjs.a.call(void 0, ya,"evaluateArkRunSensors");var ha=new Map;function Ra(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}_chunkA5EIY3HIcjs.a.call(void 0, Ra,"escapeAppliesToLiteral");function gc(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let a=e[n+1];if("*?{}[],".includes(a)||a==="\\"){t+="\\"+a,n+=1;continue}t+="/";continue}t+=r}return t}_chunkA5EIY3HIcjs.a.call(void 0, gc,"normalizeAppliesToGlob");function mc(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}_chunkA5EIY3HIcjs.a.call(void 0, mc,"appliesToBracesBalanced");function Aa(e){let t=ha.get(e);if(t)return t;let n=gc(e),r=mc(n),a="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(a+=Ra(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(a+="(?:.*/)?",l+=2):(a+=".*",l+=1):a+="[^/]*":c==="?"?a+="[^/]":c==="{"&&r?(a+="(?:",s+=1):c==="}"&&r&&s>0?(a+=")",s-=1):c===","&&r&&s>0?a+="|":a+=Ra(c)}let o=new RegExp(`^${a}$`);return ha.set(e,o),o}_chunkA5EIY3HIcjs.a.call(void 0, Aa,"arkOrderGlobToRegExp");function ka(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}_chunkA5EIY3HIcjs.a.call(void 0, ka,"isArkOrderModuleSpecifier");var va={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function yc(e,t){return!t||t.length===0?!0:t.some(n=>Aa(n).test(e))}_chunkA5EIY3HIcjs.a.call(void 0, yc,"matchesArkOrderAppliesTo");function hc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let a=r.trim().replace(/\.+$/,"");return a==="Domain"||a.startsWith("Domain.")})}_chunkA5EIY3HIcjs.a.call(void 0, hc,"isDomainRoleLayer");function de(e,t,n,r,a,s,o){let l=e.mode==="enforced"&&o;return{ruleId:va[t],sensor:t,message:a,file:n,line:r,..._optionalChain([s, 'optionalAccess', _144 => _144.fromLayer])?{fromLayer:s.fromLayer}:{},..._optionalChain([s, 'optionalAccess', _145 => _145.target])?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:le({ruleId:va[t],fromLayer:_optionalChain([s, 'optionalAccess', _146 => _146.fromLayer]),target:_optionalChain([s, 'optionalAccess', _147 => _147.target])})}}_chunkA5EIY3HIcjs.a.call(void 0, de,"finding");function Ia(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Ct(e.classification),r=[],a=t.planeRoots;if(t.mode==="enforced"&&a.length===0)r.push(de(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let f of e.planeRootHits){let g=_nullishCoalesce(c.get(f.matchedRoot), () => ([]));g.push(f),c.set(f.matchedRoot,g)}for(let f of a){let g=_nullishCoalesce(c.get(f), () => ([]));if(g.length===0){r.push(de(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(f)} matched no governed files and has no createOrderPlane factory.`,{target:f},n));continue}g.some(h=>h.hasPlaneFactory)||r.push(de(t,"arkorder-missing-plane",g[0].file,1,`ArkOrder plane root ${JSON.stringify(f)} has no createOrderPlane factory.`,{target:f},n))}}let s=new Map(e.layers.map(c=>[c.name,_nullishCoalesce(c.intentPrefixes, () => ([]))]));for(let c of e.dependencies){let f=c.specifier;if(!f||!ka(f))continue;let g=e.layerForFile(c.from);g&&hc(g,_nullishCoalesce(s.get(g), () => ([])))&&r.push(de(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:g,target:f},n))}for(let c of e.genericUpdates)r.push(de(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 o=_nullishCoalesce(t.xiKeys, () => ([]));for(let c of _nullishCoalesce(e.releaseKeyCounts, () => ([])))c.keyCount<=t.maxXiKeys||r.push(de(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 _nullishCoalesce(e.ingestWritesXi, () => ([])))r.push(de(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));for(let c of _nullishCoalesce(e.xiTtlKeys, () => ([])))r.push(de(t,"arkorder-xi-ttl",c.file,c.line,`\u03BE key ${JSON.stringify(c.key)} is a freshness field; freshness belongs on \u03C3 (freshUntil), never on \u03BE.`,{target:c.key},n));for(let c of _nullishCoalesce(e.budgetLeaks, () => ([])))r.push(de(t,"arkorder-information-budget",c.file,c.line,`Projection allowedKinds lists ${JSON.stringify(c.kind)}, which informationBudget.cannotObserve denies.`,{target:c.kind},n));let l=new Set(t.managedLayers);for(let c of o.length===0?[]:_nullishCoalesce(e.xiFieldWrites, () => ([]))){let f=e.layerForFile(c.file);!f||!l.has(f)||yc(c.file,t.appliesTo)&&r.push(de(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:f,target:c.key},n))}return r.sort((c,f)=>c.file.localeCompare(f.file)||c.ruleId.localeCompare(f.ruleId)||c.line-f.line),{findings:r,completenessReasons:[]}}_chunkA5EIY3HIcjs.a.call(void 0, Ia,"evaluateArkOrderSensors");var On="4.8.24";function xn(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}_chunkA5EIY3HIcjs.a.call(void 0, xn,"childSlicesOf");var ba=Object.freeze([{key:"sharedImportsSlice.stopAt",minVersion:On,uses:_chunkA5EIY3HIcjs.a.call(void 0, e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:On,uses:_chunkA5EIY3HIcjs.a.call(void 0, e=>_optionalChain([xn, 'call', _148 => _148(e), 'optionalAccess', _149 => _149.message])!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:On,uses:_chunkA5EIY3HIcjs.a.call(void 0, e=>{let t=_optionalChain([xn, 'call', _150 => _150(e), 'optionalAccess', _151 => _151.siblings]);return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:_chunkA5EIY3HIcjs.a.call(void 0, e=>xn(e)!==null,"uses")},{key:'sharedImportsSlice: "deny-cross-parent"',minVersion:"4.8.23",uses:_chunkA5EIY3HIcjs.a.call(void 0, e=>e.sharedImportsSlice==="deny-cross-parent","uses")},{key:"sliceIdentity",minVersion:"4.8.21",uses:_chunkA5EIY3HIcjs.a.call(void 0, e=>e.sliceIdentity!==void 0,"uses")},{key:"sharedImportsSlice",minVersion:"4.8.20",uses:_chunkA5EIY3HIcjs.a.call(void 0, e=>e.sharedImportsSlice==="deny","uses")}]);function _t(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}_chunkA5EIY3HIcjs.a.call(void 0, _t,"versionCore");function rt(e,t){let n=_t(e),r=_t(t);if(!n&&!r)return 0;if(!n)return-1;if(!r)return 1;for(let a=0;a<3;a+=1){let s=_nullishCoalesce(n[a], () => (0)),o=_nullishCoalesce(r[a], () => (0));if(s<o)return-1;if(s>o)return 1}return 0}_chunkA5EIY3HIcjs.a.call(void 0, rt,"compareArkgateVersion");function Ea(e,t){return t&&_t(t)&&rt(t,e)<0?t.replace(/^v/,""):e}_chunkA5EIY3HIcjs.a.call(void 0, Ea,"effectiveFloor");function Rc(e,t){let n=[],r=null;for(let a of ba){if(!(_nullishCoalesce(e, () => ([]))).some(o=>o&&a.uses(o)))continue;n.push(a.key);let s=Ea(a.minVersion,t);(!r||rt(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}_chunkA5EIY3HIcjs.a.call(void 0, Rc,"configVersionFloors");function Sa(e){let t=Rc(e.rules,e.runningVersion);if(!t||!_optionalChain([e, 'access', _152 => _152.pins, 'optionalAccess', _153 => _153.length]))return[];let n=e.runningVersion,r=n&&_t(n)&&rt(n,t.required)>0?n.replace(/^v/,""):t.required,a=_chunkA5EIY3HIcjs.a.call(void 0, l=>ba.filter(c=>t.keys.includes(c.key)&&rt(l.version,Ea(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,o=[];for(let l of e.pins){if(rt(l.version,t.required)>=0)continue;let c=`${l.file}\0${l.line}`;if(s.has(c))continue;s.add(c);let f=a(l);o.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,path:l.file,line:l.line,message:`ark.config.json uses ${f.join(", ")} (needs arkgate ${t.required}+). ${l.file}:${l.line} pins arkgate ${l.version}, which rejects this config at load.`,nextAction:`Bump arkgate in ${l.file} from ${l.version} to ${r}, then run Ark again.`})}return o.sort((l,c)=>l.path.localeCompare(c.path)||l.line-c.line)}_chunkA5EIY3HIcjs.a.call(void 0, Sa,"configVersionPinFindings");function q(e,t,n={}){return{ruleId:e,message:t,...n}}_chunkA5EIY3HIcjs.a.call(void 0, q,"configWarning");function Ot(e){let{config:t,rules:n,files:r,manifest:a}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(u=>typeof u!="string"))&&s.push(q("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(q("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let u of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[u];m!==void 0&&(!Number.isInteger(m)||m<0)&&s.push(q("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${u} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(_optionalChain([a, 'optionalAccess', _154 => _154.architecture, 'optionalAccess', _155 => _155.layers]))?a.architecture.layers:[],c=new Set([...o.map(u=>u.name).filter(Boolean),...l.map(u=>u.name).filter(u=>!!u)]);o.length===0&&s.push(q("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let f=new Set,g=new Set;for(let u of o){if(!u.name){s.push(q("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}f.has(u.name)&&g.add(u.name),f.add(u.name),u.forbiddenGlobals!==void 0&&(!Array.isArray(u.forbiddenGlobals)||u.forbiddenGlobals.some(v=>typeof v!="string"))&&s.push(q("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${u.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:u.name}));let m=Array.isArray(u.patterns)?u.patterns:[];if(m.length===0){s.push(q("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${u.name}" has no file patterns and will never classify files.`,{layer:u.name}));continue}for(let v of m){let w;try{w=_chunkRNQHRDCQcjs.z.call(void 0, v)}catch(b){s.push(q("CONFIG_INVALID_LAYER_PATTERN",`Layer "${u.name}" has an invalid pattern "${v}": ${b instanceof Error?b.message:String(b)}`,{layer:u.name,pattern:v}));continue}let A=u.optional===!0||u.reserved===!0||u.allowEmpty===!0;!r.some(b=>w.test(b))&&!A&&s.push(q("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${u.name}" pattern "${v}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:u.name,pattern:v,failsStrict:!1,reserved:!1}))}}for(let u of g)s.push(q("CONFIG_DUPLICATE_LAYER",`Layer "${u}" is configured more than once.`,{layer:u}));if(c.size>0)for(let u of _nullishCoalesce(n, () => ([])))u.from&&!c.has(u.from)&&s.push(q("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${u.from}".`,{fromLayer:u.from,toLayer:u.to})),u.to&&!c.has(u.to)&&s.push(q("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${u.to}".`,{fromLayer:u.from,toLayer:u.to}));let h=new Set;if(o.length>1)for(let u of r){let m=-1,v=[];for(let w of o)for(let A of _nullishCoalesce(w.patterns, () => ([]))){if(!_chunkRNQHRDCQcjs.z.call(void 0, A).test(u))continue;let b=_chunkRNQHRDCQcjs.A.call(void 0, A,u);b>m?(m=b,v=[w.name]):b===m&&!v.includes(w.name)&&v.push(w.name)}v.length>1&&h.add([...v].sort().join(" + "))}h.size>0&&s.push(q("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let p=r.filter(u=>!_chunkRNQHRDCQcjs.B.call(void 0, u,o));p.length>0&&s.push(q("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)}));for(let u of _chunkRNQHRDCQcjs.C.call(void 0, n))s.push(q("CONFIG_SLICE_IDENTITY_COLLISION",u.message,{paths:[...u.paths],fromLayer:u.from,toLayer:u.to,failsStrict:!1}));for(let u of _chunkRNQHRDCQcjs.M.call(void 0, n,r))s.push(q(u.ruleId,u.message,{failsStrict:!1,...u.path?{file:u.path}:{},...u.fromLayer?{fromLayer:u.fromLayer}:{},...u.toLayer?{toLayer:u.toLayer}:{}}));for(let u of Sa({rules:n,pins:e.arkgatePins,runningVersion:e.runningArkgateVersion}))s.push(q(u.ruleId,u.message,{failsStrict:!1,file:u.path,line:u.line,nextAction:u.nextAction}));let R=_chunkRNQHRDCQcjs.$.call(void 0, t);if(R.length>0){let u=_nullishCoalesce(R[0], () => ("this layer"));s.push(q("CONFIG_LAYER_MISSING_OWNER",`${u} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:R,nextAction:_chunkRNQHRDCQcjs.aa.call(void 0, u)}))}return s}_chunkA5EIY3HIcjs.a.call(void 0, Ot,"collectAnalysisConfigWarnings");function Ca(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",a=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:Ys({sensor:e.sensor,code:e.code})}:{},...r||a?{freezable:!1}:{},nextAction:t}}_chunkA5EIY3HIcjs.a.call(void 0, Ca,"toArkRuleEngineViolation");function Ac(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}_chunkA5EIY3HIcjs.a.call(void 0, Ac,"arkRulesMapIsOn");function _a(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}_chunkA5EIY3HIcjs.a.call(void 0, _a,"arkRuleFindingNextAction");function kc(e,t){return t.some(n=>{try{return _chunkRNQHRDCQcjs.z.call(void 0, n).test(e)}catch (e4){return!1}})}_chunkA5EIY3HIcjs.a.call(void 0, kc,"matchesAny");function vc(e,t){let n=_nullishCoalesce(e.contract.config.safety, () => ({})),r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,a=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=_nullishCoalesce(e.contract.config.dynamicImportAllowlist, () => ([])),o=t.safetyUses.filter(m=>m.kind==="ts-suppression").map(({file:m,line:v})=>({file:m,line:v})),l=t.safetyUses.filter(m=>m.kind==="any-cast").map(({file:m,line:v})=>({file:m,line:v})),c=t.safetyUses.filter(m=>(m.kind==="dynamic-import"||m.kind==="dynamic-require")&&!kc(m.file,s)).map(m=>({file:m.file,line:m.line,kind:m.kind==="dynamic-require"?"require":"import"})),f=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(m=>m.kind==="in-memory-store").map(m=>({file:m.file,line:m.line,store:_nullishCoalesce(m.symbol, () => ("in-memory store"))})),g=n.allowDisabledPeerIsolation===!0?[]:(_nullishCoalesce(e.contract.config.rules, () => ([]))).filter(m=>m.peerIsolation===!1||m.allowed===!1&&!!m.from&&m.from===m.to&&m.peerIsolation!==!0).map(m=>({from:m.from,to:m.to})),h={tsSuppressions:o,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:f,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:a}},p=[],R=c.filter(m=>m.kind==="import");if(R.length>0){let m=R[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${R.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let u=c.filter(m=>m.kind==="require");if(u.length>0){let m=u[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:m.file,line:m.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>r){let m=o[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>a){let m=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:m.file,line:m.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${a}).`})}if(f.length>0){let m=f[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:m.file,line:m.line,message:`${f.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&p.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:p}}_chunkA5EIY3HIcjs.a.call(void 0, vc,"evaluateSafety");function Ic(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}_chunkA5EIY3HIcjs.a.call(void 0, Ic,"ambientForbiddenGlobal");function Oa(e,t){let n=t.config.layers.filter(r=>(_nullishCoalesce(r.intentPrefixes, () => ([]))).length>0);return _chunkRNQHRDCQcjs.ea.call(void 0, e,n.length>0?n:_chunkRNQHRDCQcjs.da.map(r=>({name:r.layer,prefixes:r.prefixes})))}_chunkA5EIY3HIcjs.a.call(void 0, Oa,"intentLayer");function bc(e,t,n){let r=[],a=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let o=n.get(s.file);!o||!Ic(s.symbol,_nullishCoalesce(_optionalChain([a, 'access', _156 => _156.get, 'call', _157 => _157(o), 'optionalAccess', _158 => _158.forbiddenGlobals]), () => ([])))||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:o,target:s.symbol,message:`${o} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let o=n.get(s.file);if(!o)continue;let l=a.get(o),c=_nullishCoalesce(_optionalChain([l, 'optionalAccess', _159 => _159.forbiddenGlobals]), () => ([])),f=s.source==="import-based"?_optionalChain([t, 'access', _160 => _160.dependencies, 'access', _161 => _161.find, 'call', _162 => _162(g=>g.from===s.file&&g.line===s.line&&g.specifier===s.symbol&&!g.typeOnly), 'optionalAccess', _163 => _163.kind]):void 0;if(!(s.source==="ambient-global"&&ze(s.symbol,c))){if(s.source==="import-based"){let g=Re(s.symbol,c);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:o,target:s.symbol,...f?{edgeKind:f}:{},message:`${o} must not use module "${s.symbol}" because it is the import form of forbidden global "${g}".`});continue}}we(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:o,target:s.symbol,capability:s.capability,...f?{edgeKind:f}:{},message:s.source==="import-based"?`${o} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${o} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let o=n.get(s.file);if(!o)continue;for(let c of _chunkRNQHRDCQcjs.ga.call(void 0, {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:o}:{},message:c.message});if(!s.sourceIntent)continue;let l=Oa(s.sourceIntent,e.contract);!l||l===o||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:o,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${o}.`})}for(let s of t.intentReferences){let o=n.get(s.file);if(!o)continue;let l=Oa(s.intent,e.contract);if(!l)continue;let c=_chunkRNQHRDCQcjs.O.call(void 0, e.contract.config.rules,o,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let f=c.sliceVerdict,g=`${o} must not reference ${l} intent ${s.intent}.`,h=f?_chunkRNQHRDCQcjs.K.call(void 0, {surface:"intent",verdict:f,fromLayer:o,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,childMessage:_optionalChain([c, 'access', _164 => _164.rule, 'access', _165 => _165.childSlices, 'optionalAccess', _166 => _166.message]),defaultMessage:g}):_nullishCoalesce(c.rule.message, () => (g));r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:o,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},..._chunkRNQHRDCQcjs.L.call(void 0, f),message:h})}return r}_chunkA5EIY3HIcjs.a.call(void 0, bc,"contentViolations");function xt(e){let{facts:t}=e,n=Xe(e.contract.config),r=t.evidenceRequirementsHash===n,a=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,T)=>{let U=`${d.code}\0${_nullishCoalesce(d.file, () => (""))}\0${d.message}`,re=`${T.code}\0${_nullishCoalesce(T.file, () => (""))}\0${T.message}`;return U<re?-1:U>re?1:0}),o=t.files.map(d=>({...d,layer:_nullishCoalesce(_chunkRNQHRDCQcjs.B.call(void 0, d.path,e.contract.config.layers), () => (null))})),l=new Map(o.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let T=d.target?_nullishCoalesce(l.get(d.target), () => (_chunkRNQHRDCQcjs.B.call(void 0, d.target,e.contract.config.layers))):void 0;return{from:d.from,fromLayer:_nullishCoalesce(l.get(d.from), () => (null)),...d.resolution==="resolved-project"&&d.target?{to:d.target,...T?{toLayer:T}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),f=Ot({config:e.contract.config,rules:e.contract.config.rules,files:o.map(d=>d.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),g=vc(e,t),h=_nullishCoalesce(e.contract.arkRules, () => (Je())),p=o.map(d=>d.path),u={..._optionalChain([e, 'access', _167 => _167.coverageInputs, 'optionalAccess', _168 => _168.fileContents])&&Object.keys(e.coverageInputs.fileContents).length>0?la(e.coverageInputs.fileContents):{},..._nullishCoalesce(e.fileHints, () => ({}))},m=_chunkA5EIY3HIcjs.a.call(void 0, d=>_nullishCoalesce(l.get(d), () => (_chunkRNQHRDCQcjs.B.call(void 0, d,e.contract.config.layers))),"resolveLayer"),v=[...aa({arkRules:h,classShapes:_nullishCoalesce(_nullishCoalesce(e.contract.classShapes, () => (t.classShapes)), () => ([])),files:p,layerForFile:m,fileHints:u}),...oa(h,p),...ia({arkRulesActive:Ac(e.contract.config),arkRules:h,layers:_nullishCoalesce(e.contract.config.layers, () => ([])),files:p.map(d=>({path:d,layer:m(d)}))})],w=(_nullishCoalesce(_optionalChain([h, 'access', _169 => _169.invariants, 'optionalAccess', _170 => _170.length]), () => (0)))>0,A=xs({hasEnforcedInvariant:yn(h.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),b=A.length>0?[]:Os({adopted:e.adopted===!0,hasDomainInvariants:mn(h.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),O=[...A.map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...b.map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],G=v.filter(d=>d.failsStrict).map(d=>Ca(d,_a(d,!1))),K=v.filter(d=>!d.failsStrict).map(d=>({...Ca(d,_a(d,!0)),failsStrict:!1})),j=w?Cs({arkRules:h,fileContents:_nullishCoalesce(_optionalChain([e, 'access', _171 => _171.coverageInputs, 'optionalAccess', _172 => _172.fileContents]), () => ({})),testFiles:_nullishCoalesce(_optionalChain([e, 'access', _173 => _173.coverageInputs, 'optionalAccess', _174 => _174.testFiles]), () => ([])),testGlobsMissing:_optionalChain([e, 'access', _175 => _175.coverageInputs, 'optionalAccess', _176 => _176.testGlobsMissing])===!0||e.coverageInputs===void 0||(_nullishCoalesce(_optionalChain([e, 'access', _177 => _177.coverageInputs, 'access', _178 => _178.testFiles, 'optionalAccess', _179 => _179.length]), () => (0)))===0,coverageBudgetExhausted:_optionalChain([e, 'access', _180 => _180.coverageInputs, 'optionalAccess', _181 => _181.coverageBudgetExhausted])===!0,..._optionalChain([e, 'access', _182 => _182.coverageInputs, 'optionalAccess', _183 => _183.stats])?{coverageStats:e.coverageInputs.stats}:{},..._optionalChain([e, 'access', _184 => _184.coverageInputs, 'optionalAccess', _185 => _185.coverageRoots])?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},I=j.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.`})),D=j.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).`})),X=ca(o),ne=ya({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:_chunkA5EIY3HIcjs.a.call(void 0, d=>_nullishCoalesce(l.get(d), () => (_chunkRNQHRDCQcjs.B.call(void 0, d,e.contract.config.layers))),"layerForFile"),classification:X}),ue=_optionalChain([e, 'access', _186 => _186.contract, 'access', _187 => _187.config, 'access', _188 => _188.arkRun, 'optionalAccess', _189 => _189.mode]),ae=ne.findings.filter(()=>ue==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Ue=ne.findings.filter(()=>ue!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),pe=Ia({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,xiTtlKeys:t.arkOrderXiTtlKeys,budgetLeaks:t.arkOrderBudgetLeaks,dependencies:t.dependencies,layerForFile:_chunkA5EIY3HIcjs.a.call(void 0, d=>_nullishCoalesce(l.get(d), () => (_chunkRNQHRDCQcjs.B.call(void 0, d,e.contract.config.layers))),"layerForFile"),classification:X}),Tt=_optionalChain([e, 'access', _190 => _190.contract, 'access', _191 => _191.config, 'access', _192 => _192.arkOrder, 'optionalAccess', _193 => _193.mode]),st=pe.findings.filter(()=>Tt==="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}:{}})),Nn=pe.findings.filter(()=>Tt!=="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})),Ve=[...j.partial&&j.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."}]:[],...ne.completenessReasons,...pe.completenessReasons],Ie=He({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(d=>d.layer).map(d=>d.path),contentViolations:[...bc(e,t,l),...G,...O,...I,...ae,...st],edges:c,warnings:[...f,...g.warnings,...K,...D,...Ue,...Nn],safety:g.report}),at=a==="complete"&&Ve.length>0?"partial":a,Pt=at==="complete"?s:[...s,...Ve].sort((d,T)=>{let U=`${d.code}\0${_nullishCoalesce(d.file, () => (""))}\0${d.message}`,re=`${T.code}\0${_nullishCoalesce(T.file, () => (""))}\0${T.message}`;return U<re?-1:U>re?1:0}),E=Ie.violations.filter(d=>d.failsStrict!==!1),_=at==="complete"&&E.length===0,y=_&&Ie.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:at,completenessReasons:Pt,valid:_,strictValid:y,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:o,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Ie.violations,warnings:Ie.warnings}}}_chunkA5EIY3HIcjs.a.call(void 0, xt,"analyzeCanonicalResolvedProject");function xa(e){return xt({contract:e.contract,facts:Ae(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent,arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion})}_chunkA5EIY3HIcjs.a.call(void 0, xa,"analyzeResolvedProject");function wa(e){return Z(W(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}_chunkA5EIY3HIcjs.a.call(void 0, wa,"analysisTreeHash");function Ta(e){let t=nt(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],a=new Set,s=[];for(let u of e.changes){let m=u.path.replace(/\\/g,"/"),v=_e(u.path);if(!v||v===".."||v.startsWith("../")||m.startsWith("/")||/^[A-Za-z]:\//.test(m)||m.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(a.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}a.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 o=It({...e,changes:r}),l=new Map(o.ir.files.map(u=>[u.path,u])),c=o.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let m=_optionalChain([l, 'access', _194 => _194.get, 'call', _195 => _195(u.evidence.file), 'optionalAccess', _196 => _196.layer]);return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...m?{fromLayer:m}:{},edgeKind:"import",message:u.message}}),f=He({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(u=>u.path),contentViolations:c,edges:o.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}:{}}))}),g=r.map(u=>{let m=_e(u.path),v=n.get(m),w=l.get(m);return{path:m,operation:"delete"in u&&u.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},...w?{candidateContentHash:w.contentHash}:{}}}).sort((u,m)=>u.path.localeCompare(m.path)),h=[...s,...f.violations].map(u=>({...u,nextAction:le(u)})),p=h.filter(u=>u.failsStrict!==!1),R=e.changeMap?Fe({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:o.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&o.valid&&p.length===0&&(_nullishCoalesce(_optionalChain([R, 'optionalAccess', _197 => _197.structurallyConverged]), () => (!0))),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:wa(t.ir.files),candidateTreeHash:wa(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...R?{convergence:R}:{},changes:g,violations:h,warnings:f.warnings}}_chunkA5EIY3HIcjs.a.call(void 0, Ta,"preflightChange");function Ec(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let a of t.split("/"))if(!(!a||a==="."))if(a===".."){if(n.length===0)return;n.pop()}else n.push(a);let r=n.join("/");return r&&r===t?r:void 0}_chunkA5EIY3HIcjs.a.call(void 0, Ec,"canonicalChangePath");function Sc(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",_nullishCoalesce(e.projectPackageName, () => ("")),_nullishCoalesce(t.projectPackageName, () => (""))]].filter(([,r,a])=>r!==a).map(([r,a,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:a,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}_chunkA5EIY3HIcjs.a.call(void 0, Sc,"identityViolations");function Cc(e,t,n,r){let a=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":a?"update":"create",...a?{beforeContentHash:a.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}_chunkA5EIY3HIcjs.a.call(void 0, Cc,"preparedChange");function wt(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}_chunkA5EIY3HIcjs.a.call(void 0, wt,"isArkRulesPlaneRule");function Na(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,_nullishCoalesce(e.file, () => ("")),t,_nullishCoalesce(e.target, () => (e.message))].join("|")}_chunkA5EIY3HIcjs.a.call(void 0, Na,"ratchetKey");function Pa(e,t){let n=new Map;for(let r of e){if(!wt(r.ruleId)||r.failsStrict===!1)continue;let a=Na(r);n.set(a,(_nullishCoalesce(n.get(a), () => (0)))+1)}return t.map(r=>{if(!wt(r.ruleId))return r;let a=Na(r),s=_nullishCoalesce(n.get(a), () => (0));return s===0?r:(n.set(a,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}_chunkA5EIY3HIcjs.a.call(void 0, Pa,"ratchetPreExistingArkRules");function _c(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>wt(n.ruleId)),warnings:e.ir.warnings.filter(n=>wt(n.ruleId))}}}_chunkA5EIY3HIcjs.a.call(void 0, _c,"baseAnalysisSummary");function La(e){return Oc(e,Ae(e.baseFacts),Ae(e.candidateFacts))}_chunkA5EIY3HIcjs.a.call(void 0, La,"preflightResolvedChange");function Oc(e,t,n){let r=_c(xt({..._nullishCoalesce(e.baseAnalysisInputs, () => ({})),contract:e.contract,facts:t}),e.changeMap!==void 0),a=xt({..._nullishCoalesce(e.candidateAnalysisInputs, () => ({})),contract:e.contract,facts:n}),s=new Map(t.files.map(m=>[m.path,m])),o=new Map(n.files.map(m=>[m.path,m])),l=Sc(t,n),c=new Map,f=[];for(let m of e.changes){let v=Ec(m.path);if(!v){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(v)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}c.set(v,m);let w=s.get(v),A=o.get(v);if("delete"in m&&m.delete)w||l.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base facts.`}),A&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:v,line:1,message:`Candidate facts still contain deleted file ${v}.`});else{let b="content"in m?m.content:"",O=Z(b);A?A.contentHash!==O&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:v,line:1,expectedContentHash:O,candidateContentHash:A.contentHash,message:`Candidate facts for ${v} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:v,line:1,message:`Candidate facts do not contain changed file ${v}.`})}f.push(Cc(m,v,s,o))}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 m of new Set([...s.keys(),...o.keys()])){if(c.has(m))continue;let v=s.get(m),w=o.get(m);v&&w&&W(v)===W(w)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:m,line:1,message:`Candidate facts change ${m}, but the atomic change set does not declare it.`})}let g=e.changeMap?Fe({changeMap:e.changeMap,changes:f,baseDependencies:r.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:a.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0,h=Pa(r.ir.violations,a.ir.violations),p=Pa(r.ir.warnings,a.ir.warnings),R=[...l,...h].map(m=>({...m,nextAction:le(m)})),u=R.filter(m=>m.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&a.completeness==="complete"&&p.every(m=>m.failsStrict===!1)&&u.length===0&&(_nullishCoalesce(_optionalChain([g, 'optionalAccess', _198 => _198.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:a.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:f.sort((m,v)=>m.path<v.path?-1:m.path>v.path?1:0),violations:R,warnings:p}}_chunkA5EIY3HIcjs.a.call(void 0, Oc,"preflightCanonicalChange");var xc="1.1";var wc="1.0";function Da(e){return Object.keys(e).sort()}_chunkA5EIY3HIcjs.a.call(void 0, Da,"sortedKeys");function wn(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],f=Math.max(l.length,c.length);for(let g=0;g<f;g+=1)wn(l[g],c[g],`${n}[${g}]`,r);return}let a=e,s=t,o=new Set([...Da(a),...Da(s)]);for(let l of[...o].sort())wn(a[l],s[l],n?`${n}.${l}`:l,r)}_chunkA5EIY3HIcjs.a.call(void 0, wn,"walk");function Fa(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}_chunkA5EIY3HIcjs.a.call(void 0, Fa,"shadowInformationPackage");function Tn(e,t){let n=[];return wn(e,t,"",n),{equal:n.length===0,diffs:n}}_chunkA5EIY3HIcjs.a.call(void 0, Tn,"compareInformationPackages");function $a(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Tn(e[n-1],e[n]));return t}_chunkA5EIY3HIcjs.a.call(void 0, $a,"replayInformationPackages");exports.ANALYSIS_IR_SCHEMA_VERSION = ln; exports.ARK_ANALYSIS_RESULT_SCHEMA = Yr; exports.ARK_ANALYSIS_RESULT_SCHEMA_VERSION = pt; exports.ARK_DESIGN_DELTA_SCHEMA_VERSION = wc; exports.ARK_ENFORCEMENT_STATE_SCHEMA_VERSION = xc; exports.ARK_RUN_COMPONENT_LIFETIMES = _chunkA5EIY3HIcjs.d; exports.ARK_RUN_EPHEMERAL_DEFAULT = _chunkA5EIY3HIcjs.t; exports.ARK_RUN_GRAPH_DEFAULT_SLICE = _chunkA5EIY3HIcjs.i; exports.ARK_RUN_GRAPH_NODE_KINDS = _chunkA5EIY3HIcjs.k; exports.ARK_RUN_GRAPH_PROCESS_EDGE_KINDS = _chunkA5EIY3HIcjs.l; exports.ARK_RUN_GRAPH_SCHEMA_VERSION = _chunkA5EIY3HIcjs.h; exports.ARK_RUN_GRAPH_SLICES = _chunkA5EIY3HIcjs.j; exports.ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS = _chunkA5EIY3HIcjs.m; exports.ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION = _chunkA5EIY3HIcjs.c; exports.ARK_RUN_INSPECTOR_DEFAULT_HOST = _chunkA5EIY3HIcjs.z; exports.ARK_RUN_INSPECTOR_DEFAULT_PORT = _chunkA5EIY3HIcjs.A; exports.ARK_RUN_INSPECTOR_EVENTS_PATH = _chunkA5EIY3HIcjs.C; exports.ARK_RUN_INSPECTOR_GRAPH_PATH = _chunkA5EIY3HIcjs.D; exports.ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT = _chunkA5EIY3HIcjs.I; exports.ARK_RUN_INSPECTOR_OUTBOX_PATH = _chunkA5EIY3HIcjs.E; exports.ARK_RUN_INSPECTOR_SCHEMA_VERSION = _chunkA5EIY3HIcjs.y; exports.ARK_RUN_INSPECTOR_SNAPSHOT_PATH = _chunkA5EIY3HIcjs.B; exports.ARK_RUN_INSPECTOR_SSE_EVENT = _chunkA5EIY3HIcjs.G; exports.ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK = _chunkA5EIY3HIcjs.H; exports.ARK_RUN_INSPECTOR_WORKFLOWS_PATH = _chunkA5EIY3HIcjs.F; exports.ARK_RUN_TRANSPORT_KINDS = _chunkA5EIY3HIcjs.s; exports.ArkKernelConfigError = _chunkRNQHRDCQcjs.w; exports.ArkRunInspectorBindError = _chunkA5EIY3HIcjs.K; exports.ArkRunInspectorProductionError = _chunkA5EIY3HIcjs.J; exports.DEFAULT_MAX_HISTORY_SIZE = _chunkRNQHRDCQcjs.ua; exports.DIAGNOSTIC_CATALOG = dt; exports.DIAGNOSTIC_CATALOG_SCHEMA_VERSION = wo; exports.DIAGNOSTIC_DOCS_RELATIVE_PATH = Mt; exports.DIAGNOSTIC_RULE_IDS = To; exports.EventContractRegistryImpl = _chunkRNQHRDCQcjs.S; exports.EventContractViolationError = _chunkRNQHRDCQcjs.s; exports.InMemoryAuditStore = _chunkRNQHRDCQcjs.X; exports.InMemoryEventBuffer = _chunkRNQHRDCQcjs.U; exports.InMemoryOutboxStore = _chunkRNQHRDCQcjs.V; exports.InMemoryReadModelStore = _chunkRNQHRDCQcjs.ma; exports.InMemoryWorkflowStore = _chunkRNQHRDCQcjs.qa; exports.IntentRegistry = _chunkRNQHRDCQcjs.b; exports.InvalidArkRunGraphQueryError = _chunkA5EIY3HIcjs.n; exports.InvalidArkRunSendOptionError = _chunkA5EIY3HIcjs.u; exports.InvalidIntentNameError = _chunkRNQHRDCQcjs.q; exports.LayerPolicyContextError = _chunkRNQHRDCQcjs.r; exports.MANIFEST_SCHEMA_VERSION = _chunkRNQHRDCQcjs.oa; exports.ObservedLayerFlowViolationError = _chunkRNQHRDCQcjs.v; exports.POLICY_DELTA_SCHEMA_VERSION = kn; exports.PolicyEngine = _chunkRNQHRDCQcjs.h; exports.PolicyViolationError = _chunkRNQHRDCQcjs.g; exports.RESOLVED_CANDIDATE_FACTS_SCHEMA = on; exports.RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION = Se; exports.SourceMetadataOverrideError = _chunkRNQHRDCQcjs.u; exports.UnknownEventSourceError = _chunkRNQHRDCQcjs.t; exports.UnregisteredIntentError = _chunkRNQHRDCQcjs.p; exports.analyzeArchitectureConvergence = Fe; exports.analyzeChange = It; exports.analyzePolicyDelta = Bs; exports.analyzeProject = nt; exports.analyzeResolvedProject = xa; exports.appendDecisionTape = _chunkA5EIY3HIcjs.g; exports.architecturalPolicies = _chunkRNQHRDCQcjs.l; exports.arkRunGraphQueryFromSearchParams = _chunkA5EIY3HIcjs.p; exports.arkRunInspectorUrl = _chunkA5EIY3HIcjs.O; exports.buildArkRunInspectorHardening = _chunkA5EIY3HIcjs.Q; exports.buildArkRunInspectorOutboxMonitor = _chunkA5EIY3HIcjs.R; exports.buildArkRunInspectorSnapshot = _chunkA5EIY3HIcjs.V; exports.buildArkRunInspectorWorkflowsMonitor = _chunkA5EIY3HIcjs.T; exports.buildDependencyInformationPackage = _chunkA5EIY3HIcjs.f; exports.buildPublishPolicyContext = _chunkRNQHRDCQcjs.n; exports.catalogFixForRuleId = Fo; exports.catalogWhyForRuleId = $o; exports.checkAdapterGovernance = jt; exports.checkContract = es; exports.classifyArkPolicyDelta = vn; exports.classifyArkRunInspectorStoreDurability = _chunkA5EIY3HIcjs.P; exports.closeArkRunGraphQuery = _chunkA5EIY3HIcjs.o; exports.closedArkRunEphemeral = _chunkA5EIY3HIcjs.w; exports.closedArkRunTransportKind = _chunkA5EIY3HIcjs.v; exports.collectAnalysisConfigWarnings = Ot; exports.collectForbiddenCapabilityUses = Pe; exports.compareInformationPackages = Tn; exports.createAICodeGate = cs; exports.createAdapter = Qr; exports.createAdapterResult = Zo; exports.createArchitectureProfile = _chunkRNQHRDCQcjs.ha; exports.createArchitectureProfileFromArkConfig = _chunkRNQHRDCQcjs.ia; exports.createArkKernel = _chunkRNQHRDCQcjs.va; exports.createArkKernelFromConfig = _chunkRNQHRDCQcjs.xa; exports.createArkManifest = _chunkRNQHRDCQcjs.pa; exports.createArkTestHarness = Zr; exports.createAuditTrail = _chunkRNQHRDCQcjs.Y; exports.createDependencyGraph = _chunkRNQHRDCQcjs.Z; exports.createElevenLayerArkConfig = _chunkRNQHRDCQcjs.ka; exports.createEventBus = _chunkRNQHRDCQcjs.R; exports.createEventContractRegistry = _chunkRNQHRDCQcjs.T; exports.createIntentRegistry = _chunkRNQHRDCQcjs.d; exports.createLenientArkKernel = _chunkRNQHRDCQcjs.Aa; exports.createLenientArkKernelFromConfig = _chunkRNQHRDCQcjs.za; exports.createMetadataRegistry = _chunkRNQHRDCQcjs.la; exports.createObservabilityReporter = _chunkRNQHRDCQcjs.W; exports.createProjectionRegistry = _chunkRNQHRDCQcjs.na; exports.createResolvedCandidateFacts = an; exports.createSaga = _chunkRNQHRDCQcjs.sa; exports.createStrictArkKernel = _chunkRNQHRDCQcjs.wa; exports.createStrictArkKernelFromConfig = _chunkRNQHRDCQcjs.ya; exports.createWorkflowEngine = _chunkRNQHRDCQcjs.ra; exports.defaultIntentRegistry = _chunkRNQHRDCQcjs.e; exports.defineArchitectureProfilePolicy = _chunkRNQHRDCQcjs.m; exports.defineIntent = _chunkRNQHRDCQcjs.c; exports.defineLayerPolicy = _chunkRNQHRDCQcjs.j; exports.definePolicy = _chunkRNQHRDCQcjs.i; exports.definePort = Jr; exports.definePublishPolicy = _chunkRNQHRDCQcjs.o; exports.detectArchitectureCycles = En; exports.deterministicHash = Z; exports.diagnosticDocsFragment = Wr; exports.diagnosticDocsPath = Lo; exports.elevenLayerProfile = _chunkRNQHRDCQcjs.ja; exports.evaluateArchitectureGraph = He; exports.explainViolation = zs; exports.extractSemanticDependencies = Ne; exports.formatArkRunGraphMermaid = _chunkA5EIY3HIcjs.q; exports.formatArkRunInspectorSseEvent = _chunkA5EIY3HIcjs.W; exports.getDiagnosticCatalogEntry = ut; exports.isArkRunInspectorLoopbackHost = _chunkA5EIY3HIcjs.M; exports.isArkRunInspectorProductionEnv = _chunkA5EIY3HIcjs.L; exports.isCataloguedOrArkRuleFamily = Po; exports.isKnownDiagnosticCode = No; exports.isLayerPolicy = _chunkRNQHRDCQcjs.k; exports.loadContract = vt; exports.loadResolvedCandidateFacts = Ae; exports.policyDeltaAcknowledgementMatches = In; exports.preflightChange = Ta; exports.preflightResolvedChange = La; exports.replayInformationPackages = $a; exports.requestArkRunGraph = _chunkA5EIY3HIcjs.r; exports.resolveArkRunInspectorBind = _chunkA5EIY3HIcjs.N; exports.resolveArkRunSendPlan = _chunkA5EIY3HIcjs.x; exports.resolvedFactsEvidenceRequirementsHash = Xe; exports.serializeDiagnosticCatalog = Do; exports.shadowInformationPackage = Fa; exports.stableSerialize = W; exports.startArkRunInspector = _chunkRNQHRDCQcjs.ta; exports.syncRegistryToGraph = _chunkRNQHRDCQcjs._; exports.toAdapterDiagnostic = Gt; exports.unavailableArkRunInspectorOutboxMonitor = _chunkA5EIY3HIcjs.S; exports.unavailableArkRunInspectorWorkflowsMonitor = _chunkA5EIY3HIcjs.U; exports.validateIntentName = _chunkRNQHRDCQcjs.f; exports.version = _chunkRNQHRDCQcjs.a;