arkgate 4.8.24 → 4.8.26

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 (166) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +2 -2
  3. package/bin/ark-check-runtime.mjs +17 -14
  4. package/bin/ark-layer-match.mjs +115 -13
  5. package/bin/ark-mcp-runtime.mjs +36 -31
  6. package/bin/ark-shared.mjs +4 -23
  7. package/bin/lib/adoption-stance.mjs +2 -2
  8. package/bin/lib/adr-path.mjs +3 -3
  9. package/bin/lib/agent-gates.mjs +0 -61
  10. package/bin/lib/agent-homes.mjs +12 -21
  11. package/bin/lib/agent-projection-command.mjs +4 -4
  12. package/bin/lib/ambient-state.mjs +9 -30
  13. package/bin/lib/analysis-engine.mjs +14 -14
  14. package/bin/lib/architecture-scan.mjs +11 -9
  15. package/bin/lib/ark-order-doctor.mjs +3 -28
  16. package/bin/lib/ark-order-facts.mjs +6 -99
  17. package/bin/lib/ark-order-types.mjs +1 -2
  18. package/bin/lib/ark-run-doctor.mjs +3 -28
  19. package/bin/lib/ark-run-facts.mjs +30 -40
  20. package/bin/lib/ark-run-sensors.mjs +1 -1
  21. package/bin/lib/arkrule-file-hints.mjs +2 -47
  22. package/bin/lib/arkrules-contract.mjs +124 -133
  23. package/bin/lib/arkrules-sensors.mjs +7 -5
  24. package/bin/lib/check-args.mjs +63 -1
  25. package/bin/lib/ci-and-commands.mjs +8 -72
  26. package/bin/lib/ci-merge-boundary.mjs +1 -1
  27. package/bin/lib/class-source-scan.mjs +5 -5
  28. package/bin/lib/clone-detection.mjs +474 -0
  29. package/bin/lib/codex-home.mjs +1 -1
  30. package/bin/lib/config-contract-slices.mjs +44 -6
  31. package/bin/lib/config-contract.mjs +40 -117
  32. package/bin/lib/config-extras.mjs +16 -22
  33. package/bin/lib/contract-smells.mjs +33 -15
  34. package/bin/lib/core-ratchet.mjs +0 -2
  35. package/bin/lib/dashboard-cli.mjs +2 -2
  36. package/bin/lib/deep-module-coach.mjs +2 -4
  37. package/bin/lib/deploy-path.mjs +13 -38
  38. package/bin/lib/design-smells.mjs +2 -2
  39. package/bin/lib/diagnostic-catalog.mjs +8 -1
  40. package/bin/lib/doctor-advisories.mjs +55 -9
  41. package/bin/lib/doctor-green-cite.mjs +1 -1
  42. package/bin/lib/doctor-human.mjs +1 -1
  43. package/bin/lib/doctor-next-actions.mjs +2 -2
  44. package/bin/lib/doctor-plan.mjs +4 -6
  45. package/bin/lib/duplication-io.mjs +572 -0
  46. package/bin/lib/effective-contract-load.mjs +181 -44
  47. package/bin/lib/entry-points-io.mjs +424 -0
  48. package/bin/lib/extra-merge-teeth.mjs +36 -0
  49. package/bin/lib/field-install.mjs +38 -14
  50. package/bin/lib/first-run-help.mjs +7 -3
  51. package/bin/lib/flat-parent-importers.mjs +5 -3
  52. package/bin/lib/gate-files.mjs +30 -89
  53. package/bin/lib/github-enforcement.mjs +165 -28
  54. package/bin/lib/golden-pattern.mjs +1 -1
  55. package/bin/lib/hook-templates.mjs +16 -16
  56. package/bin/lib/html-report-advisories.mjs +4 -0
  57. package/bin/lib/html-report-depth.mjs +2 -2
  58. package/bin/lib/html-report.mjs +2 -2
  59. package/bin/lib/import-graph-projection.mjs +112 -0
  60. package/bin/lib/improvement-compass-doctor.mjs +1 -24
  61. package/bin/lib/invariant-coverage-io.mjs +4 -3
  62. package/bin/lib/invariant-coverage.mjs +26 -0
  63. package/bin/lib/invariant-probe-cli.mjs +347 -0
  64. package/bin/lib/invariant-probe-io.mjs +165 -0
  65. package/bin/lib/invariant-probe-runner.mjs +268 -0
  66. package/bin/lib/invariant-probe-sites.mjs +174 -0
  67. package/bin/lib/invariant-probe-workspace.mjs +183 -0
  68. package/bin/lib/invariant-probe.mjs +461 -0
  69. package/bin/lib/invariant-tests-path.mjs +16 -22
  70. package/bin/lib/literal-path-drift.mjs +4 -2
  71. package/bin/lib/managed-upgrade.mjs +2 -8
  72. package/bin/lib/mcp-adoption.mjs +4 -5
  73. package/bin/lib/mcp-hook-payload.mjs +4 -4
  74. package/bin/lib/orphan-modules-io.mjs +458 -0
  75. package/bin/lib/orphan-modules.mjs +251 -0
  76. package/bin/lib/outside-importers.mjs +197 -0
  77. package/bin/lib/package-manager.mjs +3 -3
  78. package/bin/lib/parse-health.mjs +1 -1
  79. package/bin/lib/persistence-write-hint.mjs +33 -8
  80. package/bin/lib/pin-dependent-gates.mjs +2 -2
  81. package/bin/lib/policy-delta-io.mjs +60 -12
  82. package/bin/lib/post-green-path.mjs +1 -1
  83. package/bin/lib/prepare-change.mjs +3 -9
  84. package/bin/lib/prepare-write.mjs +1 -2
  85. package/bin/lib/presets.mjs +56 -68
  86. package/bin/lib/product-copy.mjs +1 -6
  87. package/bin/lib/project-root.mjs +43 -85
  88. package/bin/lib/resolved-candidate-facts.mjs +90 -62
  89. package/bin/lib/rules-under-contract.mjs +72 -8
  90. package/bin/lib/scan-files.mjs +4 -4
  91. package/bin/lib/schema-validation.mjs +130 -0
  92. package/bin/lib/sensor-promote-cli.mjs +2 -11
  93. package/bin/lib/sensor-promote-io.mjs +33 -22
  94. package/bin/lib/sensor-promotion.mjs +1 -1
  95. package/bin/lib/skill-catalog-apply.mjs +1 -1
  96. package/bin/lib/skill-install.mjs +42 -38
  97. package/bin/lib/snippet-analysis.mjs +1 -1
  98. package/bin/lib/start-install-recovery.mjs +1 -1
  99. package/bin/lib/start-preview.mjs +1 -1
  100. package/bin/lib/states-transitions-presence.mjs +3 -3
  101. package/bin/lib/status-command.mjs +2 -18
  102. package/bin/lib/status-manifest.mjs +18 -26
  103. package/bin/lib/status-transition-catalog.mjs +0 -6
  104. package/bin/lib/suggestions.mjs +3 -3
  105. package/bin/lib/team-parliament-io.mjs +3 -17
  106. package/bin/lib/team-parliament.mjs +15 -9
  107. package/bin/lib/upgrade-behavior-changes.mjs +2 -2
  108. package/bin/lib/upgrade-command.mjs +2 -24
  109. package/bin/lib/upgrade-outcome.mjs +1 -1
  110. package/bin/lib/upstream-report.mjs +21 -10
  111. package/bin/lib/violations.mjs +10 -9
  112. package/bin/lib/weakest-link.mjs +13 -0
  113. package/bin/lib/write-path-capabilities.mjs +2 -2
  114. package/dist/chunk-G3JRBJGH.js +16 -0
  115. package/dist/chunk-R3AJ5RSZ.cjs +16 -0
  116. package/dist/{configTypes-BJbaeoj4.d.cts → configTypes-GPvvdleM.d.cts} +12 -1
  117. package/dist/{configTypes-BJbaeoj4.d.ts → configTypes-GPvvdleM.d.ts} +12 -1
  118. package/dist/eslint/index.cjs +11 -11
  119. package/dist/eslint/index.d.cts +10 -1
  120. package/dist/eslint/index.d.ts +10 -1
  121. package/dist/eslint/index.js +11 -11
  122. package/dist/index.cjs +34 -34
  123. package/dist/index.d.cts +587 -515
  124. package/dist/index.d.ts +587 -515
  125. package/dist/index.js +34 -34
  126. package/dist/nestjs/index.cjs +1 -1
  127. package/dist/nestjs/index.d.cts +1 -1
  128. package/dist/nestjs/index.d.ts +1 -1
  129. package/dist/nestjs/index.js +1 -1
  130. package/dist/order/index.cjs +1 -1
  131. package/dist/order/index.js +1 -1
  132. package/dist/runtime/index.cjs +12 -12
  133. package/dist/runtime/index.d.cts +174 -136
  134. package/dist/runtime/index.d.ts +174 -136
  135. package/dist/runtime/index.js +12 -12
  136. package/dist/{types-DRinG-vT.d.cts → types-CnauMQQL.d.cts} +33 -25
  137. package/dist/{types-DRinG-vT.d.ts → types-CnauMQQL.d.ts} +33 -25
  138. package/docs/README.md +3 -1
  139. package/docs/agent-guide.md +140 -6
  140. package/docs/ai-gates.md +15 -1
  141. package/docs/configuration.md +40 -11
  142. package/docs/diagnostics.md +119 -3
  143. package/docs/package-surface.md +4 -1
  144. package/docs/product-voice.md +7 -1
  145. package/package.json +11 -2
  146. package/schemas/ark.config.schema.json +31 -3
  147. package/schemas/ark.invariant-probe.schema.json +368 -0
  148. package/server.json +2 -2
  149. package/templates/agent-skills/README.md +1 -1
  150. package/templates/agent-skills/ark-adopt/SKILL.md +1 -0
  151. package/templates/agent-skills/ark-contract/SKILL.md +17 -0
  152. package/templates/agent-skills/ark-coverage/SKILL.md +2 -0
  153. package/templates/agent-skills/ark-explore/SKILL.md +7 -0
  154. package/templates/agent-skills/ark-fix/SKILL.md +20 -0
  155. package/templates/agent-skills/ark-place/SKILL.md +8 -0
  156. package/templates/skills/ark-adopt.md +1 -0
  157. package/templates/skills/ark-contract.md +17 -0
  158. package/templates/skills/ark-coverage.md +2 -0
  159. package/templates/skills/ark-explore.md +7 -0
  160. package/templates/skills/ark-fix.md +20 -0
  161. package/templates/skills/ark-place.md +8 -0
  162. package/bin/lib/ark-order-error.mjs +0 -18
  163. package/bin/lib/ark-order-invariants.mjs +0 -388
  164. package/bin/lib/stable-hash.mjs +0 -90
  165. package/dist/chunk-MBXCFLO4.js +0 -16
  166. package/dist/chunk-RNQHRDCQ.cjs +0 -16
package/dist/index.cjs CHANGED
@@ -1,56 +1,56 @@
1
- "use strict";var xn=Object.defineProperty;var wc=Object.getOwnPropertyDescriptor;var Tc=Object.getOwnPropertyNames;var Lc=Object.prototype.hasOwnProperty;var a=(e,t)=>xn(e,"name",{value:t,configurable:!0});var Nc=(e,t)=>{for(var n in t)xn(e,n,{get:t[n],enumerable:!0})},Pc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Tc(t))!Lc.call(e,o)&&o!==n&&xn(e,o,{get:()=>t[o],enumerable:!(r=wc(t,o))||r.enumerable});return e};var Dc=e=>Pc(xn({},"__esModule",{value:!0}),e);var $g={};Nc($g,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Et,AGENT_PROJECTION_BEGIN_MARKER:()=>Po,AGENT_PROJECTION_END_MARKER:()=>mn,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>At,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>hn,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>Vo,AGENT_SKILL_ENTRY_FILENAME:()=>Go,ANALYSIS_IR_SCHEMA_VERSION:()=>Qn,ARKORDER_RULE_IDS:()=>Lr,ARKORDER_TIER1_SENSOR_IDS:()=>Pl,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>co,ARKRUN_KERNEL_FACTORY_CALLEES:()=>ao,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>Il,ARKRUN_RULE_IDS:()=>Tr,ARKRUN_TIER1_SENSOR_IDS:()=>_l,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>lo,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>He,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>kc,ARK_ANALYSIS_RESULT_SCHEMA:()=>ts,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>It,ARK_CONFIG_SCHEMA:()=>qn,ARK_CONFIG_SCHEMA_VERSION:()=>ie,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Ql,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Jl,ARK_FIRST_CLASS_SKILL_NAMES:()=>Wr,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>pn,ARK_PROJECT_IDENTITY_SCHEMA:()=>fi,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>ns,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>pi,ARK_RULES_SCHEMA:()=>tr,ARK_RULES_SCHEMA_VERSION:()=>Ea,ARK_RULE_SENSORS:()=>Ds,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>yo,ARK_SKILL_CAPACITY:()=>In,ARK_SKILL_CAPACITY_DEDICATED_DOORS:()=>Bo,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>Yr,ARK_SKILL_NAMES:()=>bn,ARK_SKILL_NAME_COUNT:()=>zo,ARK_SKILL_NORTH_STAR:()=>Ic,ARK_SKILL_REQUIRED_SURFACES:()=>En,ARK_SKILL_STUB_REDIRECTS:()=>Gr,ARK_STATUS_MANIFEST_SCHEMA:()=>ac,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Ao,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>jr,ArkRulesValidationError:()=>we,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>Do,DIAGNOSTIC_CATALOG:()=>St,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ti,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>On,DIAGNOSTIC_RULE_IDS:()=>ni,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>yl,EffectiveContractError:()=>qt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>Uo,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>je,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>gn,IMPROVEMENT_LENS_IDS:()=>fn,MERGE_PLANES_DUAL_STAMP:()=>oo,POLICY_DELTA_SCHEMA_VERSION:()=>ur,PROJECT_BINDING_SCHEMA:()=>ss,PROJECT_EXPECTATION_SCHEMA:()=>rs,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Jn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>De,STATUS_COMPASS_FACTS_SOURCES:()=>So,STATUS_COMPASS_MODES:()=>Ro,STATUS_COMPASS_REASON_CODES:()=>un,adapterDocsCodePath:()=>vt,adapterFindingOccurrenceTargetKeys:()=>nt,adapterFindingRefFromTargetKey:()=>bt,adapterFindingTargetKey:()=>tt,agentProjectionContentIdentity:()=>Je,agentSkillEntryRelativePath:()=>Jo,agentSkillPackageFileRelativePath:()=>xc,analyzeArchitectureConvergence:()=>We,analyzeChange:()=>Qt,analyzePolicyDelta:()=>Ws,analyzeProject:()=>mt,analyzeResolvedProject:()=>go,arkRunKernelCallKind:()=>nn,arkSkillStubRedirect:()=>Ec,buildAgentProjectionBeginMarker:()=>Kr,buildAgentProjectionBlock:()=>$o,buildAgentProjectionBody:()=>Sn,buildAgentProjectionMeta:()=>Mo,buildArkRuleFileHints:()=>kr,buildEffectiveArkRules:()=>nr,buildImprovementCompass:()=>gc,buildRulesInventory:()=>Xl,buildStatusManifest:()=>rc,canPromoteInvariant:()=>lr,catalogFixForRuleId:()=>ai,catalogWhyForRuleId:()=>li,classifyArkPolicyDelta:()=>pr,classifyCoverage:()=>Fa,classifyResolvedLayerCoverage:()=>Er,classifyStatusWritePath:()=>Io,collectAnalysisConfigWarnings:()=>cn,collectEmptyAppliesToFindings:()=>Sr,collectForbiddenCapabilityUses:()=>Ge,composeMergePlanesHonesty:()=>en,countsAsCoverage:()=>Hs,createAICodeGate:()=>Cs,createAdapterResult:()=>ui,createArchitectureProfile:()=>Vt,createArchitectureProfileFromArkConfig:()=>Os,createElevenLayerArkConfig:()=>ws,createProjectId:()=>gi,createProjectIdentity:()=>mi,createResolvedCandidateFacts:()=>Zn,defaultHonestLabel:()=>Eo,demoteExtraPlaneTeethUnderClassificationFloor:()=>Al,deriveArkRuleFileHints:()=>no,describeCoverage:()=>Ks,detectArchitectureCycles:()=>mr,deterministicHash:()=>ee,diagnosticDocsFragment:()=>es,diagnosticDocsPath:()=>oi,effectiveContractPolicyPayload:()=>rr,elevenLayerProfile:()=>Kt,emptyEffectiveArkRules:()=>$e,evaluateArchitectureGraph:()=>Xe,evaluateArkOrderSensors:()=>Nr,evaluateArkRuleSensors:()=>Rr,evaluateArkRunEditorSensors:()=>uo,evaluateArkRunEditorSensorsFromSource:()=>Ol,evaluateArkRunSensors:()=>an,evaluateInvariantCoverage:()=>ar,evaluateStatusBinding:()=>ko,explainViolation:()=>qs,extraMergeTeethAllowed:()=>Ae,extractAgentProjectionBlock:()=>kn,extractArkRunDeclarationsFromSource:()=>bl,extractArkRunImportedConstructorNamesFromSource:()=>xr,extractArkRunKernelCallsFromSource:()=>Or,extractArkRunManagedNewsFromSource:()=>wr,extractArkRunValueImportDependenciesFromSource:()=>_r,extractClassShapesFromSource:()=>hl,extractSemanticDependencies:()=>Ue,flatSkillTemplateFileRelativePath:()=>Oc,formatAgentProjectionCatalogShortList:()=>Vr,formatAgentProjectionLayers:()=>yn,formatArkRunDoctorLines:()=>zl,formatImprovementCompassDoctorLines:()=>mc,formatImprovementCompassResidualLabels:()=>Lo,getDiagnosticCatalogEntry:()=>kt,inventoryToExtractionCard:()=>Zl,isArkOrderRuleId:()=>ro,isArkRunKernelModuleSpecifier:()=>Ze,isArkRunRuleId:()=>br,isArkRunTransportBypassSpecifier:()=>Cr,isArkSkillName:()=>qr,isCataloguedOrArkRuleFamily:()=>si,isExtraPlaneFinding:()=>so,isFirstClassArkSkillName:()=>Br,isKnownDiagnosticCode:()=>ri,isValidAgentSkillName:()=>Wo,loadArkConfigContract:()=>Ht,loadArkRulesContract:()=>Wt,loadContract:()=>Jt,loadResolvedCandidateFacts:()=>Oe,mergeAgentProjectionDocument:()=>Ko,normalizeExtraMergeTeethClassification:()=>Ir,normalizeSkillContent:()=>zr,normalizeStatusImprovementCompass:()=>vo,parseAgentProjectionStamp:()=>Ur,parseArkConfigJson:()=>Xn,parseArkRulesJson:()=>ba,parseSkillDescriptionVersion:()=>Cc,parseSkillDocument:()=>qo,policyDeltaAcknowledgementMatches:()=>fr,preflightChange:()=>mo,preflightResolvedChange:()=>ho,primaryImprovementCompassNextAction:()=>No,projectStatusArkRun:()=>Mr,projectStatusImprovementCompass:()=>Hr,projectionHasNonEnforcementLabel:()=>Ho,projectionMatchesPackageVersion:()=>jo,resolveEffectiveContract:()=>Ca,resolveStatusNextAction:()=>bo,resolvedFactsEvidenceRequirementsHash:()=>pt,serializeDiagnosticCatalog:()=>ii,skillDescriptionVersionPrefix:()=>Xo,stableSerialize:()=>X,stampSkillDescription:()=>_c,statusCompassResidualIsSubsetOfDoctor:()=>ic,stripSkillDescriptionVersion:()=>Zo,summarizeArkRunSection:()=>Bl,toAdapterDiagnostic:()=>wn,unavailableStatusImprovementCompass:()=>oc,validateAgentSkillDocument:()=>Yo,validateAgentSkillsPackage:()=>bc,validateSkillProductCapacity:()=>vc,version:()=>ei});module.exports=Dc($g);var ei="4.8.24";var On="docs/diagnostics.md",ti="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 St=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("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}),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("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}),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 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."),I("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."),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 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."),I("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."),I("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."),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("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."),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("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."),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.","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."),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("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}),I("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}),I("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}),I("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}),I("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}),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.")]),Qr=new Map(St.map(e=>[e.ruleId,e])),ni=Object.freeze(St.map(e=>e.ruleId));function ri(e){return typeof e=="string"&&e.length>0&&Qr.has(e)}a(ri,"isKnownDiagnosticCode");function si(e){return typeof e!="string"||e.length===0?!1:Qr.has(e)?!0:e.startsWith("ARKRULE_")}a(si,"isCataloguedOrArkRuleFamily");function kt(e){if(!(typeof e!="string"||e.length===0))return Qr.get(e)}a(kt,"getDiagnosticCatalogEntry");function es(e){return`#${kt(e)?.docsAnchor??e}`}a(es,"diagnosticDocsFragment");function oi(e){return`${On}${es(e)}`}a(oi,"diagnosticDocsPath");function ii(){return{schemaVersion:"1.0",docsPath:On,codes:St}}a(ii,"serializeDiagnosticCatalog");function ai(e){return kt(e)?.fix}a(ai,"catalogFixForRuleId");function li(e){return kt(e)?.why}a(li,"catalogWhyForRuleId");var $c=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."})]),Mc=new Map($c.map(e=>[e.reasonId,e]));function ci(e){if(!(typeof e!="string"||e.length===0))return Mc.get(e)}a(ci,"sliceReasonHint");var Fc=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,jc=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Hc=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Kc(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Fc.test(n)?"pure-shared":r==="PersistenceAdapters"&&(jc.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Hc.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(Kc,"classifyLayerImportKind");function Vc(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}a(Vc,"sliceHintAction");function Uc(e){let t=ci(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${Vc(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=Kc(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 ${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(Uc,"layerImportNextAction");function Gc(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Gc,"arkRunCallSiteName");function Bc(e){let t=Gc(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(Bc,"arkRunNextAction");function Re(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Uc(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 ${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 Bc(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(Re,"deterministicNextAction");var It="1.5",Et="docs/diagnostics.md",ts={$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 tt(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(tt,"adapterFindingTargetKey");function nt(e){let t=new Map;return e.map(n=>{let r=tt(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(nt,"adapterFindingOccurrenceTargetKeys");function bt(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(bt,"adapterFindingRefFromTargetKey");function vt(e){return`${Et}#${e}`}a(vt,"adapterDocsCodePath");function _(e){return typeof e=="string"&&e.length>0?e:void 0}a(_,"text");function di(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(di,"positiveInteger");function zc(e,t,n){return Re({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(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:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0,reasonId:_(t.reasonId)??void 0})}a(zc,"nextActionForDiagnostic");var Wc=new Set(["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]);function qc(e){let t=e.details,n=t!==null&&typeof t=="object"?t.reasonId:void 0,r=_(e.reasonId)??_(n);return r&&Wc.has(r)?r:void 0}a(qc,"sliceReasonOf");function wn(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s=qc(e),i={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(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}:{},..._(e.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{},...s?{reasonId:s}:{},...s&&_(e.universeFrom)?{universeFrom:_(e.universeFrom)}:{},...s&&_(e.universeTo)?{universeTo:_(e.universeTo)}:{}},l=n??tt(e),c=bt(l);return{ruleId:r,severity:o,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:di(e.line,1),column:di(e.column,1)},evidence:i,nextAction:_(e.nextAction)??zc(r,i,e),findingRef:c,targetKey:l,docsCodePath:vt(r)}}a(wn,"toAdapterDiagnostic");function ui(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(m=>({code:_(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(m.message)??`Analysis ${t}: required evidence is incomplete.`,..._(m.file)?{file:_(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],i=e.warnings??[],l=nt(s),c=nt(i),d=[...s.map((m,f)=>wn(m,"error",l[f])),...i.map((m,f)=>wn(m,"warning",c[f]))],u={schemaVersion:"1.5",completenessReasons:r,diagnostics:d};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...u,mode:n,valid:!1,completeness:t,...o};let m={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...u,mode:n,valid:e.valid,completeness:t,...m}:{...u,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...u,mode:n,valid:e.valid,completeness:t,...o}:{...u,mode:n,valid:!1,completeness:t,...o}}a(ui,"createAdapterResult");var pi="1.0",ns="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Tn="^sha256:[a-f0-9]{64}$",rs={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:Tn,description:"Project id previously returned by ark_identity or ark_manifest."}}},ss={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:Tn},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},fi={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ns,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:Tn},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Tn},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:rs,binding:ss}};function gi(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}a(gi,"createProjectId");function mi(e){return{schemaVersion:"1.0",...e}}a(mi,"createProjectIdentity");var is=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ls=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),cs=Object.freeze(Object.keys(ls).sort()),os=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"}),as=Object.freeze({process:Object.freeze(["process","node:process"])});function Ct(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=os[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=os[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:os[e.slice(0,s)]??null}a(Ct,"capabilityForModuleSpecifier");function Le(e,t){for(let n of t)if(as[n]?.includes(e))return n;return null}a(Le,"forbiddenGlobalForModuleSpecifier");function Ln(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=ls[r];if(o)return o}return null}a(Ln,"capabilityForAmbientName");function rt(e){if(e?.pure===!0)return[...is].sort();let n=(e?.capabilities?.deny??[]).filter(r=>is.includes(r));return[...new Set(n)].sort()}a(rt,"effectiveCapabilityDeny");function _t(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(_t,"ambientCoveredByForbiddenGlobals");function Nn(e){let t=new Set,n=new Set,r=Object.keys(ls);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 as[o]??[])t.add(`import-exact:${i}`)}for(let o of rt(e)){if(t.add(`import:${o}`),o==="process")for(let s of as.process)t.add(`import-exact:${s}`);for(let s of r)Ln(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(Nn,"loweredLayerCoverage");function Ne(e){if(e==="deny"||e==="deny-cross-parent")return e;if(e!==null&&typeof e=="object"){let t=e.mode;if(t==="deny-cross-parent")return t}}a(Ne,"sharedImportsSliceMode");function Fn(e){if(e===null||typeof e!="object")return[];let t=e.stopAt;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}a(Fn,"sharedImportsSliceStopAt");var hi=new Map;function yi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(yi,"escapeLiteral");function jn(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(jn,"normalizeGlobSeparators");function Yc(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(Yc,"bracesBalanced");function me(e){let t=hi.get(e);if(t)return t;let n=jn(e),r=Yc(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=yi(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+=yi(c)}let i=new RegExp(`^${o}$`);return hi.set(e,i),i}a(me,"globToRegExp");function Xc(e){return jn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Xc,"concreteGlobSegments");function fs(e,t){let n=jn(String(e)),r=Xc(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 d of r){let u=-1;for(let m=l;m<i.length;m+=1)if(i[m]===d){u=m;break}if(u<0)return s;c=u,l=u+1}return(c+1)*1e6+r.length*1e4+o}a(fs,"patternSpecificity");function he(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>me(i).test(n))){for(let i of s.patterns??[])if(me(i).test(n)){let l=fs(i,n);l>o&&(o=l,r=s.name)}}return r}a(he,"layerForRelativePath");function wt(e,t,n){return vi(e,t,n==="stars"?"stars":"path")}a(wt,"sliceIdForPath");function us(e,t){return vi(e,t?[...t]:void 0,bi)}a(us,"legacyStarsSliceIdForPath");var bi="stars-4.8.23";function vi(e,t,n){if(!t?.length)return;let r=String(e).split(/[/\\]/).filter(Boolean);if(r.length===0)return;let o=new Set;for(let s of t){if(typeof s!="string"||s.length===0)continue;let i=Zc(s);if(i.anchored){let l=Qc(r,i.anchored,n);if(l)return l;continue}i.bare!==void 0&&o.add(i.bare)}return rd(r,o)}a(vi,"sliceIdWithBinding");var Pn=new Map;function Zc(e){let t=Pn.get(e);if(t)return t;let n={};return Ci(e)?n={anchored:Jc(e)}:!e.includes("/")&&!e.includes("\\")&&!e.includes("*")&&(n={bare:e.toLowerCase()}),Pn.size>=1024&&Pn.clear(),Pn.set(e,n),n}a(Zc,"parsedSliceFolder");function Ci(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Ci,"isAnchoredSliceEntry");function Jc(e){return e.split(/[/\\]/).filter(t=>t.length>0).map(t=>t.toLowerCase())}a(Jc,"anchoredSlicePattern");function Qc(e,t,n){let r=Oi(e,t[0]??"");for(let o of r){let s=ed(e,t,o,n);if(s)return s}}a(Qc,"anchoredSliceIdFromPattern");function ed(e,t,n,r="path"){let o=[],s=[],i=-1,l=n;for(let c=0;c<t.length;c+=1){let d=t[c];if(d==="*"){if(l>=e.length-1){for(let u=c;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[l].toLowerCase()),s.push(!0),l+=1;continue}if(d==="**"||l>=e.length||e[l].toLowerCase()!==d)return;o.push(e[l].toLowerCase()),s.push(!1),i=o.length-1,l+=1}if(o.length!==0)return r===bi?i<0?void 0:o.slice(i).join("/"):r==="stars"?i<0?void 0:o.filter((c,d)=>d>=i||s[d]).join("/"):o.join("/")}a(ed,"bindAnchoredSlice");function _i(e){let t=-1;for(let r=0;r<e.length;r+=1)e[r]!=="*"&&(t=r);if(t<0)return null;let n=[];for(let r=0;r<e.length;r+=1)(r>=t||e[r]==="*")&&n.push(r);return n}a(_i,"starsKeptSegmentIndexes");function xi(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=td(s);if(!i)continue;let l=s.split(/[/\\]/).filter(u=>u.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let d=r.get(i)??[];d.push(s),r.set(i,d)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:nd(n.from,n.to,i,s)})}return t}a(xi,"sliceIdentityCollisions");function td(e){if(!Ci(e))return;let t=e.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(t.some(r=>r==="**"))return;let n=_i(t);if(n)return n.map(r=>t[r]).join("/")}a(td,"starsIdentityStem");function nd(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(nd,"formatSliceIdentityCollision");function rd(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(rd,"bareSliceId");function sd(e){let t=new Set;for(let n of e??[]){let o=jn(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(sd,"inferSliceFoldersFromPatterns");function gs(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 sd(r?.patterns)}a(gs,"resolveSliceFolders");function Ai(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(Ai,"normalizeSegments");function Tt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Tt,"trimTrailingSlashes");var od=["src","app"];function Oi(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return od.includes(n)&&r!==n?[0,1]:[0]}a(Oi,"anchorOffsets");function id(e){let t=Tt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(id,"isBlanketRoot");function ot(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Ai(n);for(let s of t){if(typeof s!="string"||s.length===0||id(s))continue;if(s.includes("*")){let c=Tt(s.toLowerCase());if(me(c).test(r)||me(`${c}/**`).test(r))return!0;continue}let i=Ai(s);if(i.length===0)continue;let l=Oi(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let d=!0;for(let u=0;u<i.length;u+=1)if(o[c+u]!==i[u]){d=!1;break}if(d)return!0}}return!1}a(ot,"pathUnderSharedRoot");function Ri(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(Ri,"sliceMatchesDeclaration");function Dn(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Ri(r.from,t)&&Ri(r.to,n))}a(Dn,"crossSliceEdgeAllowed");function ad(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(ad,"peerIsolationDecision");function wi(e){return Tt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(wi,"aliasGlobPattern");function Ti(e,t){let n=wi(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=ps(r),s=me(n),l=(n.split("/").pop()??"").includes("*")?null:me(`${n}/**`),c=a(d=>s.test(d)||l!==null&&l.test(d),"hit");return c(r)||o!==r&&c(o)}a(Ti,"aliasGlobMatches");function Li(e,t){return!e||!t?.length?!1:ot(e,[...t])?!0:t.some(n=>typeof n=="string"&&Ti(n,e))}a(Li,"pathMatchesSharedWalkStop");function ms(e){let t=wi(e).split("/").filter(Boolean);return t.length<2||t.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:t.slice(0,-1).join("/"),childId:t.join("/")}}a(ms,"splitAliasTarget");function Ni(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Ti(n.from,e))return n;return null}a(Ni,"firstSliceAliasEntry");function ld(e,t){let n=Ni(e,t);return n?ms(n.to):null}a(ld,"firstSliceAlias");function xt(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=wt(e,r?[...r]:void 0,t.sliceIdentity),s=$n(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=ld(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(xt,"resolveGovernedSlice");function cd(e){let t=[];for(let n of e??[]){if(typeof n!="string"||n.length===0)continue;let r=n.split(/[/\\]/).filter(Boolean).map(l=>l.toLowerCase());if(r.length===1&&r[0]&&!r[0].includes("*")){t.push({literals:[r[0],null],legacy:[r[0],null]});continue}if(r.some(l=>l==="**"||l.includes("*")&&l!=="*"))continue;let o=_i(r);if(!o||!r.includes("*"))continue;let s=a(l=>l==="*"?null:l,"star"),i=o.find(l=>r[l]!=="*")??0;t.push({literals:o.map(l=>s(r[l]??"")),legacy:r.slice(i).map(s)})}return t}a(cd,"starsUniverseShapes");function Si(e,t){return e.length===t.length&&e.every((n,r)=>n===null||t[r]==="*"||n===t[r])}a(Si,"literalsMatch");function st(e,t){let n=t.split("/").filter(Boolean).map(s=>s.toLowerCase()),r=cd(e);if(n.length===0||r.some(s=>Si(s.literals,n)))return[];let o=new Set;for(let s of r)if(s.legacy.length!==s.literals.length&&Si(s.legacy,n)){let i=[...n],l=s.literals.length-s.legacy.length;o.add([...s.literals.slice(0,l).map(()=>"*"),...i].join("/"))}return[...o].sort()}a(st,"legacyStarsIdTargets");function Pi(e,t){if(e.sliceIdentity!=="stars")return;let n=ms(t);if(n)return st(e.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(Pi,"legacyAliasUniverse");function ki(e,t,n){let r=xt(e,t,n);if(!e||t.sliceIdentity!=="stars")return r;if(r.universeId){let o=Ni(e,t);if(!wt(e,[...n],t.sliceIdentity)&&o&&Pi(t,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let i=us(e,n),l=t.childSlices,c=l?.sliceIdentity==="stars"?us(e,l.sliceFolders):void 0;return{...r,...i?{legacyUniverse:i}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(ki,"placeForPair");function hs(e,t,n,r){let o=ki(n,e,t),s=ki(r,e,t),i=o.legacyUniverse,l=s.legacyUniverse,c=a((p,y)=>{if(!p.legacyAlias||y.legacyAlias||!y.universeId||y.legacyUniverse?.toLowerCase()!==p.universeId?.toLowerCase())return p;let S=p.childId?.split("/").pop();return{...p,universeId:y.universeId,...S?{childId:`${y.universeId}/${S}`}:{}}},"adopt"),d=c(o,s),u=c(s,o),m=Dn(e.allowedCrossSlice,d.universeId,u.universeId)||e.sliceIdentity==="stars"&&(i!==d.universeId||l!==u.universeId)&&Dn(e.allowedCrossSlice,i,l),f=e.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&s.legacyChild!==void 0&&o.legacyChild!==s.legacyChild&&Di(e.childSlices.allowedCrossSlice,o.legacyChild,s.legacyChild),h=a(p=>({...p.universeId?{universeId:p.universeId}:{},...p.childId?{childId:p.childId}:{}}),"strip");return{from:h(d),to:h(u),crossSliceAllowed:m,legacyChildAllowed:f}}a(hs,"resolveGovernedSlicePair");function dd(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(dd,"peerIsolationDenyExplanation");function ud(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(ud,"crossParentExplanation");function pd(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(pd,"crossSiblingExplanation");function fd(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(fd,"parentImportsChildExplanation");function Ot(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(Ot,"universePairLabel");function gd(e,t){if(!e||!t?.length)return!1;let n=e.toLowerCase();return t.some(r=>typeof r=="string"&&r.length>0&&r.toLowerCase()===n)}a(gd,"isCommonFolderName");function $n(e,t,n){if(!e||!n?.sliceFolders?.length)return{};let r=wt(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let o=r.toLowerCase(),s=t.toLowerCase();if(o===s)return{};if(!o.startsWith(`${s}/`))return{mismatched:{childId:r,universeId:t}};let i=o.slice(s.length+1).split("/")[0];return gd(i,n.commonFolders)?{}:{childId:r}}a($n,"resolveChildSliceId");function md(e){return Tt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(md,"siblingEntryKey");function ps(e){return e.replace(/^(?:src|app)\//,"")}a(ps,"stripSrcOrApp");function hd(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=ps(t);if(!r)return!1;let o=ps(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(hd,"pathUnderSubtree");function yd(e,t,n){if(!t||!n?.length)return!1;let r=t.toLowerCase();for(let o of n){if(typeof o!="string")continue;let s=md(o);if(!(!s||s.includes("*"))&&(r===s||e&&hd(e,s)))return!0}return!1}a(yd,"importerInEnforcedSubtree");function Ad(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!yd(t,n,e.enforce)}a(Ad,"siblingCrossingAdvisory");function Mn(e){if(typeof e!="string")return null;let t=Tt(e.trim().replace(/\\/g,"/")).toLowerCase();if(!t.includes("/"))return null;let n=t.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(Mn,"childSlicePatternSegments");function Ii(e,t){let n=Mn(e),r=Mn(t);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let s=n[o];if(s!=="*"&&s!==r[o])return!1}return!0}a(Ii,"childSlicePatternMatches");function Di(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&Ii(r.from,t)&&Ii(r.to,n))return!0;return!1}a(Di,"childCrossSliceAllowed");function Rd(e,t){let n=Mn(e),r=Mn(t);if(!n||!r)return!1;let o=n.slice(0,-1),s=r.slice(0,-1);if(o.length!==s.length)return!0;for(let i=0;i<o.length;i+=1){let l=o[i],c=s[i];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(Rd,"childAllowanceSpansUniverses");function Sd(e){let t=ad({fromPath:e.fromPath,toPath:e.toPath,folderCount:e.folderCount,fromSlice:e.fromSlice,toSlice:e.toSlice,fromShared:e.fromShared,toShared:e.toShared,crossSliceAllowed:e.crossSliceAllowed,sharedImportsSlice:Ne(e.rule.sharedImportsSlice)});if(t.denied){let i=!!e.rule.childSlices&&t.reason==="cross-slice";return{crossing:t.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...i?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:i?ud(e.fromSlice,e.toSlice):dd(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??$n(e.fromPath,e.fromSlice,n).childId,o=e.toChild??$n(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?e.legacyChildAllowed||Di(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:Ad(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:pd(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:fd(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(Sd,"evaluateNestedSliceWall");function $i(e){return e?.crossing==="cross-sibling"||e?.crossing==="parent-imports-child"}a($i,"isChildWallCrossing");function Hn(e,t){return $i(t)?e?.childSlices?.message:e?.message}a(Hn,"sliceConsumerMessage");function it(e){let t=e.verdict.explanation,n=$i(e.verdict),r=n?e.childMessage:e.ruleMessage;if(e.surface==="intent"){let o=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return n&&t?`${e.childMessage??o} ${t}`:e.verdict.reasonId&&t?`${o} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${o} ${t}`:r?t?`${r} (${t})`:r:o}if(r)return t?`${r} (${t})`:r;if(t){let o=e.kind??"import";return`${e.fromLayer} must not ${o} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(it,"composeSliceDenialMessage");function Ve(e){if(!e||e.decision==="allow")return{};let t=Ot(e.fromUniverse),n=Ot(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Ve,"sliceFindingExtras");function Mi(e,t){let n=[],r=new Set,o=new Set;for(let s of e??[])if(s?.peerIsolation&&s.allowed===!1&&n.push(...kd(s,t)),!!s?.childSlices){if(!s.peerIsolation||s.allowed!==!1){n.push({ruleId:"CONFIG_CHILD_SLICES_INERT",failsStrict:!1,fromLayer:s.from,toLayer:s.to,message:`${s.from} \u2192 ${s.to}: childSlices is inert on this rule and enforces nothing. The child wall runs only inside a universe wall. Add "peerIsolation": true and "allowed": false to the same rule, or remove childSlices.`});continue}for(let i of t){let l=wt(i,s.sliceFolders,s.sliceIdentity),c=$n(i,l,s.childSlices);if(!c.mismatched)continue;let d=`${s.from}\0${s.to}\0${c.mismatched.universeId}\0${c.mismatched.childId}`;r.has(d)||(r.add(d),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:s.from,toLayer:s.to,path:i,message:`${s.from} \u2192 ${s.to}: child id ${c.mismatched.childId} does not extend universe id ${c.mismatched.universeId} (${i}).`}))}for(let i of s.childSlices.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string"||!Rd(i.from,i.to))continue;let l=`${i.from.trim().toLowerCase()}\0${i.to.trim().toLowerCase()}`;o.has(l)||(o.add(l),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:s.from,toLayer:s.to,message:`childSlices.allowedCrossSlice ${i.from} \u2192 ${i.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(Mi,"childSliceConfigFindings");function Ei(e,t){let n=new Map;if(!e?.length)return n;for(let r of t){if(typeof r!="string")continue;let o=wt(r,[...e],"stars"),s=us(r,e);if(!o||!s||o===s)continue;let i=n.get(s)??new Set;i.add(o),n.set(s,i)}return n}a(Ei,"observedIdsByLegacy");function ds(e,t,n,r){let o=r?`/${r}`:"",s=`${t[0]??e}${o}`,i=[...n.get(e.toLowerCase())??[]].sort().map(l=>`${l}${o}`);return i.length===1?`${i[0]}`:i.length>1?`${s} (one entry per module: ${i.join(", ")})`:s}a(ds,"newIdHint");function kd(e,t){let n=[],r=a(s=>n.push({ruleId:"CONFIG_SLICE_LEGACY_STARS_ID",failsStrict:!1,fromLayer:e.from,toLayer:e.to,message:`${e.from} \u2192 ${e.to}: ${s} It keeps its 4.8.23 meaning for this release only.`}),"push"),o=e.childSlices;if(e.sliceIdentity==="stars"){let s=Ei(e.sliceFolders,t);for(let i of o?.sliceAliases??[]){if(!i||typeof i.to!="string")continue;let l=ms(i.to);if(!l||Pi(e,i.to)===void 0)continue;let c=st(e.sliceFolders,l.universeId),d=l.childId.split("/").pop();r(`sliceAliases to "${i.to}" is a 4.8.23 stars id (the star before the last literal was dropped). The id is now ${ds(l.universeId,c,s,d)}; write that instead.`)}for(let i of e.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string")continue;let l=[i.from,i.to].filter(d=>d.includes("/")&&st(e.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?ds(d,st(e.sliceFolders,d),s):d,"rename");r(`allowedCrossSlice ${i.from} \u2192 ${i.to} names a 4.8.23 stars id. The ids are now ${c(i.from)} \u2192 ${c(i.to)}; write those instead.`)}}if(o?.sliceIdentity==="stars"){let s=Ei(o.sliceFolders,t);for(let i of o.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string")continue;let l=[i.from,i.to].filter(d=>st(o.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?ds(d,st(o.sliceFolders,d),s):d,"rename");r(`childSlices.allowedCrossSlice ${i.from} \u2192 ${i.to} names a 4.8.23 stars id. The ids are now ${c(i.from)} \u2192 ${c(i.to)}; write those instead.`)}}return n}a(kd,"legacyStarsIdFindings");function Fi(e){if(e!==null&&typeof e=="object"){let t=e.ratchet;if(t===!0)return"always";if(t===!1)return"never"}return"auto"}a(Fi,"siblingRatchetMode");function Ee(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=gs(o,t,r?.layers),c=hs(o,l,s,i),d=c.from,u=c.to,m=d.universeId,f=u.universeId,h=Sd({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:m,toSlice:f,fromChild:d.childId,toChild:u.childId,fromShared:!m&&ot(s,o.sharedRoots),toShared:!f&&ot(i,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(h.decision!=="allow")return{rule:o,peerIsolationReason:h.peerIsolationReason,fromSlice:m,toSlice:f,sliceVerdict:h};continue}if(t!==n)return{rule:o}}}a(Ee,"findDeniedEdgeDecision");function ji(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||Ne(i.sharedImportsSlice)==="deny")continue;let l=gs(i,t,r?.layers),c=xt(o,i,l).universeId,d=xt(s,i,l).universeId;if(!(c||!d)&&ot(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:d}}}a(ji,"findSharedImportsSliceBridge");function ys(e,t,n){return gs(e,t,n)}a(ys,"peerSliceFolders");function at(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(at,"literalText");function Vi(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(Vi,"lineOf");function Hi(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(Hi,"isTypeOnlyReference");function Ui(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(Ui,"singleFileChecker");function As(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(As,"symbolAt");function Rs(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):As(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Rs,"localDeclaration");function Ue(e,t){let n,r=[],o=a((i,l,c,d=!1)=>r.push({specifier:c,kind:l,line:Vi(t,i),typeOnly:d,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",at(e,i.moduleSpecifier),Hi(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",at(e,i.moduleSpecifier),Hi(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,d=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Rs(e,n??(n=Ui(e,t)),t,i.expression);(l||d)&&o(i,d?"require":"dynamic-import",at(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(Ue,"extractSemanticDependencies");function Id(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(Id,"staticAccessPath");function Ed(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(Ed,"runtimeIdentifierReference");function Ki(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(Ki,"bestForbiddenMatch");function Ge(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Ui(e,t),s=new Map,i=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let h of f.declarationList.declarations)e.isIdentifier(h.name)&&i.add(h.name.text);let l=a(f=>{let h=Id(e,f);if(!h)return;let p=As(o,h.root),y=p?s.get(p):void 0;return y?[...y,...h.segments.slice(1)]:Rs(e,o,t,h.root)||i.has(h.root.text)?void 0:h.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let h of f.declarationList.declarations){if(!h.initializer||!e.isIdentifier(h.name))continue;let p=l(h.initializer),y=As(o,h.name);!p||!y||s.set(y,p)}let c=[],d=new Set,u=a((f,h)=>{let p=Vi(t,h),y=`${f}:${h.getStart(t)}`;d.has(y)||(d.add(y),c.push({name:f,line:p,node:h}))},"flag"),m=a(f=>{let h=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!h){let p=l(f),y=p?Ki(r,p):void 0;y&&u(y,f)}else e.isIdentifier(f)&&r.has(f.text)&&Ed(e,f)&&!Rs(e,o,t,f)&&u(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let p=l(f.initializer);if(p)for(let y of f.name.elements){if(!e.isIdentifier(y.name))continue;let S=y.propertyName?at(e,y.propertyName)??y.propertyName.text:y.name.text,C=Ki(r,[...p,S]);C&&u(C,f.initializer)}}e.forEachChild(f,m)},"visit");return m(t),c}a(Ge,"collectForbiddenCapabilityUses");function Ss(e,t,n){let r=[];for(let o of n?.dependencies??Ue(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Ct(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ge(e,t,cs)){let s=Ln(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(Ss,"collectCapabilityUses");var ks={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."},Lt=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 Kn(e){let t=(e.intentPrefixes??[]).filter(n=>n.trim().length>0);return t.length>0?t:Lt.find(n=>n.layer===e.name)?.prefixes??[]}a(Kn,"effectiveIntentPrefixes");function Gi(e){let t=new Set(e.layers.filter(r=>Kn(r).length>0).map(r=>r.name)),n=new Set;for(let r of e.rules??[])if(!(r.allowed!==!1||r.peerIsolation===!0))for(let o of[r.from,r.to])t.has(o)||n.add(o);return[...n].sort()}a(Gi,"unresolvableLayerFlowLayers");function Is(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(Is,"resolveIntentLayer");function be(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(be,"looksLikeArkIntent");function Nt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&be(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ks.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ks.PUBLISH_MISSING_SOURCE}),t}a(Nt,"classifyPublishFacts");function J(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(J,"violation");function bd(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."}a(bd,"peerSuggestion");function lt(e,t){return e.slice(0,t).split(`
2
- `).length}a(lt,"lineOf");var vd=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Cd(e,t){return e.index+e[0].indexOf(t)}a(Cd,"captureIndex");function _d(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 d=c[1];d&&r(d,Cd(c,d))}},"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),d=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,u;for(;(u=d.exec(l))!==null;){let m=u[1];m&&r(m,c+u.index+u[0].indexOf(m))}}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(_d,"extractQuotedStrings");function xd(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(xd,"extractModuleSpecifiers");function Od(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(Od,"isSyntaxWrapper");function Es(e,t){let n=t;for(;n?.parent&&Od(e,n.parent);)n=n.parent;return n}a(Es,"unwrapWrappers");function bs(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(bs,"callCalleeName");function wd(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Es(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&bs(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&vs(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Es(e,s).parent;return!!(l&&e.isCallExpression(l)&&bs(e,l)==="publish")}return!1}a(wd,"isPublishMetadataSource");function Bi(e,t){let n=Es(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=bs(e,r);if(o&&vd.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Bi(e,r);if(e.isPropertyAssignment(r)){let o=vs(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&wd(e,r))return!0}return!1}a(Bi,"isDeclaredIntentSite");function Td(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&Bi(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(Td,"extractQuotedStringsAst");function Ld(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(Ld,"hasInfrastructureToken");function Nd(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(Nd,"isKnownInfrastructurePackage");function Pd(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(Pd,"layerHasInfrastructureRole");function Dt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Dt,"tsStringLiteralText");function vs(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(vs,"tsPropertyName");function zi(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:vs(e,r.name)===n)}a(zi,"tsObjectProperty");function $t(e,t,n){return zi(e,t,n)!==void 0}a($t,"tsObjectHasProperty");function Pt(e,t,n){let r=zi(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Pt,"tsObjectPropertyValue");function Dd(e,t){let n=Pt(e,t,"metadata");return $t(e,n,"source")}a(Dd,"tsObjectHasMetadataSource");function Wi(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Wi(e,t.name):!1:!1}a(Wi,"tsLooksLikeIntentCreatorExpression");function $d(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($d,"tsIsPublishCall");function Md(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Dt(e,n);return r!==void 0&&be(r)||$t(e,n,"intent")||Wi(e,n)}a(Md,"tsIsArkPublishCandidate");function Fd(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Dd(e,n)||$t(e,r,"source")||$t(e,o,"source")}a(Fd,"tsPublishHasSource");function jd(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Pt(e,n,"metadata");return Dt(e,Pt(e,s,"source"))??Dt(e,Pt(e,r,"source"))??Dt(e,Pt(e,o,"source"))}a(jd,"tsPublishSourceLiteral");function Hd(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],d=a(m=>o.getLineAndCharacterOfPosition(m.getStart(o)).line+1,"lineForNode"),u=a(m=>{if($d(e,m)){let f=m.arguments[0],h=Dt(e,f);for(let y of Nt({publishCall:!0,rawIntentName:h,objectHasIntent:$t(e,f,"intent"),arkPublishCandidate:Md(e,m),hasSource:Fd(e,m)}))c.push(J(y.ruleId,y.message,{line:d(m),filePath:i}));let p=jd(e,m);if(r&&l&&p&&be(p)){let y=r.resolveLayer(p);y&&y!==l&&c.push(J("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${l}.`,{line:d(m),filePath:i,target:p,fromLayer:l,toLayer:y}))}}e.forEachChild(m,u)},"visit");return u(o),c}a(Hd,"analyzePublishAst");function Cs(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,d=c?.filePath,u=c?.layer,m=e.typescript,f=m?m.createSourceFile(d??"generated.ts",s,m.ScriptTarget.Latest,!0):void 0,h=f?Ue(e.typescript,f):void 0,p=h?h.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(f),kind:R.kind,typeOnly:R.typeOnly})):xd(s),y=e.typescript?Td(e.typescript,s):_d(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(d))for(let R of h?.filter(({unresolved:k})=>k)??[]){let k=R.kind==="require";l.push(J(k?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${k?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:R.line,filePath:d}))}let S=u!==void 0&&(r.has(u)||Pd(u)),C=u!==void 0?` If "${u}" 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 R of n)if(R instanceof RegExp){R.lastIndex=0;let k=R.exec(s);R.lastIndex=0,k&&l.push(J("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:k.index===void 0?void 0:lt(s,k.index),filePath:d,suggestion:"Remove infrastructure imports from domain/application layers."+C}))}else s.includes(R)&&l.push(J("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:lt(s,s.indexOf(R)),filePath:d}));for(let R of p){let k=e.resolveImportTarget?.(R.value,d)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,d)}:void 0),v=typeof d=="string"?e.resolveImportTarget?.(d)??(e.resolveImportLayer?{layer:u,relPath:void 0}:void 0):void 0,H=k?.layer;if(H&&u){let P=Ee(e.architectureProfile?.rules,u,H,{fromPath:v?.relPath,toPath:k?.relPath,layers:e.architectureLayers});if(P){let D=P.rule;if(R.typeOnly&&!D.peerIsolation)continue;let E=!!D.peerIsolation,$=P.sliceVerdict,w=Ve($),N=Hn(D,$)??(E?`Layer "${u}" must not import across slices into "${H}".`:`Layer "${u}" must not import "${H}".`),M=E&&$?.explanation&&(w.reasonId||P.peerIsolationReason!=="cross-slice")?$.explanation:void 0;l.push(J("LAYER_IMPORT_VIOLATION",M?`${N} ${M}`:N,{line:lt(s,R.index),source:R.value,target:R.value,filePath:d,fromLayer:u,toLayer:H,...E?{peerIsolation:!0}:{},...w.reasonId?{reasonId:w.reasonId}:{},...w.universeFrom?{universeFrom:w.universeFrom}:{},...w.universeTo?{universeTo:w.universeTo}:{},...w.failsStrict===!1?{failsStrict:!1}:{},suggestion:bd(E,P.peerIsolationReason),details:{importKind:R.kind,peerIsolation:E,...R.typeOnly?{typeOnly:!0}:{},...w.reasonId?{reasonId:w.reasonId}:{}}}));continue}continue}S||R.typeOnly||!Ld(R.value)&&!Nd(R.value)||l.push(J("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:lt(s,R.index),source:R.value,target:R.value,filePath:d,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+C,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let k=R.check({source:s,context:i});if(k!==!0)if(Array.isArray(k))for(let v of k)l.push(J("POLICY_VIOLATION",v.message,{filePath:d,suggestion:`Fix violation of policy "${R.name}".`}));else k===!1?l.push(J("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(J("POLICY_VIOLATION",k.message))}if(o&&t.size>0)for(let R of y)be(R.value)&&!t.has(R.value)&&l.push(J("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:lt(s,R.index),filePath:d,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&u)for(let R of y){if(!be(R.value))continue;let k=e.architectureProfile.resolveLayer(R.value);if(!k)continue;let v=Ee(e.architectureProfile.rules,u,k,{fromPath:typeof d=="string"?d:void 0,layers:e.architectureLayers});if(v){let H=v.sliceVerdict,P=`Layer "${u}" must not reference "${k}" through "${R.value}".`,D=H?it({surface:"intent",verdict:H,fromLayer:u,toLayer:k,fromPath:typeof d=="string"?d:void 0,ruleMessage:v.rule.message,childMessage:v.rule.childSlices?.message,defaultMessage:P}):v.rule.message??P,E=Ve(H);l.push(J("LAYER_REFERENCE_VIOLATION",D,{line:lt(s,R.index),filePath:d,target:R.value,fromLayer:u,toLayer:k,...E.reasonId?{reasonId:E.reasonId}:{},...E.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:v.rule,peerIsolationReason:v.peerIsolationReason,...E.reasonId?{reasonId:E.reasonId}:{}}}))}}if(e.extensions)for(let R of e.extensions)try{let k=R.analyze(s,i);l.push(...k)}catch(k){l.push(J("EXTENSION_ERROR",`Extension "${R.name}" failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&f&&u&&e.forbiddenGlobals?.[u]?.length)try{let R=e.forbiddenGlobals[u];l.push(...Ge(e.typescript,f,R).map(k=>J("FORBIDDEN_GLOBAL",`${u} must not use the ambient global "${k.name}".`,{line:k.line,filePath:d,target:k.name,fromLayer:u,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let k of h??[]){if(k.typeOnly||!k.specifier)continue;let v=Le(k.specifier,R);v&&l.push(J("FORBIDDEN_GLOBAL",`${u} must not use module "${k.specifier}" because it is the import form of forbidden global "${v}".`,{line:k.line,filePath:d,source:k.specifier,target:k.specifier,fromLayer:u,details:{importKind:k.kind,forbiddenGlobal:v},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){l.push(J("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&f&&u&&e.capabilityWalls?.[u]?.length)try{let R=new Set(e.capabilityWalls[u]),k=e.forbiddenGlobals?.[u]??[];for(let v of Ss(e.typescript,f))R.has(v.capability)&&(v.source==="ambient-global"&&_t(v.symbol,k)||v.source==="import-based"&&Le(v.symbol,k)||l.push(J("CAPABILITY_VIOLATION",v.source==="import-based"?`${u} denies the ${v.capability} capability; found import of "${v.symbol}".`:`${u} denies the ${v.capability} capability; found ambient "${v.symbol}".`,{line:v.line,filePath:d,target:v.symbol,capability:v.capability,fromLayer:u,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){l.push(J("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...Hd(e.typescript,s,i,e.architectureProfile))}catch(R){l.push(J("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:!l.some(R=>R.failsStrict!==!1),violations:l}}}}a(Cs,"createAICodeGate");var Be={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qi={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Be,default:[]},kernelRoots:{...Be},managedLayers:{...Be,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Yi={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Be,default:[]},managedLayers:{...Be,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Be,default:[]},appliesTo:{...Be,default:[]}}};function Mt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Mt,"isObject");function Xi(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Mt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Xi,"declaredLayerNames");function Zi(e){if(!Mt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}a(Zi,"defaultedArkRun");function Ji(e){if(!Mt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}a(Ji,"defaultedArkOrder");function Qi(e,t){let n=e.arkRun;if(n===void 0||!Mt(n))return;let r=Xi(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(Qi,"validateArkRunExtra");function ea(e,t){let n=e.arkOrder;if(n===void 0||!Mt(n))return;let r=Xi(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(ea,"validateArkOrderExtra");var Un={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ia={description:'deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. The object form { mode: "deny-cross-parent", stopAt } names composition roots (bootstrap, DI registrations) the whole-graph walk never starts at or passes through; a stop file must still sit under sharedRoots, and stopAt does not silence the direct SHARED_IMPORTS_SLICE warning. arkgate 4.8.22 and older reject deny-cross-parent. arkgate 4.8.23 and older reject the object form (must be one of deny, deny-cross-parent).',oneOf:[{type:"string",enum:["deny","deny-cross-parent"]},{type:"object",additionalProperties:!1,required:["mode","stopAt"],properties:{mode:{type:"string",enum:["deny-cross-parent"]},stopAt:{...Un,minItems:1}}}]},aa={type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Runs only on a rule with peerIsolation: true and allowed: false; elsewhere it is inert and ark-check warns CONFIG_CHILD_SLICES_INERT (config load still accepts it, as 4.8.23 did). Absent keeps today's universe wall. sliceFolders names children. Flat files are universe common, and so is a commonFolders directory directly under the universe (a folder of that name inside a child belongs to that child). siblings is "deny" (default), "advisory", or { default, enforce, ratchet }. parentMayImportChild defaults to false. message is the text for inner-wall findings. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...Un,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...Un,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce, ratchet } so listed subtrees are errors while the default stays advisory. ratchet absent: a new advisory crossing fails only when the baseline in use already records an advisory crossing of this rule. ratchet true: any unrecorded advisory crossing fails when a baseline is in use. ratchet false: measure only, never fails. A string-enum build rejects the object at config load (must be one of deny, advisory). arkgate 4.8.23 and older reject ratchet (unknown field).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...Un},ratchet:{type:"boolean"}}}]},parentMayImportChild:{type:"boolean"},message:{type:"string",minLength:1,description:"Text for inner-wall findings (CROSS_SIBLING_SLICE and universe common importing a child). The rule message stays the universe-wall text (CROSS_PARENT_SLICE and fail-closed denies). Absent: ArkGate default text, never the rule message. arkgate 4.8.23 and older reject this field (unknown field)."},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A path without a wildcard also covers everything under it, as sharedRoots does. A bare name, a universe id alone, a target outside every universe shape, and a wildcard in to are rejected. Under stars identity a target written against the 4.8.23 stars id (star bindings before the last literal dropped, e.g. api/v1/x for modules/*/api/*) still loads when it maps to one universe shape, and ark-check warns CONFIG_SLICE_LEGACY_STARS_ID with the new id; it is rejected only when it maps to more than one shape. Config load checks only the shape; doctor reports a target universe no file belongs to. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each alias as an owed move. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}};function ue(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ue,"isObject");function Gn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Gn,"propertyPath");function Pe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Pe,"trimTrailingSlashes");function la(e,t){Bd(e,t),Wd(e,t),Zd(e,t),uu(e,t)}a(la,"validateSliceContract");var ta='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',na="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function Kd(e){return e==="*"||e==="**"}a(Kd,"isWildcardSegment");function ca(e){let t=e.toLowerCase().split("/").filter(o=>o.length>0&&o!==".");(t[0]==="src"||t[0]==="app")&&(t=t.slice(1));let n=t.length;for(;n>0&&Kd(t[n-1]??"");)n-=1;let r=t.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(ca,"coveredFolder");function Vd(e,t){return e.length<=t.length&&e.every((n,r)=>t[r]===n)}a(Vd,"isPrefixOf");function Ud(e,t){let n=e.layers;if(!Array.isArray(n))return[];let r=new Set([t.from,t.to].filter(s=>typeof s=="string")),o=[];for(let s of n){if(!ue(s)||typeof s.name!="string"||!r.has(s.name))continue;let i=Array.isArray(s.patterns)?s.patterns:[];for(let l of i){if(typeof l!="string")continue;let c=l.replace(/\\/g,"/").split("/"),d=c.findIndex(f=>f.includes("*")),u=d===-1?c:c.slice(0,d),m=ca(u.join("/"));m&&o.push(m)}}return o}a(Ud,"ruleLayerFolders");function Gd(e,t){let n=Pe(e.trim().replace(/\\/g,"/"));if(n.length===0)return"must be a non-empty path or glob";let r=n.replace(/^[./]+/,"");if(r===""||r==="*"||r==="**")return na;for(let s of n.split("/"))if(s.length===0||s==="."||s==="..")return"must be a path or glob without empty, . or .. segments";let o=ca(n);return o===null?null:o.length===0?na:t.some(s=>Vd(o,s))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(Gd,"stopAtEntryIssue");function Bd(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ue(r)||r.sharedImportsSlice===void 0)return;let s=r.sharedImportsSlice,i=`$.rules[${o}].sharedImportsSlice`;if(typeof s=="string"){s!=="deny"&&s!=="deny-cross-parent"&&t.push({path:i,message:ta});return}if(!ue(s)){t.push({path:i,message:ta});return}for(let u of Object.keys(s))u!=="mode"&&u!=="stopAt"&&t.push({path:Gn(i,u),message:"unknown field"});s.mode===void 0?t.push({path:`${i}.mode`,message:"is required"}):s.mode!=="deny-cross-parent"&&t.push({path:`${i}.mode`,message:'must be deny-cross-parent. stopAt has no meaning for deny; use the string "deny".'});let l=s.stopAt;if(l===void 0){t.push({path:`${i}.stopAt`,message:"is required"});return}if(!Array.isArray(l)||l.length===0){t.push({path:`${i}.stopAt`,message:"must be a non-empty array of paths or globs"});return}let c=new Set,d=Ud(e,r);l.forEach((u,m)=>{let f=`${i}.stopAt[${m}]`;if(typeof u!="string"){t.push({path:f,message:"must be a non-empty path or glob"});return}let h=Gd(u,d);if(h){t.push({path:f,message:h});return}let p=Pe(u.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(p)){t.push({path:f,message:"duplicate stopAt entry"});return}c.add(p)})})}a(Bd,"validateSharedImportsSlice");var zd=["deny","advisory"],ra='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function Wd(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ue(r))return;let s=r.childSlices;if(!ue(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){zd.includes(i)||t.push({path:l,message:ra});return}if(!ue(i)){t.push({path:l,message:ra});return}for(let d of Object.keys(i))d!=="default"&&d!=="enforce"&&d!=="ratchet"&&t.push({path:Gn(l,d),message:"unknown field"});if(i.ratchet!==void 0&&typeof i.ratchet!="boolean"&&t.push({path:`${l}.ratchet`,message:"must be a boolean"}),i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((d,u)=>{let m=`${l}.enforce[${u}]`;if(typeof d!="string"||d.trim().length===0){t.push({path:m,message:"must be a non-empty child slice id or subtree path"});return}let f=Pe(d.trim().replace(/\\/g,"/"));if(f.split("/").some(h=>h.length===0||h==="."||h==="..")){t.push({path:m,message:"must be a child slice id or subtree path without . or .."});return}if(f.includes("*")){t.push({path:m,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(f)){t.push({path:m,message:"duplicate enforce entry"});return}c.add(f)})})}a(Wd,"validateChildSliceSiblings");var qd="must be a slice id with a slash. A bare name is ambiguous across universes.",Yd="* matches one whole path segment. ** and a partial segment are not wildcards.";function Xd(e){let t=Pe(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return qd;let n=t.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return Yd}return null}a(Xd,"childCrossSlicePatternIssue");function sa(e){return Pe(e.trim().replace(/\\/g,"/")).toLowerCase()}a(sa,"childCrossSlicePatternKey");function Zd(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ue(r))return;let s=r.childSlices;if(!ue(s)||s.allowedCrossSlice===void 0)return;let i=s.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((d,u)=>{let m=`${l}[${u}]`;if(!ue(d)){t.push({path:m,message:"must be an object with from and to"});return}for(let h of Object.keys(d))h!=="from"&&h!=="to"&&t.push({path:Gn(m,h),message:"unknown field"});for(let h of["from","to"]){let p=d[h],y=`${m}.${h}`;if(typeof p!="string"||p.trim().length===0){t.push({path:y,message:"must be a non-empty slice id"});continue}let S=Xd(p);S&&t.push({path:y,message:S})}if(typeof d.from!="string"||typeof d.to!="string")return;let f=`${sa(d.from)}\0${sa(d.to)}`;if(!f.startsWith("\0")&&!f.endsWith("\0")){if(c.has(f)){t.push({path:m,message:"duplicate child slice allowance"});return}c.add(f)}})})}a(Zd,"validateChildSliceAllowedCrossSlice");var ct="must be a child of a universe shape this rule names (its universe sliceFolders shape plus one child segment). A bare name, a universe id alone, a target outside every universe shape, and a wildcard are rejected. Config load checks the shape only; doctor reports a target universe no file belongs to.",Jd="is a 4.8.23 stars id (star bindings before the last literal dropped) that maps to more than one universe shape of this rule. Write the new stars id, which keeps every star binding (e.g. orders/api/v1/x for modules/*/api/*).",Qd="overlaps a slice folder. An alias covers only files outside the slice trees.",eu="two slice aliases match the same file";function tu(e){return Pe(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(tu,"aliasPathSegments");function nu(e){let t=e[e.length-1];return t===void 0||t.includes("*")?[...e]:[...e,"**"]}a(nu,"aliasSegmentsWithSubtree");function da(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(da,"concreteGlobPrefix");function Ft(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}a(Ft,"segmentsArePrefix");function ru(e){let t=e.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(t.length<2||t[0]==="*"||t[0]==="**"||!t.some(r=>r==="*"))return null;let n=[];for(let r of t){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(ru,"anchoredSlicePrefix");function su(e,t){let n=da(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Ft(t,n)||Ft(t,o)?!0:r?Ft(n,t)&&n.length<t.length||Ft(n,["src",...t])&&n.length<t.length+1||Ft(n,["app",...t])&&n.length<t.length+1:!1}a(su,"globOverlapsAnchored");function ou(e,t){for(let r=0;r<e.length;r+=1){if(e[r]!==t&&e[r]!=="*")continue;let o=e.slice(r+1);if(o.length>=2||o.some(s=>s==="*"||s==="**"))return!0}let n=da(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(ou,"globOverlapsBare");function iu(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return ou(e,n[0]);let r=ru(t);return r?su(e,r):!1}a(iu,"globOverlapsSliceEntry");function au(e){let t=Pe(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty path glob";if(t==="*"||t==="**")return"must not cover the whole tree";for(let n of t.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(au,"aliasGlobIssue");function lu(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let o of e){if(typeof o!="string"||o.length===0)continue;let s=o.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(s.length===1&&s[0]&&!s[0].includes("*")){n.push({literals:[s[0],null]});continue}if(!s.some(i=>i==="**"||i.includes("*")&&i!=="*")&&s.includes("*")){if(r){let i=-1;for(let d=0;d<s.length;d+=1)s[d]!=="*"&&(i=d);if(i<0)continue;let l=s.filter((d,u)=>u>=i||d==="*").map(d=>d==="*"?null:d),c=s.slice(i).map(d=>d==="*"?null:d);n.push(c.length===l.length?{literals:l}:{literals:l,legacy:c});continue}n.push({literals:s.map(i=>i==="*"?null:i)})}}return n}a(lu,"universeShapes");function Vn(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(Vn,"shapeMatches");function cu(e,t){let n=Pe(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(s=>s.length===0||s==="."||s==="..")||n.includes("*")||!n.includes("/"))return ct;let r=n.split("/").map(s=>s.toLowerCase());if(t.length===0||t.some(s=>Vn(s,r)))return ct;if(t.some(s=>Vn(s,r.slice(0,-1))))return null;let o=new Set(t.filter(s=>s.legacy!==void 0&&!Vn({literals:s.legacy},r)&&Vn({literals:s.legacy},r.slice(0,-1))).map(s=>s.literals.map(i=>i??"*").join("/")));return o.size===1?null:o.size>1?Jd:ct}a(cu,"aliasTargetIssue");function oa(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(oa,"aliasGlobVariants");function du(e,t){let n=oa(e),r=oa(t);for(let o of n)if(ze(o,t,0,0,new Map))return!0;for(let o of r)if(ze(e,o,0,0,new Map))return!0;return!1}a(du,"aliasesCanMatchSameFile");function ze(e,t,n,r,o){let s=`${n}:${r}`,i=o.get(s);if(i!==void 0)return i;let l=!1;if(n===e.length&&r===t.length)l=!0;else if(n<e.length&&e[n]==="**")l=ze(e,t,n+1,r,o)||r<t.length&&ze(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=ze(e,t,n,r+1,o)||n<e.length&&ze(e,t,n+1,r,o);else if(n<e.length&&r<t.length){let c=e[n],d=t[r];(c===d||c==="*"||d==="*")&&(l=ze(e,t,n+1,r+1,o))}return o.set(s,l),l}a(ze,"globsCanMatchSame");function uu(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ue(r))return;let s=r.childSlices;if(!ue(s)||s.sliceAliases===void 0)return;let i=s.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=lu(r.sliceFolders,r.sliceIdentity),d=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(m=>typeof m=="string"&&m.length>0),u=[];i.forEach((m,f)=>{let h=`${l}[${f}]`;if(!ue(m)){t.push({path:h,message:"must be an object with from and to"});return}for(let S of Object.keys(m))S!=="from"&&S!=="to"&&t.push({path:Gn(h,S),message:"unknown field"});let p=m.from,y=m.to;if(typeof p!="string"||p.trim().length===0)t.push({path:`${h}.from`,message:"must be a non-empty path glob"});else{let S=au(p);if(S)t.push({path:`${h}.from`,message:S});else{let C=nu(tu(p));d.some(R=>iu(C,R))&&t.push({path:`${h}.from`,message:Qd});for(let R of u)if(du(R,C)){t.push({path:h,message:eu});break}u.push(C)}}if(typeof y!="string"||y.trim().length===0)t.push({path:`${h}.to`,message:ct});else{let S=cu(y,c);S&&t.push({path:`${h}.to`,message:S})}})})}a(uu,"validateChildSliceAliases");function Bn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(Bn,"normalizeStewardId");function ua(e){let t=Bn(e);return!t||_s(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(ua,"isGitHubHandle");function pu(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t.includes("@")||t.includes(" ")||_s(t))return!1;let n=t.split("@");if(n.length!==2||!n[0]||/\s/.test(t))return!1;let r=n[1].lastIndexOf(".");return r>0&&r<n[1].length-1}a(pu,"isGitHubEmail");function fu(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&ua(t[1])?Bn(t[1]):null}a(fu,"githubHandleFromEmail");function pa(e){let t=fu(e);if(t)return t;let n=Bn(e);return!n||_s(n)?null:ua(n)||pu(n)?n:null}a(pa,"canonicalStewardId");var gu=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function _s(e){let t=Bn(e);return!t||gu.test(t)}a(_s,"isAutomationAuthor");var ie="1.3",mu=["public","auth","admin","internal"];function hu(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(hu,"isFutureHouseLayer");function yu(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(yu,"layerOwnersList");function ga(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!hu(t)&&!yu(t)).map(t=>t.name)}a(ga,"layersMissingRequiredOwners");function ma(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(ma,"missingLayerOwnersNextAction");var Wn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",fa=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Au=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ru(){let e=[];for(let t of fa)for(let n of fa)t===n||Au.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Ru,"createDefaultRules");var Yn=Ru(),xs=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ae={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Wn,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:Wn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ie,default:ie},name:{type:"string",minLength:1},include:{...ae,minItems:1,default:["src"]},exclude:{...ae,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Yn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ae,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:{...ae,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ae,minItems:1},exclude:ae,intentPrefixes:ae,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...mu]},owners:{...ae,minItems:1},forbiddenGlobals:ae,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:{...ae,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 every star binding (a star before the last literal is kept too), so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...ae,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:ia,childSlices:aa}},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:{...ae,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:{...ae,minItems:1}}},arkRun:qi,arkOrder:Yi}},ve=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ "use strict";var Pn=Object.defineProperty;var zc=Object.getOwnPropertyDescriptor;var Wc=Object.getOwnPropertyNames;var qc=Object.prototype.hasOwnProperty;var a=(e,t)=>Pn(e,"name",{value:t,configurable:!0});var Yc=(e,t)=>{for(var n in t)Pn(e,n,{get:t[n],enumerable:!0})},Xc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wc(t))!qc.call(e,o)&&o!==n&&Pn(e,o,{get:()=>t[o],enumerable:!(r=zc(t,o))||r.enumerable});return e};var Zc=e=>Xc(Pn({},"__esModule",{value:!0}),e);var am={};Yc(am,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>wt,AGENT_PROJECTION_BEGIN_MARKER:()=>Mo,AGENT_PROJECTION_END_MARKER:()=>Rn,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Et,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Sn,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>zo,AGENT_SKILL_ENTRY_FILENAME:()=>qo,ANALYSIS_IR_SCHEMA_VERSION:()=>tr,ARKORDER_RULE_IDS:()=>$r,ARKORDER_TIER1_SENSOR_IDS:()=>Bl,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>fo,ARKRUN_KERNEL_FACTORY_CALLEES:()=>co,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>$l,ARKRUN_RULE_IDS:()=>Lr,ARKRUN_TIER1_SENSOR_IDS:()=>Hl,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>uo,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Ke,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Fc,ARK_ANALYSIS_RESULT_SCHEMA:()=>os,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Ot,ARK_CONFIG_SCHEMA:()=>Hn,ARK_CONFIG_SCHEMA_VERSION:()=>ae,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>rc,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>nc,ARK_FIRST_CLASS_SKILL_NAMES:()=>Zr,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>hn,ARK_PROJECT_IDENTITY_SCHEMA:()=>oc,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>Ao,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>sc,ARK_RULES_SCHEMA:()=>nr,ARK_RULES_SCHEMA_VERSION:()=>Xe,ARK_RULE_SENSORS:()=>Ds,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>ko,ARK_SKILL_CAPACITY:()=>Cn,ARK_SKILL_CAPACITY_DEDICATED_DOORS:()=>Yo,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>Qr,ARK_SKILL_NAMES:()=>xn,ARK_SKILL_NAME_COUNT:()=>Xo,ARK_SKILL_NORTH_STAR:()=>Mc,ARK_SKILL_REQUIRED_SURFACES:()=>_n,ARK_SKILL_STUB_REDIRECTS:()=>qr,ARK_STATUS_MANIFEST_SCHEMA:()=>bc,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Io,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>Ur,ArkRulesValidationError:()=>we,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>jo,DIAGNOSTIC_CATALOG:()=>_t,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>oi,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Nn,DIAGNOSTIC_RULE_IDS:()=>ii,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>wl,EffectiveContractError:()=>Xt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>Wo,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>Ve,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>An,IMPROVEMENT_LENS_IDS:()=>yn,MERGE_PLANES_DUAL_STAMP:()=>io,POLICY_DELTA_SCHEMA_VERSION:()=>fr,PROJECT_BINDING_SCHEMA:()=>So,PROJECT_EXPECTATION_SCHEMA:()=>Ro,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>er,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Fe,STATUS_COMPASS_FACTS_SOURCES:()=>vo,STATUS_COMPASS_MODES:()=>bo,STATUS_COMPASS_REASON_CODES:()=>mn,adapterDocsCodePath:()=>Pt,adapterFindingOccurrenceTargetKeys:()=>it,adapterFindingRefFromTargetKey:()=>Tt,adapterFindingTargetKey:()=>ot,agentProjectionContentIdentity:()=>tt,agentSkillEntryRelativePath:()=>ni,agentSkillPackageFileRelativePath:()=>Gc,analyzeArchitectureConvergence:()=>Ye,analyzeChange:()=>tn,analyzePolicyDelta:()=>qs,analyzeProject:()=>It,analyzeResolvedProject:()=>mo,arkRunKernelCallKind:()=>sn,arkSkillStubRedirect:()=>jc,buildAgentProjectionBeginMarker:()=>Br,buildAgentProjectionBlock:()=>Ho,buildAgentProjectionBody:()=>vn,buildAgentProjectionMeta:()=>Vo,buildArkRuleFileHints:()=>br,buildEffectiveArkRules:()=>sr,buildImprovementCompass:()=>wc,buildRulesInventory:()=>fc,buildStatusManifest:()=>Rc,canPromoteInvariant:()=>dr,catalogFixForRuleId:()=>ui,catalogWhyForRuleId:()=>pi,classifyArkPolicyDelta:()=>gr,classifyCoverage:()=>Ba,classifyResolvedLayerCoverage:()=>Er,classifyStatusWritePath:()=>Co,collectAnalysisConfigWarnings:()=>fn,collectEmptyAppliesToFindings:()=>Ir,collectForbiddenCapabilityUses:()=>qe,composeMergePlanesHonesty:()=>nn,countsAsCoverage:()=>Vs,createAICodeGate:()=>Ts,createAdapterResult:()=>mi,createArchitectureProfile:()=>jt,createArchitectureProfileFromArkConfig:()=>ds,createElevenLayerArkConfig:()=>us,createProjectId:()=>ic,createProjectIdentity:()=>ac,createResolvedCandidateFacts:()=>Qn,defaultHonestLabel:()=>_o,demoteExtraPlaneTeethUnderClassificationFloor:()=>Tl,deriveArkRuleFileHints:()=>ro,describeCoverage:()=>Ks,detectArchitectureCycles:()=>yr,deterministicHash:()=>Q,diagnosticDocsFragment:()=>ss,diagnosticDocsPath:()=>ci,effectiveContractPolicyPayload:()=>or,elevenLayerProfile:()=>Mt,emptyEffectiveArkRules:()=>Me,evaluateArchitectureGraph:()=>Qe,evaluateArkOrderSensors:()=>Dr,evaluateArkRuleSensors:()=>kr,evaluateArkRunEditorSensors:()=>go,evaluateArkRunEditorSensorsFromSource:()=>Kl,evaluateArkRunSensors:()=>cn,evaluateInvariantCoverage:()=>cr,evaluateStatusBinding:()=>Eo,explainViolation:()=>Ys,extraMergeTeethAllowed:()=>he,extractAgentProjectionBlock:()=>En,extractArkRunDeclarationsFromSource:()=>Fl,extractArkRunImportedConstructorNamesFromSource:()=>Tr,extractArkRunKernelCallsFromSource:()=>Pr,extractArkRunManagedNewsFromSource:()=>Nr,extractArkRunValueImportDependenciesFromSource:()=>wr,extractClassShapesFromSource:()=>Ol,extractSemanticDependencies:()=>We,flatSkillTemplateFileRelativePath:()=>Bc,formatAgentProjectionCatalogShortList:()=>zr,formatAgentProjectionLayers:()=>kn,formatArkRunDoctorLines:()=>cc,formatImprovementCompassDoctorLines:()=>Tc,formatImprovementCompassResidualLabels:()=>Do,getDiagnosticCatalogEntry:()=>xt,inventoryToExtractionCard:()=>gc,isArkOrderRuleId:()=>so,isArkRunKernelModuleSpecifier:()=>et,isArkRunRuleId:()=>Cr,isArkRunTransportBypassSpecifier:()=>Or,isArkSkillName:()=>Jr,isCataloguedOrArkRuleFamily:()=>li,isExtraPlaneFinding:()=>oo,isFirstClassArkSkillName:()=>Yr,isKnownDiagnosticCode:()=>ai,isValidAgentSkillName:()=>Zo,loadArkConfigContract:()=>$t,loadArkRulesContract:()=>Rt,loadContract:()=>en,loadResolvedCandidateFacts:()=>Oe,mergeAgentProjectionDocument:()=>Bo,normalizeExtraMergeTeethClassification:()=>vr,normalizeSkillContent:()=>Xr,normalizeStatusImprovementCompass:()=>Oo,parseAgentProjectionStamp:()=>Wr,parseArkConfigJson:()=>Kn,parseArkRulesJson:()=>Ca,parseSkillDescriptionVersion:()=>Kc,parseSkillDocument:()=>Jo,policyDeltaAcknowledgementMatches:()=>mr,preflightChange:()=>ho,preflightResolvedChange:()=>yo,primaryImprovementCompassNextAction:()=>Fo,projectStatusArkRun:()=>Vr,projectStatusImprovementCompass:()=>Gr,projectionHasNonEnforcementLabel:()=>Go,projectionMatchesPackageVersion:()=>Uo,resolveEffectiveContract:()=>Ta,resolveStatusNextAction:()=>xo,resolvedFactsEvidenceRequirementsHash:()=>yt,serializeDiagnosticCatalog:()=>di,skillDescriptionVersionPrefix:()=>ei,stableSerialize:()=>Y,stampSkillDescription:()=>Uc,statusCompassResidualIsSubsetOfDoctor:()=>Ic,stripSkillDescriptionVersion:()=>ti,summarizeArkRunSection:()=>lc,toAdapterDiagnostic:()=>Ln,unavailableStatusImprovementCompass:()=>kc,validateAgentSkillDocument:()=>Qo,validateAgentSkillsPackage:()=>Hc,validateSkillProductCapacity:()=>Vc,version:()=>si});module.exports=Zc(am);var si="4.8.26";var Nn="docs/diagnostics.md",oi="1.0";function b(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(b,"entry");var _t=Object.freeze([b("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."),b("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."),b("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."),b("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}),b("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."),b("CROSS_WALL_DUPLICATE","layer","Code copied across a wall","Near-identical code sits on two sides of a slice wall (or in two layers that may not import each other). The wall would deny the import, so the code was copied instead. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; they never enter the check, so the verdict does not change. Same-slice copies are counted, never listed.","Move one copy to a shared home the wall allows \u2014 a declared shared root, the universe common folder, or a layer both sides may import \u2014 then import it from both sides. One move at a time, through the write gate (/ark-place names the destination). Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("CROSS_LAYER_DUPLICATE","layer","Code copied in two layers","Near-identical code sits in two layers, and at least one of them may import the other. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; the verdict does not change.","Keep one copy in the lower layer both sides may import, and import it from the other. One move at a time, through the write gate. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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}),b("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."),b("ARKRULE_FILE_UNREFERENCED","arkrules","ArkRules file not referenced","A JSON file under arkrules/, or a slice file named arkrules.<Layer>.json beside governed code, is not in the effective catalog, so none of its rules are enforced. Drift looks like governance until someone notices.","Reference a central file from arkRules, set childSlices.arkRulesFile so a slice file is discovered, or delete it. Advisory only: it never fails the check.",{oftenAdvisory:!0}),b("ARKRULE_DUPLICATE_ID","arkrules","ArkRule id declared more than once","Two ArkRules files in one layer declare the same effective id. Central ids stay bare. A slice file is namespaced as <childId>#<localId>, so the same local id in two slices is not a duplicate.","Rename one id, or split the files onto different slices. Config load fails closed. The catalog is not enforced until the id is unique."),b("ARKRULE_SCOPE_ESCAPES_SLICE","arkrules","Slice ArkRule appliesTo leaves its slice","A file discovered from childSlices.arkRulesFile set appliesTo to a glob that can match outside that child slice. The default, when appliesTo is omitted, is the slice directory.","Narrow appliesTo to the slice directory, or omit it. Config load fails closed. The escaping rule is not enforced."),b("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}),b("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."),b("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}),b("INVARIANT_PROBE_SURVIVED","arkrules","Covering tests do not pin the invariant","The committed invariant probe (.ark/invariant-probe.json, written by arkgate-check --probe-invariants --write) shows, for files that have not changed since, that the covering tests still pass with the invariant's symbol broken on purpose (survived) or never call it (not reached). The test names the rule but does not pin it. A status and inventory line only: it never enters the check, so the verdict does not change.","Add a test case that fails when the rule is broken (the line names the change that went unnoticed), then re-run arkgate-check --probe-invariants --write and commit the file. Promotion to enforced refuses while the fresh artifact says survived or not reached; a stale, killed, inconclusive or missing result changes nothing.",{oftenAdvisory:!0}),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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."),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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."),b("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}),b("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}),b("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}),b("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}),b("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}),b("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}),b("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."),b("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}),b("ORPHAN_MODULE","drift","File nothing imports","No governed file, test or entry point imports this module. It is the leftover an agent leaves when a rewrite lands next to the old file. Status reads it from the import facts the check already resolved, so it never changes the verdict. When a dynamic import, an unresolved import or an unmapped entry could reach the file, the item says so (maybe-dynamic, maybe-unresolved) and the list is partial.","Delete the file through the write gate, one file at a time. If a framework, a script or a runtime loader uses it, add a glob with a reason to .ark/entry-points.json (optional reviewBy) instead. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("UNUSED_EXPORT","drift","Export nothing imports by name","An export no governed file or test imports by name. Listed only in status details (`--doctor --all`) and the report. Default, namespace, star, dynamic and require use count as using every export, so those files are skipped.","Drop the export keyword (or the code) if nothing outside the file needs it, or keep it when it is public API an entry point exposes. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("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.")]),rs=new Map(_t.map(e=>[e.ruleId,e])),ii=Object.freeze(_t.map(e=>e.ruleId));function ai(e){return typeof e=="string"&&e.length>0&&rs.has(e)}a(ai,"isKnownDiagnosticCode");function li(e){return typeof e!="string"||e.length===0?!1:rs.has(e)?!0:e.startsWith("ARKRULE_")}a(li,"isCataloguedOrArkRuleFamily");function xt(e){if(!(typeof e!="string"||e.length===0))return rs.get(e)}a(xt,"getDiagnosticCatalogEntry");function ss(e){return`#${xt(e)?.docsAnchor??e}`}a(ss,"diagnosticDocsFragment");function ci(e){return`${Nn}${ss(e)}`}a(ci,"diagnosticDocsPath");function di(){return{schemaVersion:"1.0",docsPath:Nn,codes:_t}}a(di,"serializeDiagnosticCatalog");function ui(e){return xt(e)?.fix}a(ui,"catalogFixForRuleId");function pi(e){return xt(e)?.why}a(pi,"catalogWhyForRuleId");var Jc=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."})]),Qc=new Map(Jc.map(e=>[e.reasonId,e]));function fi(e){if(!(typeof e!="string"||e.length===0))return Qc.get(e)}a(fi,"sliceReasonHint");var ed=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,td=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,nd=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function rd(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return ed.test(n)?"pure-shared":r==="PersistenceAdapters"&&(td.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":nd.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(rd,"classifyLayerImportKind");function sd(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}a(sd,"sliceHintAction");function od(e){let t=fi(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${sd(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=rd(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 ${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(od,"layerImportNextAction");function id(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(id,"arkRunCallSiteName");function ad(e){let t=id(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(ad,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return od(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 ${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 ad(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(ye,"deterministicNextAction");var Ot="1.5",wt="docs/diagnostics.md",os={$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 ot(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(ot,"adapterFindingTargetKey");function it(e){let t=new Map;return e.map(n=>{let r=ot(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(it,"adapterFindingOccurrenceTargetKeys");function Tt(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(Tt,"adapterFindingRefFromTargetKey");function Pt(e){return`${wt}#${e}`}a(Pt,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}a(x,"text");function gi(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(gi,"positiveInteger");function ld(e,t,n){return ye({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(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:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0,reasonId:x(t.reasonId)??void 0})}a(ld,"nextActionForDiagnostic");var cd=new Set(["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]);function dd(e){let t=e.details,n=t!==null&&typeof t=="object"?t.reasonId:void 0,r=x(e.reasonId)??x(n);return r&&cd.has(r)?r:void 0}a(dd,"sliceReasonOf");function Ln(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s=dd(e),i={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(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}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{},...s?{reasonId:s}:{},...s&&x(e.universeFrom)?{universeFrom:x(e.universeFrom)}:{},...s&&x(e.universeTo)?{universeTo:x(e.universeTo)}:{}},l=n??ot(e),c=Tt(l);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:gi(e.line,1),column:gi(e.column,1)},evidence:i,nextAction:x(e.nextAction)??ld(r,i,e),findingRef:c,targetKey:l,docsCodePath:Pt(r)}}a(Ln,"toAdapterDiagnostic");function mi(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(g=>({code:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],i=e.warnings??[],l=it(s),c=it(i),d=[...s.map((g,f)=>Ln(g,"error",l[f])),...i.map((g,f)=>Ln(g,"warning",c[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:d};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}a(mi,"createAdapterResult");var Ge={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},hi={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Ge,default:[]},kernelRoots:{...Ge},managedLayers:{...Ge,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},yi={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Ge,default:[]},managedLayers:{...Ge,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Ge,default:[]},appliesTo:{...Ge,default:[]}}};function Nt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Nt,"isObject");function ud(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Nt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(ud,"declaredLayerNames");function Ai(e){if(!Nt(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(Ai,"defaultedArkRun");function Ri(e){if(!Nt(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(Ri,"defaultedArkOrder");function Si(e,t,n,r){if(!Array.isArray(t))return;let o=ud(e);t.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!o.has(s)&&r.push({path:`$.${n}.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})})}a(Si,"validateManagedLayersDeclared");function ki(e,t){let n=e.arkRun;if(n===void 0||!Nt(n))return;let r=n.managedLayers;if(Si(e,r,"arkRun",t),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.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(r)||r.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(ki,"validateArkRunExtra");function Ii(e,t){let n=e.arkOrder;if(n===void 0||!Nt(n))return;let r=n.managedLayers;if(Si(e,r,"arkOrder",t),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(r)||r.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Ii,"validateArkOrderExtra");var Dn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Oi={description:'deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. The object form { mode: "deny-cross-parent", stopAt } names composition roots (bootstrap, DI registrations) the whole-graph walk never starts at or passes through; a stop file must still sit under sharedRoots, and stopAt does not silence the direct SHARED_IMPORTS_SLICE warning. arkgate 4.8.22 and older reject deny-cross-parent. arkgate 4.8.23 and older reject the object form (must be one of deny, deny-cross-parent).',oneOf:[{type:"string",enum:["deny","deny-cross-parent"]},{type:"object",additionalProperties:!1,required:["mode","stopAt"],properties:{mode:{type:"string",enum:["deny-cross-parent"]},stopAt:{...Dn,minItems:1}}}]},wi={type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Runs only on a rule with peerIsolation: true and allowed: false; elsewhere it is inert and ark-check warns CONFIG_CHILD_SLICES_INERT (config load still accepts it, as 4.8.23 did). Absent keeps today's universe wall. sliceFolders names children. Flat files are universe common, and so is a commonFolders directory directly under the universe (a folder of that name inside a child belongs to that child). siblings is "deny" (default), "advisory", or { default, enforce, ratchet }. parentMayImportChild defaults to false. message is the text for inner-wall findings. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...Dn,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...Dn,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce, ratchet } so listed subtrees are errors while the default stays advisory. ratchet absent: a new advisory crossing fails only when the baseline in use already records an advisory crossing of this rule. ratchet true: any unrecorded advisory crossing fails when a baseline is in use. ratchet false: measure only, never fails. A string-enum build rejects the object at config load (must be one of deny, advisory). arkgate 4.8.23 and older reject ratchet (unknown field).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...Dn},ratchet:{type:"boolean"}}}]},parentMayImportChild:{type:"boolean"},message:{type:"string",minLength:1,description:"Text for inner-wall findings (CROSS_SIBLING_SLICE and universe common importing a child). The rule message stays the universe-wall text (CROSS_PARENT_SLICE and fail-closed denies). Absent: ArkGate default text, never the rule message. arkgate 4.8.23 and older reject this field (unknown field)."},arkRulesFile:{type:"string",minLength:1,description:"Filename read at each child slice root this wall already resolved. The only token is <Layer>, replaced with a declared layer name (arkrules.<Layer>.json). No slash and no wildcard. A discovered file that omits appliesTo is scoped to that slice directory. Explicit appliesTo outside the slice fails config load (ARKRULE_SCOPE_ESCAPES_SLICE). The effective id is <childId>#<localId>. A build that rejects unknown childSlices fields fails at config load (unknown field)."},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A path without a wildcard also covers everything under it, as sharedRoots does. A bare name, a universe id alone, a target outside every universe shape, and a wildcard in to are rejected. Under stars identity a target written against the 4.8.23 stars id (star bindings before the last literal dropped, e.g. api/v1/x for modules/*/api/*) still loads when it maps to one universe shape, and ark-check warns CONFIG_SLICE_LEGACY_STARS_ID with the new id; it is rejected only when it maps to more than one shape. Config load checks only the shape; doctor reports a target universe no file belongs to. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each unpinned alias as an owed move. pinned true lists the alias separately and does not count it as debt. reason is a doctor label and does not pin by itself. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},pinned:{type:"boolean",description:"True when a framework forces the path to stay. The alias is not an owed move and does not clear other honesty debt."},reason:{type:"string",minLength:1,description:"Doctor label, such as framework-route. A label alone does not pin."}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}};function ie(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ie,"isObject");function Fn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Fn,"propertyPath");function Pe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Pe,"trimTrailingSlashes");function Ti(e,t){hd(e,t),Ad(e,t),Id(e,t),Fd(e,t),Dd(e,t)}a(Ti,"validateSliceContract");var bi='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',vi="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function pd(e){return e==="*"||e==="**"}a(pd,"isWildcardSegment");function Pi(e){let t=e.toLowerCase().split("/").filter(o=>o.length>0&&o!==".");(t[0]==="src"||t[0]==="app")&&(t=t.slice(1));let n=t.length;for(;n>0&&pd(t[n-1]??"");)n-=1;let r=t.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(Pi,"coveredFolder");function fd(e,t){return e.length<=t.length&&e.every((n,r)=>t[r]===n)}a(fd,"isPrefixOf");function gd(e,t){let n=e.layers;if(!Array.isArray(n))return[];let r=new Set([t.from,t.to].filter(s=>typeof s=="string")),o=[];for(let s of n){if(!ie(s)||typeof s.name!="string"||!r.has(s.name))continue;let i=Array.isArray(s.patterns)?s.patterns:[];for(let l of i){if(typeof l!="string")continue;let c=l.replace(/\\/g,"/").split("/"),d=c.findIndex(f=>f.includes("*")),p=d===-1?c:c.slice(0,d),g=Pi(p.join("/"));g&&o.push(g)}}return o}a(gd,"ruleLayerFolders");function md(e,t){let n=Pe(e.trim().replace(/\\/g,"/"));if(n.length===0)return"must be a non-empty path or glob";let r=n.replace(/^[./]+/,"");if(r===""||r==="*"||r==="**")return vi;for(let s of n.split("/"))if(s.length===0||s==="."||s==="..")return"must be a path or glob without empty, . or .. segments";let o=Pi(n);return o===null?null:o.length===0?vi:t.some(s=>fd(o,s))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(md,"stopAtEntryIssue");function hd(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r)||r.sharedImportsSlice===void 0)return;let s=r.sharedImportsSlice,i=`$.rules[${o}].sharedImportsSlice`;if(typeof s=="string"){s!=="deny"&&s!=="deny-cross-parent"&&t.push({path:i,message:bi});return}if(!ie(s)){t.push({path:i,message:bi});return}for(let p of Object.keys(s))p!=="mode"&&p!=="stopAt"&&t.push({path:Fn(i,p),message:"unknown field"});s.mode===void 0?t.push({path:`${i}.mode`,message:"is required"}):s.mode!=="deny-cross-parent"&&t.push({path:`${i}.mode`,message:'must be deny-cross-parent. stopAt has no meaning for deny; use the string "deny".'});let l=s.stopAt;if(l===void 0){t.push({path:`${i}.stopAt`,message:"is required"});return}if(!Array.isArray(l)||l.length===0){t.push({path:`${i}.stopAt`,message:"must be a non-empty array of paths or globs"});return}let c=new Set,d=gd(e,r);l.forEach((p,g)=>{let f=`${i}.stopAt[${g}]`;if(typeof p!="string"){t.push({path:f,message:"must be a non-empty path or glob"});return}let m=md(p,d);if(m){t.push({path:f,message:m});return}let u=Pe(p.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(u)){t.push({path:f,message:"duplicate stopAt entry"});return}c.add(u)})})}a(hd,"validateSharedImportsSlice");var yd=["deny","advisory"],Ei='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function Ad(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){yd.includes(i)||t.push({path:l,message:Ei});return}if(!ie(i)){t.push({path:l,message:Ei});return}for(let d of Object.keys(i))d!=="default"&&d!=="enforce"&&d!=="ratchet"&&t.push({path:Fn(l,d),message:"unknown field"});if(i.ratchet!==void 0&&typeof i.ratchet!="boolean"&&t.push({path:`${l}.ratchet`,message:"must be a boolean"}),i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((d,p)=>{let g=`${l}.enforce[${p}]`;if(typeof d!="string"||d.trim().length===0){t.push({path:g,message:"must be a non-empty child slice id or subtree path"});return}let f=Pe(d.trim().replace(/\\/g,"/"));if(f.split("/").some(m=>m.length===0||m==="."||m==="..")){t.push({path:g,message:"must be a child slice id or subtree path without . or .."});return}if(f.includes("*")){t.push({path:g,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(f)){t.push({path:g,message:"duplicate enforce entry"});return}c.add(f)})})}a(Ad,"validateChildSliceSiblings");var Rd="must be a slice id with a slash. A bare name is ambiguous across universes.",Sd="* matches one whole path segment. ** and a partial segment are not wildcards.";function kd(e){let t=Pe(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return Rd;let n=t.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return Sd}return null}a(kd,"childCrossSlicePatternIssue");function Ci(e){return Pe(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ci,"childCrossSlicePatternKey");function Id(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.allowedCrossSlice===void 0)return;let i=s.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((d,p)=>{let g=`${l}[${p}]`;if(!ie(d)){t.push({path:g,message:"must be an object with from and to"});return}for(let m of Object.keys(d))m!=="from"&&m!=="to"&&t.push({path:Fn(g,m),message:"unknown field"});for(let m of["from","to"]){let u=d[m],h=`${g}.${m}`;if(typeof u!="string"||u.trim().length===0){t.push({path:h,message:"must be a non-empty slice id"});continue}let k=kd(u);k&&t.push({path:h,message:k})}if(typeof d.from!="string"||typeof d.to!="string")return;let f=`${Ci(d.from)}\0${Ci(d.to)}`;if(!f.startsWith("\0")&&!f.endsWith("\0")){if(c.has(f)){t.push({path:g,message:"duplicate child slice allowance"});return}c.add(f)}})})}a(Id,"validateChildSliceAllowedCrossSlice");var at="must be a child of a universe shape this rule names (its universe sliceFolders shape plus one child segment). A bare name, a universe id alone, a target outside every universe shape, and a wildcard are rejected. Config load checks the shape only; doctor reports a target universe no file belongs to.",bd="is a 4.8.23 stars id (star bindings before the last literal dropped) that maps to more than one universe shape of this rule. Write the new stars id, which keeps every star binding (e.g. orders/api/v1/x for modules/*/api/*).",vd="overlaps a slice folder. An alias covers only files outside the slice trees.",Ed="two slice aliases match the same file";function Cd(e){return Pe(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Cd,"aliasPathSegments");function _d(e){let t=e[e.length-1];return t===void 0||t.includes("*")?[...e]:[...e,"**"]}a(_d,"aliasSegmentsWithSubtree");function Ni(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(Ni,"concreteGlobPrefix");function Lt(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}a(Lt,"segmentsArePrefix");function xd(e){let t=e.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(t.length<2||t[0]==="*"||t[0]==="**"||!t.some(r=>r==="*"))return null;let n=[];for(let r of t){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(xd,"anchoredSlicePrefix");function Od(e,t){let n=Ni(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Lt(t,n)||Lt(t,o)?!0:r?Lt(n,t)&&n.length<t.length||Lt(n,["src",...t])&&n.length<t.length+1||Lt(n,["app",...t])&&n.length<t.length+1:!1}a(Od,"globOverlapsAnchored");function wd(e,t){for(let r=0;r<e.length;r+=1){if(e[r]!==t&&e[r]!=="*")continue;let o=e.slice(r+1);if(o.length>=2||o.some(s=>s==="*"||s==="**"))return!0}let n=Ni(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(wd,"globOverlapsBare");function Td(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return wd(e,n[0]);let r=xd(t);return r?Od(e,r):!1}a(Td,"globOverlapsSliceEntry");function Pd(e){let t=Pe(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty path glob";if(t==="*"||t==="**")return"must not cover the whole tree";for(let n of t.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(Pd,"aliasGlobIssue");function Nd(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let o of e){if(typeof o!="string"||o.length===0)continue;let s=o.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(s.length===1&&s[0]&&!s[0].includes("*")){n.push({literals:[s[0],null]});continue}if(!s.some(i=>i==="**"||i.includes("*")&&i!=="*")&&s.includes("*")){if(r){let i=-1;for(let d=0;d<s.length;d+=1)s[d]!=="*"&&(i=d);if(i<0)continue;let l=s.filter((d,p)=>p>=i||d==="*").map(d=>d==="*"?null:d),c=s.slice(i).map(d=>d==="*"?null:d);n.push(c.length===l.length?{literals:l}:{literals:l,legacy:c});continue}n.push({literals:s.map(i=>i==="*"?null:i)})}}return n}a(Nd,"universeShapes");function $n(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a($n,"shapeMatches");function Ld(e,t){let n=Pe(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(s=>s.length===0||s==="."||s==="..")||n.includes("*")||!n.includes("/"))return at;let r=n.split("/").map(s=>s.toLowerCase());if(t.length===0||t.some(s=>$n(s,r)))return at;if(t.some(s=>$n(s,r.slice(0,-1))))return null;let o=new Set(t.filter(s=>s.legacy!==void 0&&!$n({literals:s.legacy},r)&&$n({literals:s.legacy},r.slice(0,-1))).map(s=>s.literals.map(i=>i??"*").join("/")));return o.size===1?null:o.size>1?bd:at}a(Ld,"aliasTargetIssue");function _i(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(_i,"aliasGlobVariants");function $d(e,t){let n=_i(e),r=_i(t);for(let o of n)if(Be(o,t,0,0,new Map))return!0;for(let o of r)if(Be(e,o,0,0,new Map))return!0;return!1}a($d,"aliasesCanMatchSameFile");function Be(e,t,n,r,o){let s=`${n}:${r}`,i=o.get(s);if(i!==void 0)return i;let l=!1;if(n===e.length&&r===t.length)l=!0;else if(n<e.length&&e[n]==="**")l=Be(e,t,n+1,r,o)||r<t.length&&Be(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=Be(e,t,n,r+1,o)||n<e.length&&Be(e,t,n+1,r,o);else if(n<e.length&&r<t.length){let c=e[n],d=t[r];(c===d||c==="*"||d==="*")&&(l=Be(e,t,n+1,r+1,o))}return o.set(s,l),l}a(Be,"globsCanMatchSame");var xi="must be a filename with exactly one <Layer> token and no slash or wildcard (arkrules.<Layer>.json)";function Dd(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.arkRulesFile===void 0)return;let i=`$.rules[${o}].childSlices.arkRulesFile`,l=s.arkRulesFile;if(typeof l!="string"||l.length===0){t.push({path:i,message:xi});return}(l.split("<Layer>").length!==2||/[*\\/]/.test(l)||l.includes(".."))&&t.push({path:i,message:xi})})}a(Dd,"validateChildSliceArkRulesFile");function Fd(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.sliceAliases===void 0)return;let i=s.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=Nd(r.sliceFolders,r.sliceIdentity),d=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(g=>typeof g=="string"&&g.length>0),p=[];i.forEach((g,f)=>{let m=`${l}[${f}]`;if(!ie(g)){t.push({path:m,message:"must be an object with from and to"});return}for(let k of Object.keys(g))k!=="from"&&k!=="to"&&k!=="pinned"&&k!=="reason"&&t.push({path:Fn(m,k),message:"unknown field"});let u=g.from,h=g.to;if(typeof u!="string"||u.trim().length===0)t.push({path:`${m}.from`,message:"must be a non-empty path glob"});else{let k=Pd(u);if(k)t.push({path:`${m}.from`,message:k});else{let C=_d(Cd(u));d.some(S=>Td(C,S))&&t.push({path:`${m}.from`,message:vd});for(let S of p)if($d(S,C)){t.push({path:m,message:Ed});break}p.push(C)}}if(typeof h!="string"||h.trim().length===0)t.push({path:`${m}.to`,message:at});else{let k=Ld(h,c);k&&t.push({path:`${m}.to`,message:k})}})})}a(Fd,"validateChildSliceAliases");function Le(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Le,"isObject");function lt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(lt,"propertyPath");function Ie(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(Ie,"valueType");function Md(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Md,"resolveSchemaRef");function Ne(e,t,n,r,o){if(t.$ref){let s=Md(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ne(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(!Le(e)){o.push({path:n,message:`must be an object; received ${Ie(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:lt(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:lt(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||Ne(e[l],i,lt(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Ne(e[i],l,lt(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Ie(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)=>Ne(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 ${Ie(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 ${Ie(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${Ie(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(Ne,"validateSchemaNode");function Mn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(Mn,"normalizeStewardId");function Li(e){let t=Mn(e);return!t||is(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Li,"isGitHubHandle");function jd(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t.includes("@")||t.includes(" ")||is(t))return!1;let n=t.split("@");if(n.length!==2||!n[0]||/\s/.test(t))return!1;let r=n[1].lastIndexOf(".");return r>0&&r<n[1].length-1}a(jd,"isGitHubEmail");function Hd(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Li(t[1])?Mn(t[1]):null}a(Hd,"githubHandleFromEmail");function $i(e){let t=Hd(e);if(t)return t;let n=Mn(e);return!n||is(n)?null:Li(n)||jd(n)?n:null}a($i,"canonicalStewardId");var Vd=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function is(e){let t=Mn(e);return!t||Vd.test(t)}a(is,"isAutomationAuthor");var ae="1.3",Kd=["public","auth","admin","internal"];function Ud(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(Ud,"isFutureHouseLayer");function Gd(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(Gd,"layerOwnersList");function Fi(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ud(t)&&!Gd(t)).map(t=>t.name)}a(Fi,"layersMissingRequiredOwners");function Mi(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(Mi,"missingLayerOwnersNextAction");var jn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Di=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Bd=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function zd(){let e=[];for(let t of Di)for(let n of Di)t===n||Bd.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(zd,"createDefaultRules");var Vn=zd(),as=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Hn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:jn,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:jn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ae,default:ae},name:{type:"string",minLength:1},include:{...le,minItems:1,default:["src"]},exclude:{...le,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Vn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...le,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{description:"A project-relative ArkRules path, or a list of paths merged into one catalog for this layer. A string keeps today's behaviour. An older build that types this value as a string rejects an array at config load.",oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1}}]},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...le,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...le,minItems:1},exclude:le,intentPrefixes:le,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Kd]},owners:{...le,minItems:1},forbiddenGlobals:le,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:{...le,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 every star binding (a star before the last literal is kept too), so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...le,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:Oi,childSlices:wi}},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:{...le,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:{...le,minItems:1}}},arkRun:hi,arkOrder:yi}},be=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
2
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ha(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ha,"isObject");function zn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(zn,"propertyPath");function dt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(dt,"valueType");function Su(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Su,"resolveSchemaRef");function jt(e,t,n,r,o){if(t.$ref){let s=Su(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}jt(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(!ha(e)){o.push({path:n,message:`must be an object; received ${dt(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:zn(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:zn(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||jt(e[l],i,zn(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&jt(e[i],l,zn(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${dt(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)=>jt(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 ${dt(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 ${dt(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${dt(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(jt,"validateNode");function ku(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"&&(pa(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(ku,"validateLayerOwners");function Iu(e){let t={...e,$schema:e.$schema===void 0?Wn:e.$schema,schemaVersion:e.schemaVersion===void 0?ie:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Yn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Zi(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ji(e.arkOrder)),t}a(Iu,"defaultedConfig");function Eu(e){return e===ie?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Eu,"migratedFromOf");function bu(){let e=new Set([ie]);for(let t of xs)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(bu,"knownInputVersions");function vu(e,t="ark.config.json"){if(!ha(e))throw new ve(t,[{path:"$",message:`must be an object; received ${dt(e)}`}]);let n=bu(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ie}`}]);if(r!=="unversioned"&&!n.has(r))throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);let o=r,s={...e},i=0;for(;o!==ie&&i<xs.length+1;){i+=1;let l=xs.find(c=>c.from===o);if(!l)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ie}`}]);o=l.to,s.schemaVersion=o}if(o!==ie)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);return{candidate:Iu(s),migratedFrom:Eu(r)}}a(vu,"migrateArkConfig");function Ht(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=vu(e,t),o=[];if(jt(n,qn,"$",qn,o),Qi(n,o),ea(n,o),ku(n,o),la(n,o),o.length>0)throw new ve(t,o);return{config:n,migratedFrom:r}}a(Ht,"loadArkConfigContract");function Xn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ve(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ht(n,t)}a(Xn,"parseArkConfigJson");function ya(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Wn,schemaVersion:ie};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(ya,"withArkConfigMetadata");function Cu(e){return e.endsWith(".")?e:`${e}.`}a(Cu,"normalizePrefix");function _u(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(_u,"byLongestPrefix");function Vt(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Cu)})),n=[...t].sort(_u),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(Vt,"createArchitectureProfile");function Os(e,t={}){return Vt({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:[...Kn(n)],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(Os,"createArchitectureProfileFromArkConfig");var xu=[{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}],Kt=Vt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:xu,rules:Yn.map(e=>({...e}))}),Ou={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 ws(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ya({include:e.include??[t],layers:Kt.layers.map(o=>({name:o.name,patterns:(Ou[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Kt.rules]})}a(ws,"createElevenLayerArkConfig");function ee(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(ee,"deterministicHash");function X(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(X).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${X(t[n])}`).join(",")}}`}a(X,"stableSerialize");function Ce(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}a(Ce,"feedText");function Ts(e,t){if(Array.isArray(e)){Ce("[",t);for(let o=0;o<e.length;o+=1){if(o>0&&Ce(",",t),!(o in e))continue;let s=e[o];if(s!==null&&typeof s=="object")Ts(s,t);else{let i=JSON.stringify(s);i!==void 0&&Ce(i,t)}}Ce("]",t);return}let n=e,r=Object.keys(n).sort();Ce("{",t);for(let o=0;o<r.length;o+=1){o>0&&Ce(",",t);let s=r[o];Ce(`${JSON.stringify(s)}:`,t);let i=n[s];i!==null&&typeof i=="object"?Ts(i,t):Ce(`${JSON.stringify(i)}`,t)}Ce("}",t)}a(Ts,"feedStable");function Ls(e){if(e===null||typeof e!="object")return ee(X(e));let t={hash:2166136261};return Ts(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}a(Ls,"stableHash");var De="1.2";var Aa=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e){let t=e.map((n,r)=>({key:X(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])}a(q,"sortCanonical");function ne(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(ne,"sortedUnique");function pt(e){let t={schemaVersion:"1.2",include:ne(e.include??[]),exclude:ne(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:ne(e.dynamicImportAllowlist??[]),layers:q(e.layers.map(n=>({name:n.name,patterns:ne(n.patterns??[]),exclude:ne(n.exclude??[]),forbiddenGlobals:ne(n.forbiddenGlobals??[]),intentPrefixes:ne(n.intentPrefixes??[]),capabilityDeny:ne(n.capabilities?.deny??[]),pure:n.pure===!0}))),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:ne(e.arkRun.compositionRoots),managedLayers:ne(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return ee(X(t))}a(pt,"resolvedFactsEvidenceRequirementsHash");function wu(e){let t=q(e.completenessReasons.map(E=>({code:E.code,message:E.message,...E.file?{file:E.file}:{}}))),n=e.files.map(E=>({...E,typeOnlyExportNames:ne(E.typeOnlyExportNames)})).sort((E,$)=>E.path<$.path?-1:E.path>$.path?1:0),r=q(e.dependencies.map(E=>({...E,...E.namedBindings?{namedBindings:ne(E.namedBindings)}:{}}))),o=q(e.capabilityUses.map(E=>({...E}))),s=q(e.ambientUses.map(E=>({...E}))),i=q(e.publishCalls.map(E=>({...E}))),l=q(e.intentReferences.map(E=>({...E}))),c=q(e.safetyUses.map(E=>({...E}))),d=q((e.classShapes??[]).map(E=>({...E,mutatingMethods:[...E.mutatingMethods??[]].map($=>({...$}))}))),u=q((e.arkRunKernelCalls??[]).map(E=>({...E}))),m=q((e.arkRunManagedNews??[]).map(E=>({...E}))),f=q((e.arkRunCompositionRootHits??[]).map(E=>({...E}))),h=q((e.arkRunDeclarations??[]).map(E=>({...E,uses:ne(E.uses),reactsTo:ne(E.reactsTo),raises:ne(E.raises),sends:ne(E.sends)}))),p=q((e.arkOrderPlaneCalls??[]).map(E=>({...E}))),y=q((e.arkOrderGenericUpdates??[]).map(E=>({...E}))),S=q((e.arkOrderRootHits??[]).map(E=>({...E}))),C=q((e.arkOrderXiFieldWrites??[]).map(E=>({...E}))),R=q((e.arkOrderIngestWritesXi??[]).map(E=>({...E}))),k=q((e.arkOrderReleaseKeyCounts??[]).map(E=>({...E}))),v=q((e.arkOrderXiTtlKeys??[]).map(E=>({...E}))),H=q((e.arkOrderBudgetLeaks??[]).map(E=>({...E}))),P=e.files.map(({path:E,contentHash:$})=>({path:E,contentHash:$})).sort((E,$)=>E.path<$.path?-1:E.path>$.path?1:0),D=Ls(P);return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:D,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:d,arkRunKernelCalls:u,arkRunManagedNews:m,arkRunCompositionRootHits:f,arkRunDeclarations:h,arkOrderPlaneCalls:p,arkOrderGenericUpdates:y,arkOrderRootHits:S,arkOrderXiFieldWrites:C,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:k,arkOrderXiTtlKeys:v,arkOrderBudgetLeaks:H}}a(wu,"canonicalResolvedFactsInput");function Ra(e){let t=wu(e);return{...t,factsHash:Ls(t)}}a(Ra,"createCanonicalResolvedCandidateFacts");function Zn(e){return Ra(Sa(K(e,"$"),!1))}a(Zn,"createResolvedCandidateFacts");function K(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(K,"asRecord");function V(e,t,n){let r=Object.keys(e).find(o=>!t.includes(o));if(r)throw new Error(`${n}.${r} is not part of schema ${"1.2"}.`)}a(V,"assertOnlyKeys");function j(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(j,"requiredText");function _e(e,t,n){if(e[t]!==void 0)return j(e,t,n)}a(_e,"optionalText");function U(e,t,n){let r=j(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(U,"requiredProjectPath");function Z(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(Z,"requiredBoolean");function Ns(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(Ns,"requiredInteger");function te(e,t,n){let r=Ns(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(te,"requiredPositiveInteger");function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(G,"requiredArray");function xe(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(xe,"enumValue");function ut(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(ut,"parseStringArray");function Tu(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(Tu,"assertUnique");function Sa(e,t){V(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=xe(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=xe(e,"completeness",["complete","partial","unavailable"],"$"),o=G(e,"completenessReasons","$").map((b,O)=>{let A=`$.completenessReasons[${O}]`,g=K(b,A);V(g,["code","message","file"],A);let L=g.file===void 0?void 0:U(g,"file",A);return{code:j(g,"code",A),message:j(g,"message",A),...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=G(e,"files","$").map((b,O)=>{let A=`$.files[${O}]`,g=K(b,A);return V(g,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],A),{path:U(g,"path",A),contentHash:j(g,"contentHash",A),parseStatus:xe(g,"parseStatus",["parsed","invalid"],A),parseDiagnosticCount:Ns(g,"parseDiagnosticCount",A),exportsOnlyTypes:Z(g,"exportsOnlyTypes",A),typeOnlyExportNames:ut(g.typeOnlyExportNames,`${A}.typeOnlyExportNames`),hasTopLevelSideEffects:Z(g,"hasTopLevelSideEffects",A)}}),i=G(e,"dependencies","$").map((b,O)=>{let A=`$.dependencies[${O}]`,g=K(b,A);V(g,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],A);let L=_e(g,"specifier",A),W=_e(g,"target",A),de=xe(g,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],A);if(de==="resolved-project"&&!W)throw new Error(`${A}.target is required for resolved-project dependencies.`);if(de!=="resolved-project"&&W)throw new Error(`${A}.target is only allowed for resolved-project dependencies.`);if(de!=="dynamic"&&!L)throw new Error(`${A}.specifier is required unless resolution is dynamic.`);return{from:U(g,"from",A),...L?{specifier:L}:{},kind:xe(g,"kind",["import","export","dynamic-import","require"],A),typeOnly:Z(g,"typeOnly",A),line:te(g,"line",A),resolution:de,...W?{target:U(g,"target",A)}:{},...g.namedBindings!==void 0?{namedBindings:ut(g.namedBindings,`${A}.namedBindings`)}:{},...g.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:Z(g,"targetTypeOnlyExports",A)}:{},...g.sourcePureTypeModule!==void 0?{sourcePureTypeModule:Z(g,"sourcePureTypeModule",A)}:{},...g.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:Z(g,"namedBindingsTypeOnly",A)}:{},...g.portProofEligible!==void 0?{portProofEligible:Z(g,"portProofEligible",A)}:{}}}),l=G(e,"capabilityUses","$").map((b,O)=>{let A=`$.capabilityUses[${O}]`,g=K(b,A);return V(g,["file","line","symbol","capability","source"],A),{file:U(g,"file",A),line:te(g,"line",A),symbol:j(g,"symbol",A),capability:xe(g,"capability",Aa,A),source:xe(g,"source",["ambient-global","import-based"],A)}}),c=G(e,"ambientUses","$").map((b,O)=>{let A=`$.ambientUses[${O}]`,g=K(b,A);return V(g,["file","line","symbol"],A),{file:U(g,"file",A),line:te(g,"line",A),symbol:j(g,"symbol",A)}}),d=G(e,"publishCalls","$").map((b,O)=>{let A=`$.publishCalls[${O}]`,g=K(b,A);V(g,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],A);let L=_e(g,"rawIntentName",A),W=_e(g,"sourceIntent",A);return{file:U(g,"file",A),line:te(g,"line",A),...L?{rawIntentName:L}:{},objectHasIntent:Z(g,"objectHasIntent",A),arkPublishCandidate:Z(g,"arkPublishCandidate",A),hasSource:Z(g,"hasSource",A),...W?{sourceIntent:W}:{}}}),u=G(e,"intentReferences","$").map((b,O)=>{let A=`$.intentReferences[${O}]`,g=K(b,A);return V(g,["file","line","intent"],A),{file:U(g,"file",A),line:te(g,"line",A),intent:j(g,"intent",A)}}),m=G(e,"safetyUses","$").map((b,O)=>{let A=`$.safetyUses[${O}]`,g=K(b,A);V(g,["file","line","kind","symbol"],A);let L=_e(g,"symbol",A),W=xe(g,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],A);if(W==="in-memory-store"&&!L)throw new Error(`${A}.symbol is required for in-memory-store facts.`);if(W!=="in-memory-store"&&L)throw new Error(`${A}.symbol is only allowed for in-memory-store facts.`);return{file:U(g,"file",A),line:te(g,"line",A),kind:W,...L?{symbol:L}:{}}});Tu(s,b=>b.path,"$.files");let f=new Set(s.map(b=>b.path));for(let b of s){if(b.parseStatus==="parsed"&&b.parseDiagnosticCount!==0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(b.parseStatus==="invalid"&&b.parseDiagnosticCount===0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(b=>b.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let b of i)if(!f.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);let p=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((b,O)=>{let A=`$.arkRunKernelCalls[${O}]`,g=K(b,A);V(g,["file","line","kind","callee","viaImport","receiver","nameLiteral"],A);let L=_e(g,"receiver",A),W=_e(g,"nameLiteral",A);return{file:U(g,"file",A),line:te(g,"line",A),kind:xe(g,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],A),callee:j(g,"callee",A),viaImport:Z(g,"viaImport",A),...L?{receiver:L}:{},...W?{nameLiteral:W}:{}}}),S=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((b,O)=>{let A=`$.arkRunManagedNews[${O}]`,g=K(b,A);V(g,["file","line","typeName","importedFrom"],A);let L=_e(g,"importedFrom",A);return{file:U(g,"file",A),line:te(g,"line",A),typeName:j(g,"typeName",A),...L?{importedFrom:L}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((b,O)=>{let A=`$.arkRunCompositionRootHits[${O}]`,g=K(b,A);return V(g,["file","matchedRoot","hasKernelFactory"],A),{file:U(g,"file",A),matchedRoot:j(g,"matchedRoot",A),hasKernelFactory:Z(g,"hasKernelFactory",A)}}),k=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),H=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((b,O)=>{let A=`$.arkOrderPlaneCalls[${O}]`,g=K(b,A);return V(g,["file","line","callee"],A),{file:U(g,"file",A),line:te(g,"line",A),callee:j(g,"callee",A)}}),D=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((b,O)=>{let A=`$.arkOrderGenericUpdates[${O}]`,g=K(b,A);return V(g,["file","line","method"],A),{file:U(g,"file",A),line:te(g,"line",A),method:j(g,"method",A)}}),$=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((b,O)=>{let A=`$.arkOrderRootHits[${O}]`,g=K(b,A);return V(g,["file","matchedRoot","hasPlaneFactory"],A),{file:U(g,"file",A),matchedRoot:j(g,"matchedRoot",A),hasPlaneFactory:Z(g,"hasPlaneFactory",A)}}),N=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((b,O)=>{let A=`$.arkOrderXiFieldWrites[${O}]`,g=K(b,A);return V(g,["file","line","key"],A),{file:U(g,"file",A),line:te(g,"line",A),key:j(g,"key",A)}}),F=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((b,O)=>{let A=`$.arkOrderIngestWritesXi[${O}]`,g=K(b,A);return V(g,["file","line"],A),{file:U(g,"file",A),line:te(g,"line",A)}}),ge=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((b,O)=>{let A=`$.arkOrderReleaseKeyCounts[${O}]`,g=K(b,A);return V(g,["file","line","keyCount"],A),{file:U(g,"file",A),line:te(g,"line",A),keyCount:te(g,"keyCount",A)}}),vn=(e.arkOrderXiTtlKeys===void 0?[]:G(e,"arkOrderXiTtlKeys","$")).map((b,O)=>{let A=`$.arkOrderXiTtlKeys[${O}]`,g=K(b,A);return V(g,["file","line","key"],A),{file:U(g,"file",A),line:te(g,"line",A),key:j(g,"key",A)}}),Xr=(e.arkOrderBudgetLeaks===void 0?[]:G(e,"arkOrderBudgetLeaks","$")).map((b,O)=>{let A=`$.arkOrderBudgetLeaks[${O}]`,g=K(b,A);return V(g,["file","line","kind"],A),{file:U(g,"file",A),line:te(g,"line",A),kind:j(g,"kind",A)}}),Rt=k.map((b,O)=>{let A=`$.arkRunDeclarations[${O}]`,g=K(b,A);return V(g,["file","line","uses","reactsTo","raises","sends"],A),{file:U(g,"file",A),line:te(g,"line",A),uses:ut(g.uses,`${A}.uses`),reactsTo:ut(g.reactsTo,`${A}.reactsTo`),raises:ut(g.raises,`${A}.raises`),sends:ut(g.sends,`${A}.sends`)}});for(let[b,O]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",d],["$.intentReferences",u],["$.safetyUses",m],["$.arkRunKernelCalls",p],["$.arkRunManagedNews",S],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",Rt],["$.arkOrderPlaneCalls",H],["$.arkOrderGenericUpdates",D],["$.arkOrderRootHits",$],["$.arkOrderXiFieldWrites",N],["$.arkOrderIngestWritesXi",F],["$.arkOrderReleaseKeyCounts",ge],["$.arkOrderXiTtlKeys",vn],["$.arkOrderBudgetLeaks",Xr]])for(let A of O)if(!f.has(A.file))throw new Error(`${b} references missing file ${A.file}.`);let Ke=_e(e,"projectPackageName","$"),Zr=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((b,O)=>{let A=`$.classShapes[${O}]`,g=K(b,A);V(g,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],A);let L=G(g,"mutatingMethods",A).map((W,de)=>{let _n=`${A}.mutatingMethods[${de}]`,Jr=K(W,_n);return V(Jr,["name","referencesGuardOrPublish"],_n),{name:j(Jr,"name",_n),referencesGuardOrPublish:Z(Jr,"referencesGuardOrPublish",_n)}});return{file:U(g,"file",A),className:j(g,"className",A),exported:Z(g,"exported",A),hasPublicMutableFields:Z(g,"hasPublicMutableFields",A),hasPublicSetters:Z(g,"hasPublicSetters",A),hasPublicConstructor:Z(g,"hasPublicConstructor",A),hasStaticFactory:Z(g,"hasStaticFactory",A),mutatingMethods:L,...g.dataOnly===void 0?{}:{dataOnly:Z(g,"dataOnly",A)},...g.truncatedUntil===void 0?{}:{truncatedUntil:Ns(g,"truncatedUntil",A)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:j(e,"resolverIdentity","$"),compilerIdentity:j(e,"compilerIdentity","$"),compilerOptionsHash:j(e,"compilerOptionsHash","$"),tsconfigHash:j(e,"tsconfigHash","$"),evidenceRequirementsHash:j(e,"evidenceRequirementsHash","$"),...Ke?{projectPackageName:Ke}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:d,intentReferences:u,safetyUses:m,classShapes:Zr,arkRunKernelCalls:p,arkRunManagedNews:S,arkRunCompositionRootHits:R,arkRunDeclarations:Rt,arkOrderPlaneCalls:H,arkOrderGenericUpdates:D,arkOrderRootHits:$,arkOrderXiFieldWrites:N,arkOrderIngestWritesXi:F,arkOrderReleaseKeyCounts:ge,arkOrderXiTtlKeys:vn,arkOrderBudgetLeaks:Xr}}a(Sa,"parseResolvedFactsInput");function Oe(e){let t=K(e,"$"),n=j(t,"factsHash","$"),r=j(t,"candidateTreeHash","$"),o=Ra(Sa(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(Oe,"loadResolvedCandidateFacts");var Lu=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},re={type:"integer",minimum:1},B={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Jn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:T,message:T,file:B}}},resolverIdentity:T,compilerIdentity:T,compilerOptionsHash:T,tsconfigHash:T,candidateTreeHash:T,evidenceRequirementsHash:T,projectPackageName:T,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:B,contentHash:T,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:T},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:B,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:B,namedBindings:{type:"array",items:T},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:B,line:re,symbol:T,capability:{enum:Lu},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:B,line:re,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:B,line:re,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:B,line:re,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},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:B,className:T,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:T,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:B,line:re,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:T,viaImport:{type:"boolean"},receiver:T,nameLiteral:T}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:B,line:re,typeName:T,importedFrom:T}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:B,matchedRoot:T,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:B,line:re,uses:{type:"array",items:T},reactsTo:{type:"array",items:T},raises:{type:"array",items:T},sends:{type:"array",items:T}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:B,line:re,callee:T}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:B,line:re,method:T}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:B,matchedRoot:T,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:re,key:T}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:B,line:re}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:B,line:re,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:re,key:T}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:re,kind:T}}},factsHash:T},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Qn="1.0";function le(e){return`${e.from}->${e.to}`}a(le,"dependencyKey");function Ut(e,t,n,r="dependency"){return{id:`${e}:${r}:${le(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${le(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${le(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${le(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${le(t)} from the candidate, then preflight again.`}:{}}}a(Ut,"dependencyFinding");function We(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[le(f),f])),s=new Map(e.baseDependencies.map(f=>[le(f),f])),i=new Map(e.candidateDependencies.map(f=>[le(f),f]));for(let f of[...n.values()].sort((h,p)=>h.path.localeCompare(p.path))){let h=r.get(f.path);h?h.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:h.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${h.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:h.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((h,p)=>h.path.localeCompare(p.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let l=new Set;for(let f of[...o.values()].sort((h,p)=>le(h).localeCompare(le(p)))){if(i.has(le(f))){t.push(Ut("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let h={from:f.to,to:f.from};i.has(le(h))?(l.add(le(h)),t.push(Ut("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ut("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,h]of[...i].sort(([p],[y])=>p.localeCompare(y)))s.has(f)||o.has(f)||l.has(f)||!c.has(h.from)&&!c.has(h.to)||t.push({...Ut("unplanned",h,`${h.from} -> ${h.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let d=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,h]of[...s].sort(([p],[y])=>p.localeCompare(y)))i.has(f)||d.has(h.from)||d.has(h.to)||!c.has(h.from)&&!c.has(h.to)||t.push({...Ut("unplanned",h,`${h.from} -> ${h.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let u={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,h)=>u[f.classification]-u[h.classification]||(f.subject===h.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(h.id));let m={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}a(We,"analyzeArchitectureConvergence");var Ea="1.0",Ps="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ds=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Nu=["no-anemic-model"],ka={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},tr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ps,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:Ps},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...Ds]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ka,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:ka}}}},we=class extends Error{static{a(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
3
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Wd(e,t){let n=e.arkRules;if(!(n===void 0||!Le(n)))for(let[r,o]of Object.entries(n)){let s=lt("$.arkRules",r);if(typeof o=="string"){o.length===0&&t.push({path:s,message:"must be a non-empty relative path string"});continue}if(!Array.isArray(o)||o.length===0){t.push({path:s,message:"must be a non-empty path string or an array of paths"});continue}let i=new Set;o.forEach((l,c)=>{let d=`${s}[${c}]`;if(typeof l!="string"||l.length===0){t.push({path:d,message:"must be a non-empty relative path string"});return}i.has(l)&&t.push({path:d,message:"duplicate path"}),i.add(l)})}}a(Wd,"validateArkRulesRefs");function qd(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"&&($i(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(qd,"validateLayerOwners");function Yd(e){let t={...e,$schema:e.$schema===void 0?jn:e.$schema,schemaVersion:e.schemaVersion===void 0?ae:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Vn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Ai(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ri(e.arkOrder)),t}a(Yd,"defaultedConfig");function Xd(e){return e===ae?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Xd,"migratedFromOf");function Zd(){let e=new Set([ae]);for(let t of as)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Zd,"knownInputVersions");function Jd(e,t="ark.config.json"){if(!Le(e))throw new be(t,[{path:"$",message:`must be an object; received ${Ie(e)}`}]);let n=Zd(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ae}`}]);if(r!=="unversioned"&&!n.has(r))throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);let o=r,s={...e},i=0;for(;o!==ae&&i<as.length+1;){i+=1;let l=as.find(c=>c.from===o);if(!l)throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ae}`}]);o=l.to,s.schemaVersion=o}if(o!==ae)throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);return{candidate:Yd(s),migratedFrom:Xd(r)}}a(Jd,"migrateArkConfig");function $t(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Jd(e,t),o=[];if(Ne(n,Hn,"$",Hn,o),ki(n,o),Ii(n,o),qd(n,o),Ti(n,o),Wd(n,o),o.length>0)throw new be(t,o);return{config:n,migratedFrom:r}}a($t,"loadArkConfigContract");function Kn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new be(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return $t(n,t)}a(Kn,"parseArkConfigJson");function ji(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:jn,schemaVersion:ae};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(ji,"withArkConfigMetadata");var ls={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."},Dt=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 Un(e){let t=(e.intentPrefixes??[]).filter(n=>n.trim().length>0);return t.length>0?t:Dt.find(n=>n.layer===e.name)?.prefixes??[]}a(Un,"effectiveIntentPrefixes");function Hi(e){let t=new Set(e.layers.filter(r=>Un(r).length>0).map(r=>r.name)),n=new Set;for(let r of e.rules??[])if(!(r.allowed!==!1||r.peerIsolation===!0))for(let o of[r.from,r.to])t.has(o)||n.add(o);return[...n].sort()}a(Hi,"unresolvableLayerFlowLayers");function cs(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(cs,"resolveIntentLayer");function ve(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(ve,"looksLikeArkIntent");function Ft(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ve(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ls.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ls.PUBLISH_MISSING_SOURCE}),t}a(Ft,"classifyPublishFacts");function Qd(e){return e.endsWith(".")?e:`${e}.`}a(Qd,"normalizePrefix");function eu(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(eu,"byLongestPrefix");function jt(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Qd)})),n=[...t].sort(eu),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(jt,"createArchitectureProfile");function ds(e,t={}){return jt({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:[...Un(n)],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(ds,"createArchitectureProfileFromArkConfig");var tu=[{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}],Mt=jt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:tu,rules:Vn.map(e=>({...e}))}),nu={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 us(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ji({include:e.include??[t],layers:Mt.layers.map(o=>({name:o.name,patterns:(nu[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Mt.rules]})}a(us,"createElevenLayerArkConfig");var fs=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ms=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),hs=Object.freeze(Object.keys(ms).sort()),ps=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"}),gs=Object.freeze({process:Object.freeze(["process","node:process"])});function Ht(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ps[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=ps[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:ps[e.slice(0,s)]??null}a(Ht,"capabilityForModuleSpecifier");function $e(e,t){for(let n of t)if(gs[n]?.includes(e))return n;return null}a($e,"forbiddenGlobalForModuleSpecifier");function Gn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=ms[r];if(o)return o}return null}a(Gn,"capabilityForAmbientName");function ct(e){if(e?.pure===!0)return[...fs].sort();let n=(e?.capabilities?.deny??[]).filter(r=>fs.includes(r));return[...new Set(n)].sort()}a(ct,"effectiveCapabilityDeny");function Vt(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(Vt,"ambientCoveredByForbiddenGlobals");function Bn(e){let t=new Set,n=new Set,r=Object.keys(ms);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 gs[o]??[])t.add(`import-exact:${i}`)}for(let o of ct(e)){if(t.add(`import:${o}`),o==="process")for(let s of gs.process)t.add(`import-exact:${s}`);for(let s of r)Gn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(Bn,"loweredLayerCoverage");function De(e){if(e==="deny"||e==="deny-cross-parent")return e;if(e!==null&&typeof e=="object"){let t=e.mode;if(t==="deny-cross-parent")return t}}a(De,"sharedImportsSliceMode");function Xn(e){if(e===null||typeof e!="object")return[];let t=e.stopAt;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}a(Xn,"sharedImportsSliceStopAt");var Vi=new Map;function Ki(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Ki,"escapeLiteral");function Zn(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(Zn,"normalizeGlobSeparators");function ru(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(ru,"bracesBalanced");function ce(e){let t=Vi.get(e);if(t)return t;let n=Zn(e),r=ru(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Ki(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+=Ki(c)}let i=new RegExp(`^${o}$`);return Vi.set(e,i),i}a(ce,"globToRegExp");function su(e){return Zn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(su,"concreteGlobSegments");function Rs(e,t){let n=Zn(String(e)),r=su(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 d of r){let p=-1;for(let g=l;g<i.length;g+=1)if(i[g]===d){p=g;break}if(p<0)return s;c=p,l=p+1}return(c+1)*1e6+r.length*1e4+o}a(Rs,"patternSpecificity");function ge(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>ce(i).test(n))){for(let i of s.patterns??[])if(ce(i).test(n)){let l=Rs(i,n);l>o&&(o=l,r=s.name)}}return r}a(ge,"layerForRelativePath");function pt(e,t,n){return Xi(e,t,n==="stars"?"stars":"path")}a(pt,"sliceIdForPath");function As(e,t){return Xi(e,t?[...t]:void 0,Yi)}a(As,"legacyStarsSliceIdForPath");var Yi="stars-4.8.23";function Xi(e,t,n){if(!t?.length)return;let r=String(e).split(/[/\\]/).filter(Boolean);if(r.length===0)return;let o=new Set;for(let s of t){if(typeof s!="string"||s.length===0)continue;let i=ou(s);if(i.anchored){let l=au(r,i.anchored,n);if(l)return l;continue}i.bare!==void 0&&o.add(i.bare)}return uu(r,o)}a(Xi,"sliceIdWithBinding");var zn=new Map;function ou(e){let t=zn.get(e);if(t)return t;let n={};return Zi(e)?n={anchored:iu(e)}:!e.includes("/")&&!e.includes("\\")&&!e.includes("*")&&(n={bare:e.toLowerCase()}),zn.size>=1024&&zn.clear(),zn.set(e,n),n}a(ou,"parsedSliceFolder");function Zi(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Zi,"isAnchoredSliceEntry");function iu(e){return e.split(/[/\\]/).filter(t=>t.length>0).map(t=>t.toLowerCase())}a(iu,"anchoredSlicePattern");function au(e,t,n){let r=Qi(e,t[0]??"");for(let o of r){let s=lu(e,t,o,n);if(s)return s}}a(au,"anchoredSliceIdFromPattern");function lu(e,t,n,r="path"){let o=[],s=[],i=-1,l=n;for(let c=0;c<t.length;c+=1){let d=t[c];if(d==="*"){if(l>=e.length-1){for(let p=c;p<t.length;p+=1)if(t[p]!=="*")return;break}o.push(e[l].toLowerCase()),s.push(!0),l+=1;continue}if(d==="**"||l>=e.length||e[l].toLowerCase()!==d)return;o.push(e[l].toLowerCase()),s.push(!1),i=o.length-1,l+=1}if(o.length!==0)return r===Yi?i<0?void 0:o.slice(i).join("/"):r==="stars"?i<0?void 0:o.filter((c,d)=>d>=i||s[d]).join("/"):o.join("/")}a(lu,"bindAnchoredSlice");function Ss(e){let t=-1;for(let r=0;r<e.length;r+=1)e[r]!=="*"&&(t=r);if(t<0)return null;let n=[];for(let r=0;r<e.length;r+=1)(r>=t||e[r]==="*")&&n.push(r);return n}a(Ss,"starsKeptSegmentIndexes");function Ji(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=cu(s);if(!i)continue;let l=s.split(/[/\\]/).filter(p=>p.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let d=r.get(i)??[];d.push(s),r.set(i,d)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:du(n.from,n.to,i,s)})}return t}a(Ji,"sliceIdentityCollisions");function cu(e){if(!Zi(e))return;let t=e.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(t.some(r=>r==="**"))return;let n=Ss(t);if(n)return n.map(r=>t[r]).join("/")}a(cu,"starsIdentityStem");function du(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(du,"formatSliceIdentityCollision");function uu(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(uu,"bareSliceId");function pu(e){let t=new Set;for(let n of e??[]){let o=Zn(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(pu,"inferSliceFoldersFromPatterns");function ks(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 pu(r?.patterns)}a(ks,"resolveSliceFolders");function Ui(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(Ui,"normalizeSegments");function Bt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Bt,"trimTrailingSlashes");var fu=["src","app"];function Qi(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return fu.includes(n)&&r!==n?[0,1]:[0]}a(Qi,"anchorOffsets");function gu(e){let t=Bt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(gu,"isBlanketRoot");function ut(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Ui(n);for(let s of t){if(typeof s!="string"||s.length===0||gu(s))continue;if(s.includes("*")){let c=Bt(s.toLowerCase());if(ce(c).test(r)||ce(`${c}/**`).test(r))return!0;continue}let i=Ui(s);if(i.length===0)continue;let l=Qi(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let d=!0;for(let p=0;p<i.length;p+=1)if(o[c+p]!==i[p]){d=!1;break}if(d)return!0}}return!1}a(ut,"pathUnderSharedRoot");function Gi(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(Gi,"sliceMatchesDeclaration");function Wn(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Gi(r.from,t)&&Gi(r.to,n))}a(Wn,"crossSliceEdgeAllowed");function mu(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(mu,"peerIsolationDecision");function ea(e){return Bt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(ea,"aliasGlobPattern");function ta(e,t){let n=ea(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=qn(r),s=ce(n),l=(n.split("/").pop()??"").includes("*")?null:ce(`${n}/**`),c=a(d=>s.test(d)||l!==null&&l.test(d),"hit");return c(r)||o!==r&&c(o)}a(ta,"aliasGlobMatches");function na(e,t){return!e||!t?.length?!1:ut(e,[...t])?!0:t.some(n=>typeof n=="string"&&ta(n,e))}a(na,"pathMatchesSharedWalkStop");function Is(e){let t=ea(e).split("/").filter(Boolean);return t.length<2||t.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:t.slice(0,-1).join("/"),childId:t.join("/")}}a(Is,"splitAliasTarget");function ra(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&ta(n.from,e))return n;return null}a(ra,"firstSliceAliasEntry");function hu(e,t){let n=ra(e,t);return n?Is(n.to):null}a(hu,"firstSliceAlias");function Kt(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=pt(e,r?[...r]:void 0,t.sliceIdentity),s=Gt(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=hu(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Kt,"resolveGovernedSlice");function yu(e){let t=[];for(let n of e??[]){if(typeof n!="string"||n.length===0)continue;let r=n.split(/[/\\]/).filter(Boolean).map(l=>l.toLowerCase());if(r.length===1&&r[0]&&!r[0].includes("*")){t.push({literals:[r[0],null],legacy:[r[0],null]});continue}if(r.some(l=>l==="**"||l.includes("*")&&l!=="*"))continue;let o=Ss(r);if(!o||!r.includes("*"))continue;let s=a(l=>l==="*"?null:l,"star"),i=o.find(l=>r[l]!=="*")??0;t.push({literals:o.map(l=>s(r[l]??"")),legacy:r.slice(i).map(s)})}return t}a(yu,"starsUniverseShapes");function Bi(e,t){return e.length===t.length&&e.every((n,r)=>n===null||t[r]==="*"||n===t[r])}a(Bi,"literalsMatch");function dt(e,t){let n=t.split("/").filter(Boolean).map(s=>s.toLowerCase()),r=yu(e);if(n.length===0||r.some(s=>Bi(s.literals,n)))return[];let o=new Set;for(let s of r)if(s.legacy.length!==s.literals.length&&Bi(s.legacy,n)){let i=[...n],l=s.literals.length-s.legacy.length;o.add([...s.literals.slice(0,l).map(()=>"*"),...i].join("/"))}return[...o].sort()}a(dt,"legacyStarsIdTargets");function sa(e,t){if(e.sliceIdentity!=="stars")return;let n=Is(t);if(n)return dt(e.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(sa,"legacyAliasUniverse");function zi(e,t,n){let r=Kt(e,t,n);if(!e||t.sliceIdentity!=="stars")return r;if(r.universeId){let o=ra(e,t);if(!pt(e,[...n],t.sliceIdentity)&&o&&sa(t,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let i=As(e,n),l=t.childSlices,c=l?.sliceIdentity==="stars"?As(e,l.sliceFolders):void 0;return{...r,...i?{legacyUniverse:i}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(zi,"placeForPair");function bs(e,t,n,r){let o=zi(n,e,t),s=zi(r,e,t),i=o.legacyUniverse,l=s.legacyUniverse,c=a((u,h)=>{if(!u.legacyAlias||h.legacyAlias||!h.universeId||h.legacyUniverse?.toLowerCase()!==u.universeId?.toLowerCase())return u;let k=u.childId?.split("/").pop();return{...u,universeId:h.universeId,...k?{childId:`${h.universeId}/${k}`}:{}}},"adopt"),d=c(o,s),p=c(s,o),g=Wn(e.allowedCrossSlice,d.universeId,p.universeId)||e.sliceIdentity==="stars"&&(i!==d.universeId||l!==p.universeId)&&Wn(e.allowedCrossSlice,i,l),f=e.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&s.legacyChild!==void 0&&o.legacyChild!==s.legacyChild&&ia(e.childSlices.allowedCrossSlice,o.legacyChild,s.legacyChild),m=a(u=>({...u.universeId?{universeId:u.universeId}:{},...u.childId?{childId:u.childId}:{}}),"strip");return{from:m(d),to:m(p),crossSliceAllowed:g,legacyChildAllowed:f}}a(bs,"resolveGovernedSlicePair");function Au(e,t,n){let r=e.split(/[/\\]/).filter(Boolean).map(s=>s.toLowerCase()),o=t.split("/").filter(Boolean).map(s=>s.toLowerCase());if(r.length===0||o.length===0||r.some(s=>s==="**"||s.includes("*")&&s!=="*"))return null;if(n==="stars"){let s=Ss(r);if(!s||s.length!==o.length)return null;let i=[...r];for(let l=0;l<s.length;l+=1){let c=s[l]??0;if(r[c]!=="*"&&r[c]!==o[l])return null;i[c]=o[l]??""}return i.join("/")}if(r.length!==o.length)return null;for(let s=0;s<r.length;s+=1)if(r[s]!=="*"&&r[s]!==o[s])return null;return o.join("/")}a(Au,"childPatternDirectory");function Ru(e,t){let n=qn(e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase()).split("/"),r=t.split("/"),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}a(Ru,"sharedDirectoryPrefix");function Su(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase();return n.startsWith("src/")&&!t.startsWith("src/")?`src/${t}`:n.startsWith("app/")&&!t.startsWith("app/")?`app/${t}`:t}a(Su,"withSourcePrefix");function ku(e,t,n){let r=null;for(let o of n.sliceFolders){if(typeof o!="string")continue;let s=Au(o,t,n.sliceIdentity);if(!s)continue;let i=Ru(e,s);(!r||i>r.score||i===r.score&&s.length<r.dir.length)&&(r={dir:s,score:i})}return r?Su(e,r.dir):""}a(ku,"sliceAliasDestination");var Iu="<Layer>";function bu(e,t){let n=Iu;if(!e.includes(n)||e.split(n).length!==2||/[*\\/]/.test(e))return null;let r=e.replace(n,t);return!r||r.includes("..")?null:r}a(bu,"sliceRuleFileName");function oa(e){let t=[...new Set(e.layers.filter(o=>typeof o=="string"&&o.length>0))].sort(),n=[],r=new Set;for(let o of e.rules??[]){let s=o?.childSlices,i=s?.arkRulesFile;if(!s||typeof i!="string")continue;let l=new Map;for(let c of e.files){if(typeof c!="string"||c.length===0)continue;let d=o.sliceFolders?.length?pt(c,o.sliceFolders,o.sliceIdentity):void 0,p=Gt(c,d,s);if(!p.childId||l.has(p.childId))continue;let g=ku(c,p.childId,s);g&&l.set(p.childId,g)}for(let[c,d]of[...l.entries()].sort((p,g)=>p[0].localeCompare(g[0])))for(let p of t){let g=bu(i,p);if(!g)continue;let f=`${d}/${g}`.replace(/\\/g,"/");r.has(`${p}\0${f}`)||(r.add(`${p}\0${f}`),n.push({path:f,childId:c,layer:p,defaultAppliesTo:[`${d}/**`]}))}}return n}a(oa,"resolveSliceRulePlan");function vu(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(vu,"peerIsolationDenyExplanation");function Eu(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Eu,"crossParentExplanation");function Cu(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(Cu,"crossSiblingExplanation");function _u(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(_u,"parentImportsChildExplanation");function Ut(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(Ut,"universePairLabel");function xu(e,t){if(!e||!t?.length)return!1;let n=e.toLowerCase();return t.some(r=>typeof r=="string"&&r.length>0&&r.toLowerCase()===n)}a(xu,"isCommonFolderName");function Gt(e,t,n){if(!e||!n?.sliceFolders?.length)return{};let r=pt(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let o=r.toLowerCase(),s=t.toLowerCase();if(o===s)return{};if(!o.startsWith(`${s}/`))return{mismatched:{childId:r,universeId:t}};let i=o.slice(s.length+1).split("/")[0];return xu(i,n.commonFolders)?{}:{childId:r}}a(Gt,"resolveChildSliceId");function Ou(e){return Bt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ou,"siblingEntryKey");function qn(e){return e.replace(/^(?:src|app)\//,"")}a(qn,"stripSrcOrApp");function wu(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=qn(t);if(!r)return!1;let o=qn(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(wu,"pathUnderSubtree");function Tu(e,t,n){if(!t||!n?.length)return!1;let r=t.toLowerCase();for(let o of n){if(typeof o!="string")continue;let s=Ou(o);if(!(!s||s.includes("*"))&&(r===s||e&&wu(e,s)))return!0}return!1}a(Tu,"importerInEnforcedSubtree");function Pu(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!Tu(t,n,e.enforce)}a(Pu,"siblingCrossingAdvisory");function Yn(e){if(typeof e!="string")return null;let t=Bt(e.trim().replace(/\\/g,"/")).toLowerCase();if(!t.includes("/"))return null;let n=t.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(Yn,"childSlicePatternSegments");function Wi(e,t){let n=Yn(e),r=Yn(t);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let s=n[o];if(s!=="*"&&s!==r[o])return!1}return!0}a(Wi,"childSlicePatternMatches");function ia(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&Wi(r.from,t)&&Wi(r.to,n))return!0;return!1}a(ia,"childCrossSliceAllowed");function Nu(e,t){let n=Yn(e),r=Yn(t);if(!n||!r)return!1;let o=n.slice(0,-1),s=r.slice(0,-1);if(o.length!==s.length)return!0;for(let i=0;i<o.length;i+=1){let l=o[i],c=s[i];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(Nu,"childAllowanceSpansUniverses");function Lu(e){let t=mu({fromPath:e.fromPath,toPath:e.toPath,folderCount:e.folderCount,fromSlice:e.fromSlice,toSlice:e.toSlice,fromShared:e.fromShared,toShared:e.toShared,crossSliceAllowed:e.crossSliceAllowed,sharedImportsSlice:De(e.rule.sharedImportsSlice)});if(t.denied){let i=!!e.rule.childSlices&&t.reason==="cross-slice";return{crossing:t.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...i?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:i?Eu(e.fromSlice,e.toSlice):vu(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??Gt(e.fromPath,e.fromSlice,n).childId,o=e.toChild??Gt(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?e.legacyChildAllowed||ia(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:Pu(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:Cu(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:_u(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(Lu,"evaluateNestedSliceWall");function aa(e){return e?.crossing==="cross-sibling"||e?.crossing==="parent-imports-child"}a(aa,"isChildWallCrossing");function Jn(e,t){return aa(t)?e?.childSlices?.message:e?.message}a(Jn,"sliceConsumerMessage");function ft(e){let t=e.verdict.explanation,n=aa(e.verdict),r=n?e.childMessage:e.ruleMessage;if(e.surface==="intent"){let o=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return n&&t?`${e.childMessage??o} ${t}`:e.verdict.reasonId&&t?`${o} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${o} ${t}`:r?t?`${r} (${t})`:r:o}if(r)return t?`${r} (${t})`:r;if(t){let o=e.kind??"import";return`${e.fromLayer} must not ${o} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(ft,"composeSliceDenialMessage");function ze(e){if(!e||e.decision==="allow")return{};let t=Ut(e.fromUniverse),n=Ut(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(ze,"sliceFindingExtras");function la(e,t){let n=[],r=new Set,o=new Set;for(let s of e??[])if(s?.peerIsolation&&s.allowed===!1&&n.push(...$u(s,t)),!!s?.childSlices){if(!s.peerIsolation||s.allowed!==!1){n.push({ruleId:"CONFIG_CHILD_SLICES_INERT",failsStrict:!1,fromLayer:s.from,toLayer:s.to,message:`${s.from} \u2192 ${s.to}: childSlices is inert on this rule and enforces nothing. The child wall runs only inside a universe wall. Add "peerIsolation": true and "allowed": false to the same rule, or remove childSlices.`});continue}for(let i of t){let l=pt(i,s.sliceFolders,s.sliceIdentity),c=Gt(i,l,s.childSlices);if(!c.mismatched)continue;let d=`${s.from}\0${s.to}\0${c.mismatched.universeId}\0${c.mismatched.childId}`;r.has(d)||(r.add(d),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:s.from,toLayer:s.to,path:i,message:`${s.from} \u2192 ${s.to}: child id ${c.mismatched.childId} does not extend universe id ${c.mismatched.universeId} (${i}).`}))}for(let i of s.childSlices.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string"||!Nu(i.from,i.to))continue;let l=`${i.from.trim().toLowerCase()}\0${i.to.trim().toLowerCase()}`;o.has(l)||(o.add(l),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:s.from,toLayer:s.to,message:`childSlices.allowedCrossSlice ${i.from} \u2192 ${i.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(la,"childSliceConfigFindings");function qi(e,t){let n=new Map;if(!e?.length)return n;for(let r of t){if(typeof r!="string")continue;let o=pt(r,[...e],"stars"),s=As(r,e);if(!o||!s||o===s)continue;let i=n.get(s)??new Set;i.add(o),n.set(s,i)}return n}a(qi,"observedIdsByLegacy");function ys(e,t,n,r){let o=r?`/${r}`:"",s=`${t[0]??e}${o}`,i=[...n.get(e.toLowerCase())??[]].sort().map(l=>`${l}${o}`);return i.length===1?`${i[0]}`:i.length>1?`${s} (one entry per module: ${i.join(", ")})`:s}a(ys,"newIdHint");function $u(e,t){let n=[],r=a(s=>n.push({ruleId:"CONFIG_SLICE_LEGACY_STARS_ID",failsStrict:!1,fromLayer:e.from,toLayer:e.to,message:`${e.from} \u2192 ${e.to}: ${s} It keeps its 4.8.23 meaning for this release only.`}),"push"),o=e.childSlices;if(e.sliceIdentity==="stars"){let s=qi(e.sliceFolders,t);for(let i of o?.sliceAliases??[]){if(!i||typeof i.to!="string")continue;let l=Is(i.to);if(!l||sa(e,i.to)===void 0)continue;let c=dt(e.sliceFolders,l.universeId),d=l.childId.split("/").pop();r(`sliceAliases to "${i.to}" is a 4.8.23 stars id (the star before the last literal was dropped). The id is now ${ys(l.universeId,c,s,d)}; write that instead.`)}for(let i of e.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string")continue;let l=[i.from,i.to].filter(d=>d.includes("/")&&dt(e.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?ys(d,dt(e.sliceFolders,d),s):d,"rename");r(`allowedCrossSlice ${i.from} \u2192 ${i.to} names a 4.8.23 stars id. The ids are now ${c(i.from)} \u2192 ${c(i.to)}; write those instead.`)}}if(o?.sliceIdentity==="stars"){let s=qi(o.sliceFolders,t);for(let i of o.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string")continue;let l=[i.from,i.to].filter(d=>dt(o.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?ys(d,dt(o.sliceFolders,d),s):d,"rename");r(`childSlices.allowedCrossSlice ${i.from} \u2192 ${i.to} names a 4.8.23 stars id. The ids are now ${c(i.from)} \u2192 ${c(i.to)}; write those instead.`)}}return n}a($u,"legacyStarsIdFindings");function ca(e){if(e!==null&&typeof e=="object"){let t=e.ratchet;if(t===!0)return"always";if(t===!1)return"never"}return"auto"}a(ca,"siblingRatchetMode");function Ee(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=ks(o,t,r?.layers),c=bs(o,l,s,i),d=c.from,p=c.to,g=d.universeId,f=p.universeId,m=Lu({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:g,toSlice:f,fromChild:d.childId,toChild:p.childId,fromShared:!g&&ut(s,o.sharedRoots),toShared:!f&&ut(i,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(m.decision!=="allow")return{rule:o,peerIsolationReason:m.peerIsolationReason,fromSlice:g,toSlice:f,sliceVerdict:m};continue}if(t!==n)return{rule:o}}}a(Ee,"findDeniedEdgeDecision");function da(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||De(i.sharedImportsSlice)==="deny")continue;let l=ks(i,t,r?.layers),c=Kt(o,i,l).universeId,d=Kt(s,i,l).universeId;if(!(c||!d)&&ut(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:d}}}a(da,"findSharedImportsSliceBridge");function vs(e,t,n){return ks(e,t,n)}a(vs,"peerSliceFolders");function gt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(gt,"literalText");function fa(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(fa,"lineOf");function ua(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(ua,"isTypeOnlyReference");function ga(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(ga,"singleFileChecker");function Es(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Es,"symbolAt");function Cs(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Es(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Cs,"localDeclaration");function We(e,t){let n,r=[],o=a((i,l,c,d=!1)=>r.push({specifier:c,kind:l,line:fa(t,i),typeOnly:d,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",gt(e,i.moduleSpecifier),ua(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",gt(e,i.moduleSpecifier),ua(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",gt(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,d=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Cs(e,n??(n=ga(e,t)),t,i.expression);(l||d)&&o(i,d?"require":"dynamic-import",gt(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(We,"extractSemanticDependencies");function Du(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=gt(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}a(Du,"staticAccessPath");function Fu(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(Fu,"runtimeIdentifierReference");function pa(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(pa,"bestForbiddenMatch");function qe(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ga(e,t),s=new Map,i=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&i.add(m.name.text);let l=a(f=>{let m=Du(e,f);if(!m)return;let u=Es(o,m.root),h=u?s.get(u):void 0;return h?[...h,...m.segments.slice(1)]:Cs(e,o,t,m.root)||i.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let u=l(m.initializer),h=Es(o,m.name);!u||!h||s.set(h,u)}let c=[],d=new Set,p=a((f,m)=>{let u=fa(t,m),h=`${f}:${m.getStart(t)}`;d.has(h)||(d.add(h),c.push({name:f,line:u,node:m}))},"flag"),g=a(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let u=l(f),h=u?pa(r,u):void 0;h&&p(h,f)}else e.isIdentifier(f)&&r.has(f.text)&&Fu(e,f)&&!Cs(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let u=l(f.initializer);if(u)for(let h of f.name.elements){if(!e.isIdentifier(h.name))continue;let k=h.propertyName?gt(e,h.propertyName)??h.propertyName.text:h.name.text,C=pa(r,[...u,k]);C&&p(C,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),c}a(qe,"collectForbiddenCapabilityUses");function _s(e,t,n){let r=[];for(let o of n?.dependencies??We(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Ht(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??qe(e,t,hs)){let s=Gn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}a(_s,"collectCapabilityUses");function Z(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(Z,"violation");function Mu(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."}a(Mu,"peerSuggestion");function mt(e,t){return e.slice(0,t).split(`
4
+ `).length}a(mt,"lineOf");var ju=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Hu(e,t){return e.index+e[0].indexOf(t)}a(Hu,"captureIndex");function Vu(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 d=c[1];d&&r(d,Hu(c,d))}},"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),d=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=d.exec(l))!==null;){let g=p[1];g&&r(g,c+p.index+p[0].indexOf(g))}}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(Vu,"extractQuotedStrings");function Ku(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(Ku,"extractModuleSpecifiers");function Uu(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(Uu,"isSyntaxWrapper");function xs(e,t){let n=t;for(;n?.parent&&Uu(e,n.parent);)n=n.parent;return n}a(xs,"unwrapWrappers");function Os(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(Os,"callCalleeName");function Gu(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=xs(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Os(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&ws(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=xs(e,s).parent;return!!(l&&e.isCallExpression(l)&&Os(e,l)==="publish")}return!1}a(Gu,"isPublishMetadataSource");function ma(e,t){let n=xs(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Os(e,r);if(o&&ju.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return ma(e,r);if(e.isPropertyAssignment(r)){let o=ws(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Gu(e,r))return!0}return!1}a(ma,"isDeclaredIntentSite");function Bu(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&ma(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(Bu,"extractQuotedStringsAst");function zu(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(zu,"hasInfrastructureToken");function Wu(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(Wu,"isKnownInfrastructurePackage");function qu(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(qu,"layerHasInfrastructureRole");function Wt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Wt,"tsStringLiteralText");function ws(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(ws,"tsPropertyName");function ha(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ws(e,r.name)===n)}a(ha,"tsObjectProperty");function qt(e,t,n){return ha(e,t,n)!==void 0}a(qt,"tsObjectHasProperty");function zt(e,t,n){let r=ha(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(zt,"tsObjectPropertyValue");function Yu(e,t){let n=zt(e,t,"metadata");return qt(e,n,"source")}a(Yu,"tsObjectHasMetadataSource");function ya(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?ya(e,t.name):!1:!1}a(ya,"tsLooksLikeIntentCreatorExpression");function Xu(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(Xu,"tsIsPublishCall");function Zu(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Wt(e,n);return r!==void 0&&ve(r)||qt(e,n,"intent")||ya(e,n)}a(Zu,"tsIsArkPublishCandidate");function Ju(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Yu(e,n)||qt(e,r,"source")||qt(e,o,"source")}a(Ju,"tsPublishHasSource");function Qu(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=zt(e,n,"metadata");return Wt(e,zt(e,s,"source"))??Wt(e,zt(e,r,"source"))??Wt(e,zt(e,o,"source"))}a(Qu,"tsPublishSourceLiteral");function ep(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],d=a(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=a(g=>{if(Xu(e,g)){let f=g.arguments[0],m=Wt(e,f);for(let h of Ft({publishCall:!0,rawIntentName:m,objectHasIntent:qt(e,f,"intent"),arkPublishCandidate:Zu(e,g),hasSource:Ju(e,g)}))c.push(Z(h.ruleId,h.message,{line:d(g),filePath:i}));let u=Qu(e,g);if(r&&l&&u&&ve(u)){let h=r.resolveLayer(u);h&&h!==l&&c.push(Z("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${h}, but the target file is classified as ${l}.`,{line:d(g),filePath:i,target:u,fromLayer:l,toLayer:h}))}}e.forEachChild(g,p)},"visit");return p(o),c}a(ep,"analyzePublishAst");function Ts(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,d=c?.filePath,p=c?.layer,g=e.typescript,f=g?g.createSourceFile(d??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?We(e.typescript,f):void 0,u=m?m.filter(S=>S.specifier!==void 0).map(S=>({value:S.specifier,index:S.node.getStart(f),kind:S.kind,typeOnly:S.typeOnly})):Ku(s),h=e.typescript?Bu(e.typescript,s):Vu(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(d))for(let S of m?.filter(({unresolved:I})=>I)??[]){let I=S.kind==="require";l.push(Z(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:S.line,filePath:d}))}let k=p!==void 0&&(r.has(p)||qu(p)),C=p!==void 0?` If "${p}" 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 S of n)if(S instanceof RegExp){S.lastIndex=0;let I=S.exec(s);S.lastIndex=0,I&&l.push(Z("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${S}`,{line:I.index===void 0?void 0:mt(s,I.index),filePath:d,suggestion:"Remove infrastructure imports from domain/application layers."+C}))}else s.includes(S)&&l.push(Z("FORBIDDEN_SUBSTRING",`Forbidden substring: ${S}`,{line:mt(s,s.indexOf(S)),filePath:d}));for(let S of u){let I=e.resolveImportTarget?.(S.value,d)??(e.resolveImportLayer?{layer:e.resolveImportLayer(S.value,d)}:void 0),E=typeof d=="string"?e.resolveImportTarget?.(d)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,H=I?.layer;if(H&&p){let N=Ee(e.architectureProfile?.rules,p,H,{fromPath:E?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(N){let $=N.rule;if(S.typeOnly&&!$.peerIsolation)continue;let v=!!$.peerIsolation,D=N.sliceVerdict,w=ze(D),P=Jn($,D)??(v?`Layer "${p}" must not import across slices into "${H}".`:`Layer "${p}" must not import "${H}".`),M=v&&D?.explanation&&(w.reasonId||N.peerIsolationReason!=="cross-slice")?D.explanation:void 0;l.push(Z("LAYER_IMPORT_VIOLATION",M?`${P} ${M}`:P,{line:mt(s,S.index),source:S.value,target:S.value,filePath:d,fromLayer:p,toLayer:H,...v?{peerIsolation:!0}:{},...w.reasonId?{reasonId:w.reasonId}:{},...w.universeFrom?{universeFrom:w.universeFrom}:{},...w.universeTo?{universeTo:w.universeTo}:{},...w.failsStrict===!1?{failsStrict:!1}:{},suggestion:Mu(v,N.peerIsolationReason),details:{importKind:S.kind,peerIsolation:v,...S.typeOnly?{typeOnly:!0}:{},...w.reasonId?{reasonId:w.reasonId}:{}}}));continue}continue}k||S.typeOnly||!zu(S.value)&&!Wu(S.value)||l.push(Z("FORBIDDEN_IMPORT",`Forbidden ${S.kind} target: "${S.value}".`,{line:mt(s,S.index),source:S.value,target:S.value,filePath:d,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+C,details:{importKind:S.kind}}))}if(e.policies)for(let S of e.policies){let I=S.check({source:s,context:i});if(I!==!0)if(Array.isArray(I))for(let E of I)l.push(Z("POLICY_VIOLATION",E.message,{filePath:d,suggestion:`Fix violation of policy "${S.name}".`}));else I===!1?l.push(Z("POLICY_VIOLATION",`Policy ${S.name} failed on generated code`)):l.push(Z("POLICY_VIOLATION",I.message))}if(o&&t.size>0)for(let S of h)ve(S.value)&&!t.has(S.value)&&l.push(Z("UNKNOWN_INTENT",`Unknown intent reference: "${S.value}"`,{line:mt(s,S.index),filePath:d,target:S.value,suggestion:`Register intent "${S.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let S of h){if(!ve(S.value))continue;let I=e.architectureProfile.resolveLayer(S.value);if(!I)continue;let E=Ee(e.architectureProfile.rules,p,I,{fromPath:typeof d=="string"?d:void 0,layers:e.architectureLayers});if(E){let H=E.sliceVerdict,N=`Layer "${p}" must not reference "${I}" through "${S.value}".`,$=H?ft({surface:"intent",verdict:H,fromLayer:p,toLayer:I,fromPath:typeof d=="string"?d:void 0,ruleMessage:E.rule.message,childMessage:E.rule.childSlices?.message,defaultMessage:N}):E.rule.message??N,v=ze(H);l.push(Z("LAYER_REFERENCE_VIOLATION",$,{line:mt(s,S.index),filePath:d,target:S.value,fromLayer:p,toLayer:I,...v.reasonId?{reasonId:v.reasonId}:{},...v.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:E.rule,peerIsolationReason:E.peerIsolationReason,...v.reasonId?{reasonId:v.reasonId}:{}}}))}}if(e.extensions)for(let S of e.extensions)try{let I=S.analyze(s,i);l.push(...I)}catch(I){l.push(Z("EXTENSION_ERROR",`Extension "${S.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let S=e.forbiddenGlobals[p];l.push(...qe(e.typescript,f,S).map(I=>Z("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${I.name}".`,{line:I.line,filePath:d,target:I.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of m??[]){if(I.typeOnly||!I.specifier)continue;let E=$e(I.specifier,S);E&&l.push(Z("FORBIDDEN_GLOBAL",`${p} must not use module "${I.specifier}" because it is the import form of forbidden global "${E}".`,{line:I.line,filePath:d,source:I.specifier,target:I.specifier,fromLayer:p,details:{importKind:I.kind,forbiddenGlobal:E},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(S){l.push(Z("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let S=new Set(e.capabilityWalls[p]),I=e.forbiddenGlobals?.[p]??[];for(let E of _s(e.typescript,f))S.has(E.capability)&&(E.source==="ambient-global"&&Vt(E.symbol,I)||E.source==="import-based"&&$e(E.symbol,I)||l.push(Z("CAPABILITY_VIOLATION",E.source==="import-based"?`${p} denies the ${E.capability} capability; found import of "${E.symbol}".`:`${p} denies the ${E.capability} capability; found ambient "${E.symbol}".`,{line:E.line,filePath:d,target:E.symbol,capability:E.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(S){l.push(Z("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript)try{l.push(...ep(e.typescript,s,i,e.architectureProfile))}catch(S){l.push(Z("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:!l.some(S=>S.failsStrict!==!1),violations:l}}}}a(Ts,"createAICodeGate");function Q(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(Q,"deterministicHash");function Y(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Y).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Y(t[n])}`).join(",")}}`}a(Y,"stableSerialize");function Ce(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}a(Ce,"feedText");function Ps(e,t){if(Array.isArray(e)){Ce("[",t);for(let o=0;o<e.length;o+=1){if(o>0&&Ce(",",t),!(o in e))continue;let s=e[o];if(s!==null&&typeof s=="object")Ps(s,t);else{let i=JSON.stringify(s);i!==void 0&&Ce(i,t)}}Ce("]",t);return}let n=e,r=Object.keys(n).sort();Ce("{",t);for(let o=0;o<r.length;o+=1){o>0&&Ce(",",t);let s=r[o];Ce(`${JSON.stringify(s)}:`,t);let i=n[s];i!==null&&typeof i=="object"?Ps(i,t):Ce(`${JSON.stringify(i)}`,t)}Ce("}",t)}a(Ps,"feedStable");function Ns(e){if(e===null||typeof e!="object")return Q(Y(e));let t={hash:2166136261};return Ps(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}a(Ns,"stableHash");var Fe="1.2",Aa=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e){let t=e.map((n,r)=>({key:Y(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])}a(W,"sortCanonical");function te(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(te,"sortedUnique");function yt(e){let t={schemaVersion:"1.2",include:te(e.include??[]),exclude:te(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:te(e.dynamicImportAllowlist??[]),layers:W(e.layers.map(n=>({name:n.name,patterns:te(n.patterns??[]),exclude:te(n.exclude??[]),forbiddenGlobals:te(n.forbiddenGlobals??[]),intentPrefixes:te(n.intentPrefixes??[]),capabilityDeny:te(n.capabilities?.deny??[]),pure:n.pure===!0}))),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:te(e.arkRun.compositionRoots),managedLayers:te(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return Q(Y(t))}a(yt,"resolvedFactsEvidenceRequirementsHash");function tp(e){let t=W(e.completenessReasons.map(v=>({code:v.code,message:v.message,...v.file?{file:v.file}:{}}))),n=e.files.map(v=>({...v,typeOnlyExportNames:te(v.typeOnlyExportNames)})).sort((v,D)=>v.path<D.path?-1:v.path>D.path?1:0),r=W(e.dependencies.map(v=>({...v,...v.namedBindings?{namedBindings:te(v.namedBindings)}:{}}))),o=W(e.capabilityUses.map(v=>({...v}))),s=W(e.ambientUses.map(v=>({...v}))),i=W(e.publishCalls.map(v=>({...v}))),l=W(e.intentReferences.map(v=>({...v}))),c=W(e.safetyUses.map(v=>({...v}))),d=W((e.classShapes??[]).map(v=>({...v,mutatingMethods:[...v.mutatingMethods??[]].map(D=>({...D}))}))),p=W((e.arkRunKernelCalls??[]).map(v=>({...v}))),g=W((e.arkRunManagedNews??[]).map(v=>({...v}))),f=W((e.arkRunCompositionRootHits??[]).map(v=>({...v}))),m=W((e.arkRunDeclarations??[]).map(v=>({...v,uses:te(v.uses),reactsTo:te(v.reactsTo),raises:te(v.raises),sends:te(v.sends)}))),u=W((e.arkOrderPlaneCalls??[]).map(v=>({...v}))),h=W((e.arkOrderGenericUpdates??[]).map(v=>({...v}))),k=W((e.arkOrderRootHits??[]).map(v=>({...v}))),C=W((e.arkOrderXiFieldWrites??[]).map(v=>({...v}))),S=W((e.arkOrderIngestWritesXi??[]).map(v=>({...v}))),I=W((e.arkOrderReleaseKeyCounts??[]).map(v=>({...v}))),E=W((e.arkOrderXiTtlKeys??[]).map(v=>({...v}))),H=W((e.arkOrderBudgetLeaks??[]).map(v=>({...v}))),N=e.files.map(({path:v,contentHash:D})=>({path:v,contentHash:D})).sort((v,D)=>v.path<D.path?-1:v.path>D.path?1:0),$=Ns(N);return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:$,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:d,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:u,arkOrderGenericUpdates:h,arkOrderRootHits:k,arkOrderXiFieldWrites:C,arkOrderIngestWritesXi:S,arkOrderReleaseKeyCounts:I,arkOrderXiTtlKeys:E,arkOrderBudgetLeaks:H}}a(tp,"canonicalResolvedFactsInput");function Ra(e){let t=tp(e);return{...t,factsHash:Ns(t)}}a(Ra,"createCanonicalResolvedCandidateFacts");function Qn(e){return Ra(Sa(V(e,"$"),!1))}a(Qn,"createResolvedCandidateFacts");function V(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(V,"asRecord");function K(e,t,n){let r=Object.keys(e).find(o=>!t.includes(o));if(r)throw new Error(`${n}.${r} is not part of schema ${"1.2"}.`)}a(K,"assertOnlyKeys");function j(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(j,"requiredText");function _e(e,t,n){if(e[t]!==void 0)return j(e,t,n)}a(_e,"optionalText");function U(e,t,n){let r=j(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(U,"requiredProjectPath");function X(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(X,"requiredBoolean");function Ls(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(Ls,"requiredInteger");function ee(e,t,n){let r=Ls(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(ee,"requiredPositiveInteger");function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(G,"requiredArray");function xe(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(xe,"enumValue");function ht(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}a(ht,"parseStringArray");function np(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(np,"assertUnique");function Sa(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts","arkOrderXiTtlKeys","arkOrderBudgetLeaks",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=xe(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=xe(e,"completeness",["complete","partial","unavailable"],"$"),o=G(e,"completenessReasons","$").map((_,R)=>{let y=`$.completenessReasons[${R}]`,A=V(_,y);K(A,["code","message","file"],y);let L=A.file===void 0?void 0:U(A,"file",y);return{code:j(A,"code",y),message:j(A,"message",y),...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=G(e,"files","$").map((_,R)=>{let y=`$.files[${R}]`,A=V(_,y);return K(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:U(A,"path",y),contentHash:j(A,"contentHash",y),parseStatus:xe(A,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Ls(A,"parseDiagnosticCount",y),exportsOnlyTypes:X(A,"exportsOnlyTypes",y),typeOnlyExportNames:ht(A.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:X(A,"hasTopLevelSideEffects",y)}}),i=G(e,"dependencies","$").map((_,R)=>{let y=`$.dependencies[${R}]`,A=V(_,y);K(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let L=_e(A,"specifier",y),se=_e(A,"target",y),st=xe(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(st==="resolved-project"&&!se)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(st!=="resolved-project"&&se)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(st!=="dynamic"&&!L)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:U(A,"from",y),...L?{specifier:L}:{},kind:xe(A,"kind",["import","export","dynamic-import","require"],y),typeOnly:X(A,"typeOnly",y),line:ee(A,"line",y),resolution:st,...se?{target:U(A,"target",y)}:{},...A.namedBindings!==void 0?{namedBindings:ht(A.namedBindings,`${y}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:X(A,"targetTypeOnlyExports",y)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:X(A,"sourcePureTypeModule",y)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:X(A,"namedBindingsTypeOnly",y)}:{},...A.portProofEligible!==void 0?{portProofEligible:X(A,"portProofEligible",y)}:{}}}),l=G(e,"capabilityUses","$").map((_,R)=>{let y=`$.capabilityUses[${R}]`,A=V(_,y);return K(A,["file","line","symbol","capability","source"],y),{file:U(A,"file",y),line:ee(A,"line",y),symbol:j(A,"symbol",y),capability:xe(A,"capability",Aa,y),source:xe(A,"source",["ambient-global","import-based"],y)}}),c=G(e,"ambientUses","$").map((_,R)=>{let y=`$.ambientUses[${R}]`,A=V(_,y);return K(A,["file","line","symbol"],y),{file:U(A,"file",y),line:ee(A,"line",y),symbol:j(A,"symbol",y)}}),d=G(e,"publishCalls","$").map((_,R)=>{let y=`$.publishCalls[${R}]`,A=V(_,y);K(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let L=_e(A,"rawIntentName",y),se=_e(A,"sourceIntent",y);return{file:U(A,"file",y),line:ee(A,"line",y),...L?{rawIntentName:L}:{},objectHasIntent:X(A,"objectHasIntent",y),arkPublishCandidate:X(A,"arkPublishCandidate",y),hasSource:X(A,"hasSource",y),...se?{sourceIntent:se}:{}}}),p=G(e,"intentReferences","$").map((_,R)=>{let y=`$.intentReferences[${R}]`,A=V(_,y);return K(A,["file","line","intent"],y),{file:U(A,"file",y),line:ee(A,"line",y),intent:j(A,"intent",y)}}),g=G(e,"safetyUses","$").map((_,R)=>{let y=`$.safetyUses[${R}]`,A=V(_,y);K(A,["file","line","kind","symbol"],y);let L=_e(A,"symbol",y),se=xe(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(se==="in-memory-store"&&!L)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(se!=="in-memory-store"&&L)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:U(A,"file",y),line:ee(A,"line",y),kind:se,...L?{symbol:L}:{}}});np(s,_=>_.path,"$.files");let f=new Set(s.map(_=>_.path));for(let _ of s){if(_.parseStatus==="parsed"&&_.parseDiagnosticCount!==0)throw new Error(`$.files[${_.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(_.parseStatus==="invalid"&&_.parseDiagnosticCount===0)throw new Error(`$.files[${_.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(_=>_.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let _ of i)if(!f.has(_.from))throw new Error(`$.dependencies references missing source file ${_.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((_,R)=>{let y=`$.arkRunKernelCalls[${R}]`,A=V(_,y);K(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let L=_e(A,"receiver",y),se=_e(A,"nameLiteral",y);return{file:U(A,"file",y),line:ee(A,"line",y),kind:xe(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:j(A,"callee",y),viaImport:X(A,"viaImport",y),...L?{receiver:L}:{},...se?{nameLiteral:se}:{}}}),k=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((_,R)=>{let y=`$.arkRunManagedNews[${R}]`,A=V(_,y);K(A,["file","line","typeName","importedFrom"],y);let L=_e(A,"importedFrom",y);return{file:U(A,"file",y),line:ee(A,"line",y),typeName:j(A,"typeName",y),...L?{importedFrom:L}:{}}}),S=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((_,R)=>{let y=`$.arkRunCompositionRootHits[${R}]`,A=V(_,y);return K(A,["file","matchedRoot","hasKernelFactory"],y),{file:U(A,"file",y),matchedRoot:j(A,"matchedRoot",y),hasKernelFactory:X(A,"hasKernelFactory",y)}}),I=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),H=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((_,R)=>{let y=`$.arkOrderPlaneCalls[${R}]`,A=V(_,y);return K(A,["file","line","callee"],y),{file:U(A,"file",y),line:ee(A,"line",y),callee:j(A,"callee",y)}}),$=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((_,R)=>{let y=`$.arkOrderGenericUpdates[${R}]`,A=V(_,y);return K(A,["file","line","method"],y),{file:U(A,"file",y),line:ee(A,"line",y),method:j(A,"method",y)}}),D=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((_,R)=>{let y=`$.arkOrderRootHits[${R}]`,A=V(_,y);return K(A,["file","matchedRoot","hasPlaneFactory"],y),{file:U(A,"file",y),matchedRoot:j(A,"matchedRoot",y),hasPlaneFactory:X(A,"hasPlaneFactory",y)}}),P=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((_,R)=>{let y=`$.arkOrderXiFieldWrites[${R}]`,A=V(_,y);return K(A,["file","line","key"],y),{file:U(A,"file",y),line:ee(A,"line",y),key:j(A,"key",y)}}),F=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((_,R)=>{let y=`$.arkOrderIngestWritesXi[${R}]`,A=V(_,y);return K(A,["file","line"],y),{file:U(A,"file",y),line:ee(A,"line",y)}}),ke=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((_,R)=>{let y=`$.arkOrderReleaseKeyCounts[${R}]`,A=V(_,y);return K(A,["file","line","keyCount"],y),{file:U(A,"file",y),line:ee(A,"line",y),keyCount:ee(A,"keyCount",y)}}),es=(e.arkOrderXiTtlKeys===void 0?[]:G(e,"arkOrderXiTtlKeys","$")).map((_,R)=>{let y=`$.arkOrderXiTtlKeys[${R}]`,A=V(_,y);return K(A,["file","line","key"],y),{file:U(A,"file",y),line:ee(A,"line",y),key:j(A,"key",y)}}),Ue=(e.arkOrderBudgetLeaks===void 0?[]:G(e,"arkOrderBudgetLeaks","$")).map((_,R)=>{let y=`$.arkOrderBudgetLeaks[${R}]`,A=V(_,y);return K(A,["file","line","kind"],y),{file:U(A,"file",y),line:ee(A,"line",y),kind:j(A,"kind",y)}}),rt=I.map((_,R)=>{let y=`$.arkRunDeclarations[${R}]`,A=V(_,y);return K(A,["file","line","uses","reactsTo","raises","sends"],y),{file:U(A,"file",y),line:ee(A,"line",y),uses:ht(A.uses,`${y}.uses`),reactsTo:ht(A.reactsTo,`${y}.reactsTo`),raises:ht(A.raises,`${y}.raises`),sends:ht(A.sends,`${y}.sends`)}});for(let[_,R]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",d],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",k],["$.arkRunCompositionRootHits",S],["$.arkRunDeclarations",rt],["$.arkOrderPlaneCalls",H],["$.arkOrderGenericUpdates",$],["$.arkOrderRootHits",D],["$.arkOrderXiFieldWrites",P],["$.arkOrderIngestWritesXi",F],["$.arkOrderReleaseKeyCounts",ke],["$.arkOrderXiTtlKeys",es],["$.arkOrderBudgetLeaks",Ue]])for(let y of R)if(!f.has(y.file))throw new Error(`${_} references missing file ${y.file}.`);let On=_e(e,"projectPackageName","$"),wn=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((_,R)=>{let y=`$.classShapes[${R}]`,A=V(_,y);K(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],y);let L=G(A,"mutatingMethods",y).map((se,st)=>{let Tn=`${y}.mutatingMethods[${st}]`,ns=V(se,Tn);return K(ns,["name","referencesGuardOrPublish"],Tn),{name:j(ns,"name",Tn),referencesGuardOrPublish:X(ns,"referencesGuardOrPublish",Tn)}});return{file:U(A,"file",y),className:j(A,"className",y),exported:X(A,"exported",y),hasPublicMutableFields:X(A,"hasPublicMutableFields",y),hasPublicSetters:X(A,"hasPublicSetters",y),hasPublicConstructor:X(A,"hasPublicConstructor",y),hasStaticFactory:X(A,"hasStaticFactory",y),mutatingMethods:L,...A.dataOnly===void 0?{}:{dataOnly:X(A,"dataOnly",y)},...A.truncatedUntil===void 0?{}:{truncatedUntil:Ls(A,"truncatedUntil",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:j(e,"resolverIdentity","$"),compilerIdentity:j(e,"compilerIdentity","$"),compilerOptionsHash:j(e,"compilerOptionsHash","$"),tsconfigHash:j(e,"tsconfigHash","$"),evidenceRequirementsHash:j(e,"evidenceRequirementsHash","$"),...On?{projectPackageName:On}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:d,intentReferences:p,safetyUses:g,classShapes:wn,arkRunKernelCalls:u,arkRunManagedNews:k,arkRunCompositionRootHits:S,arkRunDeclarations:rt,arkOrderPlaneCalls:H,arkOrderGenericUpdates:$,arkOrderRootHits:D,arkOrderXiFieldWrites:P,arkOrderIngestWritesXi:F,arkOrderReleaseKeyCounts:ke,arkOrderXiTtlKeys:es,arkOrderBudgetLeaks:Ue}}a(Sa,"parseResolvedFactsInput");function Oe(e){let t=V(e,"$"),n=j(t,"factsHash","$"),r=j(t,"candidateTreeHash","$"),o=Ra(Sa(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(Oe,"loadResolvedCandidateFacts");var rp=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},ne={type:"integer",minimum:1},B={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},er={$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:T,message:T,file:B}}},resolverIdentity:T,compilerIdentity:T,compilerOptionsHash:T,tsconfigHash:T,candidateTreeHash:T,evidenceRequirementsHash:T,projectPackageName:T,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:B,contentHash:T,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:T},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:B,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ne,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:B,namedBindings:{type:"array",items:T},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:B,line:ne,symbol:T,capability:{enum:rp},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:B,line:ne,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:B,line:ne,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:B,line:ne,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:ne,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},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:B,className:T,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:T,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:B,line:ne,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:T,viaImport:{type:"boolean"},receiver:T,nameLiteral:T}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:B,line:ne,typeName:T,importedFrom:T}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:B,matchedRoot:T,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:B,line:ne,uses:{type:"array",items:T},reactsTo:{type:"array",items:T},raises:{type:"array",items:T},sends:{type:"array",items:T}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:B,line:ne,callee:T}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:B,line:ne,method:T}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:B,matchedRoot:T,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:ne,key:T}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:B,line:ne}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:B,line:ne,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:ne,key:T}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:ne,kind:T}}},factsHash:T},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 tr="1.0";function ka(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(ka,"canonicalProjectPath");function At(e){return e.flatMap(t=>t.to?[{from:t.from,to:t.to}]:[])}a(At,"resolvedEdgeDependencies");function de(e){return`${e.from}->${e.to}`}a(de,"dependencyKey");function Yt(e,t,n,r="dependency"){return{id:`${e}:${r}:${de(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${de(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${de(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${de(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${de(t)} from the candidate, then preflight again.`}:{}}}a(Yt,"dependencyFinding");function Ye(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[de(f),f])),s=new Map(e.baseDependencies.map(f=>[de(f),f])),i=new Map(e.candidateDependencies.map(f=>[de(f),f]));for(let f of[...n.values()].sort((m,u)=>m.path.localeCompare(u.path))){let m=r.get(f.path);m?m.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${m.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((m,u)=>m.path.localeCompare(u.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let l=new Set;for(let f of[...o.values()].sort((m,u)=>de(m).localeCompare(de(u)))){if(i.has(de(f))){t.push(Yt("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};i.has(de(m))?(l.add(de(m)),t.push(Yt("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(Yt("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,m]of[...i].sort(([u],[h])=>u.localeCompare(h)))s.has(f)||o.has(f)||l.has(f)||!c.has(m.from)&&!c.has(m.to)||t.push({...Yt("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let d=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([u],[h])=>u.localeCompare(h)))i.has(f)||d.has(m.from)||d.has(m.to)||!c.has(m.from)&&!c.has(m.to)||t.push({...Yt("unplanned",m,`${m.from} -> ${m.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,m)=>p[f.classification]-p[m.classification]||(f.subject===m.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(m.id));let g={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}a(Ye,"analyzeArchitectureConvergence");var Xe="1.0",$s="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ds=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],sp=["no-anemic-model"],Ia={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},nr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:$s,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:$s},schemaVersion:{type:"string",const:Xe,default:Xe},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:[...Ds]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ia,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:Ia}}}},we=class extends Error{static{a(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
5
5
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
6
- `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function zt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(zt,"isObject");function er(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(er,"propertyPath");function Gt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(Gt,"valueType");function Pu(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Pu,"resolveSchemaRef");function Bt(e,t,n,r,o){if(t.$ref){let s=Pu(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Bt(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(!zt(e)){o.push({path:n,message:`must be an object; received ${Gt(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:er(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:er(n,i),message:"unknown field"});else if(zt(t.additionalProperties)){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||Bt(e[l],i,er(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Bt(e[i],l,er(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Gt(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)=>Bt(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 ${Gt(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${Gt(e)}`})}a(Bt,"validateNode");function Du(e){return{...e,$schema:e.$schema===void 0?Ps:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}a(Du,"defaultedArkRules");function Ia(e){return e==="enforced"?"enforced":"advisory"}a(Ia,"normalizeMode");function $u(e){return Nu.includes(e)}a($u,"isTier2Sensor");function Mu(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],o=new Set;n.forEach((s,i)=>{if(!zt(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.structure[${i}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),typeof s.sensor=="string"&&$u(s.sensor)&&s.mode==="enforced"&&t.push({path:`$.structure[${i}].mode`,message:`${l?`rule ${JSON.stringify(l)} uses sensor `:"sensor "}${JSON.stringify(s.sensor)}, which is Tier-2 advisory-only and cannot be enforced${l?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.structure[${i}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((s,i)=>{if(!zt(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.invariants[${i}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.invariants[${i}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}a(Mu,"validateSemantics");function Wt(e,t="arkrules.json",n){if(!zt(e))throw new we(t,[{path:"$",message:`must be an object; received ${Gt(e)}`}]);let r=Du(e),o=[];if(Bt(r,tr,"$",tr,o),Mu(r,o),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&o.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),o.length>0)throw new we(t,o);return{config:r}}a(Wt,"loadArkRulesContract");function ba(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new we(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return Wt(r,t,n)}a(ba,"parseArkRulesJson");function nr(e){let t={},n=[],r=[],o=[...e].sort((s,i)=>s.layer.localeCompare(i.layer));for(let s of o){let i=(s.file.structure??[]).map(c=>({...c,mode:Ia(c.mode),provenance:{sourceFile:s.sourceFile,ruleId:c.id,layer:s.layer}})),l=(s.file.invariants??[]).map(c=>({...c,mode:Ia(c.mode),provenance:{sourceFile:s.sourceFile,ruleId:c.id,layer:s.layer}}));t[s.layer]={sourceFile:s.sourceFile,structure:i,invariants:l},n.push(...i),r.push(...l)}return n.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),r.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}a(nr,"buildEffectiveArkRules");function $e(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a($e,"emptyEffectiveArkRules");var qt=class extends Error{static{a(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function op(e){return{...e,$schema:e.$schema===void 0?$s:e.$schema,schemaVersion:e.schemaVersion===void 0?Xe:e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}a(op,"defaultedArkRules");function ba(e){return e==="enforced"?"enforced":"advisory"}a(ba,"normalizeMode");function ip(e){return sp.includes(e)}a(ip,"isTier2Sensor");function ap(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],o=new Set;n.forEach((s,i)=>{if(!Le(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.structure[${i}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),typeof s.sensor=="string"&&ip(s.sensor)&&s.mode==="enforced"&&t.push({path:`$.structure[${i}].mode`,message:`${l?`rule ${JSON.stringify(l)} uses sensor `:"sensor "}${JSON.stringify(s.sensor)}, which is Tier-2 advisory-only and cannot be enforced${l?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.structure[${i}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((s,i)=>{if(!Le(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.invariants[${i}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.invariants[${i}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}a(ap,"validateSemantics");function Rt(e,t="arkrules.json",n){if(!Le(e))throw new we(t,[{path:"$",message:`must be an object; received ${Ie(e)}`}]);let r=op(e),o=[];if(Ne(r,nr,"$",nr,o),ap(r,o),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&o.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),o.length>0)throw new we(t,o);return{config:r}}a(Rt,"loadArkRulesContract");function Ca(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new we(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return Rt(r,t,n)}a(Ca,"parseArkRulesJson");function rr(e,t){return e.childId?`${e.childId}#${t}`:t}a(rr,"effectiveRuleId");function va(e,t){if(t&&t.length>0)return[...t];if(e.childId&&e.defaultAppliesTo&&e.defaultAppliesTo.length>0)return[...e.defaultAppliesTo]}a(va,"effectiveAppliesTo");function Ea(e,t){return{sourceFile:e.sourceFile,ruleId:rr(e,t),layer:e.layer,...e.childId?{childId:e.childId}:{}}}a(Ea,"provenanceFor");function _a(e,t){let n=t.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase(),r=e.trim().replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase();if(!r||!n||r.includes(".."))return!1;if(r===n||r===`${n}/**`||r===`${n}/*`)return!0;if(r.startsWith(`${n}/`)){let i=r.slice(n.length+1).split("/"),l=i.indexOf("**");return l!==-1&&l!==i.length-1?!1:i.every(c=>c.length>0)}let o=n.replace(/^(?:src|app)\//,""),s=r.replace(/^(?:src|app)\//,"");return o!==n||s!==r?_a(s,o):!1}a(_a,"appliesToPatternInsideSlice");function xa(e){if(!e.childId||!e.defaultAppliesTo?.length)return[];let t=String(e.defaultAppliesTo[0]).replace(/\/\*\*$/,""),n=[],r=[...e.file.structure??[],...e.file.invariants??[]];for(let o of r)for(let s of o.appliesTo??[])_a(s,t)||n.push({id:o.id,pattern:s});return n}a(xa,"sliceScopeEscapes");function Oa(e){let t=new Map,n=new Map;for(let r of e){let o=[...(r.file.structure??[]).map(s=>s.id),...(r.file.invariants??[]).map(s=>s.id)];for(let s of o){let i=rr(r,s),l=`${r.layer}\0${i}`,c=t.get(l);if(!c){t.set(l,{id:i,layer:r.layer,sourceFiles:[r.sourceFile]});continue}let d=n.get(l)??{id:i,layer:r.layer,sourceFiles:[...c.sourceFiles]};d.sourceFiles.includes(r.sourceFile)||d.sourceFiles.push(r.sourceFile),n.set(l,d)}}return[...n.values()]}a(Oa,"duplicateArkRuleIds");function sr(e){let t={},n=[],r=[],o=[...e].sort((s,i)=>s.layer.localeCompare(i.layer)||s.sourceFile.localeCompare(i.sourceFile));for(let s of o){let i=(s.file.structure??[]).map(d=>{let p=va(s,d.appliesTo);return{...d,id:rr(s,d.id),...p?{appliesTo:p}:{appliesTo:void 0},mode:ba(d.mode),provenance:Ea(s,d.id)}}),l=(s.file.invariants??[]).map(d=>{let p=va(s,d.appliesTo);return{...d,id:rr(s,d.id),...p?{appliesTo:p}:{appliesTo:void 0},mode:ba(d.mode),provenance:Ea(s,d.id)}}),c=t[s.layer];c?(c.sourceFiles||(c.sourceFiles=[c.sourceFile]),c.sourceFiles.includes(s.sourceFile)||c.sourceFiles.push(s.sourceFile),c.structure.push(...i),c.invariants.push(...l)):t[s.layer]={sourceFile:s.sourceFile,sourceFiles:[s.sourceFile],structure:i,invariants:l},n.push(...i),r.push(...l)}return n.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),r.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),{schemaVersion:Xe,byLayer:t,structure:n,invariants:r}}a(sr,"buildEffectiveArkRules");function Me(){return{schemaVersion:Xe,byLayer:{},structure:[],invariants:[]}}a(Me,"emptyEffectiveArkRules");var Xt=class extends Error{static{a(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
7
7
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
8
- `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function va(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(va,"normalizeRel");function Ca(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let c of[...e.discoveredArkRulesFiles].sort())r.push({path:c,message:`ArkRules file ${JSON.stringify(c)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:$e(),warnings:r}}let o=new Set(e.config.layers.map(c=>c.name)),s=[],i=[],l=new Set;for(let c of Object.keys(n).sort()){let d=n[c],u=`$.arkRules[${JSON.stringify(c)}]`;if(typeof d!="string"||d.length===0){s.push({path:u,message:"must be a non-empty relative path string"});continue}if(d.startsWith("/")||/^[A-Za-z]:[\\/]/.test(d)){s.push({path:u,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(c)){s.push({path:u,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let m=va(d);l.add(m);let f=e.fileContents[m]??e.fileContents[d];if(f===void 0){s.push({path:u,message:`referenced ArkRules file ${JSON.stringify(m)} is missing`});continue}try{let h=Wt(JSON.parse(f),m,c);i.push({layer:c,sourceFile:m,file:h.config})}catch(h){if(h instanceof we)for(let p of h.issues)s.push({path:`${u}${p.path==="$"?"":p.path.replace(/^\$/,"")}`,message:`${m}: ${p.message}`});else h instanceof SyntaxError?s.push({path:u,message:`referenced ArkRules file ${JSON.stringify(m)} is not valid JSON: ${h.message}`}):s.push({path:u,message:`referenced ArkRules file ${JSON.stringify(m)} failed to load: ${h instanceof Error?h.message:String(h)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let d=va(c);l.has(d)||r.push({path:d,message:`ArkRules file ${JSON.stringify(d)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(s.length>0)throw new qt(t,s);return{config:e.config,arkRules:nr(i),warnings:r}}a(Ca,"resolveEffectiveContract");function $s(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a($s,"omitLayerDescriptions");function rr(e){let{stewards:t,...n}=$s(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(rr,"effectiveContractPolicyPayload");var Fu=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),ju=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),Hu=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function Ku(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 o=n;for(;o>=0&&/[A-Za-z0-9_$]/.test(e[o]);)o-=1;return Hu.has(e.slice(o+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:ju.has(r)}a(Ku,"slashStartsRegex");function Vu(e,t){if(!Ku(e,t))return t;let n=t+1,r=!1;for(;n<e.length;){let o=e[n];if(o===`
9
- `||o==="\r")return t;if(o==="\\"){n+=2;continue}if(r)o==="]"&&(r=!1);else if(o==="[")r=!0;else if(o==="/"){for(n+=1;n<e.length&&/[A-Za-z]/.test(e[n]);)n+=1;return n}n+=1}return t}a(Vu,"skipRegexLiteral");function qe(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
10
- `,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 Vu(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}a(qe,"skipStringOrComment");function Se(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=qe(e,n);continue}break}return n}a(Se,"skipWsAndComments");function sr(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}}a(sr,"readIdent");function Me(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=qe(e,s);if(i!==s){s=i;continue}let l=e[s];l===n?o+=1:l===r&&!(r===">"&&e[s-1]==="=")&&(o-=1),s+=1}return o===0?s:null}a(Me,"skipBalanced");function or(e){let t=[],n=0,r;for(;n<e.length&&(n=Se(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let u=sr(e,s);if(!u||!Fu.has(u.ident))break;o.push(u.ident),s=Se(e,u.end)}if(o.length===1&&o[0]==="static"&&e[s]==="{"){let u=Me(e,s,"{","}");if(u==null){r=e.length;break}n=u;continue}let i=sr(e,s);if(!i){n+=1;continue}if(s=Se(e,i.end),e[s]==="<"){let u=Me(e,s,"<",">");if(u==null){r=e.length;break}s=Se(e,u)}if(e[s]==="("){let u=Me(e,s,"(",")");if(u==null){r=e.length;break}if(s=Se(e,u),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let m=qe(e,s);if(m!==s){s=m;continue}s+=1}if(e[s]==="{"){let m=Me(e,s,"{","}");if(m==null){r=e.length;break}t.push({name:i.ident,modifiers:o,kind:"method",body:e.slice(s+1,m-1)}),n=m;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,d=0;for(;s<e.length;){let u=qe(e,s);if(u!==s){s=u;continue}let m=e[s];if(m==="{")l+=1;else if(m==="}"){if(l===0)break;l-=1}else if(m==="(")c+=1;else if(m===")")c-=1;else if(m==="[")d+=1;else if(m==="]")d-=1;else if(m===";"&&l===0&&c===0&&d===0){s+=1;break}s+=1}s>=e.length&&(l>0||c>0||d>0)&&(r=e.length),t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(or,"scanClassMembers");function _a(e,t){let n=t;for(;n<e.length;){let r=Se(e,n);if(r!==n){n=r;continue}let o=e[n];if(o==="{")return n;if(o===";")return null;if(o==="<"||o==="("||o==="["){let i=Me(e,n,o,o==="<"?">":o==="("?")":"]");if(i==null)return null;n=i;continue}if(o==='"'||o==="'"||o==="`"){n=qe(e,n);continue}n+=1}return null}a(_a,"findClassBodyBrace");function ir(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,o=xa(e),s;for(;(s=r.exec(o))!==null;){let i=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=_a(e,s.index+s[0].length);if(c==null){n.push({name:i,start:s.index,exported:l,bodyStart:null,bodyEnd:null});continue}let d=Me(e,c,"{","}");n.push({name:i,start:s.index,exported:l,bodyStart:c+1,bodyEnd:d==null?null:d-1})}return n}a(ir,"findClassDeclarations");function xa(e){let t="",n=0;for(;n<e.length;){let r=qe(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}a(xa,"maskStringsAndComments");function Oa(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=xa(e),o=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),s=new RegExp(`\\b(?:(namespace|module)\\s+${o}\\s*\\{|(?:const|let|var)\\s+${o}\\s*(?::[^=;]+?)?=(?!=|>)\\s*(class\\b)?)`,"g"),i;for(;(i=s.exec(r))!==null;){let l,c;if(i[1])c="namespace",l=i.index+i[0].length-1;else if(i[2])c="class-expression",l=_a(e,i.index+i[0].length);else{c="object";let u=Se(e,i.index+i[0].length);l=e[u]==="{"?u:null}if(l==null)continue;let d=Me(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:d==null?e.length:d-1})}return n}a(Oa,"findMemberContainers");function wa(e){let t=[],n=0,r=!0;for(;n<e.length;){let o=qe(e,n);if(o!==n){n=o,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=Me(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 i=sr(e,n);for(;i&&(i.ident==="async"||i.ident==="get"||i.ident==="set");){let l=Se(e,i.end);e[l]==="*"&&(l=Se(e,l+1));let c=sr(e,l);if(!c)break;i=c}if(i){let l=Se(e,i.end);("(:,<".includes(e[l]??"")||l>=e.length)&&t.push(i.ident),n=i.end,r=!1;continue}}if(r&&s==="*"){n+=1;continue}/\s/.test(s)||(r=!1),n+=1}return t}a(wa,"objectLiteralMemberNames");var Uu="INVARIANT_TESTS_PATH_MISSING",Gu="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.",Bu="INVARIANT_COVERAGE_ROOTS_MISSING",zu="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 Ta(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(Ta,"formatCoverageDiscards");function Pa(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}a(Pa,"isUnderCoverageRoot");function Fs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Fs,"escapeRegExp");function ft(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(ft,"normalizePath");function js(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]!==`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function wa(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(wa,"normalizeRel");function Ta(e,t="ark.config.json"){let n=e.config.arkRules??{},r=[],o=Object.keys(n).length>0,s=!!(e.governedFiles&&e.governedFiles.length>0);if(!o&&!s){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let g of[...e.discoveredArkRulesFiles].sort())r.push({path:g,message:`ArkRules file ${JSON.stringify(g)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:Me(),warnings:r}}let i=new Set(e.config.layers.map(g=>g.name)),l=[],c=[],d=new Set,p=a((g,f,m)=>{if(m instanceof we){for(let u of m.issues)l.push({path:`${g}${u.path==="$"?"":u.path.replace(/^\$/,"")}`,message:`${f}: ${u.message}`});return}if(m instanceof SyntaxError){l.push({path:g,message:`referenced ArkRules file ${JSON.stringify(f)} is not valid JSON: ${m.message}`});return}l.push({path:g,message:`referenced ArkRules file ${JSON.stringify(f)} failed to load: ${m instanceof Error?m.message:String(m)}`})},"pushLoadIssue");for(let g of Object.keys(n).sort()){let f=n[g],m=`$.arkRules[${JSON.stringify(g)}]`,u=Array.isArray(f)?f:typeof f=="string"?[f]:null;if(!u||u.length===0||u.some(h=>typeof h!="string"||h.length===0)){l.push({path:m,message:"must be a non-empty path string or an array of paths"});continue}if(!i.has(g)){l.push({path:m,message:`layer ${JSON.stringify(g)} is not declared in layers[]`});continue}u.forEach((h,k)=>{let C=u.length===1&&typeof f=="string"?m:`${m}[${k}]`;if(h.startsWith("/")||/^[A-Za-z]:[\\/]/.test(h)){l.push({path:C,message:"must be a project-relative path (absolute paths are not allowed)"});return}let S=wa(h);d.add(S);let I=e.fileContents[S]??e.fileContents[h];if(I===void 0){l.push({path:C,message:`referenced ArkRules file ${JSON.stringify(S)} is missing`});return}try{let E=Rt(JSON.parse(I),S,g);c.push({layer:g,sourceFile:S,file:E.config})}catch(E){p(C,S,E)}})}if(e.governedFiles&&e.governedFiles.length>0){let g=oa({files:e.governedFiles,rules:e.config.rules,layers:[...i]});for(let f of g){let m=e.fileContents[f.path];if(m!==void 0){d.add(f.path);try{let u=Rt(JSON.parse(m),f.path,f.layer),h={layer:f.layer,sourceFile:f.path,file:u.config,childId:f.childId,defaultAppliesTo:f.defaultAppliesTo},k=xa(h);if(k.length>0){l.push({path:f.path,message:`ARKRULE_SCOPE_ESCAPES_SLICE: ${f.path} appliesTo ${k.map(C=>C.pattern).join(", ")} escapes ${f.childId}`});continue}c.push(h)}catch(u){p(f.path,f.path,u)}}}}for(let g of Oa(c))l.push({path:`$.arkRules[${JSON.stringify(g.layer)}]`,message:`ARKRULE_DUPLICATE_ID: ${g.id} is declared in ${g.sourceFiles.join(", ")}`});if(e.discoveredArkRulesFiles)for(let g of[...e.discoveredArkRulesFiles].sort()){let f=wa(g);d.has(f)||r.push({path:f,message:`ArkRules file ${JSON.stringify(f)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(l.length>0)throw new Xt(t,l);return{config:e.config,arkRules:sr(c),warnings:r}}a(Ta,"resolveEffectiveContract");function Fs(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(Fs,"omitLayerDescriptions");function or(e){let{stewards:t,...n}=Fs(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(or,"effectiveContractPolicyPayload");var lp=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),cp=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),dp=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function up(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 o=n;for(;o>=0&&/[A-Za-z0-9_$]/.test(e[o]);)o-=1;return dp.has(e.slice(o+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:cp.has(r)}a(up,"slashStartsRegex");function pp(e,t){if(!up(e,t))return t;let n=t+1,r=!1;for(;n<e.length;){let o=e[n];if(o===`
9
+ `||o==="\r")return t;if(o==="\\"){n+=2;continue}if(r)o==="]"&&(r=!1);else if(o==="[")r=!0;else if(o==="/"){for(n+=1;n<e.length&&/[A-Za-z]/.test(e[n]);)n+=1;return n}n+=1}return t}a(pp,"skipRegexLiteral");function Ze(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
10
+ `,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 pp(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}a(Ze,"skipStringOrComment");function Ae(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=Ze(e,n);continue}break}return n}a(Ae,"skipWsAndComments");function ir(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}}a(ir,"readIdent");function je(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=Ze(e,s);if(i!==s){s=i;continue}let l=e[s];l===n?o+=1:l===r&&!(r===">"&&e[s-1]==="=")&&(o-=1),s+=1}return o===0?s:null}a(je,"skipBalanced");function ar(e){let t=[],n=0,r;for(;n<e.length&&(n=Ae(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=ir(e,s);if(!p||!lp.has(p.ident))break;o.push(p.ident),s=Ae(e,p.end)}if(o.length===1&&o[0]==="static"&&e[s]==="{"){let p=je(e,s,"{","}");if(p==null){r=e.length;break}n=p;continue}let i=ir(e,s);if(!i){n+=1;continue}if(s=Ae(e,i.end),e[s]==="<"){let p=je(e,s,"<",">");if(p==null){r=e.length;break}s=Ae(e,p)}if(e[s]==="("){let p=je(e,s,"(",")");if(p==null){r=e.length;break}if(s=Ae(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=Ze(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=je(e,s,"{","}");if(g==null){r=e.length;break}t.push({name:i.ident,modifiers:o,kind:"method",body:e.slice(s+1,g-1)}),n=g;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,d=0;for(;s<e.length;){let p=Ze(e,s);if(p!==s){s=p;continue}let g=e[s];if(g==="{")l+=1;else if(g==="}"){if(l===0)break;l-=1}else if(g==="(")c+=1;else if(g===")")c-=1;else if(g==="[")d+=1;else if(g==="]")d-=1;else if(g===";"&&l===0&&c===0&&d===0){s+=1;break}s+=1}s>=e.length&&(l>0||c>0||d>0)&&(r=e.length),t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(ar,"scanClassMembers");function Pa(e,t){let n=t;for(;n<e.length;){let r=Ae(e,n);if(r!==n){n=r;continue}let o=e[n];if(o==="{")return n;if(o===";")return null;if(o==="<"||o==="("||o==="["){let i=je(e,n,o,o==="<"?">":o==="("?")":"]");if(i==null)return null;n=i;continue}if(o==='"'||o==="'"||o==="`"){n=Ze(e,n);continue}n+=1}return null}a(Pa,"findClassBodyBrace");function lr(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,o=Na(e),s;for(;(s=r.exec(o))!==null;){let i=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=Pa(e,s.index+s[0].length);if(c==null){n.push({name:i,start:s.index,exported:l,bodyStart:null,bodyEnd:null});continue}let d=je(e,c,"{","}");n.push({name:i,start:s.index,exported:l,bodyStart:c+1,bodyEnd:d==null?null:d-1})}return n}a(lr,"findClassDeclarations");function Na(e){let t="",n=0;for(;n<e.length;){let r=Ze(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}a(Na,"maskStringsAndComments");function La(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=Na(e),o=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),s=new RegExp(`\\b(?:(namespace|module)\\s+${o}\\s*\\{|(?:const|let|var)\\s+${o}\\s*(?::[^=;]+?)?=(?!=|>)\\s*(class\\b)?)`,"g"),i;for(;(i=s.exec(r))!==null;){let l,c;if(i[1])c="namespace",l=i.index+i[0].length-1;else if(i[2])c="class-expression",l=Pa(e,i.index+i[0].length);else{c="object";let p=Ae(e,i.index+i[0].length);l=e[p]==="{"?p:null}if(l==null)continue;let d=je(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:d==null?e.length:d-1})}return n}a(La,"findMemberContainers");function $a(e){let t=[],n=0,r=!0;for(;n<e.length;){let o=Ze(e,n);if(o!==n){n=o,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=je(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 i=ir(e,n);for(;i&&(i.ident==="async"||i.ident==="get"||i.ident==="set");){let l=Ae(e,i.end);e[l]==="*"&&(l=Ae(e,l+1));let c=ir(e,l);if(!c)break;i=c}if(i){let l=Ae(e,i.end);("(:,<".includes(e[l]??"")||l>=e.length)&&t.push(i.ident),n=i.end,r=!1;continue}}if(r&&s==="*"){n+=1;continue}/\s/.test(s)||(r=!1),n+=1}return t}a($a,"objectLiteralMemberNames");function Da(e){return e==="survived"||e==="not-reached"}a(Da,"verdictRefusesPromotion");function fp(e){switch(e.operator){case"negate-guard":return"the guard is negated";case"drop-throw":return"the throw is removed";case"flip-comparison":return`\`${e.original}\` becomes \`${e.replacement}\``;case"boundary-shift":return`the boundary moves (\`${e.original}\` becomes \`${e.replacement}\`)`;case"const-shift":return`\`${e.original}\` becomes \`${e.replacement}\``}}a(fp,"changeText");function Fa(e,t){if(t.verdict==="not-reached")return`Invariant ${e}: the covering tests load the file but never call the declared symbol (mutation probe: not reached); add a test that calls it and re-run --probe-invariants --write before promoting.`;let n=t.survivors[0],r=n?` (${fp(n)} at line ${n.line})`:"";return`Invariant ${e}: the mutation probe shows the covering tests do not pin it${r}; strengthen the test and re-run --probe-invariants --write before promoting.`}a(Fa,"probeRefusalReason");var gp="INVARIANT_TESTS_PATH_MISSING",mp="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.",hp="INVARIANT_COVERAGE_ROOTS_MISSING",yp="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 Ma(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(Ma,"formatCoverageDiscards");function Va(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(Va,"isUnderCoverageRoot");function js(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(js,"escapeRegExp");function St(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(St,"normalizePath");function Hs(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]!==`
11
11
  `;)n.push(" "),r+=1;continue}if(s==="/"&&i==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
12
12
  `?`
13
13
  `:" "),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 d=e[r+1];t?n.push(" ",d===void 0?"":" "):(n.push("\\"),d!==void 0&&n.push(d)),r+=d===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
14
- `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(js,"maskNonCode");function Wu(e,t){if(!t)return;let n=Fs(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(js(e,!1))?.[2];return s===void 0?void 0:s}a(Wu,"matchTestTitle");function Da(e,t){if(!t)return;let n=Fs(t),r=js(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(Da,"declarationShape");function qu(e,t,n){let r=a(o=>or(o).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let o of ir(e))if(!(o.name!==t||o.bodyStart==null)&&r(e.slice(o.bodyStart,o.bodyEnd??e.length)))return"method";for(let o of Oa(e,t)){let s=e.slice(o.bodyStart,o.bodyEnd);if(o.kind==="class-expression"&&r(s)||o.kind==="object"&&wa(s).includes(n))return"method";if(o.kind==="namespace"){let i=Da(s,n);if(i==="function"||i==="const")return i}}}a(qu,"classMemberShape");function Yu(e,t){let n=e.lastIndexOf(`
14
+ `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(Hs,"maskNonCode");function Ap(e,t){if(!t)return;let n=js(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(Hs(e,!1))?.[2];return s===void 0?void 0:s}a(Ap,"matchTestTitle");function Ka(e,t){if(!t)return;let n=js(t),r=Hs(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(Ka,"declarationShape");function Rp(e,t,n){let r=a(o=>ar(o).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let o of lr(e))if(!(o.name!==t||o.bodyStart==null)&&r(e.slice(o.bodyStart,o.bodyEnd??e.length)))return"method";for(let o of La(e,t)){let s=e.slice(o.bodyStart,o.bodyEnd);if(o.kind==="class-expression"&&r(s)||o.kind==="object"&&$a(s).includes(n))return"method";if(o.kind==="namespace"){let i=Ka(s,n);if(i==="function"||i==="const")return i}}}a(Rp,"classMemberShape");function Sp(e,t){let n=e.lastIndexOf(`
15
15
  `,t-1)+1,r=e.indexOf(`
16
- `,t);return e.slice(n,r===-1?e.length:r)}a(Yu,"lineAt");function Xu(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(Xu,"isImportLine");function La(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(Xu(Yu(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]!==`
17
- `;)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 d=l;for(i(o,"string"),o+=1;o<s;){let u=e[o];if(u==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(u===d){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(La,"mentionContext");function $a(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1&&t[t.length-2]||null,name:n}:void 0}a($a,"symbolNeedle");function Zu(e){return $a(e.coverage?.symbol)?.name??e.id}a(Zu,"declaredLabel");function Na(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Na,"sortedContentFiles");function Ma(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(h=>ft(h))),s=(t.coverageRoots??[]).filter(h=>typeof h=="string"&&h.length>0),i=e.coverage?.test!==!1&&n,l=$a(e.coverage?.symbol??void 0),c,d;if(i){for(let h of r){let p=t.fileContents[h];if(!p)continue;let y=Wu(p,e.id);if(y!==void 0){if(s.length===0||Pa(h,s)){c={file:h,title:y};break}d??={file:h,title:y}}}c??=d}let u;if(l)for(let h of Na(t.fileContents)){if(o.has(ft(h)))continue;let p=t.fileContents[h];if(!p)continue;let y=l.className?qu(p,l.className,l.name):Da(p,l.name);if(y){u={file:h,shape:y};break}}let m;if(!c&&!u){if(i)for(let h of r){let p=t.fileContents[h];if(!p)continue;let y=La(p,e.id,!0);if(y){m={file:h,context:y};break}}if(!m&&l)for(let h of Na(t.fileContents)){if(o.has(ft(h)))continue;let p=t.fileContents[h];if(!p)continue;let y=La(p,l.name,!1);if(y){m={file:h,context:y};break}}}let f=c?{kind:"test-title",file:c.file,title:c.title}:u?{kind:"declaration",file:u.file,shape:u.shape}:m?{kind:"mention-only",file:m.file,context:m.context}:{kind:"none"};return f.kind==="mention-only"&&f.context==="comment"&&l&&Ju(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...u?{declaration:u}:{}}}a(Ma,"rankCoverage");function Ju(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${Fs(n)}(?=$|[^A-Za-z0-9_$])`),s=ft(r);for(let i of Object.keys(e)){if(t.has(ft(i))||ft(i)===s)continue;let l=e[i];if(l&&o.test(js(l,!0)))return!0}return!1}a(Ju,"symbolInCodeElsewhere");function Fa(e,t){return Ma(e,t).best}a(Fa,"classifyCoverage");function Hs(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Hs,"countsAsCoverage");function Qu(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(Qu,"mentionWhere");function Ks(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} ${Zu(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Qu(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(Ks,"describeCoverage");function ar(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=Ta(s),l=Ta(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",d=(e.coverageRoots??[]).filter(p=>typeof p=="string"&&p.length>0),u=d.length>0,m=d.join(", "),f=[],h=[];for(let p of t){let y=p.coverage?.test!==!1,S=p.coverage?.symbol,C=!r&&y,R=Ma(p,{fileContents:e.fileContents,testFiles:n,coverageRoots:d},C),k=R.best,v=[];C&&R.testTitle&&v.push("test-title"),R.declaration&&v.push("symbol");let H=Hs(k),P,D;C&&R.testTitle&&(P=R.testTitle.file,u&&(D=!Pa(P,d)));let E=R.declaration?.file,$=R.declaration?.shape,w=p.coverage?.test===!0||!!S||p.coverage===void 0,N=p.coverage?.test===!1&&!S,M=w&&H||N&&p.mode!=="enforced"?!0:H,F=r&&y&&!H;if(f.push({invariantId:p.id,layer:p.provenance.layer,sourceFile:p.provenance.sourceFile,mode:p.mode,covered:M&&!F,evidence:v,partial:F,description:p.description,...P!==void 0?{testEvidenceFile:P}:{},...E!==void 0?{symbolEvidenceFile:E}:{},...$!==void 0?{shape:$}:{},...D!==void 0?{outsideDeclaredRoots:D}:{},coverageRootsDeclared:u}),D===!0&&P!==void 0&&h.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${p.id} is covered only by ${P}, which is outside the declared coverage roots (${m}). 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:P,line:1,arkruleId:p.id,arkruleSource:p.provenance.sourceFile,fromLayer:p.provenance.layer,severity:"warning",failsStrict:!1}),!M||F){let oe=p.mode==="enforced"&&!F,ge=r||n.length===0?"never-had-tests":"tests-disappeared";h.push({ruleId:"INVARIANT_UNCOVERED",message:(F?o?`Invariant ${p.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${p.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:N?`Invariant ${p.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 ${p.id}: ${Ks(p,k)} (${ge==="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.`)+(F&&o?l:i),file:p.provenance.sourceFile,line:1,arkruleId:p.id,arkruleSource:p.provenance.sourceFile,fromLayer:p.provenance.layer,severity:oe?"error":"warning",failsStrict:oe,kind:ge})}}return{coverage:f,violations:h,partial:f.some(p=>p.partial)}}a(ar,"evaluateInvariantCoverage");function lr(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 ${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(lr,"canPromoteInvariant");function Ms(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(Ms,"nonEmptyPathStrings");function ep(e){return!e||typeof e!="object"?[]:[...Ms(e.testGlobs),...Ms(e.coverageRoots)]}a(ep,"configuredInvariantTestsPaths");function tp(e){return ep(e).length>0}a(tp,"hasConfiguredInvariantTestsPath");function Vs(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Vs,"catalogDemandsInvariantTestsPath");function ja(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Vs(e.invariants);return e.adopted!==!0||!t?[]:tp(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Uu,message:Gu,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(ja,"collectMissingInvariantTestsPathFindings");function np(e){return!e||typeof e!="object"?[]:Ms(e.coverageRoots)}a(np,"configuredCoverageRoots");function rp(e){return np(e).length>0}a(rp,"hasConfiguredCoverageRoots");function Us(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Us,"catalogHasEnforcedInvariant");function Ha(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Us(e.invariants)?rp(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Bu,message:zu,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(Ha,"collectMissingCoverageRootsFindings");var ur="1.0",sp="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function x(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${sp}`: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(x,"addFinding");function z(e){return[...new Set(e??[])].sort()}a(z,"sortedUnique");function ye(e,t,n,r,o){let s=z(n),i=z(r),l=new Set(s),c=new Set(i),d=i.filter(m=>!l.has(m)),u=s.filter(m=>!c.has(m));d.length===0&&u.length===0||(d.length>0&&x(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),u.length>0&&x(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(ye,"compareStringSets");function Yt(e,t,n,r,o,s,i){if(n===r)return;x(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(Yt,"compareBoolean");function dr(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(dr,"keyed");function op(e,t,n){let r=dr(t,s=>s.name),o=dr(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&x(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){x(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){x(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;ye(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."}),ye(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 d=Nn(i),u=Nn(l);ye(e,`${c}.forbiddenGlobals`,d.rawGlobals,u.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ye(e,`${c}.capabilities`,d.atoms,u.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")&&x(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)}),Yt(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."),Yt(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(op,"compareLayers");function ip(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=dr(t,r),s=dr(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&x(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),d=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?x(e,{kind:"deny-added",path:d,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):x(e,{kind:"allow-added",path:d,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&&x(e,{kind:"deny-removed",path:d,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&x(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${d}.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 u=l.peerIsolation===!0,m=c.peerIsolation===!0;if(u!==m){let S=l.from===l.to&&c.from===c.to;x(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${d}.peerIsolation`,classification:S?m?"strengthening":"weakening":"judgment-required",message:S?m?"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:u,after:m})}z(l.sliceFolders).join("\0")!==z(c.sliceFolders).join("\0")&&x(e,{kind:"slice-folders-changed",path:`${d}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:z(l.sliceFolders),after:z(c.sliceFolders)});let f=l.sliceIdentity??"path",h=c.sliceIdentity??"path";if(f!==h&&x(e,{kind:"slice-identity-changed",path:`${d}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:h}),!u&&!m)continue;cr(e,`${d}.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."),cr(e,`${d}.allowedCrossSlice`,"cross-slice-allowance",z((l.allowedCrossSlice??[]).map(zs)),z((c.allowedCrossSlice??[]).map(zs)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let p=Ne(l.sharedImportsSlice)??null,y=Ne(c.sharedImportsSlice)??null;if(p!==y){let S=Xa(y)>Xa(p);x(e,{kind:"shared-imports-slice",path:`${d}.sharedImportsSlice`,classification:S?"strengthening":"weakening",message:Rp(p,y),before:p,after:y})}else y==="deny-cross-parent"&&cr(e,`${d}.sharedImportsSlice.stopAt`,"shared-walk-stop",Va(l.sharedImportsSlice),Va(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.");lp(e,d,l,c)}}a(ip,"compareRules");function Ka(e){let t=e.childSlices;return t?JSON.stringify([z(t.sliceFolders??[]),t.sliceIdentity??"path",z(t.commonFolders??[])]):""}a(Ka,"childSliceFoldersKey");function Va(e){return z(Fn(e).map(t=>Xt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Va,"stopAtKeys");function Ua(e){return e==="always"?2:e==="auto"?1:0}a(Ua,"siblingRatchetRank");function ap(e){return z((e??[]).map(t=>Xt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(ap,"enforceKeys");function Ga(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:ap(t.enforce),ratchet:Fi(t)}}a(Ga,"childSliceSiblingPolicy");function lp(e,t,n,r){let o=Ga(n),s=Ga(r);if(o===null&&s===null)return;if(o===null&&s!==null){x(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(o!==null&&s===null){x(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(Ka(n)!==Ka(r)){x(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(o===null||s===null)return;if(o.mode!==s.mode){let c=s.mode==="advisory";x(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:o.mode,after:s.mode})}else if(o.mode==="advisory"&&(cp(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce),o.ratchet!==s.ratchet)){let c=Ua(s.ratchet)>Ua(o.ratchet);x(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:o.ratchet,after:s.ratchet})}let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&x(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:i,after:l}),fp(e,t,n,r),pp(e,t,n,r)}a(lp,"compareChildSlices");function cp(e,t,n,r){if(JSON.stringify(n)===JSON.stringify(r))return;let o=r.filter(l=>!n.includes(l)),s=n.filter(l=>!r.includes(l)),i=o.length>0&&s.length>0;x(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":o.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":o.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(cp,"compareSiblingEnforceList");function zs(e){return JSON.stringify([e.from,e.to])}a(zs,"crossSliceKey");function Ba(e){return z((e.childSlices?.allowedCrossSlice??[]).map(zs))}a(Ba,"childCrossSliceKeys");function gt(e){return Xt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(gt,"allowanceSegments");function za(e,t){let n=gt(e),r=gt(t);if(n.length===0||n.length!==r.length)return!1;let o=!1;for(let s=0;s<n.length;s+=1)if(n[s]!==r[s]){if(n[s]==="*"&&r[s]!=="*"){o=!0;continue}return!1}return o}a(za,"patternWidens");function dp(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=gt(n[0]).join("/")===gt(r[0]).join("/"),s=gt(n[1]).join("/")===gt(r[1]).join("/"),i=za(n[0],r[0]),l=za(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(dp,"allowanceWidens");function up(e){return JSON.stringify([Xt(e.from.trim().replace(/\\/g,"/")).toLowerCase(),Xt(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(up,"aliasEntryKey");function Wa(e){return z((e.childSlices?.sliceAliases??[]).map(up))}a(Wa,"sliceAliasKeys");function pp(e,t,n,r){let o=Wa(n),s=Wa(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(d=>!o.includes(d)),l=o.filter(d=>!s.includes(d)),c=i.length>0&&l.length>0;x(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:o,after:s})}a(pp,"compareSliceAliases");function fp(e,t,n,r){let o=Ba(n),s=Ba(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(c=>!o.includes(c)),l=o.filter(c=>!s.includes(c));if(i.length>0&&l.length>0&&l.filter(d=>!i.some(u=>dp(u,d))).length===0){x(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:o,after:s});return}cr(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",o,s,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}a(fp,"compareChildCrossSliceAllowances");function cr(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(u=>!r.includes(u)),c=r.filter(u=>!o.includes(u)),d=l.length>0&&c.length>0;x(e,{kind:d?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:d?"judgment-required":l.length>0?"weakening":"strengthening",message:d?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(cr,"compareDeclaredExceptions");function gp(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&&x(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"])Yt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(gp,"compareSafety");function Gs(e){return e.mode==="enforced"?"enforced":"advisory"}a(Gs,"arkRunMode");function Bs(e){return e.mode==="enforced"?"enforced":"advisory"}a(Bs,"arkOrderMode");function mp(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){x(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Bs(o)}).`,after:o});return}if(r&&!o){x(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Bs(r),l=Bs(o);if(i!==l){let c=i==="advisory"&&l==="enforced";x(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})}ye(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."}),ye(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(mp,"compareArkOrder");function hp(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){x(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Gs(o)}).`,after:o});return}if(r&&!o){x(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Gs(r),l=Gs(o);if(i!==l){let c=i==="advisory"&&l==="enforced";x(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})}ye(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."}),ye(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."}),Yt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(hp,"compareArkRun");function yp(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(yp,"overallClassification");function qa(e,t){return`${e}::${t}`}a(qa,"ruleKey");function Ya(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(qa(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(qa(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Ya,"indexEffectiveRules");function Ap(e,t,n,r,o,s){let i=new Map((s??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},d=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let f of d){let h=l[f],p=c[f],y=`$.arkRules[${f}]`;if(h===void 0&&p!==void 0){x(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:p});continue}if(h!==void 0&&p===void 0){x(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:h});continue}h!==p&&x(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:h,after:p})}let u=Ya(r),m=Ya(o);for(let f of[...new Set([...u.structure.keys(),...m.structure.keys()])].sort()){let h=u.structure.get(f),p=m.structure.get(f),y=`$.arkRules.structure[${f}]`;if(!h&&p){x(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${p.id} was added (${p.mode}).`,after:p});continue}if(h&&!p){x(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${h.id} was removed.`,before:h});continue}if(!(!h||!p)){if(h.mode!==p.mode){let S=h.mode==="advisory"&&p.mode==="enforced";x(e,{kind:S?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:S?"strengthening":"weakening",message:S?`Structure ArkRule ${p.id} was promoted to enforced.`:`Structure ArkRule ${p.id} was demoted to advisory.`,before:h.mode,after:p.mode})}h.sensor!==p.sensor&&x(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${p.id} changed sensor identity.`,before:h.sensor,after:p.sensor})}}for(let f of[...new Set([...u.invariants.keys(),...m.invariants.keys()])].sort()){let h=u.invariants.get(f),p=m.invariants.get(f),y=`$.arkRules.invariants[${f}]`;if(!h&&p){x(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${p.id} was added (${p.mode}).`,after:p});continue}if(h&&!p){x(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${h.id} was removed.`,before:h});continue}if(!(!h||!p)&&h.mode!==p.mode)if(h.mode==="advisory"&&p.mode==="enforced"){let C=i?.get(p.id),R=lr(C);R.ok?x(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${p.id} was promoted to enforced (coverage evidence present).`,before:h.mode,after:p.mode}):x(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${p.id} cannot be promoted to enforced: ${R.reason}`,before:h.mode,after:p.mode})}else x(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${p.id} was demoted to advisory.`,before:h.mode,after:p.mode})}}a(Ap,"compareArkRules");function pr(e,t,n){let r=[];ye(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ye(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."}),ye(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."}),Yt(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";x(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)&&x(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}),op(r,e.layers,t.layers),ip(r,e.rules,t.rules),gp(r,e,t),Ap(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),hp(r,e,t),mp(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:ur,classification:yp(r),findings:r}}a(pr,"classifyArkPolicyDelta");function fr(e,t){if(!e||e.schemaVersion!==ur||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(fr,"policyDeltaAcknowledgementMatches");function Xt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Xt,"trimTrailingSlashes");function Xa(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(Xa,"sharedImportsSliceRank");function Rp(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."}a(Rp,"sharedImportsSliceMessage");function Ye(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(Ye,"normalizePath");function Za(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(Za,"isIdentifierStart");function gr(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(gr,"isIdentifierCharacter");function ce(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ce,"skipWhitespace");function Zt(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(Zt,"readString");function pe(e,t,n){return e.startsWith(t,n)&&!gr(e[n-1])&&!gr(e[n+t.length])}a(pe,"isWordAt");function Ja(e,t){let n=ce(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ce(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!pe(e,"type",n))return!1;let o=ce(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||pe(e,"as",o)||!Za(e[o]))return!1;for(n=o;n<e.length&&gr(e[n]);)n+=1;if(n=ce(e,n),pe(e,"as",n)){if(n=ce(e,n+2),!Za(e[n]))return!1;for(;n<e.length&&gr(e[n]);)n+=1}r=!0}return!1}a(Ja,"bracedNamedBindingsAreTypeOnly");function Sp(e,t){if(t=ce(e,t+6),e[t]==="(")return Zt(e,ce(e,t+1));let n=!1;if(pe(e,"type",t)){let o=ce(e,t+4);e[o]!==","&&!pe(e,"from",o)&&(n=!0)}else Ja(e,t)&&(n=!0);let r=Qa(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(Sp,"specifierAfterImport");function kp(e,t){t=t+6;let n=ce(e,t),r=!1;if(pe(e,"type",n)){let s=ce(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Ja(e,n)&&(r=!0);let o=Qa(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(kp,"specifierAfterExport");function Qa(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(pe(e,"from",t))return Zt(e,ce(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Zt(e,t);if(t>0&&(pe(e,"import",t)||pe(e,"export",t)))return}}a(Qa,"specifierInStaticStatement");function Ip(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(Ip,"skipTemplateLiteral");function Ep(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ce(e,t+7);if(e[r]!=="(")return;r=ce(e,r+1);let o=Zt(e,r);return o?{...o,requireCall:!0}:void 0}a(Ep,"specifierAfterRequire");function bp(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(`
18
- `,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=Ip(e,n);continue}if(r==="'"||r==='"'){let s=Zt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&pe(e,"import",n)?Sp(e,n):r==="e"&&pe(e,"export",n)?kp(e,n):r==="r"&&pe(e,"require",n)?Ep(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(bp,"moduleSpecifiers");function el(e,t){let n=[],r=[];for(let o of bp(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let d=Ct(s);if(!d)continue;let u=e.content.slice(0,o.offset).split(`
19
- `).length;r.push({file:e.path,symbol:s,capability:d,evidence:{kind:"import",file:e.path,line:u,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
20
- `).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=vp(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(el,"moduleFactsFor");function vp(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(vp,"resolveSpecifier");function tl(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Ee(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});if(!o)continue;let s=o.rule;n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:Hn(s,o.sliceVerdict)??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(tl,"violationsFor");var Cp={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 _p(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(_p,"hasActiveArkRules");function xp(e,t){return _p(e,t)?ee(X(rr({config:e,arkRules:t,warnings:[]}))):ee(X($s(e)))}a(xp,"policyHashFor");function Jt(e,t,n){let r=typeof e=="string"?Xn(e,t):Ht(e,t),o=n?.arkRules??$e();return{...r,arkRules:o,policyHash:xp(r.config,o)}}a(Jt,"loadContract");function Ws(e){let t=Jt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Jt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=pr(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&&fr(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(Ws,"analyzePolicyDelta");function mt(e){let t=e.files.map(m=>{let f=Ye(m.path);return{path:f,content:m.content,contentHash:ee(m.content),layer:he(f,e.contract.config.layers)??null}}).sort((m,f)=>m.path.localeCompare(f.path)),n=new Map(t.map(m=>[m.path,m])),r=[],o=[];for(let m of t){let f=el(m,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=tl(r,e.contract.config),i=new Map(e.contract.config.layers.map(m=>[m.name,m])),l=new Map(e.contract.config.layers.map(m=>[m.name,new Set(rt(m))]));for(let m of o){let f=n.get(m.file)?.layer;if(!f)continue;let h=i.get(f),p=Le(m.symbol,h?.forbiddenGlobals??[]);if(p){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${m.symbol}" because it is the import form of forbidden global "${p}".`,symbol:m.symbol,evidence:m.evidence});continue}l.get(f)?.has(m.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let c=t.length===0?"complete":"partial",d=c==="complete"?[]:[{...Cp}],u={schemaVersion:Qn,policyHash:e.contract.policyHash,compilerOptionsHash:ee(X(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:d,valid:c==="complete"&&s.length===0,ir:u}}a(mt,"analyzeProject");function Qt(e){let t=new Map(e.files.map(n=>[Ye(n.path),n]));for(let n of e.changes){let r=Ye(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return mt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(Qt,"analyzeChange");function qs(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(qs,"explainViolation");function mr(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 m of[...e.get(c)??[]].sort())e.has(m)&&(n.has(m)?o.has(m)&&r.set(c,Math.min(r.get(c)??0,n.get(m)??0)):(l(m),r.set(c,Math.min(r.get(c)??0,r.get(m)??0))));if(r.get(c)!==n.get(c))return;let d=[],u;do{if(u=s.pop(),u===void 0)break;o.delete(u),d.push(u)}while(u!==c);d.length>1&&i.push(d.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,d)=>c[0]<d[0]?-1:c[0]>d[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(mr,"detectArchitectureCycles");function Xe(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let i=Ee(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let f=ji(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});f&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:f.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:f.toPath,toSlice:f.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${f.fromPath} \u2192 slice ${f.toSlice} (${f.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,d=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),u=i.sliceVerdict,m=u?it({surface:"import",verdict:u,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.message,childMessage:l.childSlices?.message}):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}:{},...Ve(u),message:d?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...d?{failsStrict:!1,severity:"warning"}:{}})}t.push(...Tp(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=mr(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(Xe,"evaluateArchitectureGraph");var Op="CROSS_PARENT_VIA_SHARED",wp="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function nl(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&Ne(r.sharedImportsSlice)==="deny-cross-parent")return r}a(nl,"denyingCrossParentRule");function Ys(e,t,n,r){let o=xt(n,e,ys(e,t,r)).universeId;return o?{kind:"slice",id:o}:ot(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Ys,"placeFile");function rl(e,t){return Li(t,Fn(e.sharedImportsSlice))}a(rl,"isWalkStop");function Tp(e){let t=e.rules??[];if(!t.some(s=>Ne(s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=Lp(s);if(!i)continue;let l=n.get(i.from);l?l.push(i):n.set(i.from,[i])}for(let s of n.values())s.sort((i,l)=>i.to<l.to?-1:i.to>l.to?1:i.line-l.line);let r=new Map,o=[...n.values()].flat();o.sort((s,i)=>s.from<i.from?-1:s.from>i.from?1:s.to<i.to?-1:s.to>i.to?1:0);for(let s of o){let i=nl(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Ys(i,s.fromLayer,s.from,e.config.layers),c=Ys(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||rl(i,s.to))continue;let d=[{file:s.to,path:[s.from,s.to]}],u=new Set([s.to]);for(;d.length>0;){let m=d.shift();if(!m)break;for(let f of n.get(m.file)??[]){let h=nl(t,f.fromLayer,f.toLayer);if(!h)continue;let p=Ys(h,f.fromLayer,f.to,e.config.layers);if(p.kind==="shared"){if(u.has(f.to)||rl(h,f.to))continue;u.add(f.to),d.push({file:f.to,path:[...m.path,f.to]});continue}if(p.kind!=="slice"||p.id.toLowerCase()===l.id.toLowerCase()||Dn(i.allowedCrossSlice,l.id,p.id))continue;if(i.sliceIdentity==="stars"){let k=hs(i,ys(i,s.fromLayer,e.config.layers),s.from,f.to);if(k.crossSliceAllowed||k.from.universeId&&k.from.universeId===k.to.universeId)continue}let y=[...m.path,f.to],S=`${s.from}\0${f.to}`,C={file:s.from,target:f.to,line:s.line,fromLayer:s.fromLayer,toLayer:f.toLayer,fromSlice:l.id,toSlice:p.id,path:y},R=r.get(S);(!R||y.length<R.path.length||y.length===R.path.length&&y.join("\0")<R.path.join("\0"))&&r.set(S,C)}}}return[...r.values()].sort((s,i)=>s.file<i.file?-1:s.file>i.file?1:s.target<i.target?-1:s.target>i.target?1:0).map(s=>{let i=Ot(s.fromSlice),l=Ot(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:Op,file:s.file,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.target,peerIsolation:!0,...i&&l?{universeFrom:i,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}. ${wp}`}})}a(Tp,"crossParentViaSharedViolations");function Lp(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}}a(Lp,"valueHop");function sl(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(sl,"structureFreezeTarget");var Np=/\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)/,Pp=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,Dp=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,$p=["db","tx","client","prisma","prismaClient","drizzle"],Mp="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",Fp="\\bINSERT\\s+INTO\\b|\\bUPDATE\\s+[A-Za-z_][\\w.]*\\s+SET\\b|\\bDELETE\\s+FROM\\b",ol="\\((?:[^()]|\\([^()]*\\))*\\)",jp=`\\bnew\\s+PrismaClient\\s*${ol}|\\bdrizzle\\s*${ol}`,Hp=/(?<![\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,Kp=/(?<![\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 Vp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Vp,"escapeRegExp");function hr(e){return Np.test(e)||Pp.test(e)}a(hr,"sourceImportsPersistenceDriverText");function il(e,t,n){let r=new RegExp(e.source,"g"),o;for(;(o=r.exec(t))!==null;)o[1]&&n.add(o[1])}a(il,"collectFirstGroup");function Up(e){let t=new Set;il(Hp,e,t),il(Kp,e,t);let n=new RegExp(Dp.source,"g"),r;for(;(r=n.exec(e))!==null;)for(let o of(r[1]??"").split(",")){let s=o.trim().replace(/^type\s+/,"").split(/\s+as\s+/),i=(s[1]??s[0]??"").trim();/^[A-Za-z_$][\w$]*$/.test(i)&&t.add(i)}return[...t].sort()}a(Up,"persistenceClientBindings");function Xs(e){let t=[...$p,...Up(e)].map(Vp).join("|");return new RegExp(`(?:\\b(?:${t})(?![\\w$])|${jp})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${Mp}\\s*\\(|${Fp}`,"i").test(e)}a(Xs,"sourceHasPersistenceWrite");var Gp=["no-anemic-model"],dl=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Zs=new RegExp(`\\b(${dl.join("|")})\\b`),ul="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Js=new RegExp(`\\bthis\\.${ul}\\.push\\s*\\(`),Bp=new RegExp(`^this\\.${ul}\\s*=\\s*\\[\\s*\\]`),zp=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,Wp=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g;function Qs(){return`${dl.join(", ")}, or events-array .push(`}a(Qs,"expectedDomainInvariantWordsPhrase");function qp(e){return Zs.test(e)||Js.test(e)}a(qp,"referencesGuardOrPublish");function eo(e,t,n){let r=e.slice(t);if(Bp.test(r))return!0;if(!zp.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}a(eo,"isIdiomaticEventsReset");function Yp(e,t){let n=new RegExp(Wp.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!eo(t,r.index,e))return!0;return!1}a(Yp,"methodAssignsThis");function al(e,t){return t==null?e:{...e,truncatedUntil:t}}a(al,"attachShapeTruncation");function pl(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}a(pl,"shapeTruncatedUntil");function Xp(e){let t=pl(e);return t==null?"":` shape analysed until character ${t}`}a(Xp,"shapeTruncationSuffix");function ll(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(ll,"escapeGlobLiteral");function Zp(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+=ll(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ll(o)}return new RegExp(`^${n}$`)}a(Zp,"globToRegExp");function ht(e,t){return!t||t.length===0?!0:t.some(n=>Zp(n).test(e))}a(ht,"matchesAppliesTo");function fl(e){return Gp.includes(e)}a(fl,"isTier2");function gl(e){return e.mode==="enforced"&&!fl(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(gl,"severityFor");function Fe(e,t,n,r=1){let{severity:o,failsStrict:s}=gl(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(Fe,"baseViolation");function yr(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(yr,"isInRuleLayer");function Ar(e,t,n){return t.filter(r=>!(!r.exported||!ht(r.file,e.appliesTo)||!yr(r.file,e,n)))}a(Ar,"shapesForRule");function to(e,t,n){let r=pl(t);if(r!=null)return Fe(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}a(to,"truncatedShapeViolation");function Jp(e,t,n){let r=[];for(let o of Ar(e,t,n)){let s=to(e,o,"members");s&&r.push(s),(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Fe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}a(Jp,"evaluateAggregatePrivateState");function Qp(e,t,n){let r=[];for(let o of Ar(e,t,n)){let s=to(e,o,"constructors and factories");if(s&&r.push(s),o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Fe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}a(Qp,"evaluateAlwaysValidFactory");function ef(e,t,n){let r=[],o=Qs();for(let s of Ar(e,t,n)){let i=Xp(s),l=to(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Fe(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(ef,"evaluateDomainEventOnMutation");function tf(e,t){let n=[];for(let r of t.files)ht(r,e.appliesTo)&&yr(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Fe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(tf,"evaluateOrchestrationOnly");function nf(e,t){let n=[];for(let r of t.files)ht(r,e.appliesTo)&&yr(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Fe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(nf,"evaluateThinAdapter");function rf(e,t){let n=[];for(let r of t.files)ht(r,e.appliesTo)&&yr(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Fe(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(rf,"evaluateWritesViaAggregate");function sf(e,t,n){let r=[];for(let o of Ar(e,t,n))if(o.dataOnly===!0){let s=Fe(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(sf,"evaluateNoAnemicModel");function Rr(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(...Jp(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Qp(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...ef(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...tf(n,e));break;case"thin-adapter":t.push(...nf(n,e));break;case"writes-via-aggregate":t.push(...rf(n,e));break;case"no-anemic-model":t.push(...sf(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(Rr,"evaluateArkRuleSensors");function Sr(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=>ht(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=gl(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=>ht(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(Sr,"collectEmptyAppliesToFindings");var cl=64;function of(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(of,"stripTrailingDots");function af(e){let t=e.trim(),n=t.length>cl?t.slice(0,cl):t;return of(n)}a(af,"normalizeIntentPrefix");function lf(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(lf,"layerNameLooksDomain");function cf(e){return e.some(t=>{let n=af(t);return n==="Domain"||n.startsWith("Domain.")})}a(cf,"ownsDomainIntent");function df(e,t=[]){return lf(e)||cf(t)}a(df,"isDomainRoleLayerName");function ml(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>df(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let d=typeof c.layer=="string"?c.layer:"";return d.length>0&&n.has(d)}))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)&&!fl(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(ml,"collectEmptyInvariantCatalogFindings");function uf(e){return e==="PersistenceAdapters"}a(uf,"isPersistenceDriverLayer");function pf(e,t){if(hr(e))return!0;if(!t)return!1;for(let n of t){if(uf(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(hr(o))return!0}return!1}a(pf,"sourceImportsPersistenceDriver");var ff=/\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*=)/,gf=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,mf=/\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*=/,hf=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function no(e,t,n){if(!t)return null;let r=pf(t,n),o=r&&Xs(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(mf.source,"g"))??[],i=t.match(new RegExp(hf.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,d=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,u=ff.test(t)||gf.test(t),m=s.length>=1||i.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=r&&m||u&&m||r&&f&&(l>=4||s.length>=1)||u&&r;return!d&&!h&&!o?null:{...d?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(no,"deriveArkRuleFileHints");function kr(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=no(r,o,t?.[s]);i&&(n[s]=i)}return n}a(kr,"buildArkRuleFileHints");var yf=new Set(["if","match","when"]);function hl(e,t){let n=[];for(let r of ir(t,{exportedOnly:!0})){let o=r.name;if(r.bodyStart==null){n.push(al({file:e,className:o,exported:!0,hasPublicMutableFields:!1,hasPublicSetters:!1,hasPublicConstructor:!1,hasStaticFactory:!1,mutatingMethods:[]},r.start));continue}let s=r.bodyStart,i=r.bodyEnd==null,l=t.slice(s,r.bodyEnd??t.length),c=or(l),d=i?t.length:c.truncatedAt==null?void 0:s+c.truncatedAt,u=c.members.filter(k=>!(k.kind!=="field"||k.name==="constructor"||k.modifiers.includes("private")||k.modifiers.includes("protected")||k.modifiers.includes("readonly")||k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set"))),m=u.length>0,f=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(l),h=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(l),p=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(l)&&!h,y=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(l)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(l),S=[];for(let k of c.members)k.kind==="method"&&k.name!=="constructor"&&(k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set")||yf.has(k.name)||Yp(k.name,k.body)&&S.push({name:k.name,referencesGuardOrPublish:qp(k.body)}));let R=c.members.filter(k=>k.kind==="method").length<=1&&u.length>=2&&m;n.push(al({file:e,className:o,exported:!0,hasPublicMutableFields:m,hasPublicSetters:f,hasPublicConstructor:p,hasStaticFactory:y,mutatingMethods:[...S],dataOnly:R},d))}return n}a(hl,"extractClassShapesFromSource");var yl=50;function Ir(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(Ir,"normalizeExtraMergeTeethClassification");function Ae(e){let t=Ir(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(Ae,"extraMergeTeethAllowed");function Er(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(Er,"classifyResolvedLayerCoverage");function br(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}a(br,"isArkRunRuleId");function ro(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}a(ro,"isArkOrderRuleId");function so(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")||t.startsWith("ARKORDER_")}a(so,"isExtraPlaneFinding");function Al(e,t={}){if(!Array.isArray(e)||Ae(t))return e;for(let n of e)so(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}a(Al,"demoteExtraPlaneTeethUnderClassificationFloor");var oo="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function ke(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}a(ke,"countOrZero");function en(e={}){let t=Ir(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=Ae(t),i=e.arkRules,l=ke(i?.structureEnforced),c=ke(i?.structureTotal),d=typeof i?.structureAdvisory=="number"?ke(i.structureAdvisory):Math.max(0,c-l),u=ke(i?.invariantEnforced),m=ke(i?.invariantTotal),f=typeof i?.invariantAdvisory=="number"?ke(i.invariantAdvisory):Math.max(0,m-u),h=l>0||u>0,p=e.arkRun?.present===!0,y=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,S=ke(e.arkRun?.residualCount),C=p&&y==="enforced",R=C&&s,k=e.arkOrder?.present===!0,v=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,H=ke(e.arkOrder?.residualCount),P=k&&v==="enforced",D=P&&s,E=h||C||P,$=E&&s,w=E&&o&&!s,N;if($){let F=[];h&&F.push("enforced structure/invariant findings"),C&&F.push("enforced ArkRun skip findings"),P&&F.push("enforced ArkOrder skip findings"),N=`Layer graph failures plus ${F.join(" and ")} (advisory extras never fail merge alone).`}else if(w)N=`Layer graph only \u2014 enforced ${[h?"ArkRules structure/invariant":null,C?"ArkRun":null,P?"ArkOrder":null].filter(oe=>!!oe).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`;else{let F=p?y==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",oe=k?v==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";N="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+F+oe}let M={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:d,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:m,enforced:u,advisory:f,covered:ke(i?.covered),uncovered:ke(i?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:p,mode:y,residualCount:S,extraMergeTeeth:R,note:p?y==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},arkOrder:{role:"pattern-slaving",present:k,mode:v,residualCount:H,extraMergeTeeth:D,note:k?v==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:$,dualPlaneStamp:oo,failMergeWhen:N};return o&&(M.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),M}a(en,"composeMergePlanesHonesty");var ao=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"],Af="ArkModule",Rf=["forRoot","forRootAsync"],Sf=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"],kl=new Set(["eventBus"]),kf=new Set(["publisher","eventBus"]),If=new Set(Rf),Ef=new Set(Sf),Il=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],vr=new Set(ao),bf=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),El=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function Ze(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}a(Ze,"isArkRunKernelModuleSpecifier");var lo=["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"],io=new Set(lo);function Cr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(io.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(io.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:io.has(e.slice(0,r))}a(Cr,"isArkRunTransportBypassSpecifier");function nn(e){if(vr.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}a(nn,"arkRunKernelCallKind");function rn(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}a(rn,"lineAt");function sn(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}a(sn,"stripCommentsPreservingLines");function vf(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let o=r[2]??"";return o.length>0?o:void 0}a(vf,"firstStringLiteralArg");function Rl(e,t,n){let r=Math.max(0,t-n.length-8),o=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(o)}a(Rl,"keywordBefore");function on(e,t){let n=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;)r[1]||t(r[2]??"",r[3]??"")}a(on,"parseValueImportClause");function Cf(e,t){on(sn(e),t)}a(Cf,"forEachArkRunValueImportClause");function _r(e,t){let n=sn(t),r=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(n))!==null;){let l=s[3]??"";if(!l)continue;let c=s[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!s[1],line:rn(t,s.index),resolution:"resolved-external"})}let i=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=i.exec(n))!==null;){let l=s[1]??"";if(!l)continue;let c=s[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:rn(t,s.index),resolution:"resolved-external"})}return r}a(_r,"extractArkRunValueImportDependenciesFromSource");function xr(e){let t=[];return Cf(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let o of r[1].split(",")){let s=o.trim();if(!s||s.startsWith("type "))continue;let i=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),l=i?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],c=i?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),tn(t)}a(xr,"extractArkRunImportedConstructorNamesFromSource");function _f(e){let t=new Map,n=new Set;return on(e,(r,o)=>{if(!Ze(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());i?.[1]&&t.set(i[1],i[1]);let l=/\{([^}]*)\}/.exec(r);if(l?.[1])for(let c of l[1].split(",")){let d=c.trim();if(!d||d.startsWith("type "))continue;let u=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(d);if(u){t.set(u[2],u[1]);continue}let m=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(d);m?.[1]&&t.set(m[1],m[1])}}),{named:t,namespaces:n}}a(_f,"collectKernelImportBindings");function xf(e,t){let n=new Set(t);return on(e,(r,o)=>{let s=/\{([^}]*)\}/.exec(r);if(s?.[1])for(let i of s[1].split(",")){let l=i.trim();if(!l||l.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(l),d=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],u=c?.[1]??d;!d||!u||!/^[A-Z]/.test(u)||(Ze(o)||t.has(u)||t.has(d))&&(n.add(d),n.add(u))}}),n}a(xf,"collectImportedConstructors");function Of(e,t){let n;return on(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}a(Of,"importedFromForName");function wf(e){let t=new Set,n=/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;){if(!Ze(r[2]??""))continue;let o=/\{([^}]*)\}/.exec(r[1]??"");if(o?.[1])for(let s of o[1].split(",")){let i=s.trim().replace(/^type\s+/,""),l=/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i),c=l?.[1]??i,d=l?.[2]??i;Ef.has(c)&&t.add(d)}}return t}a(wf,"collectKernelTypeNames");function Tf(e,t){let n=e.split(".");if(n.length===2)return t.namespaces.has(n[0])&&vr.has(n[1]);if(n.length!==1)return!1;let r=t.named.get(n[0]);return r!==void 0&&vr.has(r)}a(Tf,"isFactoryCalleeExpression");function Lf(e,t,n,r){on(e,(o,s)=>{if(!t(s))return;let i=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(o);i?.[1]&&(n.add(i[1]),r?.add(i[1]));let l=/^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(o.trim());l?.[1]&&n.add(l[1]);let c=/\{([^}]*)\}/.exec(o);for(let d of c?.[1]?.split(",")??[]){let u=d.trim();if(!u||u.startsWith("type "))continue;let m=/([A-Za-z_$][\w$]*)$/.exec(u)?.[1];m&&n.add(m)}})}a(Lf,"addRootModuleImports");function Nf(e,t){let{receivers:n,calleeBindings:r}=t,o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:await\s+)?(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)\b/g,s=/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*[;\n)]/g,i=/(?:\b(?:const|let|var)\s+|\bthis\s*\.\s*|(?:^|[;{}\n])\s*)([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?(?<![=!<>])=(?![=>])\s*(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*(?:as\s+[A-Za-z_$][\w$.<>]*\s*)?(?=[;\n,)])/g,l=/([A-Za-z_$][\w$]*)\s*\??\s*:\s*typeof\s+([A-Za-z_$][\w$]*)\b/g,c;for(let d=!0;d;){d=!1;for(let u of[i,l])for(u.lastIndex=0;(c=u.exec(e))!==null;)!n.has(c[2])||n.has(c[1])||(n.add(c[1]),d=!0);for(o.lastIndex=0;(c=o.exec(e))!==null;)n.has(c[2])&&(!kf.has(c[3])&&!t.rootNamespaces.has(c[2])||n.has(c[1])||(n.add(c[1]),d=!0));for(s.lastIndex=0;(c=s.exec(e))!==null;)if(n.has(c[2]))for(let u of c[1].split(",")){let m=/^\s*([A-Za-z_$][\w$]*)\s*(?::\s*([A-Za-z_$][\w$]*))?\s*$/.exec(u);if(!m)continue;let f=m[1],h=m[2]??f;if(kl.has(f)){if(n.has(h))continue;n.add(h),d=!0}else nn(f)&&!vr.has(f)&&r.add(h)}}}a(Nf,"addDerivedReceivers");function Pf(e,t,n){let r={receivers:new Set,calleeBindings:new Set,rootNamespaces:new Set};n&&Lf(e,n,r.receivers,r.rootNamespaces);let o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:await\s+)?((?:[A-Za-z_$][\w$]*\s*\.\s*)?[A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(/g,s;for(;(s=o.exec(e))!==null;)Tf(s[2].replace(/\s+/g,""),t)&&r.receivers.add(s[1]);let i=wf(e);if(i.size>0){let l=/([A-Za-z_$][\w$]*)\s*\??\s*:\s*(?:Readonly\s*<\s*)?([A-Za-z_$][\w$]*)\b/g;for(;(s=l.exec(e))!==null;)i.has(s[2])&&r.receivers.add(s[1])}return Nf(e,r),r}a(Pf,"traceKernelReceivers");function Df(e,t){let n=0;for(let r=t;r>=0;r-=1){let o=e[r];if(o===")")n+=1;else if(o==="("&&(n-=1,n===0))return r}return-1}a(Df,"matchingOpenParen");function Sl(e){let t=e.split(".").map(n=>n.trim()).filter(n=>n.length>0);return t[0]==="this"?t.slice(1):t}a(Sl,"chainParts");function $f(e,t){let n=e.slice(Math.max(0,t-400),t),r=/((?:[A-Za-z_$][\w$]*\s*\??\.\s*)+)$/.exec(n);if(r?.[1]){let d=n.slice(0,n.length-r[1].length);return/[)\]]\s*$/.test(d)||/\.\s*$/.test(d)?{parts:["<expr>"],viaPublisherCall:!1}:{parts:Sl(r[1].replace(/\?/g,"")),viaPublisherCall:!1}}let o=/\)\s*\??\.\s*$/.exec(n);if(!o)return;let s=t-n.length+o.index,i=Df(e,s);if(i<0)return{parts:["<expr>"],viaPublisherCall:!1};let l=e.slice(Math.max(0,i-400),i),c=/((?:[A-Za-z_$][\w$]*\s*\??\.\s*)+)publisher\s*(?:<[^>]*>)?\s*$/.exec(l);return c?.[1]?{parts:Sl(c[1].replace(/\?/g,"")),viaPublisherCall:!0}:{parts:["<expr>"],viaPublisherCall:!1}}a($f,"receiverChainBefore");function Mf(e,t,n){let[r,...o]=e.parts;return r?o.length===0&&t.namespaces.has(r)?!0:El.has(r)||!n.receivers.has(r)?!1:(n.rootNamespaces.has(r)?o.slice(1):o).every(i=>kl.has(i)):!1}a(Mf,"chainReachesKernel");function Ff(e){let t=new Set,n=a((c,d,u)=>{let m=c.get(d);m!==void 0&&m!==u?t.add(d):c.set(d,u)},"bind"),r=new Map,o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(['"])((?:\\.|[^\\])*?)\2\s*(?:as\s+const\s*)?[;\n,)]/g,s;for(;(s=o.exec(e))!==null;)s[3]&&n(r,s[1],s[3]);for(let c of t)r.delete(c);let i=new Map(r),l=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:[A-Za-z_$][\w$]*\s*\.\s*)*(?:define|defineIntent)\s*(?:<[^>]*>)?\s*\(\s*(?:(['"])((?:\\.|[^\\])*?)\2|([A-Za-z_$][\w$]*)\s*[,)])/g;for(;(s=l.exec(e))!==null;){let c=s[3]??(s[4]?r.get(s[4]):void 0);c?n(i,s[1],c):(t.has(s[4]??"")||i.has(s[1]))&&t.add(s[1])}for(let c of t)i.delete(c);return i}a(Ff,"collectDefinedIntentNames");function jf(e,t){return/^\s*([A-Za-z_$][\w$]*)\s*[,)]/.exec(e.slice(t))?.[1]}a(jf,"firstIdentifierArg");function Hf(e,t){return be(e)?!0:(t??[]).some(n=>{let r=n.trim();if(!r)return!1;let o=r.endsWith(".")?r:`${r}.`;return e.startsWith(o)&&/^[A-Za-z0-9_.]+$/.test(e.slice(o.length))})}a(Hf,"carriesIntentPrefix");function Kf(e){if(!e)return;if(e.viaPublisherCall)return"publisher";let t=e.parts[e.parts.length-1];return t==="<expr>"?void 0:t}a(Kf,"receiverName");function Vf(e,t,n){if(!e||t===void 0||!Hf(t,n))return!1;let r=e.parts[0];return r!==void 0&&r!=="<expr>"&&!El.has(r)}a(Vf,"untracedKernelNameEvidence");function Or(e,t,n={}){let r=sn(t),o=_f(r),s=Pf(r,o,n.isKernelRootSpecifier),i=Ff(r),l=[],c=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,d;for(;(d=c.exec(r))!==null;){let u=d[1],m=d.index;if(Rl(r,m,"function")||Rl(r,m,"class"))continue;let f=$f(r,m),h=Kf(f),p=o.named.get(u)??u,y=nn(p)??nn(u),S=o.named.has(u)||s.calleeBindings.has(u)||f?.parts.length===1&&o.namespaces.has(f.parts[0]);if(!y&&If.has(u)&&f?.parts.length===1&&o.named.get(f.parts[0])===Af&&(y="factory",S=!0),!y||y==="factory"&&f!==void 0&&!S)continue;let C=m+d[0].length,R=vf(r,C);if(y!=="factory"&&(f===void 0?!S:!Mf(f,o,s))&&!Vf(f,R,n.intentPrefixes))continue;let k=jf(r,C),v=R??(k?i.get(k):void 0);l.push({file:e,line:rn(t,m),kind:y,callee:u,viaImport:S,...h?{receiver:h}:{},...v?{nameLiteral:v}:{}})}return l}a(Or,"extractArkRunKernelCallsFromSource");function wr(e,t,n){let r=sn(t),o=xf(r,n),s=[],i=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=i.exec(r))!==null;){let c=l[1];if(bf.has(c)||!o.has(c))continue;let d=Of(r,c);s.push({file:e,line:rn(t,l.index),typeName:c,...d?{importedFrom:d}:{}})}return s}a(wr,"extractArkRunManagedNewsFromSource");function Uf(e,t){let n=0,r;for(let o=t;o<e.length;o+=1){let s=e[o];if(r){if(s==="\\"){o+=1;continue}s===r&&(r=void 0);continue}if(s==="'"||s==='"'||s==="`"){r=s;continue}if(s==="[")n+=1;else if(s==="]"&&(n-=1,n===0))return o}return-1}a(Uf,"matchingBracketEnd");function Gf(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,i;for(;(i=s.exec(r))!==null;){let l=i[2]??"";l.length>0&&o.push(l)}return o}a(Gf,"stringLiteralsInList");function tn(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(tn,"uniqueSorted");function bl(e,t){let n=sn(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],i=[],l=[],c,d;for(;(d=r.exec(n))!==null;){let u=n.slice(d.index+d[0].length),m=/^\s*\[/.exec(u);if(!m)continue;let f=d.index+d[0].length+(m[0].length-1),h=Uf(n,f);if(h<0)continue;let p=Gf(n,f,h);if(p.length===0)continue;c===void 0&&(c=d.index);let y=d[1];y==="uses"?o.push(...p):y==="reactsTo"?s.push(...p):y==="raises"?i.push(...p):l.push(...p)}return c===void 0?[]:[{file:e,line:rn(t,c),uses:tn(o),reactsTo:tn(s),raises:tn(i),sends:tn(l)}]}a(bl,"extractArkRunDeclarationsFromSource");var _l=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Bf=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],zf=new Set(Bf);function Wf(e){return zf.has(e)}a(Wf,"isArkRunEditorSensor");var Tr={"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"},co="ARKRUN_INTERACTION_NAME_INCOMPLETE";function xl(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(xl,"isDomainRoleLayer");function qf(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(qf,"compareFindings");function Te(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Tr[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:Re({ruleId:Tr[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Te,"finding");function Yf(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(Yf,"bagForFile");function vl(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(vl,"emitKinds");function Cl(e){return e==="subscribe"||e==="register-handler"}a(Cl,"handleKinds");function Xf(e){return e==="resolve"||e==="resolve-singleton"}a(Xf,"dependKinds");function Zf(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Te(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((d,u)=>d.file.localeCompare(u.file));if(l.length===0){r.push(Te(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(d=>d.hasKernelFactory))continue;let c=l[0];r.push(Te(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel / *FromConfig, or ArkModule.forRoot / forRootAsync from arkgate/nestjs).`,{target:i},n))}return r}a(Zf,"evaluateMissingRoot");function Jf(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||!Ze(c))continue;let d=r(l.from);d&&xl(d,s.get(d)??[])&&i.push(Te(e,"arkrun-kernel-in-domain",l.from,l.line,`${d} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:d,target:c},o))}return i}a(Jf,"evaluateKernelInDomain");function Qf(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(u=>[u.name,u.intentPrefixes??[]])),c=new Set(r.filter(u=>u.hasKernelFactory).map(u=>u.file)),d=[];for(let u of n){if(c.has(u.file))continue;let m=u.typeName;if(e.ignoreDirectNewForErrors!==!1&&(m.endsWith("Error")||m==="Error")||m.endsWith("DTO")||m.endsWith("VO"))continue;let f=o(u.file);!f||!i.has(f)||xl(f,l.get(f)??[])||d.push(Te(e,"arkrun-direct-new",u.file,u.line,`${f} must not construct ${u.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:u.typeName},s))}return d}a(Qf,"evaluateDirectNew");function eg(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(!vl(c.kind)&&!Cl(c.kind)&&!Xf(c.kind))continue;let d=r(c.file);if(!d||!l.has(d))continue;if(!c.nameLiteral){e.mode==="enforced"&&c.kind!=="publisher"&&i.push({code:co,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 u=Yf(n,c.file);if(vl(c.kind)){if(u.raises.has(c.nameLiteral)||u.sends.has(c.nameLiteral))continue;s.push(Te(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:d,target:c.nameLiteral},o));continue}if(Cl(c.kind)){if(u.reactsTo.has(c.nameLiteral))continue;s.push(Te(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:d,target:c.nameLiteral},o));continue}u.uses.has(c.nameLiteral)||s.push(Te(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:d,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(eg,"evaluateUndeclared");function tg(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||!Cr(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(Te(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(tg,"evaluateTransportBypass");function an(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Ae(e.classification),r=eg(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Zf(t,e.compositionRootHits,n),...Jf(t,e.layers,e.dependencies,e.layerForFile,n),...Qf(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...tg(t,e.dependencies,e.layerForFile,n)].sort(qf),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,d=`${l.code}\0${l.file??""}\0${l.message}`;return c<d?-1:c>d?1:0});return{findings:o,completenessReasons:s}}a(an,"evaluateArkRunSensors");function uo(e){return{findings:an(e).findings.filter(n=>Wf(n.sensor)),completenessReasons:[]}}a(uo,"evaluateArkRunEditorSensors");function ng(e,t){if(e===t)return!0;let n=e.indexOf("*");if(n<0)return!1;let r=e.slice(0,n).replace(/\/$/,"");return r.length>0&&(t===r||t.startsWith(`${r}/`))}a(ng,"fileMatchesCompositionRoot");function rg(e,t,n){let r=Or(t,n).some(i=>i.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let i of s)ng(i,t)&&o.push({file:t,matchedRoot:i,hasKernelFactory:r});return o}a(rg,"compositionRootHitsForSource");function Ol(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(xr(e.source));return uo({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:wr(e.file,e.source,n),compositionRootHits:rg(t,e.file,e.source),declarations:[],dependencies:_r(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}a(Ol,"evaluateArkRunEditorSensorsFromSource");var wl=new Map;function Tl(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Tl,"escapeAppliesToLiteral");function sg(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(sg,"normalizeAppliesToGlob");function og(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(og,"appliesToBracesBalanced");function Ll(e){let t=wl.get(e);if(t)return t;let n=sg(e),r=og(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Tl(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+=Tl(c)}let i=new RegExp(`^${o}$`);return wl.set(e,i),i}a(Ll,"arkOrderGlobToRegExp");function Nl(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Nl,"isArkOrderModuleSpecifier");var Pl=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],Lr={"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 ig(e,t){return!t||t.length===0?!0:t.some(n=>Ll(n).test(e))}a(ig,"matchesArkOrderAppliesTo");function ag(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(ag,"isDomainRoleLayer");function Ie(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Lr[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:Re({ruleId:Lr[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Ie,"finding");function Nr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Ae(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Ie(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let d of e.planeRootHits){let u=c.get(d.matchedRoot)??[];u.push(d),c.set(d.matchedRoot,u)}for(let d of o){let u=c.get(d)??[];if(u.length===0){r.push(Ie(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(d)} matched no governed files and has no createOrderPlane factory.`,{target:d},n));continue}u.some(m=>m.hasPlaneFactory)||r.push(Ie(t,"arkorder-missing-plane",u[0].file,1,`ArkOrder plane root ${JSON.stringify(d)} has no createOrderPlane factory.`,{target:d},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let d=c.specifier;if(!d||!Nl(d))continue;let u=e.layerForFile(c.from);u&&ag(u,s.get(u)??[])&&r.push(Ie(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:u,target:d},n))}for(let c of e.genericUpdates)r.push(Ie(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Ie(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(Ie(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));for(let c of e.xiTtlKeys??[])r.push(Ie(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 e.budgetLeaks??[])r.push(Ie(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 i.length===0?[]:e.xiFieldWrites??[]){let d=e.layerForFile(c.file);!d||!l.has(d)||ig(c.file,t.appliesTo)&&r.push(Ie(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:d,target:c.key},n))}return r.sort((c,d)=>c.file.localeCompare(d.file)||c.ruleId.localeCompare(d.ruleId)||c.line-d.line),{findings:r,completenessReasons:[]}}a(Nr,"evaluateArkOrderSensors");var po="4.8.24";function fo(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}a(fo,"childSlicesOf");var Dl=Object.freeze([{key:"sharedImportsSlice.stopAt",minVersion:po,uses:a(e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:po,uses:a(e=>fo(e)?.message!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:po,uses:a(e=>{let t=fo(e)?.siblings;return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:a(e=>fo(e)!==null,"uses")},{key:'sharedImportsSlice: "deny-cross-parent"',minVersion:"4.8.23",uses:a(e=>e.sharedImportsSlice==="deny-cross-parent","uses")},{key:"sliceIdentity",minVersion:"4.8.21",uses:a(e=>e.sliceIdentity!==void 0,"uses")},{key:"sharedImportsSlice",minVersion:"4.8.20",uses:a(e=>e.sharedImportsSlice==="deny","uses")}]);function Pr(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}a(Pr,"versionCore");function ln(e,t){let n=Pr(e),r=Pr(t);if(!n&&!r)return 0;if(!n)return-1;if(!r)return 1;for(let o=0;o<3;o+=1){let s=n[o]??0,i=r[o]??0;if(s<i)return-1;if(s>i)return 1}return 0}a(ln,"compareArkgateVersion");function $l(e,t){return t&&Pr(t)&&ln(t,e)<0?t.replace(/^v/,""):e}a($l,"effectiveFloor");function lg(e,t){let n=[],r=null;for(let o of Dl){if(!(e??[]).some(i=>i&&o.uses(i)))continue;n.push(o.key);let s=$l(o.minVersion,t);(!r||ln(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}a(lg,"configVersionFloors");function Ml(e){let t=lg(e.rules,e.runningVersion);if(!t||!e.pins?.length)return[];let n=e.runningVersion,r=n&&Pr(n)&&ln(n,t.required)>0?n.replace(/^v/,""):t.required,o=a(l=>Dl.filter(c=>t.keys.includes(c.key)&&ln(l.version,$l(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,i=[];for(let l of e.pins){if(ln(l.version,t.required)>=0)continue;let c=`${l.file}\0${l.line}`;if(s.has(c))continue;s.add(c);let d=o(l);i.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,path:l.file,line:l.line,message:`ark.config.json uses ${d.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 i.sort((l,c)=>l.path.localeCompare(c.path)||l.line-c.line)}a(Ml,"configVersionPinFindings");function Q(e,t,n={}){return{ruleId:e,message:t,...n}}a(Q,"configWarning");function cn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(p=>typeof p!="string"))&&s.push(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 p of["maxTsSuppressions","maxAnyCasts"]){let y=t.safety[p];y!==void 0&&(!Number.isInteger(y)||y<0)&&s.push(Q("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${p} 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(p=>p.name).filter(Boolean),...l.map(p=>p.name).filter(p=>!!p)]);i.length===0&&s.push(Q("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let d=new Set,u=new Set;for(let p of i){if(!p.name){s.push(Q("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}d.has(p.name)&&u.add(p.name),d.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(S=>typeof S!="string"))&&s.push(Q("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${p.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:p.name}));let y=Array.isArray(p.patterns)?p.patterns:[];if(y.length===0){s.push(Q("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let S of y){let C;try{C=me(S)}catch(k){s.push(Q("CONFIG_INVALID_LAYER_PATTERN",`Layer "${p.name}" has an invalid pattern "${S}": ${k instanceof Error?k.message:String(k)}`,{layer:p.name,pattern:S}));continue}let R=p.optional===!0||p.reserved===!0||p.allowEmpty===!0;!r.some(k=>C.test(k))&&!R&&s.push(Q("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${p.name}" pattern "${S}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:p.name,pattern:S,failsStrict:!1,reserved:!1}))}}for(let p of u)s.push(Q("CONFIG_DUPLICATE_LAYER",`Layer "${p}" is configured more than once.`,{layer:p}));if(c.size>0)for(let p of n??[])p.from&&!c.has(p.from)&&s.push(Q("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${p.from}".`,{fromLayer:p.from,toLayer:p.to})),p.to&&!c.has(p.to)&&s.push(Q("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${p.to}".`,{fromLayer:p.from,toLayer:p.to}));let m=new Set;if(i.length>1)for(let p of r){let y=-1,S=[];for(let C of i)for(let R of C.patterns??[]){if(!me(R).test(p))continue;let k=fs(R,p);k>y?(y=k,S=[C.name]):k===y&&!S.includes(C.name)&&S.push(C.name)}S.length>1&&m.add([...S].sort().join(" + "))}m.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: ${[...m].join(", ")}.`,{pairs:[...m]}));let f=r.filter(p=>!he(p,i));f.length>0&&s.push(Q("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));for(let p of xi(n))s.push(Q("CONFIG_SLICE_IDENTITY_COLLISION",p.message,{paths:[...p.paths],fromLayer:p.from,toLayer:p.to,failsStrict:!1}));for(let p of Mi(n,r))s.push(Q(p.ruleId,p.message,{failsStrict:!1,...p.path?{file:p.path}:{},...p.fromLayer?{fromLayer:p.fromLayer}:{},...p.toLayer?{toLayer:p.toLayer}:{}}));for(let p of Ml({rules:n,pins:e.arkgatePins,runningVersion:e.runningArkgateVersion}))s.push(Q(p.ruleId,p.message,{failsStrict:!1,file:p.path,line:p.line,nextAction:p.nextAction}));let h=ga(t);if(h.length>0){let p=h[0]??"this layer";s.push(Q("CONFIG_LAYER_MISSING_OWNER",`${p} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:h,nextAction:ma(p)}))}return s}a(cn,"collectAnalysisConfigWarnings");function Fl(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:sl({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(Fl,"toArkRuleEngineViolation");function cg(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(cg,"arkRulesMapIsOn");function jl(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(jl,"arkRuleFindingNextAction");function dg(e,t){return t.some(n=>{try{return me(n).test(e)}catch{return!1}})}a(dg,"matchesAny");function ug(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:S})=>({file:y,line:S})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:S})=>({file:y,line:S})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!dg(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),d=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),u=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),m={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:d,disabledPeerIsolationRules:u,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],h=c.filter(y=>y.kind==="import");if(h.length>0){let y=h[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${h.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let p=c.filter(y=>y.kind==="require");if(p.length>0){let y=p[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let y=i[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(d.length>0){let y=d[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${d.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 u.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${u.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:f}}a(ug,"evaluateSafety");function pg(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(pg,"ambientForbiddenGlobal");function Hl(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Is(e,n.length>0?n:Lt.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Hl,"intentLayer");function fg(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||!pg(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??[],d=s.source==="import-based"?t.dependencies.find(u=>u.from===s.file&&u.line===s.line&&u.specifier===s.symbol&&!u.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&_t(s.symbol,c))){if(s.source==="import-based"){let u=Le(s.symbol,c);if(u){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...d?{edgeKind:d}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${u}".`});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,...d?{edgeKind:d}:{},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 Nt({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=Hl(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=Hl(s.intent,e.contract);if(!l)continue;let c=Ee(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let d=c.sliceVerdict,u=`${i} must not reference ${l} intent ${s.intent}.`,m=d?it({surface:"intent",verdict:d,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,childMessage:c.rule.childSlices?.message,defaultMessage:u}):c.rule.message??u;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}:{},...Ve(d),message:m})}return r}a(fg,"contentViolations");function Dr(e){let{facts:t}=e,n=pt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((g,L)=>{let W=`${g.code}\0${g.file??""}\0${g.message}`,de=`${L.code}\0${L.file??""}\0${L.message}`;return W<de?-1:W>de?1:0}),i=t.files.map(g=>({...g,layer:he(g.path,e.contract.config.layers)??null})),l=new Map(i.map(g=>[g.path,g.layer])),c=t.dependencies.map(g=>{let L=g.target?l.get(g.target)??he(g.target,e.contract.config.layers):void 0;return{from:g.from,fromLayer:l.get(g.from)??null,...g.resolution==="resolved-project"&&g.target?{to:g.target,...L?{toLayer:L}:{}}:{},line:g.line,kind:g.kind,typeOnly:g.typeOnly,...g.targetTypeOnlyExports?{targetTypeOnlyExports:g.targetTypeOnlyExports}:{},...g.sourcePureTypeModule?{sourcePureTypeModule:g.sourcePureTypeModule}:{},...g.namedBindingsTypeOnly?{namedBindingsTypeOnly:g.namedBindingsTypeOnly}:{},...g.portProofEligible?{portProofEligible:g.portProofEligible}:{}}}),d=cn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(g=>g.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),u=ug(e,t),m=e.contract.arkRules??$e(),f=i.map(g=>g.path),p={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?kr(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=a(g=>l.get(g)??he(g,e.contract.config.layers),"resolveLayer"),S=[...Rr({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:y,fileHints:p}),...Sr(m,f),...ml({arkRulesActive:cg(e.contract.config),arkRules:m,layers:e.contract.config.layers??[],files:f.map(g=>({path:g,layer:y(g)}))})],C=(m.invariants?.length??0)>0,R=Ha({hasEnforcedInvariant:Us(m.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),k=R.length>0?[]:ja({adopted:e.adopted===!0,hasDomainInvariants:Vs(m.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),v=[...R.map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.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})),...k.map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.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}))],H=S.filter(g=>g.failsStrict).map(g=>Fl(g,jl(g,!1))),P=S.filter(g=>!g.failsStrict).map(g=>({...Fl(g,jl(g,!0)),failsStrict:!1})),D=C?ar({arkRules:m,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},E=D.violations.filter(g=>g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,nextAction:`Add a test title or declared symbol covering ${g.arkruleId} (declared in ${g.arkruleSource}), then preflight again.`})),$=D.violations.filter(g=>!g.failsStrict).map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,arkruleId:g.arkruleId,arkruleSource:g.arkruleSource,failsStrict:!1,nextAction:g.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${g.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${g.arkruleId} in ${g.arkruleSource} (advisory / partial).`})),w=Er(i),N=an({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(g=>l.get(g)??he(g,e.contract.config.layers),"layerForFile"),classification:w}),M=e.contract.config.arkRun?.mode,F=N.findings.filter(()=>M==="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:g.failsStrict,...g.severity?{severity:g.severity}:{}})),oe=N.findings.filter(()=>M!=="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:!1})),ge=Nr({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:a(g=>l.get(g)??he(g,e.contract.config.layers),"layerForFile"),classification:w}),et=e.contract.config.arkOrder?.mode,vn=ge.findings.filter(()=>et==="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:g.failsStrict,...g.severity?{severity:g.severity}:{}})),Qo=ge.findings.filter(()=>et!=="enforced").map(g=>({ruleId:g.ruleId,file:g.file,line:g.line,message:g.message,fromLayer:g.fromLayer,target:g.target,nextAction:g.nextAction,sensor:g.sensor,failsStrict:!1})),Rt=[...D.partial&&D.coverage.some(g=>g.mode==="enforced"&&g.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...N.completenessReasons,...ge.completenessReasons],Ke=Xe({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(g=>g.layer).map(g=>g.path),contentViolations:[...fg(e,t,l),...H,...v,...E,...F,...vn],edges:c,warnings:[...d,...u.warnings,...P,...$,...oe,...Qo],safety:u.report}),Cn=o==="complete"&&Rt.length>0?"partial":o,Zr=Cn==="complete"?s:[...s,...Rt].sort((g,L)=>{let W=`${g.code}\0${g.file??""}\0${g.message}`,de=`${L.code}\0${L.file??""}\0${L.message}`;return W<de?-1:W>de?1:0}),b=Ke.violations.filter(g=>g.failsStrict!==!1),O=Cn==="complete"&&b.length===0,A=O&&Ke.warnings.every(g=>g.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Cn,completenessReasons:Zr,valid:O,strictValid:A,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:u.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(g=>g.name),edges:c,capabilityUses:t.capabilityUses,violations:Ke.violations,warnings:Ke.warnings}}}a(Dr,"analyzeCanonicalResolvedProject");function go(e){return Dr({contract:e.contract,facts:Oe(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent,arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion})}a(go,"analyzeResolvedProject");function Kl(e){return ee(X(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Kl,"analysisTreeHash");function mo(e){let t=mt(e),n=new Map(t.ir.files.map(p=>[p.path,p])),r=[],o=new Set,s=[];for(let p of e.changes){let y=p.path.replace(/\\/g,"/"),S=Ye(p.path);if(!S||S===".."||S.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(S)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:S,line:1,message:`The atomic change set contains more than one operation for ${S}.`});continue}o.add(S),"delete"in p&&p.delete&&!n.has(S)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:S,line:1,message:`Cannot delete ${S} because it is not present in the supplied base tree.`}),r.push("delete"in p&&p.delete?{path:S,delete:!0}:{path:S,content:"content"in p?p.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=Qt({...e,changes:r}),l=new Map(i.ir.files.map(p=>[p.path,p])),c=i.ir.violations.filter(p=>p.ruleId==="CAPABILITY_VIOLATION"||p.ruleId==="FORBIDDEN_GLOBAL").map(p=>{let y=l.get(p.evidence.file)?.layer;return{ruleId:p.ruleId,file:p.evidence.file,line:p.evidence.line,target:p.symbol,...p.capability?{capability:p.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:p.message}}),d=Xe({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(p=>p.path),contentViolations:c,edges:i.ir.edges.filter(p=>!!p.fromLayer).map(p=>({from:p.from,fromLayer:p.fromLayer,...p.to?{to:p.to}:{},...p.toLayer?{toLayer:p.toLayer}:{},line:p.evidence.line,kind:"import",...p.typeOnly?{typeOnly:!0}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),u=r.map(p=>{let y=Ye(p.path),S=n.get(y),C=l.get(y);return{path:y,operation:"delete"in p&&p.delete?"delete":S?"update":"create",...S?{beforeContentHash:S.contentHash}:{},...C?{candidateContentHash:C.contentHash}:{}}}).sort((p,y)=>p.path.localeCompare(y.path)),m=[...s,...d.violations].map(p=>({...p,nextAction:Re(p)})),f=m.filter(p=>p.failsStrict!==!1),h=e.changeMap?We({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:i.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&f.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Kl(t.ir.files),candidateTreeHash:Kl(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:u,violations:m,warnings:d.warnings}}a(mo,"preflightChange");function gg(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(gg,"canonicalChangePath");function mg(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(mg,"identityViolations");function hg(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(hg,"preparedChange");function $r(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}a($r,"isArkRulesPlaneRule");function Vl(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,e.file??"",t,e.target??e.message].join("|")}a(Vl,"ratchetKey");function Ul(e,t){let n=new Map;for(let r of e){if(!$r(r.ruleId)||r.failsStrict===!1)continue;let o=Vl(r);n.set(o,(n.get(o)??0)+1)}return t.map(r=>{if(!$r(r.ruleId))return r;let o=Vl(r),s=n.get(o)??0;return s===0?r:(n.set(o,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}a(Ul,"ratchetPreExistingArkRules");function yg(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>$r(n.ruleId)),warnings:e.ir.warnings.filter(n=>$r(n.ruleId))}}}a(yg,"baseAnalysisSummary");function ho(e){return Ag(e,Oe(e.baseFacts),Oe(e.candidateFacts))}a(ho,"preflightResolvedChange");function Ag(e,t,n){let r=yg(Dr({...e.baseAnalysisInputs??{},contract:e.contract,facts:t}),e.changeMap!==void 0),o=Dr({...e.candidateAnalysisInputs??{},contract:e.contract,facts:n}),s=new Map(t.files.map(y=>[y.path,y])),i=new Map(n.files.map(y=>[y.path,y])),l=mg(t,n),c=new Map,d=[];for(let y of e.changes){let S=gg(y.path);if(!S){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(S)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:S,line:1,message:`The atomic change set contains more than one operation for ${S}.`});continue}c.set(S,y);let C=s.get(S),R=i.get(S);if("delete"in y&&y.delete)C||l.push({ruleId:"DELETE_TARGET_MISSING",file:S,line:1,message:`Cannot delete ${S} because it is not present in the supplied base facts.`}),R&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:S,line:1,message:`Candidate facts still contain deleted file ${S}.`});else{let k="content"in y?y.content:"",v=ee(k);R?R.contentHash!==v&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:S,line:1,expectedContentHash:v,candidateContentHash:R.contentHash,message:`Candidate facts for ${S} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:S,line:1,message:`Candidate facts do not contain changed file ${S}.`})}d.push(hg(y,S,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 y of new Set([...s.keys(),...i.keys()])){if(c.has(y))continue;let S=s.get(y),C=i.get(y);S&&C&&X(S)===X(C)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:y,line:1,message:`Candidate facts change ${y}, but the atomic change set does not declare it.`})}let u=e.changeMap?We({changeMap:e.changeMap,changes:d,baseDependencies:r.ir.edges.flatMap(y=>y.to?[{from:y.from,to:y.to}]:[]),candidateDependencies:o.ir.edges.flatMap(y=>y.to?[{from:y.from,to:y.to}]:[])}):void 0,m=Ul(r.ir.violations,o.ir.violations),f=Ul(r.ir.warnings,o.ir.warnings),h=[...l,...m].map(y=>({...y,nextAction:Re(y)})),p=h.filter(y=>y.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.completeness==="complete"&&f.every(y=>y.failsStrict===!1)&&p.length===0&&(u?.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}:{},...u?{convergence:u}:{},changes:d.sort((y,S)=>y.path<S.path?-1:y.path>S.path?1:0),violations:h,warnings:f}}a(Ag,"preflightCanonicalChange");var yo="1.0",Rg=12,Sg="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",kg="Next: /ark-runtime to wire one candidate.";function Gl(e){return e==="enforced"||e==="advisory"?e:null}a(Gl,"closedMode");function Ig(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!br(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}a(Ig,"uniqueArkRunRuleIds");function Eg(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Gl(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}a(Eg,"extraFromConfig");function Bl(e={}){let t=Eg(e.arkRun),n=t.present&&Array.isArray(e.layerFlow?.layers)?Gi({layers:e.layerFlow.layers,rules:Array.isArray(e.layerFlow.rules)?e.layerFlow.rules:[]}):[],r=t.present?Ig(e.findings):[],o=r.slice(0,Rg),s=r.length,i=en({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),l=t.present&&t.mode==="enforced"&&Ae(e.classification),c;return t.present?t.mode==="advisory"?c="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":l?c="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":c="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":c="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:yo,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:o},extraMergeTeeth:l,failMergeWhen:i.failMergeWhen,note:c,mergePlanes:i,layerFlowUnresolvable:n}}a(Bl,"summarizeArkRunSection");function Mr(e={}){let t=e.present===!0,n=Gl(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}a(Mr,"projectStatusArkRun");function zl(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[Sg,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),i=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${i}`),r.push(kg)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");let o=Array.isArray(e.layerFlowUnresolvable)?e.layerFlowUnresolvable:[];return o.length>0&&r.push(`Runtime layer flow: ${o.join(", ")} name(s) in a deny rule but map to no intent (no intentPrefixes, not a canonical layer). A kernel from this config cannot enforce those rules \u2014 add intentPrefixes (ARKRUN_LAYER_FLOW_UNRESOLVABLE).`),e.failMergeWhen&&r.push(e.failMergeWhen),r}a(zl,"formatArkRunDoctorLines");function bg(e){let t=e.split("|",1)[0]??"";return t.startsWith("ARKRULE_")||t.startsWith("INVARIANT_")}a(bg,"isArkRulesFrozenKey");function Fr(e,t){return e.slice(0,t).split(`
21
- `).length}a(Fr,"lineOf");function Wl(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Wl,"normalizeInventoryPath");function Yl(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}a(Yl,"ownsIntent");function ql(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Yl(t,["Domain"])}a(ql,"isDomainLayer");function vg(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Yl(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}a(vg,"isControllerEligibleLayer");function Cg(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}a(Cg,"isNonPilotSurface");function Xl(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,u])=>[Wl(d),u])),o=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),s=(e.layerContexts??[]).find(d=>ql(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,u]of Object.entries(e.fileContents).sort(([m],[f])=>m.localeCompare(f))){let m=Wl(d);if(Cg(m)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let f=r.has(m),h=r.get(m),p=h?o.get(h)??[]:[],y=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(m)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(m)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(m),S=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(m),C=/(?:^|\/)actions?(?:\/|\.|$)/i.test(m)||/['"]use server['"]/.test(u),R=/controller|handler|resolver/i.test(d)||S||C||/route\.(?:ts|js|tsx|jsx)$/i.test(m)&&!y||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),k=f?!!(h&&vg(h,p)&&R):R,v=f?!!(h&&ql(h,p)):/domain|entity|aggregate|model/i.test(d),H=!f||v||k;if(k&&!y){let w=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,N;for(;(N=w.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:d,line:Fr(u,N.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:h,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let P=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,D,E=a(w=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(w)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(w)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(w)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(w)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(w)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(w)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(w)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(w)||/_(?:OID|OIDS)$/i.test(w)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(w)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(w),"isInfraMagicName"),$=a((w,N)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(w)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(w))return!0;let M=N.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(N)&&(/\s/.test(M)||/[.!?…]$/.test(M))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(w))},"isUxMessageConstant");for(;(D=P.exec(u))!==null;){let w=D[2],N=D[3]??"";!H||E(w)||$(w,N)||y&&!v||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(m)&&!v||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:d,line:Fr(u,D.index),message:`Magic business constant ${w} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:h,suggestedArkRule:{layer:s,invariantId:`INV-${w}`},neverMechanicalSafe:!0}))}if(v){let w=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,N;for(;(N=w.exec(u))!==null;){let M=N[2]??"",F=(M.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(M.match(/:\s*[A-Za-z]/g)??[]).length>=2&&F<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:d,line:Fr(u,N.index),message:`Class ${N[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:h,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(v&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(m)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(m)||/(?:^|\/)errors?(?:\/|$)/i.test(m))){let N=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,M;for(;(M=N.exec(u))!==null;){let F=u.lastIndexOf("class ",M.index),oe=F>=0?u.indexOf("{",F):-1,ge=F>=0&&oe>=F&&oe<M.index?u.slice(F,oe):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(ge)||eo(u,M.index))continue;let et=u.slice(Math.max(0,M.index-200),M.index+200);if(!Zs.test(et)&&!Js.test(et)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:Fr(u,M.index),message:`Domain field mutation without nearby ${Qs()}.`,confidence:"heuristic",governedLayer:h,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let i=new Set(e.contractedRuleIds??[]);t.sort((d,u)=>+(u.confidence==="direct-evidence")-+(d.confidence==="direct-evidence")||d.file.localeCompare(u.file)||d.line-u.line||d.kind.localeCompare(u.kind)||d.id.localeCompare(u.id));let l=new Set((e.contractedStructure??[]).map(d=>`${d.layer}\0${d.sensor}`)),c=t.filter(d=>{let u=d.suggestedArkRule;return u?u.invariantId&&i.has(u.invariantId)?!0:u.structureId?u.sensor&&l.has(`${u.layer}\0${u.sensor}`)?!0:i.has(u.structureId):!1:!1}).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).filter(bg).length,notAScore:!0}}a(Xl,"buildRulesInventory");function Zl(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}a(Zl,"inventoryToExtractionCard");var Jl="1.1";var Ql="1.0";function _g(e){return e==="enforced"||e==="advisory"?e:null}a(_g,"closedMode");function ec(e={}){let t=e.present===!0,n=_g(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}a(ec,"projectStatusArkOrder");var jr="1.0",Ao="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Ro=["full","subset","unavailable"],So=["doctor-facts","report-snapshot","none"],un={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},tc=/^sha256:[a-f0-9]{64}$/;function ko(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!tc.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let o=e.expectedRootRelation??"unknown";return o==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:o==="exact"||o==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}a(ko,"evaluateStatusBinding");function Io(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}a(Io,"classifyStatusWritePath");function Eo(e,t){let n=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${n} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${n}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}a(Eo,"defaultHonestLabel");function nc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(nc,"normalizedConfigErrors");function bo(e,t,n,r,o){if(e.nextActionOverride?.id&&e.nextActionOverride.summary)return{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary};if(t.status==="mismatch")return{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."};if(t.status==="unverified"&&e.expectation)return{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."};if(!e.resolvedConfigPath)return{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."};let s=nc(e.configErrors);return s.length>0?{id:"fix-config",summary:`The Ark config is invalid, so ark-check, MCP and ESLint refuse it \u2014 fix: ${s.slice(0,3).join("; ")}${s.length>3?` (+${s.length-3} more)`:""}`}:r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check --report to refresh the last-check snapshot (a plain check or --doctor does not update .ark/reports/latest.json).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check --report to refresh the snapshot."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report to freeze session evidence (--doctor does not write the snapshot)."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:o.arkRulesLoaded&&(o.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}}a(bo,"resolveStatusNextAction");function rc(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&tc.test(e.projectId)?e.projectId:null,r=ko({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,i=Io({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Eo(i,s),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:dn(e.activeViolations),frozenResidual:dn(e.frozenResidual)},d={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:dn(e.rulesInventoried),underContract:dn(e.rulesUnderContract),frozenResidual:dn(e.rulesFrozenResidual)},u={writePath:i,host:s,honestLabel:l},m={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},f={schemaVersion:jr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:u,lastCheck:c,rules:d,nextAction:bo(e,r,u,c,d)},h=nc(e.configErrors);m.resolvedConfigPath&&h.length>0&&(f.contract={valid:!1,errors:h});let p=vo(e.improvementCompass);return p&&(f.improvementCompass=p),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Mr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=ec(e.arkOrder)),f}a(rc,"buildStatusManifest");var sc=new Set(Ro),xg=new Set(So);function Hr(e){let t=sc.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&xg.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let i={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:un.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(i.contractHash=r),i}let o=Array.isArray(e.topResidual)?e.topResidual.filter(i=>typeof i=="string"&&i.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:un.FACTS_PARTIAL,s.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),n&&(s.factsSource=n),r&&(s.contractHash=r),s}a(Hr,"projectStatusImprovementCompass");function oc(e={}){return Hr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??un.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --report to write the session snapshot (--doctor shows full lenses but does not write it). Status never invents green.",factsSource:"none",contractHash:e.contractHash})}a(oc,"unavailableStatusImprovementCompass");function vo(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let n;return typeof t.mode=="string"&&sc.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Hr({mode:n,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}a(vo,"normalizeStatusImprovementCompass");function ic(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let o of n)if(!(typeof o!="string"||o.length===0)&&!r.has(o))return!1;return!0}a(ic,"statusCompassResidualIsSubsetOfDoctor");function dn(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}a(dn,"numberOrNull");var ac={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ao,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:jr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},contract:{type:"object",description:"Present only when the resolved config fails the shared contract validator (the same fail-closed rules ark-check, MCP and ESLint apply).",additionalProperties:!1,required:["valid","errors"],properties:{valid:{const:!1},errors:{type:"array",minItems:1,items:{type:"string",minLength:1}}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},arkOrder:{type:"object",description:"ArkOrder extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var pn="1.0",fn=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],gn=5,je=["scalability","resilience","security"],yt=new Set(je),Co={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},_o={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},xo={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function Oo(e){return _o[e]??e}a(Oo,"improvementCompassHumanLabel");function wo(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}a(wo,"smellIdOf");function To(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}a(To,"violationRuleId");function Y(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}a(Y,"pushEvidence");function se(e,t,n){yt.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}a(se,"markResidual");function lc(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${_o[e]} \u2014 no residual from current sensors.`}}a(lc,"defaultOkSummary");function cc(){return fn.map(e=>yt.has(e)?{id:e,status:"out-of-scope",summary:xo[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:lc(e),evidence:[]}:{id:e,status:"ok",summary:lc(e),evidence:[]})}a(cc,"createInitialImprovementCompassLenses");function Og(e,t){for(let n of t){let r=wo(n);if(!r)continue;let o=n.outcome||n.message||void 0,i=(Array.isArray(n.evidence)?n.evidence:[])[0],l=a((u,m,f)=>{let h=e.get(u);!h||yt.has(u)||(Y(h,"designSmells",r,o),i&&Y(h,"designSmells",i,r),se(h,m,f))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},d={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":l("soc","Business rules still mix with UI or presentation surfaces.",c),l("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",c);break;case"facade-sql-in-routes":l("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",c),l("dip","Transport depends on concrete persistence instead of a port.",d);break;case"io-under-application":l("soc","Application/business code reaches I/O directly \u2014 separation is weak.",c),l("dip","I/O is not inverted behind ports/adapters.",d),l("testability","Direct I/O under application code hurts pure unit testing.",d);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}a(Og,"mapDesignSmells");function wg(e){return e.failsStrict===!1||e.typeOnly===!0}a(wg,"isTypeOnlyPlacementDebt");function Tg(e,t){for(let n of t){let r=To(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),i=a((c,d,u)=>{let m=e.get(c);!m||yt.has(c)||(Y(m,"violations",r,o),n.file&&Y(m,"violations",n.file,r),se(m,d,u))},"attach");if(wg(n)){i("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let l={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){i("coupling","Import graph edges violate the layer contract.",l);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){i("coupling","Import cycles couple modules tightly.",l);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){i("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(s==="FORBIDDEN_GLOBAL"||s.startsWith("FORBIDDEN_")){i("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),i("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(s==="CAPABILITY_VIOLATION"){i("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),i("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"||s==="INVARIANT_TESTS_PATH_MISSING"||s==="INVARIANT_COVERAGE_ROOTS_MISSING"){i("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),i("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}a(Tg,"mapViolations");function Lg(e,t){let n=Number(t.cycleCount)||0;if(n>0){let h=e.get("coupling");Y(h,"cycles",`count:${n}`),se(h,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let h=e.get("coupling");Y(h,"peerIsolation",`count:${r}`),se(h,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let h=e.get("cohesion");Y(h,"physicalCohesion",`findings:${o}`),se(h,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let p=e.get("srp");Y(p,"physicalCohesion",`findings:${o}`),se(p,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,i=Number(t.forbiddenGlobalResidual)||0;if(s>0||i>0){let h=e.get("dip");s>0&&Y(h,"capability",`residual:${s}`),i>0&&Y(h,"forbiddenGlobals",`residual:${i}`),se(h,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let p=e.get("testability");s>0&&Y(p,"capability",`residual:${s}`),i>0&&Y(p,"forbiddenGlobals",`residual:${i}`),se(p,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let h=e.get("encapsulation");Y(h,"arkRules",`structureResidual:${l}`),se(h,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let p=e.get("domain");Y(p,"arkRules",`structureResidual:${l}`),se(p,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let h=e.get("maintainability");Y(h,"designFitness","design-weak"),se(h,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let h=e.get("maintainability");t.dirtyBaselineRisk===!0&&Y(h,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&Y(h,"baseline",`stale:${t.baselineStale}`),se(h,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let c=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&c>=10&&e.get("maintainability").status!=="residual"){let h=e.get("maintainability");Y(h,"baseline",`frozen:${c}`),se(h,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let d=Number(t.ungovernedDirCount)||0,u=Number(t.emptyLayerCount)||0;if(d>0||u>0){let h=e.get("modularity");d>0&&Y(h,"coverage",`ungovernedDirs:${d}`),u>0&&Y(h,"coverage",`emptyLayers:${u}`),se(h,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let h=e.get("modularity");Y(h,"goldenPattern","absent"),se(h,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let m=e.get("stack");(t.stackKind??null)==="typescript"?m.status==="ok"&&(m.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(m.status="not-instrumented",m.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",m.evidence=[],m.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}a(Lg,"mapCountsAndFlags");function dc(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>wo(r).localeCompare(wo(o)));Og(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=To(r).localeCompare(To(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});Tg(e,n)}Lg(e,t)}a(dc,"projectImprovementCompassFacts");function uc(e){for(let t of je){let n=e.get(t);n.status="out-of-scope",n.summary=xo[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}a(uc,"lockImprovementCompassOutOfScope");function pc(e){for(let t of e)t.evidence.sort((n,r)=>{let o=n.source.localeCompare(r.source);return o!==0?o:n.ref.localeCompare(r.ref)})}a(pc,"sortImprovementCompassEvidence");function fc(e){return e.filter(n=>n.status==="residual"&&!yt.has(n.id)).slice().sort((n,r)=>{let o=Co[n.id]??150,s=Co[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}a(fc,"finalizeImprovementCompassTopResidual");function gc(e={}){let t=cc(),n=new Map(t.map(o=>[o.id,o]));dc(n,e),uc(n),pc(t);let r=fc(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(i=>({...i}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}a(gc,"buildImprovementCompass");function Lo(e){return e.topResidual.map(t=>Oo(t))}a(Lo,"formatImprovementCompassResidualLabels");function No(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}a(No,"primaryImprovementCompassNextAction");function mc(e){let t=Lo(e),n=je.map(s=>Oo(s)),r=No(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&o.push(`Next: ${r.ref} \u2014 ${r.summary}`),o}a(mc,"formatImprovementCompassDoctorLines");var He="1.0",Po="<!-- arkgate:agent-projection:begin",mn="<!-- arkgate:agent-projection:end -->",hn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",At=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),Do=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]);function Je(e){let t=String(e??"").replace(/\r\n/g,`
22
- `),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}a(Je,"agentProjectionContentIdentity");function An(e){return String(e??"").replace(/\r\n/g,`
23
- `)}a(An,"normalizeNewlines");function Qe(e){let t=An(e);return t.endsWith(`
16
+ `,t);return e.slice(n,r===-1?e.length:r)}a(Sp,"lineAt");function kp(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(kp,"isImportLine");function ja(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(kp(Sp(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]!==`
17
+ `;)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 d=l;for(i(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===d){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(ja,"mentionContext");function Ua(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1&&t[t.length-2]||null,name:n}:void 0}a(Ua,"symbolNeedle");function Ip(e){return Ua(e.coverage?.symbol)?.name??e.id}a(Ip,"declaredLabel");function Ha(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Ha,"sortedContentFiles");function Ga(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(m=>St(m))),s=(t.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),i=e.coverage?.test!==!1&&n,l=Ua(e.coverage?.symbol??void 0),c,d;if(i){for(let m of r){let u=t.fileContents[m];if(!u)continue;let h=Ap(u,e.id);if(h!==void 0){if(s.length===0||Va(m,s)){c={file:m,title:h};break}d??={file:m,title:h}}}c??=d}let p;if(l)for(let m of Ha(t.fileContents)){if(o.has(St(m)))continue;let u=t.fileContents[m];if(!u)continue;let h=l.className?Rp(u,l.className,l.name):Ka(u,l.name);if(h){p={file:m,shape:h};break}}let g;if(!c&&!p){if(i)for(let m of r){let u=t.fileContents[m];if(!u)continue;let h=ja(u,e.id,!0);if(h){g={file:m,context:h};break}}if(!g&&l)for(let m of Ha(t.fileContents)){if(o.has(St(m)))continue;let u=t.fileContents[m];if(!u)continue;let h=ja(u,l.name,!1);if(h){g={file:m,context:h};break}}}let f=c?{kind:"test-title",file:c.file,title:c.title}:p?{kind:"declaration",file:p.file,shape:p.shape}:g?{kind:"mention-only",file:g.file,context:g.context}:{kind:"none"};return f.kind==="mention-only"&&f.context==="comment"&&l&&bp(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...p?{declaration:p}:{}}}a(Ga,"rankCoverage");function bp(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${js(n)}(?=$|[^A-Za-z0-9_$])`),s=St(r);for(let i of Object.keys(e)){if(t.has(St(i))||St(i)===s)continue;let l=e[i];if(l&&o.test(Hs(l,!0)))return!0}return!1}a(bp,"symbolInCodeElsewhere");function Ba(e,t){return Ga(e,t).best}a(Ba,"classifyCoverage");function Vs(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Vs,"countsAsCoverage");function vp(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(vp,"mentionWhere");function Ks(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} ${Ip(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${vp(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(Ks,"describeCoverage");function cr(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=Ma(s),l=Ma(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",d=(e.coverageRoots??[]).filter(u=>typeof u=="string"&&u.length>0),p=d.length>0,g=d.join(", "),f=[],m=[];for(let u of t){let h=u.coverage?.test!==!1,k=u.coverage?.symbol,C=!r&&h,S=Ga(u,{fileContents:e.fileContents,testFiles:n,coverageRoots:d},C),I=S.best,E=[];C&&S.testTitle&&E.push("test-title"),S.declaration&&E.push("symbol");let H=Vs(I),N,$;C&&S.testTitle&&(N=S.testTitle.file,p&&($=!Va(N,d)));let v=S.declaration?.file,D=S.declaration?.shape,w=u.coverage?.test===!0||!!k||u.coverage===void 0,P=u.coverage?.test===!1&&!k,M=w&&H||P&&u.mode!=="enforced"?!0:H,F=r&&h&&!H;if(f.push({invariantId:u.id,layer:u.provenance.layer,sourceFile:u.provenance.sourceFile,mode:u.mode,covered:M&&!F,evidence:E,partial:F,description:u.description,...N!==void 0?{testEvidenceFile:N}:{},...v!==void 0?{symbolEvidenceFile:v}:{},...D!==void 0?{shape:D}:{},...$!==void 0?{outsideDeclaredRoots:$}:{},coverageRootsDeclared:p}),$===!0&&N!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${u.id} is covered only by ${N}, which is outside the declared coverage roots (${g}). 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:N,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:"warning",failsStrict:!1}),!M||F){let re=u.mode==="enforced"&&!F,ke=r||n.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(F?o?`Invariant ${u.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${u.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:P?`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}: ${Ks(u,I)} (${ke==="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.`)+(F&&o?l:i),file:u.provenance.sourceFile,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:re?"error":"warning",failsStrict:re,kind:ke})}}return{coverage:f,violations:m,partial:f.some(u=>u.partial)}}a(cr,"evaluateInvariantCoverage");function dr(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 ${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.`}:e.probe?.fresh===!0&&Da(e.probe.verdict)?{ok:!1,reason:Fa(e.invariantId,e.probe),blocker:"probe-survived"}:{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(dr,"canPromoteInvariant");function Ms(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(Ms,"nonEmptyPathStrings");function Ep(e){return!e||typeof e!="object"?[]:[...Ms(e.testGlobs),...Ms(e.coverageRoots)]}a(Ep,"configuredInvariantTestsPaths");function Cp(e){return Ep(e).length>0}a(Cp,"hasConfiguredInvariantTestsPath");function Us(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Us,"catalogDemandsInvariantTestsPath");function za(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Us(e.invariants);return e.adopted!==!0||!t?[]:Cp(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:gp,message:mp,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(za,"collectMissingInvariantTestsPathFindings");function _p(e){return!e||typeof e!="object"?[]:Ms(e.coverageRoots)}a(_p,"configuredCoverageRoots");function xp(e){return _p(e).length>0}a(xp,"hasConfiguredCoverageRoots");function Gs(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Gs,"catalogHasEnforcedInvariant");function Wa(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Gs(e.invariants)?xp(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:hp,message:yp,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(Wa,"collectMissingCoverageRootsFindings");var fr="1.0",Op="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function O(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Op}`: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(O,"addFinding");function z(e){return[...new Set(e??[])].sort()}a(z,"sortedUnique");function me(e,t,n,r,o){let s=z(n),i=z(r),l=new Set(s),c=new Set(i),d=i.filter(g=>!l.has(g)),p=s.filter(g=>!c.has(g));d.length===0&&p.length===0||(d.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),p.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(me,"compareStringSets");function Zt(e,t,n,r,o,s,i){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(Zt,"compareBoolean");function pr(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(pr,"keyed");function wp(e,t,n){let r=pr(t,s=>s.name),o=pr(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&O(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){O(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",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){O(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;me(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."}),me(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 d=Bn(i),p=Bn(l);me(e,`${c}.forbiddenGlobals`,d.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),me(e,`${c}.capabilities`,d.atoms,p.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")&&O(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:z(i.intentPrefixes),after:z(l.intentPrefixes)}),Zt(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Zt(e,`${c}.optional`,i.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}a(wp,"compareLayers");function Tp(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=pr(t,r),s=pr(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&O(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),d=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?O(e,{kind:"deny-added",path:d,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):O(e,{kind:"allow-added",path:d,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&&O(e,{kind:"deny-removed",path:d,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&O(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${d}.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 p=l.peerIsolation===!0,g=c.peerIsolation===!0;if(p!==g){let k=l.from===l.to&&c.from===c.to;O(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${d}.peerIsolation`,classification:k?g?"strengthening":"weakening":"judgment-required",message:k?g?"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:p,after:g})}z(l.sliceFolders).join("\0")!==z(c.sliceFolders).join("\0")&&O(e,{kind:"slice-folders-changed",path:`${d}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:z(l.sliceFolders),after:z(c.sliceFolders)});let f=l.sliceIdentity??"path",m=c.sliceIdentity??"path";if(f!==m&&O(e,{kind:"slice-identity-changed",path:`${d}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:m}),!p&&!g)continue;ur(e,`${d}.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."),ur(e,`${d}.allowedCrossSlice`,"cross-slice-allowance",z((l.allowedCrossSlice??[]).map(Ws)),z((c.allowedCrossSlice??[]).map(Ws)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let u=De(l.sharedImportsSlice)??null,h=De(c.sharedImportsSlice)??null;if(u!==h){let k=sl(h)>sl(u);O(e,{kind:"shared-imports-slice",path:`${d}.sharedImportsSlice`,classification:k?"strengthening":"weakening",message:zp(u,h),before:u,after:h})}else h==="deny-cross-parent"&&ur(e,`${d}.sharedImportsSlice.stopAt`,"shared-walk-stop",Ya(l.sharedImportsSlice),Ya(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.");Np(e,d,l,c)}}a(Tp,"compareRules");function qa(e){let t=e.childSlices;return t?JSON.stringify([z(t.sliceFolders??[]),t.sliceIdentity??"path",z(t.commonFolders??[])]):""}a(qa,"childSliceFoldersKey");function Ya(e){return z(Xn(e).map(t=>Jt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Ya,"stopAtKeys");function Xa(e){return e==="always"?2:e==="auto"?1:0}a(Xa,"siblingRatchetRank");function Pp(e){return z((e??[]).map(t=>Jt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Pp,"enforceKeys");function Za(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:Pp(t.enforce),ratchet:ca(t)}}a(Za,"childSliceSiblingPolicy");function Np(e,t,n,r){let o=Za(n),s=Za(r);if(o===null&&s===null)return;if(o===null&&s!==null){O(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(o!==null&&s===null){O(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(qa(n)!==qa(r)){O(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(o===null||s===null)return;if(o.mode!==s.mode){let c=s.mode==="advisory";O(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:o.mode,after:s.mode})}else if(o.mode==="advisory"&&(Lp(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce),o.ratchet!==s.ratchet)){let c=Xa(s.ratchet)>Xa(o.ratchet);O(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:o.ratchet,after:s.ratchet})}let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&O(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:i,after:l}),Mp(e,t,n,r),Fp(e,t,n,r)}a(Np,"compareChildSlices");function ol(e,t){if(JSON.stringify(e)===JSON.stringify(t))return null;let n=t.filter(o=>!e.includes(o)),r=e.filter(o=>!t.includes(o));return{added:n,removed:r,bothWays:n.length>0&&r.length>0}}a(ol,"stringListDelta");function Lp(e,t,n,r){let o=ol(n,r);if(!o)return;let{added:s,bothWays:i}=o;O(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":s.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":s.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(Lp,"compareSiblingEnforceList");function Ws(e){return JSON.stringify([e.from,e.to])}a(Ws,"crossSliceKey");function Ja(e){return z((e.childSlices?.allowedCrossSlice??[]).map(Ws))}a(Ja,"childCrossSliceKeys");function kt(e){return Jt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(kt,"allowanceSegments");function Qa(e,t){let n=kt(e),r=kt(t);if(n.length===0||n.length!==r.length)return!1;let o=!1;for(let s=0;s<n.length;s+=1)if(n[s]!==r[s]){if(n[s]==="*"&&r[s]!=="*"){o=!0;continue}return!1}return o}a(Qa,"patternWidens");function $p(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=kt(n[0]).join("/")===kt(r[0]).join("/"),s=kt(n[1]).join("/")===kt(r[1]).join("/"),i=Qa(n[0],r[0]),l=Qa(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a($p,"allowanceWidens");function Dp(e){return JSON.stringify([Jt(e.from.trim().replace(/\\/g,"/")).toLowerCase(),Jt(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Dp,"aliasEntryKey");function el(e){return z((e.childSlices?.sliceAliases??[]).map(Dp))}a(el,"sliceAliasKeys");function Fp(e,t,n,r){let o=el(n),s=el(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(d=>!o.includes(d)),l=o.filter(d=>!s.includes(d)),c=i.length>0&&l.length>0;O(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:o,after:s})}a(Fp,"compareSliceAliases");function Mp(e,t,n,r){let o=Ja(n),s=Ja(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(c=>!o.includes(c)),l=o.filter(c=>!s.includes(c));if(i.length>0&&l.length>0&&l.filter(d=>!i.some(p=>$p(p,d))).length===0){O(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:o,after:s});return}ur(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",o,s,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}a(Mp,"compareChildCrossSliceAllowances");function ur(e,t,n,r,o,s,i){let l=ol(r,o);if(!l)return;let{added:c,bothWays:d}=l;O(e,{kind:d?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:d?"judgment-required":c.length>0?"weakening":"strengthening",message:d?`${s} Entries were added and removed in the same change.`:c.length>0?s:i,before:r,after:o})}a(ur,"compareDeclaredExceptions");function jp(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&O(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Zt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(jp,"compareSafety");function Bs(e){return e.mode==="enforced"?"enforced":"advisory"}a(Bs,"arkRunMode");function zs(e){return e.mode==="enforced"?"enforced":"advisory"}a(zs,"arkOrderMode");function Hp(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${zs(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=zs(r),l=zs(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}me(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."}),me(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(Hp,"compareArkOrder");function Vp(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Bs(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Bs(r),l=Bs(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}me(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."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Zt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Vp,"compareArkRun");function Kp(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(Kp,"overallClassification");function tl(e,t){return`${e}::${t}`}a(tl,"ruleKey");function nl(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(tl(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(tl(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(nl,"indexEffectiveRules");function Up(e){return typeof e=="string"?e.length>0?[e]:[]:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(Up,"arkRulesRefPaths");function Gp(e,t){if(!e)return[];let n=new Set;for(let r of[...e.structure,...e.invariants])r.provenance?.layer===t&&r.provenance.sourceFile&&n.add(r.provenance.sourceFile);return[...n]}a(Gp,"arkRulesLayerSources");function rl(e,t,n){return[...new Set([...Up(e),...Gp(t,n)])].sort()}a(rl,"arkRulesCatalogPaths");function Bp(e,t,n,r,o,s){let i=new Map((s??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},d=new Set([...Object.keys(l),...Object.keys(c)]);for(let f of[...r?.structure??[],...r?.invariants??[],...o?.structure??[],...o?.invariants??[]])f.provenance?.layer&&d.add(f.provenance.layer);for(let f of[...d].sort()){let m=l[f],u=c[f],h=`$.arkRules[${f}]`,k=rl(m,r,f),C=rl(u,o,f);if(k.join("\0")===C.join("\0"))continue;if(typeof m=="string"&&typeof u=="string"&&m!==u&&k.length===1&&C.length===1&&k[0]===m&&C[0]===u){O(e,{kind:"arkrules-ref-path-changed",path:h,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:m,after:u});continue}let S=new Set(k),I=new Set(C);for(let E of C)S.has(E)||O(e,{kind:"arkrules-ref-added",path:E,classification:"strengthening",message:`ArkRules reference for layer ${f} was added (${E}).`,after:E});for(let E of k)I.has(E)||O(e,{kind:"arkrules-ref-removed",path:E,classification:"weakening",message:`ArkRules reference for layer ${f} was removed (${E}).`,before:E})}let p=nl(r),g=nl(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),u=g.structure.get(f),h=`$.arkRules.structure[${f}]`;if(!m&&u){O(e,{kind:"arkrule-structure-added",path:h,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(m&&!u){O(e,{kind:"arkrule-structure-removed",path:h,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!u)){if(m.mode!==u.mode){let k=m.mode==="advisory"&&u.mode==="enforced";O(e,{kind:k?"arkrule-promoted":"arkrule-demoted",path:`${h}.mode`,classification:k?"strengthening":"weakening",message:k?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:m.mode,after:u.mode})}m.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${h}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:m.sensor,after:u.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),u=g.invariants.get(f),h=`$.arkRules.invariants[${f}]`;if(!m&&u){O(e,{kind:"arkrule-invariant-added",path:h,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(m&&!u){O(e,{kind:"arkrule-invariant-removed",path:h,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!u)&&m.mode!==u.mode)if(m.mode==="advisory"&&u.mode==="enforced"){let C=i?.get(u.id),S=dr(C);S.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${h}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${h}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${S.reason}`,before:m.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${h}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:m.mode,after:u.mode})}}a(Bp,"compareArkRules");function gr(e,t,n){let r=[];me(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),me(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."}),me(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Zt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&O(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),wp(r,e.layers,t.layers),Tp(r,e.rules,t.rules),jp(r,e,t),Bp(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Vp(r,e,t),Hp(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:fr,classification:Kp(r),findings:r}}a(gr,"classifyArkPolicyDelta");function mr(e,t){if(!e||e.schemaVersion!==fr||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(mr,"policyDeltaAcknowledgementMatches");function Jt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Jt,"trimTrailingSlashes");function sl(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(sl,"sharedImportsSliceRank");function zp(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."}a(zp,"sharedImportsSliceMessage");function Je(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(Je,"normalizePath");function il(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(il,"isIdentifierStart");function hr(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(hr,"isIdentifierCharacter");function ue(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ue,"skipWhitespace");function Qt(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(Qt,"readString");function pe(e,t,n){return e.startsWith(t,n)&&!hr(e[n-1])&&!hr(e[n+t.length])}a(pe,"isWordAt");function al(e,t){let n=ue(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ue(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!pe(e,"type",n))return!1;let o=ue(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||pe(e,"as",o)||!il(e[o]))return!1;for(n=o;n<e.length&&hr(e[n]);)n+=1;if(n=ue(e,n),pe(e,"as",n)){if(n=ue(e,n+2),!il(e[n]))return!1;for(;n<e.length&&hr(e[n]);)n+=1}r=!0}return!1}a(al,"bracedNamedBindingsAreTypeOnly");function Wp(e,t){if(t=ue(e,t+6),e[t]==="(")return Qt(e,ue(e,t+1));let n=!1;if(pe(e,"type",t)){let o=ue(e,t+4);e[o]!==","&&!pe(e,"from",o)&&(n=!0)}else al(e,t)&&(n=!0);let r=ll(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(Wp,"specifierAfterImport");function qp(e,t){t=t+6;let n=ue(e,t),r=!1;if(pe(e,"type",n)){let s=ue(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else al(e,n)&&(r=!0);let o=ll(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(qp,"specifierAfterExport");function ll(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(pe(e,"from",t))return Qt(e,ue(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Qt(e,t);if(t>0&&(pe(e,"import",t)||pe(e,"export",t)))return}}a(ll,"specifierInStaticStatement");function Yp(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(Yp,"skipTemplateLiteral");function Xp(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ue(e,t+7);if(e[r]!=="(")return;r=ue(e,r+1);let o=Qt(e,r);return o?{...o,requireCall:!0}:void 0}a(Xp,"specifierAfterRequire");function Zp(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(`
18
+ `,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=Yp(e,n);continue}if(r==="'"||r==='"'){let s=Qt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&pe(e,"import",n)?Wp(e,n):r==="e"&&pe(e,"export",n)?qp(e,n):r==="r"&&pe(e,"require",n)?Xp(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(Zp,"moduleSpecifiers");function cl(e,t){let n=[],r=[];for(let o of Zp(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let d=Ht(s);if(!d)continue;let p=e.content.slice(0,o.offset).split(`
19
+ `).length;r.push({file:e.path,symbol:s,capability:d,evidence:{kind:"import",file:e.path,line:p,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
20
+ `).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=Jp(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(cl,"moduleFactsFor");function Jp(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(Jp,"resolveSpecifier");function dl(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Ee(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});if(!o)continue;let s=o.rule;n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:Jn(s,o.sliceVerdict)??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(dl,"violationsFor");var Qp={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 ef(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(ef,"hasActiveArkRules");function tf(e,t){return ef(e,t)?Q(Y(or({config:e,arkRules:t,warnings:[]}))):Q(Y(Fs(e)))}a(tf,"policyHashFor");function en(e,t,n){let r=typeof e=="string"?Kn(e,t):$t(e,t),o=n?.arkRules??Me();return{...r,arkRules:o,policyHash:tf(r.config,o)}}a(en,"loadContract");function qs(e){let t=en(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=en(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=gr(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&&mr(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(qs,"analyzePolicyDelta");function It(e){let t=e.files.map(g=>{let f=Je(g.path);return{path:f,content:g.content,contentHash:Q(g.content),layer:ge(f,e.contract.config.layers)??null}}).sort((g,f)=>g.path.localeCompare(f.path)),n=new Map(t.map(g=>[g.path,g])),r=[],o=[];for(let g of t){let f=cl(g,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=dl(r,e.contract.config),i=new Map(e.contract.config.layers.map(g=>[g.name,g])),l=new Map(e.contract.config.layers.map(g=>[g.name,new Set(ct(g))]));for(let g of o){let f=n.get(g.file)?.layer;if(!f)continue;let m=i.get(f),u=$e(g.symbol,m?.forbiddenGlobals??[]);if(u){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${u}".`,symbol:g.symbol,evidence:g.evidence});continue}l.get(f)?.has(g.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let c=t.length===0?"complete":"partial",d=c==="complete"?[]:[{...Qp}],p={schemaVersion:tr,policyHash:e.contract.policyHash,compilerOptionsHash:Q(Y(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:d,valid:c==="complete"&&s.length===0,ir:p}}a(It,"analyzeProject");function tn(e){let t=new Map(e.files.map(n=>[Je(n.path),n]));for(let n of e.changes){let r=Je(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return It({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(tn,"analyzeChange");function Ys(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(Ys,"explainViolation");function yr(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 g of[...e.get(c)??[]].sort())e.has(g)&&(n.has(g)?o.has(g)&&r.set(c,Math.min(r.get(c)??0,n.get(g)??0)):(l(g),r.set(c,Math.min(r.get(c)??0,r.get(g)??0))));if(r.get(c)!==n.get(c))return;let d=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),d.push(p)}while(p!==c);d.length>1&&i.push(d.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,d)=>c[0]<d[0]?-1:c[0]>d[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(yr,"detectArchitectureCycles");function Qe(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let i=Ee(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let f=da(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});f&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:f.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:f.toPath,toSlice:f.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${f.fromPath} \u2192 slice ${f.toSlice} (${f.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,d=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=i.sliceVerdict,g=p?ft({surface:"import",verdict:p,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.message,childMessage:l.childSlices?.message}):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}:{},...ze(p),message:d?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...d?{failsStrict:!1,severity:"warning"}:{}})}t.push(...sf(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=yr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}a(Qe,"evaluateArchitectureGraph");var nf="CROSS_PARENT_VIA_SHARED",rf="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function ul(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&De(r.sharedImportsSlice)==="deny-cross-parent")return r}a(ul,"denyingCrossParentRule");function Xs(e,t,n,r){let o=Kt(n,e,vs(e,t,r)).universeId;return o?{kind:"slice",id:o}:ut(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Xs,"placeFile");function pl(e,t){return na(t,Xn(e.sharedImportsSlice))}a(pl,"isWalkStop");function sf(e){let t=e.rules??[];if(!t.some(s=>De(s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=of(s);if(!i)continue;let l=n.get(i.from);l?l.push(i):n.set(i.from,[i])}for(let s of n.values())s.sort((i,l)=>i.to<l.to?-1:i.to>l.to?1:i.line-l.line);let r=new Map,o=[...n.values()].flat();o.sort((s,i)=>s.from<i.from?-1:s.from>i.from?1:s.to<i.to?-1:s.to>i.to?1:0);for(let s of o){let i=ul(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Xs(i,s.fromLayer,s.from,e.config.layers),c=Xs(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||pl(i,s.to))continue;let d=[{file:s.to,path:[s.from,s.to]}],p=new Set([s.to]);for(;d.length>0;){let g=d.shift();if(!g)break;for(let f of n.get(g.file)??[]){let m=ul(t,f.fromLayer,f.toLayer);if(!m)continue;let u=Xs(m,f.fromLayer,f.to,e.config.layers);if(u.kind==="shared"){if(p.has(f.to)||pl(m,f.to))continue;p.add(f.to),d.push({file:f.to,path:[...g.path,f.to]});continue}if(u.kind!=="slice"||u.id.toLowerCase()===l.id.toLowerCase()||Wn(i.allowedCrossSlice,l.id,u.id))continue;if(i.sliceIdentity==="stars"){let I=bs(i,vs(i,s.fromLayer,e.config.layers),s.from,f.to);if(I.crossSliceAllowed||I.from.universeId&&I.from.universeId===I.to.universeId)continue}let h=[...g.path,f.to],k=`${s.from}\0${f.to}`,C={file:s.from,target:f.to,line:s.line,fromLayer:s.fromLayer,toLayer:f.toLayer,fromSlice:l.id,toSlice:u.id,path:h},S=r.get(k);(!S||h.length<S.path.length||h.length===S.path.length&&h.join("\0")<S.path.join("\0"))&&r.set(k,C)}}}return[...r.values()].sort((s,i)=>s.file<i.file?-1:s.file>i.file?1:s.target<i.target?-1:s.target>i.target?1:0).map(s=>{let i=Ut(s.fromSlice),l=Ut(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:nf,file:s.file,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.target,peerIsolation:!0,...i&&l?{universeFrom:i,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}. ${rf}`}})}a(sf,"crossParentViaSharedViolations");function of(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}}a(of,"valueHop");function fl(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(fl,"structureFreezeTarget");var af=/\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)/,lf=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,cf=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,df=["db","tx","client","prisma","prismaClient","drizzle"],uf="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",yl=/\b(?:INSERT\s+INTO|(?<!\b(?:FOR(?:\s+NO\s+KEY)?|DO)\s)UPDATE(?:\s+ONLY)?(?!\s+(?:OF|SET)\b)|DELETE\s+FROM(?:\s+ONLY)?|MERGE\s+INTO|TRUNCATE(?:\s+TABLE)?(?:\s+ONLY)?)\s+(?:(?:(?:"[^"]*"|[A-Za-z_][\w$]*)\s*\.\s*)?(?:"[^"]*"|[A-Za-z_][\w$]*)|\$\{[^}]+\})/i,pf=/^(?:await|return|throw|yield|new|typeof|void|delete|if|else|case|of|in|instanceof|async|function|class|const|let|var|import|export|from|as|default|type)$/,gl=/(^|[^\w$])([A-Za-z_$][\w$]*)\s*`((?:[^`\\]|\\[\s\S])*)`/g,ff=/\bINSERT\s+INTO\b[\s\S]*?\bON\s+CONFLICT\b[\s\S]*?\bDO\s+UPDATE\s+SET\b[^;`]*/gi,ml="\\((?:[^()]|\\([^()]*\\))*\\)",gf=`\\bnew\\s+PrismaClient\\s*${ml}|\\bdrizzle\\s*${ml}`,mf=/(?<![\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,hf=/(?<![\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 yf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(yf,"escapeRegExp");function Ar(e){return af.test(e)||lf.test(e)}a(Ar,"sourceImportsPersistenceDriverText");function hl(e,t,n){let r=new RegExp(e.source,"g"),o;for(;(o=r.exec(t))!==null;)o[1]&&n.add(o[1])}a(hl,"collectFirstGroup");function Af(e){let t=new Set;hl(mf,e,t),hl(hf,e,t);let n=new RegExp(cf.source,"g"),r;for(;(r=n.exec(e))!==null;)for(let o of(r[1]??"").split(",")){let s=o.trim().replace(/^type\s+/,"").split(/\s+as\s+/),i=(s[1]??s[0]??"").trim();/^[A-Za-z_$][\w$]*$/.test(i)&&t.add(i)}return[...t].sort()}a(Af,"persistenceClientBindings");function Al(e){return e.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|`(?:[^`\\]|\\[\s\S])*`|'(?:[^'\\]|\\[\s\S])*'|"(?:[^"\\]|\\[\s\S])*"/g,t=>t.charCodeAt(0)===47?t.replace(/[^\n]/g," "):t.charCodeAt(0)===96?t.replace(/--[^\n`]*/g,n=>" ".repeat(n.length)):t)}a(Al,"blankPersistenceComments");function Rl(e){let t=Al(e);gl.lastIndex=0;let n;for(;(n=gl.exec(t))!==null;)if(!pf.test(n[2]??"")&&yl.test((n[3]??"").replace(ff," ")))return!0;return!1}a(Rl,"sourceHasTaggedSqlWrite");function Zs(e){let t=Al(e),n=[...df,...Af(t)].map(yf).join("|");return new RegExp(`(?:\\b(?:${n})(?![\\w$])|${gf})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${uf}\\s*\\(`,"i").test(t)?!0:yl.test(t)}a(Zs,"sourceHasPersistenceWrite");var Rf=["no-anemic-model"],bl=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Js=new RegExp(`\\b(${bl.join("|")})\\b`),vl="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Qs=new RegExp(`\\bthis\\.${vl}\\.push\\s*\\(`),Sf=new RegExp(`^this\\.${vl}\\s*=\\s*\\[\\s*\\]`),kf=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,If=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g;function eo(){return`${bl.join(", ")}, or events-array .push(`}a(eo,"expectedDomainInvariantWordsPhrase");function bf(e){return Js.test(e)||Qs.test(e)}a(bf,"referencesGuardOrPublish");function to(e,t,n){let r=e.slice(t);if(Sf.test(r))return!0;if(!kf.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}a(to,"isIdiomaticEventsReset");function vf(e,t){let n=new RegExp(If.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!to(t,r.index,e))return!0;return!1}a(vf,"methodAssignsThis");function Sl(e,t){return t==null?e:{...e,truncatedUntil:t}}a(Sl,"attachShapeTruncation");function El(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}a(El,"shapeTruncatedUntil");function Ef(e){let t=El(e);return t==null?"":` shape analysed until character ${t}`}a(Ef,"shapeTruncationSuffix");function kl(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(kl,"escapeGlobLiteral");function Cf(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+=kl(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=kl(o)}return new RegExp(`^${n}$`)}a(Cf,"globToRegExp");function bt(e,t){return!t||t.length===0?!0:t.some(n=>Cf(n).test(e))}a(bt,"matchesAppliesTo");function Cl(e){return Rf.includes(e)}a(Cl,"isTier2");function _l(e){return e.mode==="enforced"&&!Cl(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(_l,"severityFor");function He(e,t,n,r=1){let{severity:o,failsStrict:s}=_l(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(He,"baseViolation");function Rr(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(Rr,"isInRuleLayer");function Sr(e,t,n){return t.filter(r=>!(!r.exported||!bt(r.file,e.appliesTo)||!Rr(r.file,e,n)))}a(Sr,"shapesForRule");function no(e,t,n){let r=El(t);if(r!=null)return He(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}a(no,"truncatedShapeViolation");function _f(e,t,n){let r=[];for(let o of Sr(e,t,n)){let s=no(e,o,"members");s&&r.push(s),(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(He(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}a(_f,"evaluateAggregatePrivateState");function xf(e,t,n){let r=[];for(let o of Sr(e,t,n)){let s=no(e,o,"constructors and factories");if(s&&r.push(s),o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(He(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}a(xf,"evaluateAlwaysValidFactory");function Of(e,t,n){let r=[],o=eo();for(let s of Sr(e,t,n)){let i=Ef(s),l=no(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(He(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(Of,"evaluateDomainEventOnMutation");function wf(e,t){let n=[];for(let r of t.files)bt(r,e.appliesTo)&&Rr(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(He(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(wf,"evaluateOrchestrationOnly");function Tf(e,t){let n=[];for(let r of t.files)bt(r,e.appliesTo)&&Rr(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(He(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(Tf,"evaluateThinAdapter");function Pf(e,t){let n=[];for(let r of t.files)bt(r,e.appliesTo)&&Rr(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(He(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(Pf,"evaluateWritesViaAggregate");function Nf(e,t,n){let r=[];for(let o of Sr(e,t,n))if(o.dataOnly===!0){let s=He(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(Nf,"evaluateNoAnemicModel");function kr(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(..._f(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...xf(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Of(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...wf(n,e));break;case"thin-adapter":t.push(...Tf(n,e));break;case"writes-via-aggregate":t.push(...Pf(n,e));break;case"no-anemic-model":t.push(...Nf(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(kr,"evaluateArkRuleSensors");function Ir(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=>bt(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=_l(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=>bt(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(Ir,"collectEmptyAppliesToFindings");var Il=64;function Lf(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(Lf,"stripTrailingDots");function $f(e){let t=e.trim(),n=t.length>Il?t.slice(0,Il):t;return Lf(n)}a($f,"normalizeIntentPrefix");function Df(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(Df,"layerNameLooksDomain");function Ff(e){return e.some(t=>{let n=$f(t);return n==="Domain"||n.startsWith("Domain.")})}a(Ff,"ownsDomainIntent");function Mf(e,t=[]){return Df(e)||Ff(t)}a(Mf,"isDomainRoleLayerName");function xl(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Mf(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let d=typeof c.layer=="string"?c.layer:"";return d.length>0&&n.has(d)}))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)&&!Cl(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(xl,"collectEmptyInvariantCatalogFindings");function jf(e){return e==="PersistenceAdapters"}a(jf,"isPersistenceDriverLayer");function Hf(e,t){if(Ar(e))return!0;if(!t)return!1;for(let n of t){if(jf(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Ar(o))return!0}return!1}a(Hf,"sourceImportsPersistenceDriver");var Vf=/\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*=)/,Kf=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Uf=/\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*=/,Gf=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function ro(e,t,n){if(!t)return null;let r=Hf(t,n),o=r&&Zs(t)||Rl(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Uf.source,"g"))??[],i=t.match(new RegExp(Gf.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,d=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,p=Vf.test(t)||Kf.test(t),g=s.length>=1||i.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=r&&g||p&&g||r&&f&&(l>=4||s.length>=1)||p&&r;return!d&&!m&&!o?null:{...d?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(ro,"deriveArkRuleFileHints");function br(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=ro(r,o,t?.[s]);i&&(n[s]=i)}return n}a(br,"buildArkRuleFileHints");var Bf=new Set(["if","match","when"]);function Ol(e,t){let n=[];for(let r of lr(t,{exportedOnly:!0})){let o=r.name;if(r.bodyStart==null){n.push(Sl({file:e,className:o,exported:!0,hasPublicMutableFields:!1,hasPublicSetters:!1,hasPublicConstructor:!1,hasStaticFactory:!1,mutatingMethods:[]},r.start));continue}let s=r.bodyStart,i=r.bodyEnd==null,l=t.slice(s,r.bodyEnd??t.length),c=ar(l),d=i?t.length:c.truncatedAt==null?void 0:s+c.truncatedAt,p=c.members.filter(I=>!(I.kind!=="field"||I.name==="constructor"||I.modifiers.includes("private")||I.modifiers.includes("protected")||I.modifiers.includes("readonly")||I.modifiers.includes("static")||I.modifiers.includes("get")||I.modifiers.includes("set"))),g=p.length>0,f=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(l),m=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(l),u=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(l)&&!m,h=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(l)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(l),k=[];for(let I of c.members)I.kind==="method"&&I.name!=="constructor"&&(I.modifiers.includes("static")||I.modifiers.includes("get")||I.modifiers.includes("set")||Bf.has(I.name)||vf(I.name,I.body)&&k.push({name:I.name,referencesGuardOrPublish:bf(I.body)}));let S=c.members.filter(I=>I.kind==="method").length<=1&&p.length>=2&&g;n.push(Sl({file:e,className:o,exported:!0,hasPublicMutableFields:g,hasPublicSetters:f,hasPublicConstructor:u,hasStaticFactory:h,mutatingMethods:[...k],dataOnly:S},d))}return n}a(Ol,"extractClassShapesFromSource");var wl=50;function vr(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(vr,"normalizeExtraMergeTeethClassification");function he(e){let t=vr(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(he,"extraMergeTeethAllowed");function Er(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(Er,"classifyResolvedLayerCoverage");function Cr(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}a(Cr,"isArkRunRuleId");function so(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}a(so,"isArkOrderRuleId");function oo(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")||t.startsWith("ARKORDER_")}a(oo,"isExtraPlaneFinding");function Tl(e,t={}){if(!Array.isArray(e)||he(t))return e;for(let n of e)oo(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}a(Tl,"demoteExtraPlaneTeethUnderClassificationFloor");var io="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function ao(e){return{active:e?.active===!0,structureEnforced:e?.structureEnforced,structureTotal:e?.structureTotal,structureAdvisory:e?.structureAdvisory,invariantEnforced:e?.invariantEnforced,invariantTotal:e?.invariantTotal,invariantAdvisory:e?.invariantAdvisory,covered:e?.covered,uncovered:e?.uncovered}}a(ao,"mergePlanesArkRulesInput");function _r(e={}){let t=e.present===!0,n=e.mode==="enforced"||e.mode==="advisory"?e.mode:null,r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}a(_r,"projectExtraPlaneStatus");function Re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}a(Re,"countOrZero");function nn(e={}){let t=vr(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=he(t),i=e.arkRules,l=Re(i?.structureEnforced),c=Re(i?.structureTotal),d=typeof i?.structureAdvisory=="number"?Re(i.structureAdvisory):Math.max(0,c-l),p=Re(i?.invariantEnforced),g=Re(i?.invariantTotal),f=typeof i?.invariantAdvisory=="number"?Re(i.invariantAdvisory):Math.max(0,g-p),m=l>0||p>0,u=e.arkRun?.present===!0,h=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,k=Re(e.arkRun?.residualCount),C=u&&h==="enforced",S=C&&s,I=e.arkOrder?.present===!0,E=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,H=Re(e.arkOrder?.residualCount),N=I&&E==="enforced",$=N&&s,v=m||C||N,D=v&&s,w=v&&o&&!s,P;if(D){let F=[];m&&F.push("enforced structure/invariant findings"),C&&F.push("enforced ArkRun skip findings"),N&&F.push("enforced ArkOrder skip findings"),P=`Layer graph failures plus ${F.join(" and ")} (advisory extras never fail merge alone).`}else if(w)P=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,C?"ArkRun":null,N?"ArkOrder":null].filter(re=>!!re).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`;else{let F=u?h==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",re=I?E==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";P="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+F+re}let M={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:d,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:g,enforced:p,advisory:f,covered:Re(i?.covered),uncovered:Re(i?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:u,mode:h,residualCount:k,extraMergeTeeth:S,note:u?h==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},arkOrder:{role:"pattern-slaving",present:I,mode:E,residualCount:H,extraMergeTeeth:$,note:I?E==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:D,dualPlaneStamp:io,failMergeWhen:P};return o&&(M.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),M}a(nn,"composeMergePlanesHonesty");var co=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"],zf="ArkModule",Wf=["forRoot","forRootAsync"],qf=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"],Ll=new Set(["eventBus"]),Yf=new Set(["publisher","eventBus"]),Xf=new Set(Wf),Zf=new Set(qf),$l=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],xr=new Set(co),Jf=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Dl=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function et(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}a(et,"isArkRunKernelModuleSpecifier");var uo=["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"],lo=new Set(uo);function Or(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(lo.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(lo.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:lo.has(e.slice(0,r))}a(Or,"isArkRunTransportBypassSpecifier");function sn(e){if(xr.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}a(sn,"arkRunKernelCallKind");function on(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}a(on,"lineAt");function an(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}a(an,"stripCommentsPreservingLines");function Qf(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let o=r[2]??"";return o.length>0?o:void 0}a(Qf,"firstStringLiteralArg");function Pl(e,t,n){let r=Math.max(0,t-n.length-8),o=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(o)}a(Pl,"keywordBefore");function ln(e,t){let n=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;)r[1]||t(r[2]??"",r[3]??"")}a(ln,"parseValueImportClause");function eg(e,t){ln(an(e),t)}a(eg,"forEachArkRunValueImportClause");function wr(e,t){let n=an(t),r=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(n))!==null;){let l=s[3]??"";if(!l)continue;let c=s[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!s[1],line:on(t,s.index),resolution:"resolved-external"})}let i=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=i.exec(n))!==null;){let l=s[1]??"";if(!l)continue;let c=s[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:on(t,s.index),resolution:"resolved-external"})}return r}a(wr,"extractArkRunValueImportDependenciesFromSource");function po(e){let t=/\{([^}]*)\}/.exec(e);if(!t?.[1])return[];let n=[];for(let r of t[1].split(",")){let o=r.trim();if(!o||o.startsWith("type "))continue;let s=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),i=s?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],l=s?.[1]??i;i&&l&&n.push({local:i,original:l})}return n}a(po,"bracedValueImportBindings");function Tr(e){let t=[];return eg(e,n=>{for(let{local:r,original:o}of po(n))/^[A-Z]/.test(o)&&t.push(r,o)}),rn(t)}a(Tr,"extractArkRunImportedConstructorNamesFromSource");function tg(e){let t=new Map,n=new Set;return ln(e,(r,o)=>{if(!et(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());i?.[1]&&t.set(i[1],i[1]);for(let{local:l,original:c}of po(r))t.set(l,c)}),{named:t,namespaces:n}}a(tg,"collectKernelImportBindings");function ng(e,t){let n=new Set(t);return ln(e,(r,o)=>{for(let{local:s,original:i}of po(r))/^[A-Z]/.test(i)&&(et(o)||t.has(i)||t.has(s))&&(n.add(s),n.add(i))}),n}a(ng,"collectImportedConstructors");function rg(e,t){let n;return ln(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}a(rg,"importedFromForName");function sg(e){let t=new Set,n=/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;){if(!et(r[2]??""))continue;let o=/\{([^}]*)\}/.exec(r[1]??"");if(o?.[1])for(let s of o[1].split(",")){let i=s.trim().replace(/^type\s+/,""),l=/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i),c=l?.[1]??i,d=l?.[2]??i;Zf.has(c)&&t.add(d)}}return t}a(sg,"collectKernelTypeNames");function og(e,t){let n=e.split(".");if(n.length===2)return t.namespaces.has(n[0])&&xr.has(n[1]);if(n.length!==1)return!1;let r=t.named.get(n[0]);return r!==void 0&&xr.has(r)}a(og,"isFactoryCalleeExpression");function ig(e,t,n,r){ln(e,(o,s)=>{if(!t(s))return;let i=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(o);i?.[1]&&(n.add(i[1]),r?.add(i[1]));let l=/^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(o.trim());l?.[1]&&n.add(l[1]);let c=/\{([^}]*)\}/.exec(o);for(let d of c?.[1]?.split(",")??[]){let p=d.trim();if(!p||p.startsWith("type "))continue;let g=/([A-Za-z_$][\w$]*)$/.exec(p)?.[1];g&&n.add(g)}})}a(ig,"addRootModuleImports");function ag(e,t){let{receivers:n,calleeBindings:r}=t,o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:await\s+)?(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)\b/g,s=/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*[;\n)]/g,i=/(?:\b(?:const|let|var)\s+|\bthis\s*\.\s*|(?:^|[;{}\n])\s*)([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?(?<![=!<>])=(?![=>])\s*(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*(?:as\s+[A-Za-z_$][\w$.<>]*\s*)?(?=[;\n,)])/g,l=/([A-Za-z_$][\w$]*)\s*\??\s*:\s*typeof\s+([A-Za-z_$][\w$]*)\b/g,c;for(let d=!0;d;){d=!1;for(let p of[i,l])for(p.lastIndex=0;(c=p.exec(e))!==null;)!n.has(c[2])||n.has(c[1])||(n.add(c[1]),d=!0);for(o.lastIndex=0;(c=o.exec(e))!==null;)n.has(c[2])&&(!Yf.has(c[3])&&!t.rootNamespaces.has(c[2])||n.has(c[1])||(n.add(c[1]),d=!0));for(s.lastIndex=0;(c=s.exec(e))!==null;)if(n.has(c[2]))for(let p of c[1].split(",")){let g=/^\s*([A-Za-z_$][\w$]*)\s*(?::\s*([A-Za-z_$][\w$]*))?\s*$/.exec(p);if(!g)continue;let f=g[1],m=g[2]??f;if(Ll.has(f)){if(n.has(m))continue;n.add(m),d=!0}else sn(f)&&!xr.has(f)&&r.add(m)}}}a(ag,"addDerivedReceivers");function lg(e,t,n){let r={receivers:new Set,calleeBindings:new Set,rootNamespaces:new Set};n&&ig(e,n,r.receivers,r.rootNamespaces);let o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:await\s+)?((?:[A-Za-z_$][\w$]*\s*\.\s*)?[A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(/g,s;for(;(s=o.exec(e))!==null;)og(s[2].replace(/\s+/g,""),t)&&r.receivers.add(s[1]);let i=sg(e);if(i.size>0){let l=/([A-Za-z_$][\w$]*)\s*\??\s*:\s*(?:Readonly\s*<\s*)?([A-Za-z_$][\w$]*)\b/g;for(;(s=l.exec(e))!==null;)i.has(s[2])&&r.receivers.add(s[1])}return ag(e,r),r}a(lg,"traceKernelReceivers");function cg(e,t){let n=0;for(let r=t;r>=0;r-=1){let o=e[r];if(o===")")n+=1;else if(o==="("&&(n-=1,n===0))return r}return-1}a(cg,"matchingOpenParen");function Nl(e){let t=e.split(".").map(n=>n.trim()).filter(n=>n.length>0);return t[0]==="this"?t.slice(1):t}a(Nl,"chainParts");function dg(e,t){let n=e.slice(Math.max(0,t-400),t),r=/((?:[A-Za-z_$][\w$]*\s*\??\.\s*)+)$/.exec(n);if(r?.[1]){let d=n.slice(0,n.length-r[1].length);return/[)\]]\s*$/.test(d)||/\.\s*$/.test(d)?{parts:["<expr>"],viaPublisherCall:!1}:{parts:Nl(r[1].replace(/\?/g,"")),viaPublisherCall:!1}}let o=/\)\s*\??\.\s*$/.exec(n);if(!o)return;let s=t-n.length+o.index,i=cg(e,s);if(i<0)return{parts:["<expr>"],viaPublisherCall:!1};let l=e.slice(Math.max(0,i-400),i),c=/((?:[A-Za-z_$][\w$]*\s*\??\.\s*)+)publisher\s*(?:<[^>]*>)?\s*$/.exec(l);return c?.[1]?{parts:Nl(c[1].replace(/\?/g,"")),viaPublisherCall:!0}:{parts:["<expr>"],viaPublisherCall:!1}}a(dg,"receiverChainBefore");function ug(e,t,n){let[r,...o]=e.parts;return r?o.length===0&&t.namespaces.has(r)?!0:Dl.has(r)||!n.receivers.has(r)?!1:(n.rootNamespaces.has(r)?o.slice(1):o).every(i=>Ll.has(i)):!1}a(ug,"chainReachesKernel");function pg(e){let t=new Set,n=a((c,d,p)=>{let g=c.get(d);g!==void 0&&g!==p?t.add(d):c.set(d,p)},"bind"),r=new Map,o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(['"])((?:\\.|[^\\])*?)\2\s*(?:as\s+const\s*)?[;\n,)]/g,s;for(;(s=o.exec(e))!==null;)s[3]&&n(r,s[1],s[3]);for(let c of t)r.delete(c);let i=new Map(r),l=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:[A-Za-z_$][\w$]*\s*\.\s*)*(?:define|defineIntent)\s*(?:<[^>]*>)?\s*\(\s*(?:(['"])((?:\\.|[^\\])*?)\2|([A-Za-z_$][\w$]*)\s*[,)])/g;for(;(s=l.exec(e))!==null;){let c=s[3]??(s[4]?r.get(s[4]):void 0);c?n(i,s[1],c):(t.has(s[4]??"")||i.has(s[1]))&&t.add(s[1])}for(let c of t)i.delete(c);return i}a(pg,"collectDefinedIntentNames");function fg(e,t){return/^\s*([A-Za-z_$][\w$]*)\s*[,)]/.exec(e.slice(t))?.[1]}a(fg,"firstIdentifierArg");function gg(e,t){return ve(e)?!0:(t??[]).some(n=>{let r=n.trim();if(!r)return!1;let o=r.endsWith(".")?r:`${r}.`;return e.startsWith(o)&&/^[A-Za-z0-9_.]+$/.test(e.slice(o.length))})}a(gg,"carriesIntentPrefix");function mg(e){if(!e)return;if(e.viaPublisherCall)return"publisher";let t=e.parts[e.parts.length-1];return t==="<expr>"?void 0:t}a(mg,"receiverName");function hg(e,t,n){if(!e||t===void 0||!gg(t,n))return!1;let r=e.parts[0];return r!==void 0&&r!=="<expr>"&&!Dl.has(r)}a(hg,"untracedKernelNameEvidence");function Pr(e,t,n={}){let r=an(t),o=tg(r),s=lg(r,o,n.isKernelRootSpecifier),i=pg(r),l=[],c=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,d;for(;(d=c.exec(r))!==null;){let p=d[1],g=d.index;if(Pl(r,g,"function")||Pl(r,g,"class"))continue;let f=dg(r,g),m=mg(f),u=o.named.get(p)??p,h=sn(u)??sn(p),k=o.named.has(p)||s.calleeBindings.has(p)||f?.parts.length===1&&o.namespaces.has(f.parts[0]);if(!h&&Xf.has(p)&&f?.parts.length===1&&o.named.get(f.parts[0])===zf&&(h="factory",k=!0),!h||h==="factory"&&f!==void 0&&!k)continue;let C=g+d[0].length,S=Qf(r,C);if(h!=="factory"&&(f===void 0?!k:!ug(f,o,s))&&!hg(f,S,n.intentPrefixes))continue;let I=fg(r,C),E=S??(I?i.get(I):void 0);l.push({file:e,line:on(t,g),kind:h,callee:p,viaImport:k,...m?{receiver:m}:{},...E?{nameLiteral:E}:{}})}return l}a(Pr,"extractArkRunKernelCallsFromSource");function Nr(e,t,n){let r=an(t),o=ng(r,n),s=[],i=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=i.exec(r))!==null;){let c=l[1];if(Jf.has(c)||!o.has(c))continue;let d=rg(r,c);s.push({file:e,line:on(t,l.index),typeName:c,...d?{importedFrom:d}:{}})}return s}a(Nr,"extractArkRunManagedNewsFromSource");function yg(e,t){let n=0,r;for(let o=t;o<e.length;o+=1){let s=e[o];if(r){if(s==="\\"){o+=1;continue}s===r&&(r=void 0);continue}if(s==="'"||s==='"'||s==="`"){r=s;continue}if(s==="[")n+=1;else if(s==="]"&&(n-=1,n===0))return o}return-1}a(yg,"matchingBracketEnd");function Ag(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,i;for(;(i=s.exec(r))!==null;){let l=i[2]??"";l.length>0&&o.push(l)}return o}a(Ag,"stringLiteralsInList");function rn(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(rn,"uniqueSorted");function Fl(e,t){let n=an(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],i=[],l=[],c,d;for(;(d=r.exec(n))!==null;){let p=n.slice(d.index+d[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=d.index+d[0].length+(g[0].length-1),m=yg(n,f);if(m<0)continue;let u=Ag(n,f,m);if(u.length===0)continue;c===void 0&&(c=d.index);let h=d[1];h==="uses"?o.push(...u):h==="reactsTo"?s.push(...u):h==="raises"?i.push(...u):l.push(...u)}return c===void 0?[]:[{file:e,line:on(t,c),uses:rn(o),reactsTo:rn(s),raises:rn(i),sends:rn(l)}]}a(Fl,"extractArkRunDeclarationsFromSource");var Hl=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Rg=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Sg=new Set(Rg);function kg(e){return Sg.has(e)}a(kg,"isArkRunEditorSensor");var Lr={"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"},fo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Vl(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(Vl,"isDomainRoleLayer");function Ig(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Ig,"compareFindings");function Te(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Lr[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:ye({ruleId:Lr[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Te,"finding");function bg(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(bg,"bagForFile");function Ml(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(Ml,"emitKinds");function jl(e){return e==="subscribe"||e==="register-handler"}a(jl,"handleKinds");function vg(e){return e==="resolve"||e==="resolve-singleton"}a(vg,"dependKinds");function Eg(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Te(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((d,p)=>d.file.localeCompare(p.file));if(l.length===0){r.push(Te(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(d=>d.hasKernelFactory))continue;let c=l[0];r.push(Te(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel / *FromConfig, or ArkModule.forRoot / forRootAsync from arkgate/nestjs).`,{target:i},n))}return r}a(Eg,"evaluateMissingRoot");function Cg(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||!et(c))continue;let d=r(l.from);d&&Vl(d,s.get(d)??[])&&i.push(Te(e,"arkrun-kernel-in-domain",l.from,l.line,`${d} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:d,target:c},o))}return i}a(Cg,"evaluateKernelInDomain");function _g(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),c=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),d=[];for(let p of n){if(c.has(p.file))continue;let g=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let f=o(p.file);!f||!i.has(f)||Vl(f,l.get(f)??[])||d.push(Te(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return d}a(_g,"evaluateDirectNew");function xg(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(!Ml(c.kind)&&!jl(c.kind)&&!vg(c.kind))continue;let d=r(c.file);if(!d||!l.has(d))continue;if(!c.nameLiteral){e.mode==="enforced"&&c.kind!=="publisher"&&i.push({code:fo,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 p=bg(n,c.file);if(Ml(c.kind)){if(p.raises.has(c.nameLiteral)||p.sends.has(c.nameLiteral))continue;s.push(Te(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:d,target:c.nameLiteral},o));continue}if(jl(c.kind)){if(p.reactsTo.has(c.nameLiteral))continue;s.push(Te(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:d,target:c.nameLiteral},o));continue}p.uses.has(c.nameLiteral)||s.push(Te(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:d,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(xg,"evaluateUndeclared");function Og(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||!Or(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(Te(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(Og,"evaluateTransportBypass");function cn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=he(e.classification),r=xg(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Eg(t,e.compositionRootHits,n),...Cg(t,e.layers,e.dependencies,e.layerForFile,n),..._g(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Og(t,e.dependencies,e.layerForFile,n)].sort(Ig),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,d=`${l.code}\0${l.file??""}\0${l.message}`;return c<d?-1:c>d?1:0});return{findings:o,completenessReasons:s}}a(cn,"evaluateArkRunSensors");function go(e){return{findings:cn(e).findings.filter(n=>kg(n.sensor)),completenessReasons:[]}}a(go,"evaluateArkRunEditorSensors");function wg(e,t){if(e===t)return!0;let n=e.indexOf("*");if(n<0)return!1;let r=e.slice(0,n).replace(/\/$/,"");return r.length>0&&(t===r||t.startsWith(`${r}/`))}a(wg,"fileMatchesCompositionRoot");function Tg(e,t,n){let r=Pr(t,n).some(i=>i.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let i of s)wg(i,t)&&o.push({file:t,matchedRoot:i,hasKernelFactory:r});return o}a(Tg,"compositionRootHitsForSource");function Kl(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(Tr(e.source));return go({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Nr(e.file,e.source,n),compositionRootHits:Tg(t,e.file,e.source),declarations:[],dependencies:wr(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}a(Kl,"evaluateArkRunEditorSensorsFromSource");function Ul(e){return ce(e)}a(Ul,"arkOrderGlobToRegExp");function Gl(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Gl,"isArkOrderModuleSpecifier");var Bl=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],$r={"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 Pg(e,t){return!t||t.length===0?!0:t.some(n=>Ul(n).test(e))}a(Pg,"matchesArkOrderAppliesTo");function Ng(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(Ng,"isDomainRoleLayer");function Se(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:$r[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:ye({ruleId:$r[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Se,"finding");function Dr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=he(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Se(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 d of e.planeRootHits){let p=c.get(d.matchedRoot)??[];p.push(d),c.set(d.matchedRoot,p)}for(let d of o){let p=c.get(d)??[];if(p.length===0){r.push(Se(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(d)} matched no governed files and has no createOrderPlane factory.`,{target:d},n));continue}p.some(g=>g.hasPlaneFactory)||r.push(Se(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(d)} has no createOrderPlane factory.`,{target:d},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let d=c.specifier;if(!d||!Gl(d))continue;let p=e.layerForFile(c.from);p&&Ng(p,s.get(p)??[])&&r.push(Se(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:d},n))}for(let c of e.genericUpdates)r.push(Se(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(Se(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(Se(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 e.xiTtlKeys??[])r.push(Se(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 e.budgetLeaks??[])r.push(Se(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 i.length===0?[]:e.xiFieldWrites??[]){let d=e.layerForFile(c.file);!d||!l.has(d)||Pg(c.file,t.appliesTo)&&r.push(Se(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:d,target:c.key},n))}return r.sort((c,d)=>c.file.localeCompare(d.file)||c.ruleId.localeCompare(d.ruleId)||c.line-d.line),{findings:r,completenessReasons:[]}}a(Dr,"evaluateArkOrderSensors");var dn="4.8.24";function un(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}a(un,"childSlicesOf");var zl=Object.freeze([{key:"childSlices.arkRulesFile",minVersion:dn,uses:a(e=>typeof un(e)?.arkRulesFile=="string","uses")},{key:"childSlices.sliceAliases.pinned",minVersion:dn,uses:a(e=>{let t=un(e)?.sliceAliases;return Array.isArray(t)?t.some(n=>{if(n===null||typeof n!="object")return!1;let r=n;return r.pinned!==void 0||r.reason!==void 0}):!1},"uses")},{key:"sharedImportsSlice.stopAt",minVersion:dn,uses:a(e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:dn,uses:a(e=>un(e)?.message!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:dn,uses:a(e=>{let t=un(e)?.siblings;return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:a(e=>un(e)!==null,"uses")},{key:'sharedImportsSlice: "deny-cross-parent"',minVersion:"4.8.23",uses:a(e=>e.sharedImportsSlice==="deny-cross-parent","uses")},{key:"sliceIdentity",minVersion:"4.8.21",uses:a(e=>e.sliceIdentity!==void 0,"uses")},{key:"sharedImportsSlice",minVersion:"4.8.20",uses:a(e=>e.sharedImportsSlice==="deny","uses")}]);function Fr(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}a(Fr,"versionCore");function pn(e,t){let n=Fr(e),r=Fr(t);if(!n&&!r)return 0;if(!n)return-1;if(!r)return 1;for(let o=0;o<3;o+=1){let s=n[o]??0,i=r[o]??0;if(s<i)return-1;if(s>i)return 1}return 0}a(pn,"compareArkgateVersion");function Wl(e,t){return t&&Fr(t)&&pn(t,e)<0?t.replace(/^v/,""):e}a(Wl,"effectiveFloor");function Lg(e,t){let n=[],r=null;for(let o of zl){if(!(e??[]).some(i=>i&&o.uses(i)))continue;n.push(o.key);let s=Wl(o.minVersion,t);(!r||pn(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}a(Lg,"configVersionFloors");function ql(e){let t=Lg(e.rules,e.runningVersion);if(!t||!e.pins?.length)return[];let n=e.runningVersion,r=n&&Fr(n)&&pn(n,t.required)>0?n.replace(/^v/,""):t.required,o=a(l=>zl.filter(c=>t.keys.includes(c.key)&&pn(l.version,Wl(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,i=[];for(let l of e.pins){if(pn(l.version,t.required)>=0)continue;let c=`${l.file}\0${l.line}`;if(s.has(c))continue;s.add(c);let d=o(l);i.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,path:l.file,line:l.line,message:`ark.config.json uses ${d.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 i.sort((l,c)=>l.path.localeCompare(c.path)||l.line-c.line)}a(ql,"configVersionPinFindings");function J(e,t,n={}){return{ruleId:e,message:t,...n}}a(J,"configWarning");function fn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(u=>typeof u!="string"))&&s.push(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 u of["maxTsSuppressions","maxAnyCasts"]){let h=t.safety[u];h!==void 0&&(!Number.isInteger(h)||h<0)&&s.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${u} 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(u=>u.name).filter(Boolean),...l.map(u=>u.name).filter(u=>!!u)]);i.length===0&&s.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let d=new Set,p=new Set;for(let u of i){if(!u.name){s.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}d.has(u.name)&&p.add(u.name),d.add(u.name),u.forbiddenGlobals!==void 0&&(!Array.isArray(u.forbiddenGlobals)||u.forbiddenGlobals.some(k=>typeof k!="string"))&&s.push(J("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 h=Array.isArray(u.patterns)?u.patterns:[];if(h.length===0){s.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${u.name}" has no file patterns and will never classify files.`,{layer:u.name}));continue}for(let k of h){let C;try{C=ce(k)}catch(I){s.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${u.name}" has an invalid pattern "${k}": ${I instanceof Error?I.message:String(I)}`,{layer:u.name,pattern:k}));continue}let S=u.optional===!0||u.reserved===!0||u.allowEmpty===!0;!r.some(I=>C.test(I))&&!S&&s.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${u.name}" pattern "${k}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:u.name,pattern:k,failsStrict:!1,reserved:!1}))}}for(let u of p)s.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${u}" is configured more than once.`,{layer:u}));if(c.size>0)for(let u of n??[])u.from&&!c.has(u.from)&&s.push(J("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(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${u.to}".`,{fromLayer:u.from,toLayer:u.to}));let g=new Set;if(i.length>1)for(let u of r){let h=-1,k=[];for(let C of i)for(let S of C.patterns??[]){if(!ce(S).test(u))continue;let I=Rs(S,u);I>h?(h=I,k=[C.name]):I===h&&!k.includes(C.name)&&k.push(C.name)}k.length>1&&g.add([...k].sort().join(" + "))}g.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: ${[...g].join(", ")}.`,{pairs:[...g]}));let f=r.filter(u=>!ge(u,i));f.length>0&&s.push(J("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));for(let u of Ji(n))s.push(J("CONFIG_SLICE_IDENTITY_COLLISION",u.message,{paths:[...u.paths],fromLayer:u.from,toLayer:u.to,failsStrict:!1}));for(let u of la(n,r))s.push(J(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 ql({rules:n,pins:e.arkgatePins,runningVersion:e.runningArkgateVersion}))s.push(J(u.ruleId,u.message,{failsStrict:!1,file:u.path,line:u.line,nextAction:u.nextAction}));let m=Fi(t);if(m.length>0){let u=m[0]??"this layer";s.push(J("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:m,nextAction:Mi(u)}))}return s}a(fn,"collectAnalysisConfigWarnings");function Yl(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:fl({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(Yl,"toArkRuleEngineViolation");function $g(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a($g,"arkRulesMapIsOn");function Xl(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(Xl,"arkRuleFindingNextAction");function Dg(e,t){return t.some(n=>{try{return ce(n).test(e)}catch{return!1}})}a(Dg,"matchesAny");function Fg(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(h=>h.kind==="ts-suppression").map(({file:h,line:k})=>({file:h,line:k})),l=t.safetyUses.filter(h=>h.kind==="any-cast").map(({file:h,line:k})=>({file:h,line:k})),c=t.safetyUses.filter(h=>(h.kind==="dynamic-import"||h.kind==="dynamic-require")&&!Dg(h.file,s)).map(h=>({file:h.file,line:h.line,kind:h.kind==="dynamic-require"?"require":"import"})),d=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(h=>h.kind==="in-memory-store").map(h=>({file:h.file,line:h.line,store:h.symbol??"in-memory store"})),p=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(h=>h.peerIsolation===!1||h.allowed===!1&&!!h.from&&h.from===h.to&&h.peerIsolation!==!0).map(h=>({from:h.from,to:h.to})),g={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:d,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],m=c.filter(h=>h.kind==="import");if(m.length>0){let h=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let u=c.filter(h=>h.kind==="require");if(u.length>0){let h=u[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let h=i[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let h=l[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(d.length>0){let h=d[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:h.file,line:h.line,message:`${d.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 p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:f}}a(Fg,"evaluateSafety");function Mg(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(Mg,"ambientForbiddenGlobal");function Zl(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return cs(e,n.length>0?n:Dt.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Zl,"intentLayer");function jg(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||!Mg(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??[],d=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&Vt(s.symbol,c))){if(s.source==="import-based"){let p=$e(s.symbol,c);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...d?{edgeKind:d}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}ct(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...d?{edgeKind:d}:{},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 Ft({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=Zl(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=Zl(s.intent,e.contract);if(!l)continue;let c=Ee(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let d=c.sliceVerdict,p=`${i} must not reference ${l} intent ${s.intent}.`,g=d?ft({surface:"intent",verdict:d,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,childMessage:c.rule.childSlices?.message,defaultMessage:p}):c.rule.message??p;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}:{},...ze(d),message:g})}return r}a(jg,"contentViolations");function Jl(e,t){return t==="enforced"?{violations:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:n.failsStrict,...n.severity?{severity:n.severity}:{}})),warnings:[]}:{violations:[],warnings:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:!1}))}}a(Jl,"splitExtraPlaneFindings");function Mr(e){let{facts:t}=e,n=yt(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,y)=>{let A=`${R.code}\0${R.file??""}\0${R.message}`,L=`${y.code}\0${y.file??""}\0${y.message}`;return A<L?-1:A>L?1:0}),i=t.files.map(R=>({...R,layer:ge(R.path,e.contract.config.layers)??null})),l=new Map(i.map(R=>[R.path,R.layer])),c=t.dependencies.map(R=>{let y=R.target?l.get(R.target)??ge(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,...y?{toLayer:y}:{}}:{},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}:{}}}),d=fn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(R=>R.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),p=Fg(e,t),g=e.contract.arkRules??Me(),f=i.map(R=>R.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?br(e.coverageInputs.fileContents):{},...e.fileHints??{}},h=a(R=>l.get(R)??ge(R,e.contract.config.layers),"resolveLayer"),k=[...kr({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:h,fileHints:u}),...Ir(g,f),...xl({arkRulesActive:$g(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(R=>({path:R,layer:h(R)}))})],C=(g.invariants?.length??0)>0,S=Wa({hasEnforcedInvariant:Gs(g.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),I=S.length>0?[]:za({adopted:e.adopted===!0,hasDomainInvariants:Us(g.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),E=[...S.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})),...I.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}))],H=k.filter(R=>R.failsStrict).map(R=>Yl(R,Xl(R,!1))),N=k.filter(R=>!R.failsStrict).map(R=>({...Yl(R,Xl(R,!0)),failsStrict:!1})),$=C?cr({arkRules:g,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},v=$.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.`})),D=$.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).`})),w=Er(i),P=cn({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)??ge(R,e.contract.config.layers),"layerForFile"),classification:w}),{violations:M,warnings:F}=Jl(P.findings,e.contract.config.arkRun?.mode),re=Dr({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:a(R=>l.get(R)??ge(R,e.contract.config.layers),"layerForFile"),classification:w}),{violations:ke,warnings:Ct}=Jl(re.findings,e.contract.config.arkOrder?.mode),ts=[...$.partial&&$.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."}]:[],...P.completenessReasons,...re.completenessReasons],Ue=Qe({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(R=>R.layer).map(R=>R.path),contentViolations:[...jg(e,t,l),...H,...E,...v,...M,...ke],edges:c,warnings:[...d,...p.warnings,...N,...D,...F,...Ct],safety:p.report}),rt=o==="complete"&&ts.length>0?"partial":o,On=rt==="complete"?s:[...s,...ts].sort((R,y)=>{let A=`${R.code}\0${R.file??""}\0${R.message}`,L=`${y.code}\0${y.file??""}\0${y.message}`;return A<L?-1:A>L?1:0}),ri=Ue.violations.filter(R=>R.failsStrict!==!1),wn=rt==="complete"&&ri.length===0,_=wn&&Ue.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:rt,completenessReasons:On,valid:wn,strictValid:_,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.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:Ue.violations,warnings:Ue.warnings}}}a(Mr,"analyzeCanonicalResolvedProject");function mo(e){return Mr({contract:e.contract,facts:Oe(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent,arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion})}a(mo,"analyzeResolvedProject");function Ql(e){return Q(Y(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Ql,"analysisTreeHash");function ho(e){let t=It(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],o=new Set,s=[];for(let u of e.changes){let h=u.path.replace(/\\/g,"/"),k=Je(u.path);if(!k||k===".."||k.startsWith("../")||h.startsWith("/")||/^[A-Za-z]:\//.test(h)||h.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(k)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}o.add(k),"delete"in u&&u.delete&&!n.has(k)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:k,delete:!0}:{path:k,content:"content"in u?u.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=tn({...e,changes:r}),l=new Map(i.ir.files.map(u=>[u.path,u])),c=i.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let h=l.get(u.evidence.file)?.layer;return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...h?{fromLayer:h}:{},edgeKind:"import",message:u.message}}),d=Qe({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(u=>u.path),contentViolations:c,edges:i.ir.edges.filter(u=>!!u.fromLayer).map(u=>({from:u.from,fromLayer:u.fromLayer,...u.to?{to:u.to}:{},...u.toLayer?{toLayer:u.toLayer}:{},line:u.evidence.line,kind:"import",...u.typeOnly?{typeOnly:!0}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(u=>{let h=Je(u.path),k=n.get(h),C=l.get(h);return{path:h,operation:"delete"in u&&u.delete?"delete":k?"update":"create",...k?{beforeContentHash:k.contentHash}:{},...C?{candidateContentHash:C.contentHash}:{}}}).sort((u,h)=>u.path.localeCompare(h.path)),g=[...s,...d.violations].map(u=>({...u,nextAction:ye(u)})),f=g.filter(u=>u.failsStrict!==!1),m=e.changeMap?Ye({changeMap:e.changeMap,changes:p,baseDependencies:At(t.ir.edges),candidateDependencies:At(i.ir.edges)}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Ql(t.ir.files),candidateTreeHash:Ql(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:d.warnings}}a(ho,"preflightChange");function Hg(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(Hg,"identityViolations");function Vg(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(Vg,"preparedChange");function jr(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}a(jr,"isArkRulesPlaneRule");function ec(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,e.file??"",t,e.target??e.message].join("|")}a(ec,"ratchetKey");function tc(e,t){let n=new Map;for(let r of e){if(!jr(r.ruleId)||r.failsStrict===!1)continue;let o=ec(r);n.set(o,(n.get(o)??0)+1)}return t.map(r=>{if(!jr(r.ruleId))return r;let o=ec(r),s=n.get(o)??0;return s===0?r:(n.set(o,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}a(tc,"ratchetPreExistingArkRules");function Kg(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>jr(n.ruleId)),warnings:e.ir.warnings.filter(n=>jr(n.ruleId))}}}a(Kg,"baseAnalysisSummary");function yo(e){return Ug(e,Oe(e.baseFacts),Oe(e.candidateFacts))}a(yo,"preflightResolvedChange");function Ug(e,t,n){let r=Kg(Mr({...e.baseAnalysisInputs??{},contract:e.contract,facts:t}),e.changeMap!==void 0),o=Mr({...e.candidateAnalysisInputs??{},contract:e.contract,facts:n}),s=new Map(t.files.map(h=>[h.path,h])),i=new Map(n.files.map(h=>[h.path,h])),l=Hg(t,n),c=new Map,d=[];for(let h of e.changes){let k=ka(h.path);if(!k){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(k)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}c.set(k,h);let C=s.get(k),S=i.get(k);if("delete"in h&&h.delete)C||l.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base facts.`}),S&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:k,line:1,message:`Candidate facts still contain deleted file ${k}.`});else{let I="content"in h?h.content:"",E=Q(I);S?S.contentHash!==E&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:k,line:1,expectedContentHash:E,candidateContentHash:S.contentHash,message:`Candidate facts for ${k} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:k,line:1,message:`Candidate facts do not contain changed file ${k}.`})}d.push(Vg(h,k,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 h of new Set([...s.keys(),...i.keys()])){if(c.has(h))continue;let k=s.get(h),C=i.get(h);k&&C&&Y(k)===Y(C)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:h,line:1,message:`Candidate facts change ${h}, but the atomic change set does not declare it.`})}let p=e.changeMap?Ye({changeMap:e.changeMap,changes:d,baseDependencies:At(r.ir.edges),candidateDependencies:At(o.ir.edges)}):void 0,g=tc(r.ir.violations,o.ir.violations),f=tc(r.ir.warnings,o.ir.warnings),m=[...l,...g].map(h=>({...h,nextAction:ye(h)})),u=m.filter(h=>h.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.completeness==="complete"&&f.every(h=>h.failsStrict===!1)&&u.length===0&&(p?.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}:{},...p?{convergence:p}:{},changes:d.sort((h,k)=>h.path<k.path?-1:h.path>k.path?1:0),violations:m,warnings:f}}a(Ug,"preflightCanonicalChange");var nc="1.1";var rc="1.0";var sc="1.0",Ao="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Hr="^sha256:[a-f0-9]{64}$",Ro={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:Hr,description:"Project id previously returned by ark_identity or ark_manifest."}}},So={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:Hr},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},oc={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ao,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:Hr},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Hr},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Ro,binding:So}};function ic(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}a(ic,"createProjectId");function ac(e){return{schemaVersion:"1.0",...e}}a(ac,"createProjectIdentity");var ko="1.0",Gg=12,Bg="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",zg="Next: /ark-runtime to wire one candidate.";function Wg(e){return e==="enforced"||e==="advisory"?e:null}a(Wg,"closedMode");function qg(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Cr(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}a(qg,"uniqueArkRunRuleIds");function Yg(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Wg(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}a(Yg,"extraFromConfig");function lc(e={}){let t=Yg(e.arkRun),n=t.present&&Array.isArray(e.layerFlow?.layers)?Hi({layers:e.layerFlow.layers,rules:Array.isArray(e.layerFlow.rules)?e.layerFlow.rules:[]}):[],r=t.present?qg(e.findings):[],o=r.slice(0,Gg),s=r.length,i=nn({classification:e.classification,arkRules:ao(e.arkRules),arkRun:{present:t.present,mode:t.mode,residualCount:s}}),l=t.present&&t.mode==="enforced"&&he(e.classification),c;return t.present?t.mode==="advisory"?c="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":l?c="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":c="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":c="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:ko,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:o},extraMergeTeeth:l,failMergeWhen:i.failMergeWhen,note:c,mergePlanes:i,layerFlowUnresolvable:n}}a(lc,"summarizeArkRunSection");function Vr(e={}){return _r(e)}a(Vr,"projectStatusArkRun");function cc(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[Bg,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),i=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${i}`),r.push(zg)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");let o=Array.isArray(e.layerFlowUnresolvable)?e.layerFlowUnresolvable:[];return o.length>0&&r.push(`Runtime layer flow: ${o.join(", ")} name(s) in a deny rule but map to no intent (no intentPrefixes, not a canonical layer). A kernel from this config cannot enforce those rules \u2014 add intentPrefixes (ARKRUN_LAYER_FLOW_UNRESOLVABLE).`),e.failMergeWhen&&r.push(e.failMergeWhen),r}a(cc,"formatArkRunDoctorLines");function Xg(e){let t=e.split("|",1)[0]??"";return t.startsWith("ARKRULE_")||t.startsWith("INVARIANT_")}a(Xg,"isArkRulesFrozenKey");function Kr(e,t){return e.slice(0,t).split(`
21
+ `).length}a(Kr,"lineOf");function dc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(dc,"normalizeInventoryPath");function pc(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}a(pc,"ownsIntent");function uc(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||pc(t,["Domain"])}a(uc,"isDomainLayer");function Zg(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||pc(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}a(Zg,"isControllerEligibleLayer");function Jg(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}a(Jg,"isNonPilotSurface");function fc(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,p])=>[dc(d),p])),o=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),s=(e.layerContexts??[]).find(d=>uc(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,p]of Object.entries(e.fileContents).sort(([g],[f])=>g.localeCompare(f))){let g=dc(d);if(Jg(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(p.slice(0,320)))continue;let f=r.has(g),m=r.get(g),u=m?o.get(m)??[]:[],h=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),k=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),C=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(p),S=/controller|handler|resolver/i.test(d)||k||C||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!h||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(p)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(p)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(p),I=f?!!(m&&Zg(m,u)&&S):S,E=f?!!(m&&uc(m,u)):/domain|entity|aggregate|model/i.test(d),H=!f||E||I;if(I&&!h){let w=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,P;for(;(P=w.exec(p))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:d,line:Kr(p,P.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:m,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let N=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,$,v=a(w=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(w)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(w)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(w)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(w)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(w)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(w)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(w)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(w)||/_(?:OID|OIDS)$/i.test(w)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(w)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(w),"isInfraMagicName"),D=a((w,P)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(w)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(w))return!0;let M=P.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(P)&&(/\s/.test(M)||/[.!?…]$/.test(M))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(w))},"isUxMessageConstant");for(;($=N.exec(p))!==null;){let w=$[2],P=$[3]??"";!H||v(w)||D(w,P)||h&&!E||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!E||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:d,line:Kr(p,$.index),message:`Magic business constant ${w} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:s,invariantId:`INV-${w}`},neverMechanicalSafe:!0}))}if(E){let w=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,P;for(;(P=w.exec(p))!==null;){let M=P[2]??"",F=(M.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(M.match(/:\s*[A-Za-z]/g)??[]).length>=2&&F<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:d,line:Kr(p,P.index),message:`Class ${P[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(E&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let P=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,M;for(;(M=P.exec(p))!==null;){let F=p.lastIndexOf("class ",M.index),re=F>=0?p.indexOf("{",F):-1,ke=F>=0&&re>=F&&re<M.index?p.slice(F,re):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(ke)||to(p,M.index))continue;let Ct=p.slice(Math.max(0,M.index-200),M.index+200);if(!Js.test(Ct)&&!Qs.test(Ct)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:Kr(p,M.index),message:`Domain field mutation without nearby ${eo()}.`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let i=new Set(e.contractedRuleIds??[]);t.sort((d,p)=>+(p.confidence==="direct-evidence")-+(d.confidence==="direct-evidence")||d.file.localeCompare(p.file)||d.line-p.line||d.kind.localeCompare(p.kind)||d.id.localeCompare(p.id));let l=new Set((e.contractedStructure??[]).map(d=>`${d.layer}\0${d.sensor}`)),c=t.filter(d=>{let p=d.suggestedArkRule;return p?p.invariantId&&i.has(p.invariantId)?!0:p.structureId?p.sensor&&l.has(`${p.layer}\0${p.sensor}`)?!0:i.has(p.structureId):!1:!1}).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).filter(Xg).length,notAScore:!0}}a(fc,"buildRulesInventory");function gc(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}a(gc,"inventoryToExtractionCard");function mc(e={}){return _r(e)}a(mc,"projectStatusArkOrder");function hc(e){return{type:"object",description:`${e} extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.`,additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}a(hc,"extraPlaneStatusSchema");var Ur="1.0",Io="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",bo=["full","subset","unavailable"],vo=["doctor-facts","report-snapshot","none"],mn={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},yc=/^sha256:[a-f0-9]{64}$/;function Eo(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!yc.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let o=e.expectedRootRelation??"unknown";return o==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:o==="exact"||o==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}a(Eo,"evaluateStatusBinding");function Co(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}a(Co,"classifyStatusWritePath");function _o(e,t){let n=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${n} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${n}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}a(_o,"defaultHonestLabel");function Ac(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(Ac,"normalizedConfigErrors");function xo(e,t,n,r,o){if(e.nextActionOverride?.id&&e.nextActionOverride.summary)return{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary};if(t.status==="mismatch")return{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."};if(t.status==="unverified"&&e.expectation)return{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."};if(!e.resolvedConfigPath)return{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."};let s=Ac(e.configErrors);return s.length>0?{id:"fix-config",summary:`The Ark config is invalid, so ark-check, MCP and ESLint refuse it \u2014 fix: ${s.slice(0,3).join("; ")}${s.length>3?` (+${s.length-3} more)`:""}`}:r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check --report to refresh the last-check snapshot (a plain check or --doctor does not update .ark/reports/latest.json).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check --report to refresh the snapshot."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report to freeze session evidence (--doctor does not write the snapshot)."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:o.arkRulesLoaded&&(o.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}}a(xo,"resolveStatusNextAction");function Rc(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&yc.test(e.projectId)?e.projectId:null,r=Eo({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,i=Co({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():_o(i,s),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:gn(e.activeViolations),frozenResidual:gn(e.frozenResidual)},d={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:gn(e.rulesInventoried),underContract:gn(e.rulesUnderContract),frozenResidual:gn(e.rulesFrozenResidual)},p={writePath:i,host:s,honestLabel:l},g={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},f={schemaVersion:Ur,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:c,rules:d,nextAction:xo(e,r,p,c,d)},m=Ac(e.configErrors);g.resolvedConfigPath&&m.length>0&&(f.contract={valid:!1,errors:m});let u=Oo(e.improvementCompass);return u&&(f.improvementCompass=u),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Vr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=mc(e.arkOrder)),f}a(Rc,"buildStatusManifest");var Sc=new Set(bo),Qg=new Set(vo);function Gr(e){let t=Sc.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Qg.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let i={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:mn.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(i.contractHash=r),i}let o=Array.isArray(e.topResidual)?e.topResidual.filter(i=>typeof i=="string"&&i.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:mn.FACTS_PARTIAL,s.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),n&&(s.factsSource=n),r&&(s.contractHash=r),s}a(Gr,"projectStatusImprovementCompass");function kc(e={}){return Gr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??mn.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --report to write the session snapshot (--doctor shows full lenses but does not write it). Status never invents green.",factsSource:"none",contractHash:e.contractHash})}a(kc,"unavailableStatusImprovementCompass");function Oo(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let n;return typeof t.mode=="string"&&Sc.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Gr({mode:n,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}a(Oo,"normalizeStatusImprovementCompass");function Ic(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let o of n)if(!(typeof o!="string"||o.length===0)&&!r.has(o))return!1;return!0}a(Ic,"statusCompassResidualIsSubsetOfDoctor");function gn(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}a(gn,"numberOrNull");var bc={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Io,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:Ur},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},contract:{type:"object",description:"Present only when the resolved config fails the shared contract validator (the same fail-closed rules ark-check, MCP and ESLint apply).",additionalProperties:!1,required:["valid","errors"],properties:{valid:{const:!1},errors:{type:"array",minItems:1,items:{type:"string",minLength:1}}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:hc("ArkRun"),arkOrder:hc("ArkOrder")}};var hn="1.0",yn=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],An=5,Ve=["scalability","resilience","security"],vt=new Set(Ve),wo={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},To={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},Po={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function No(e){return To[e]??e}a(No,"improvementCompassHumanLabel");function Lo(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}a(Lo,"smellIdOf");function $o(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}a($o,"violationRuleId");function q(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}a(q,"pushEvidence");function oe(e,t,n){vt.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}a(oe,"markResidual");function vc(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${To[e]} \u2014 no residual from current sensors.`}}a(vc,"defaultOkSummary");function Ec(){return yn.map(e=>vt.has(e)?{id:e,status:"out-of-scope",summary:Po[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:vc(e),evidence:[]}:{id:e,status:"ok",summary:vc(e),evidence:[]})}a(Ec,"createInitialImprovementCompassLenses");function em(e,t){for(let n of t){let r=Lo(n);if(!r)continue;let o=n.outcome||n.message||void 0,i=(Array.isArray(n.evidence)?n.evidence:[])[0],l=a((p,g,f)=>{let m=e.get(p);!m||vt.has(p)||(q(m,"designSmells",r,o),i&&q(m,"designSmells",i,r),oe(m,g,f))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},d={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":l("soc","Business rules still mix with UI or presentation surfaces.",c),l("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",c);break;case"facade-sql-in-routes":l("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",c),l("dip","Transport depends on concrete persistence instead of a port.",d);break;case"io-under-application":l("soc","Application/business code reaches I/O directly \u2014 separation is weak.",c),l("dip","I/O is not inverted behind ports/adapters.",d),l("testability","Direct I/O under application code hurts pure unit testing.",d);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}a(em,"mapDesignSmells");function tm(e){return e.failsStrict===!1||e.typeOnly===!0}a(tm,"isTypeOnlyPlacementDebt");function nm(e,t){for(let n of t){let r=$o(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),i=a((c,d,p)=>{let g=e.get(c);!g||vt.has(c)||(q(g,"violations",r,o),n.file&&q(g,"violations",n.file,r),oe(g,d,p))},"attach");if(tm(n)){i("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let l={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){i("coupling","Import graph edges violate the layer contract.",l);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){i("coupling","Import cycles couple modules tightly.",l);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){i("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(s==="FORBIDDEN_GLOBAL"||s.startsWith("FORBIDDEN_")){i("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),i("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(s==="CAPABILITY_VIOLATION"){i("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),i("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"||s==="INVARIANT_TESTS_PATH_MISSING"||s==="INVARIANT_COVERAGE_ROOTS_MISSING"){i("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),i("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}a(nm,"mapViolations");function rm(e,t){let n=Number(t.cycleCount)||0;if(n>0){let m=e.get("coupling");q(m,"cycles",`count:${n}`),oe(m,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let m=e.get("coupling");q(m,"peerIsolation",`count:${r}`),oe(m,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let m=e.get("cohesion");q(m,"physicalCohesion",`findings:${o}`),oe(m,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let u=e.get("srp");q(u,"physicalCohesion",`findings:${o}`),oe(u,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,i=Number(t.forbiddenGlobalResidual)||0;if(s>0||i>0){let m=e.get("dip");s>0&&q(m,"capability",`residual:${s}`),i>0&&q(m,"forbiddenGlobals",`residual:${i}`),oe(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let u=e.get("testability");s>0&&q(u,"capability",`residual:${s}`),i>0&&q(u,"forbiddenGlobals",`residual:${i}`),oe(u,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let m=e.get("encapsulation");q(m,"arkRules",`structureResidual:${l}`),oe(m,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let u=e.get("domain");q(u,"arkRules",`structureResidual:${l}`),oe(u,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let m=e.get("maintainability");q(m,"designFitness","design-weak"),oe(m,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let m=e.get("maintainability");t.dirtyBaselineRisk===!0&&q(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&q(m,"baseline",`stale:${t.baselineStale}`),oe(m,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let c=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&c>=10&&e.get("maintainability").status!=="residual"){let m=e.get("maintainability");q(m,"baseline",`frozen:${c}`),oe(m,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let d=Number(t.ungovernedDirCount)||0,p=Number(t.emptyLayerCount)||0;if(d>0||p>0){let m=e.get("modularity");d>0&&q(m,"coverage",`ungovernedDirs:${d}`),p>0&&q(m,"coverage",`emptyLayers:${p}`),oe(m,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let m=e.get("modularity");q(m,"goldenPattern","absent"),oe(m,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}a(rm,"mapCountsAndFlags");function Cc(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>Lo(r).localeCompare(Lo(o)));em(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=$o(r).localeCompare($o(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});nm(e,n)}rm(e,t)}a(Cc,"projectImprovementCompassFacts");function _c(e){for(let t of Ve){let n=e.get(t);n.status="out-of-scope",n.summary=Po[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}a(_c,"lockImprovementCompassOutOfScope");function xc(e){for(let t of e)t.evidence.sort((n,r)=>{let o=n.source.localeCompare(r.source);return o!==0?o:n.ref.localeCompare(r.ref)})}a(xc,"sortImprovementCompassEvidence");function Oc(e){return e.filter(n=>n.status==="residual"&&!vt.has(n.id)).slice().sort((n,r)=>{let o=wo[n.id]??150,s=wo[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}a(Oc,"finalizeImprovementCompassTopResidual");function wc(e={}){let t=Ec(),n=new Map(t.map(o=>[o.id,o]));Cc(n,e),_c(n),xc(t);let r=Oc(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(i=>({...i}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}a(wc,"buildImprovementCompass");function Do(e){return e.topResidual.map(t=>No(t))}a(Do,"formatImprovementCompassResidualLabels");function Fo(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}a(Fo,"primaryImprovementCompassNextAction");function Tc(e){let t=Do(e),n=Ve.map(s=>No(s)),r=Fo(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&o.push(`Next: ${r.ref} \u2014 ${r.summary}`),o}a(Tc,"formatImprovementCompassDoctorLines");var Ke="1.0",Mo="<!-- arkgate:agent-projection:begin",Rn="<!-- arkgate:agent-projection:end -->",Sn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",Et=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),jo=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]);function tt(e){let t=String(e??"").replace(/\r\n/g,`
22
+ `),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}a(tt,"agentProjectionContentIdentity");function In(e){return String(e??"").replace(/\r\n/g,`
23
+ `)}a(In,"normalizeNewlines");function nt(e){let t=In(e);return t.endsWith(`
24
24
  `)?t:`${t}
25
- `}a(Qe,"ensureTrailingNewline");function Rn(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}a(Rn,"safeVersion");function hc(e){return e==="compact"?"compact":"full"}a(hc,"resolveProfile");function Kr(e){let t=Rn(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}a(Kr,"buildAgentProjectionBeginMarker");function yn(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
25
+ `}a(nt,"ensureTrailingNewline");function bn(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}a(bn,"safeVersion");function Pc(e){return e==="compact"?"compact":"full"}a(Pc,"resolveProfile");function Br(e){let t=bn(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}a(Br,"buildAgentProjectionBeginMarker");function kn(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
26
26
  |-------|----------|-----------------|
27
27
  ${e.map(n=>{let r=n.name?.trim()||"Unknown",o=n.patterns??[],s=n.intentPrefixes??[],i=o.map(c=>`\`${c}\``).join(", ")||"\u2014",l=s.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${i} | ${l} |`}).join(`
28
- `)}`}a(yn,"formatAgentProjectionLayers");function Vr(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(o=>o&&typeof o.ruleId=="string"&&o.ruleId.length>0).map(o=>{let s=typeof o.title=="string"&&o.title.trim()?o.title.trim():o.ruleId;return`- \`${o.ruleId}\` \u2014 ${s}`}).join(`
28
+ `)}`}a(kn,"formatAgentProjectionLayers");function zr(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(o=>o&&typeof o.ruleId=="string"&&o.ruleId.length>0).map(o=>{let s=typeof o.title=="string"&&o.title.trim()?o.title.trim():o.ruleId;return`- \`${o.ruleId}\` \u2014 ${s}`}).join(`
29
29
  `)}
30
30
 
31
- Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}a(Vr,"formatAgentProjectionCatalogShortList");function Sn(e){let t=Rn(e.arkgateVersion),n=hc(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",o=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",s=typeof e.host=="string"?e.host.trim().toLowerCase():"",i=s&&s!=="unknown"?s:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],d=["## ArkGate agent contract projection","",hn,"","Contener \xB7 Guiar \xB7 Ordenar \u2014 contain the write, guide the next step, order leftover mess. Skills never enforce.","",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,`- **projectionSchema:** \`${"1.0"}\``,`- **profile:** \`${n}\`${i?` \xB7 **host:** \`${i}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?d.push("### Primary path","","1. Run doctor (`ark-check --doctor`) \u2014 what is wrong and what to do first. Prefer the project-local CLI; do not wait on MCP \u201Cstill connecting\u201D.","2. Name leftover work in plain language; never \u201Cdone\u201D on green imports alone while leftover design work remains.","3. Identity handshake is optional when the CLI already resolved the project root. Call `ark_identity` only when using MCP evidence.","4. Read the rules file with `ark_manifest` (same expectation) or the local `ark.config.json`. `ark://manifest` is compatibility-only / unverified.","5. Place files inside configured layers; validate; run the check command above on violations \u2014 fix the import, do not weaken the rules file.","6. Single door: illegal imports \u2192 fix; leftover design work \u2192 map then one small refactor with user OK.","","### Layers (summary)","",yn(l),""):d.push("### Contract layers","",yn(l),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",Vr(c,o),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),d.push("### Enforcement surfaces (authoritative)","",At.map(u=>`- \`${u}\``).join(`
31
+ Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}a(zr,"formatAgentProjectionCatalogShortList");function vn(e){let t=bn(e.arkgateVersion),n=Pc(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",o=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",s=typeof e.host=="string"?e.host.trim().toLowerCase():"",i=s&&s!=="unknown"?s:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],d=["## ArkGate agent contract projection","",Sn,"","Contener \xB7 Guiar \xB7 Ordenar \u2014 contain the write, guide the next step, order leftover mess. Skills never enforce.","",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,`- **projectionSchema:** \`${"1.0"}\``,`- **profile:** \`${n}\`${i?` \xB7 **host:** \`${i}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?d.push("### Primary path","","1. Run doctor (`ark-check --doctor`) \u2014 what is wrong and what to do first. Prefer the project-local CLI; do not wait on MCP \u201Cstill connecting\u201D.","2. Name leftover work in plain language; never \u201Cdone\u201D on green imports alone while leftover design work remains.","3. Identity handshake is optional when the CLI already resolved the project root. Call `ark_identity` only when using MCP evidence.","4. Read the rules file with `ark_manifest` (same expectation) or the local `ark.config.json`. `ark://manifest` is compatibility-only / unverified.","5. Place files inside configured layers; validate; run the check command above on violations \u2014 fix the import, do not weaken the rules file.","6. Single door: illegal imports \u2192 fix; leftover design work \u2192 map then one small refactor with user OK.","","### Layers (summary)","",kn(l),""):d.push("### Contract layers","",kn(l),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",zr(c,o),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),d.push("### Enforcement surfaces (authoritative)","",Et.map(p=>`- \`${p}\``).join(`
32
32
  `),""),d.join(`
33
33
  `).replace(/\n{3,}/g,`
34
34
 
35
35
  `).trimEnd()+`
36
- `}a(Sn,"buildAgentProjectionBody");function $o(e){let t=Sn(e);return`${Kr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
37
- ${t}${mn}
38
- `}a($o,"buildAgentProjectionBlock");function Mo(e){let t=Sn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Rn(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...At],contentIdentity:Je(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:hc(e.profile)}}a(Mo,"buildAgentProjectionMeta");var Fo=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,yc=/<!--\s*arkgate:agent-projection:end\s*-->/i,Ng=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Pg=/\bschema=([A-Za-z0-9._+-]+)/i;function kn(e){let t=An(e??""),n=Fo.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,o=r+n[0].length,s=t.slice(o),i=yc.exec(s);if(!i)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=i.index,c=l+i[0].length,d=s.slice(0,l);d.startsWith(`
39
- `)&&(d=d.slice(1));let u=t.slice(r,o+c),m=s.slice(c);return{block:u,body:d,before:t.slice(0,r),after:m,beginAttrs:n[1]??""}}a(kn,"extractAgentProjectionBlock");function Ur(e){let t=String(e??""),r=Fo.exec(t)?.[1]??t,o=Ng.exec(r),s=Pg.exec(r),i=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:i}}a(Ur,"parseAgentProjectionStamp");function jo(e,t){let n=Ur(e).arkgateVersion;return n?n===Rn(t):!1}a(jo,"projectionMatchesPackageVersion");function Ho(e){return String(e??"").includes("non-authoritative")}a(Ho,"projectionHasNonEnforcementLabel");function Ko(e,t){let n=Qe(An(t)),o=kn(n).body??n.replace(Fo,"").replace(yc,"").trim()+`
40
- `,s=Je(o);if(e==null||!String(e).trim())return{content:Qe(`# Ark Enforcement
36
+ `}a(vn,"buildAgentProjectionBody");function Ho(e){let t=vn(e);return`${Br({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
37
+ ${t}${Rn}
38
+ `}a(Ho,"buildAgentProjectionBlock");function Vo(e){let t=vn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:bn(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...Et],contentIdentity:tt(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:Pc(e.profile)}}a(Vo,"buildAgentProjectionMeta");var Ko=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Nc=/<!--\s*arkgate:agent-projection:end\s*-->/i,sm=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,om=/\bschema=([A-Za-z0-9._+-]+)/i;function En(e){let t=In(e??""),n=Ko.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,o=r+n[0].length,s=t.slice(o),i=Nc.exec(s);if(!i)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=i.index,c=l+i[0].length,d=s.slice(0,l);d.startsWith(`
39
+ `)&&(d=d.slice(1));let p=t.slice(r,o+c),g=s.slice(c);return{block:p,body:d,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}a(En,"extractAgentProjectionBlock");function Wr(e){let t=String(e??""),r=Ko.exec(t)?.[1]??t,o=sm.exec(r),s=om.exec(r),i=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:i}}a(Wr,"parseAgentProjectionStamp");function Uo(e,t){let n=Wr(e).arkgateVersion;return n?n===bn(t):!1}a(Uo,"projectionMatchesPackageVersion");function Go(e){return String(e??"").includes("non-authoritative")}a(Go,"projectionHasNonEnforcementLabel");function Bo(e,t){let n=nt(In(t)),o=En(n).body??n.replace(Ko,"").replace(Nc,"").trim()+`
40
+ `,s=tt(o);if(e==null||!String(e).trim())return{content:nt(`# Ark Enforcement
41
41
 
42
- ${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let i=An(e),l=kn(i);if(l.block!=null){let d=l.body??"";if(Je(d)===s)return{content:Qe(i),action:"unchanged",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0};let u=l.before.replace(/\s*$/,`
42
+ ${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let i=In(e),l=En(i);if(l.block!=null){let d=l.body??"";if(tt(d)===s)return{content:nt(i),action:"unchanged",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0};let p=l.before.replace(/\s*$/,`
43
43
 
44
- `),m=l.after.replace(/^\s*/,`
45
- `);return{content:Qe(`${u}${n.trimEnd()}
46
- ${m}`),action:"block-replaced",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(i);if(c&&c.index!=null){let d=c.index+c[1].length,u=i.slice(0,d).replace(/\s*$/,`
44
+ `),g=l.after.replace(/^\s*/,`
45
+ `);return{content:nt(`${p}${n.trimEnd()}
46
+ ${g}`),action:"block-replaced",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(i);if(c&&c.index!=null){let d=c.index+c[1].length,p=i.slice(0,d).replace(/\s*$/,`
47
47
 
48
- `),m=i.slice(d).replace(/^\s*/,`
49
- `);return{content:Qe(`${u}${n.trimEnd()}
50
- ${m}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:Qe(`${n.trimEnd()}
48
+ `),g=i.slice(d).replace(/^\s*/,`
49
+ `);return{content:nt(`${p}${n.trimEnd()}
50
+ ${g}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:nt(`${n.trimEnd()}
51
51
 
52
- ${i.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}a(Ko,"mergeAgentProjectionDocument");var kc="1.0",Vo="templates/agent-skills",Uo="templates/skills",Go="SKILL.md",Ic=Object.freeze(["Contener","Guiar","Ordenar"]),Wr=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),Gr=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),In=Object.freeze({Layers:["ark-adopt","ark-place","ark-explore","ark-autopilot","ark-coverage","ark-explain"],ArkRules:["ark-adopt","ark-explore","ark-autopilot"],ArkRun:["ark-adopt","ark-runtime","ark-place","ark-autopilot"],ArkOrder:["ark-adopt","ark-order","ark-place","ark-autopilot"],Contener:["ark-adopt","ark-place","ark-upgrade"],Guiar:["ark-explore","ark-autopilot","ark-explain","ark-coverage","ark-runtime"],Ordenar:["ark-order"]}),En=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),Bo=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),Ac="Contener \xB7 Guiar \xB7 Ordenar",Rc="Do not invent `/ark-order`",bn=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-order","ark-place","ark-runtime","ark-think","ark-upgrade"]),zo=bn.length,Dg=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Wo(e){return typeof e!="string"||e.length<1||e.length>64?!1:Dg.test(e)}a(Wo,"isValidAgentSkillName");function qr(e){return bn.includes(e)}a(qr,"isArkSkillName");function Br(e){return Wr.includes(e)}a(Br,"isFirstClassArkSkillName");function Ec(e){return e in Gr?Gr[e]:null}a(Ec,"arkSkillStubRedirect");function qo(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
52
+ ${i.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}a(Bo,"mergeAgentProjectionDocument");var Fc="1.0",zo="templates/agent-skills",Wo="templates/skills",qo="SKILL.md",Mc=Object.freeze(["Contener","Guiar","Ordenar"]),Zr=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),qr=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),Cn=Object.freeze({Layers:["ark-adopt","ark-place","ark-explore","ark-autopilot","ark-coverage","ark-explain"],ArkRules:["ark-adopt","ark-explore","ark-autopilot"],ArkRun:["ark-adopt","ark-runtime","ark-place","ark-autopilot"],ArkOrder:["ark-adopt","ark-order","ark-place","ark-autopilot"],Contener:["ark-adopt","ark-place","ark-upgrade"],Guiar:["ark-explore","ark-autopilot","ark-explain","ark-coverage","ark-runtime"],Ordenar:["ark-order"]}),_n=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),Yo=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),Lc="Contener \xB7 Guiar \xB7 Ordenar",$c="Do not invent `/ark-order`",xn=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-order","ark-place","ark-runtime","ark-think","ark-upgrade"]),Xo=xn.length,im=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Zo(e){return typeof e!="string"||e.length<1||e.length>64?!1:im.test(e)}a(Zo,"isValidAgentSkillName");function Jr(e){return xn.includes(e)}a(Jr,"isArkSkillName");function Yr(e){return Zr.includes(e)}a(Yr,"isFirstClassArkSkillName");function jc(e){return e in qr?qr[e]:null}a(jc,"arkSkillStubRedirect");function Jo(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
53
53
  `)?`\r
54
54
  `:`
55
- `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let u=1;u<o;u+=1){let m=r[u]??"";if(m.trim()===""||m.trimStart().startsWith("#"))continue;let f=m.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let h=f[1],p=f[2]??"";(p.startsWith('"')&&p.endsWith('"')&&p.length>=2||p.startsWith("'")&&p.endsWith("'")&&p.length>=2)&&(p=p.slice(1,-1)),s[h]=p}let i=r.slice(o+1).join(n),l=typeof s.name=="string"&&s.name.length>0?s.name:null,c=typeof s.description=="string"&&s.description.length>0?s.description:null,d=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:l,description:c,license:d},body:i}}a(qo,"parseSkillDocument");function Yo(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=qo(e.content);if(!s.hasFrontmatter||!s.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${o}" is missing YAML frontmatter fences.`,skillName:o||void 0}),r;let{name:i,description:l}=s.frontmatter,c=i??(o||void 0);return!i||!Wo(i)?r.push({code:"INVALID_NAME",message:`Skill name "${i??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):i!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${i}" must match directory name "${o}".`,skillName:i}):t&&!qr(i)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${i}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:i}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${o}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${o}" is missing a non-empty description.`,skillName:c}),n&&s.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${o}" has an empty instruction body.`,skillName:c}),r}a(Yo,"validateAgentSkillDocument");function bc(e){let t=[],n=new Set,r=[];for(let o of e){let s=String(o.name??"");if(n.has(s)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${s}".`,skillName:s});continue}n.add(s),r.push(s),t.push(...Yo({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&zr(o.content)!==zr(o.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${s}" does not match flat template templates/skills/${s}.md.`,skillName:s})}for(let o of bn)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)qr(o)||(t.some(s=>s.code==="UNKNOWN_SKILL_NAME"&&s.skillName===o)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:zo,presentCount:r.length}}a(bc,"validateAgentSkillsPackage");function fe(e,t){e.push(t)}a(fe,"pushCapacityIssue");function Sc(e,t){return e.includes(t)}a(Sc,"skillMentionsSurface");function vc(e){let t=[],n=e.skills??{},r=Object.keys(In);for(let s of En)r.includes(s)||fe(t,{code:"CAPACITY_SURFACE_MISSING",surface:s,message:`The capacity table dropped ${s}. Skills must keep covering Layers, ArkRules, ArkRun, ArkOrder plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back on ARK_SKILL_CAPACITY.`});for(let s of r)En.includes(s)||fe(t,{code:"CAPACITY_SURFACE_UNMAPPED",surface:s,message:`The capacity table lists ${s}, which is not a product surface. Keep the table to Layers, ArkRules, ArkRun, ArkOrder and Contener \xB7 Guiar \xB7 Ordenar.`});for(let s of En){let i=In[s];if(!i||i.length===0)continue;for(let c of i)Br(c)||fe(t,{code:"CAPACITY_DOOR_NOT_FIRST_CLASS",surface:s,skillName:c,message:`/${c} is listed for ${s} but is not a first-class door. Leftover names are shortcuts. Point ${s} at a first-class skill.`});i.filter(c=>{let d=n[c];return typeof d=="string"&&Sc(d,s)}).length===0&&fe(t,{code:"CAPACITY_BODY_GAP",surface:s,message:`Skills no longer cover ${s}. The product has four parts (Layers, ArkRules, ArkRun, ArkOrder) plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back in a first-class skill${s==="ArkOrder"||s==="Ordenar"?" \u2014 usually /ark-order":s==="ArkRun"?" \u2014 usually /ark-runtime":""} so agents still know when to use it.`})}for(let[s,i]of Object.entries(Bo)){if(!In[s]?.includes(i)||!Br(i)){fe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:i,message:`/${i} is the first-class door for ${s}. Keep it on that surface. Leftover names like /ark-think are shortcuts, not a replacement.`});continue}let c=n[i];(typeof c!="string"||!Sc(c,s))&&fe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:i,message:`/${i} no longer talks about ${s}. That door is how agents reach this part of the product. Put ${s} back in the skill body.`})}for(let s of Wr){let i=n[s];if(typeof i!="string"){fe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is a first-class door but has no skill body in this check. Ship the template so agents know when to use it.`});continue}let l=i.includes(Ac),c=/When \/ not when|\*\*When:\*\*/.test(i),d=/Not when|Do \*\*not\*\* use|Prefer instead/.test(i),u=/Handoff|hand off|`\/ark-/i.test(i);(!l||!c||!d||!u)&&fe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is missing when / not when / handoff or Contener \xB7 Guiar \xB7 Ordenar. First-class skills must say when to use them and which sibling to call next.`}),i.includes(Rc)&&fe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}let o=e.hubs??{};for(let[s,i]of Object.entries(o)){let l=String(i??"");l.includes("/ark-order")||fe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer names /ark-order. Host instructions must stay at 100% of the product. Add /ark-order back, or you left the order plane behind.`}),l.includes(Ac)||fe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer says Contener \xB7 Guiar \xB7 Ordenar. Keep that filter in the living docs so agents pick the right sibling.`}),l.includes(Rc)&&fe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}return{ok:t.length===0,issues:t}}a(vc,"validateSkillProductCapacity");var Yr=/^arkgate@(\S+)\.\s/;function Xo(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}a(Xo,"skillDescriptionVersionPrefix");function Zo(e){return String(e??"").replace(Yr,"")}a(Zo,"stripSkillDescriptionVersion");function Cc(e){return String(e??"").match(Yr)?.[1]??null}a(Cc,"parseSkillDescriptionVersion");function _c(e,t){let n=Zo(e),r=typeof t=="string"?t.trim():"";return r?`${Xo(r)}${n}`:n}a(_c,"stampSkillDescription");function zr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
56
- `)}a(zr,"normalizeSkillContent");function Jo(e){return`${e}/${Go}`}a(Jo,"agentSkillEntryRelativePath");function xc(e){return`${Vo}/${Jo(e)}`}a(xc,"agentSkillPackageFileRelativePath");function Oc(e){return`${Uo}/${e}.md`}a(Oc,"flatSkillTemplateFileRelativePath");0&&(module.exports={ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,AGENT_PROJECTION_BEGIN_MARKER,AGENT_PROJECTION_END_MARKER,AGENT_PROJECTION_ENFORCEMENT_SURFACES,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,AGENT_SKILL_ENTRY_FILENAME,ANALYSIS_IR_SCHEMA_VERSION,ARKORDER_RULE_IDS,ARKORDER_TIER1_SENSOR_IDS,ARKRUN_INTERACTION_NAME_INCOMPLETE,ARKRUN_KERNEL_FACTORY_CALLEES,ARKRUN_KERNEL_INTERACTION_CALLEES,ARKRUN_RULE_IDS,ARKRUN_TIER1_SENSOR_IDS,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,ARK_AGENT_PROJECTION_SCHEMA_VERSION,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_FIRST_CLASS_SKILL_NAMES,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,ARK_PROJECT_IDENTITY_SCHEMA,ARK_PROJECT_IDENTITY_SCHEMA_URL,ARK_PROJECT_IDENTITY_SCHEMA_VERSION,ARK_RULES_SCHEMA,ARK_RULES_SCHEMA_VERSION,ARK_RULE_SENSORS,ARK_RUN_DOCTOR_SCHEMA_VERSION,ARK_SKILL_CAPACITY,ARK_SKILL_CAPACITY_DEDICATED_DOORS,ARK_SKILL_DESCRIPTION_VERSION_PATTERN,ARK_SKILL_NAMES,ARK_SKILL_NAME_COUNT,ARK_SKILL_NORTH_STAR,ARK_SKILL_REQUIRED_SURFACES,ARK_SKILL_STUB_REDIRECTS,ARK_STATUS_MANIFEST_SCHEMA,ARK_STATUS_MANIFEST_SCHEMA_URL,ARK_STATUS_MANIFEST_SCHEMA_VERSION,ArkRulesValidationError,DEFAULT_AGENT_PROJECTION_RULE_IDS,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EXTRA_MERGE_TEETH_GOVERNED_FLOOR,EffectiveContractError,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,IMPROVEMENT_LENS_IDS,MERGE_PLANES_DUAL_STAMP,POLICY_DELTA_SCHEMA_VERSION,PROJECT_BINDING_SCHEMA,PROJECT_EXPECTATION_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,STATUS_COMPASS_FACTS_SOURCES,STATUS_COMPASS_MODES,STATUS_COMPASS_REASON_CODES,adapterDocsCodePath,adapterFindingOccurrenceTargetKeys,adapterFindingRefFromTargetKey,adapterFindingTargetKey,agentProjectionContentIdentity,agentSkillEntryRelativePath,agentSkillPackageFileRelativePath,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,arkRunKernelCallKind,arkSkillStubRedirect,buildAgentProjectionBeginMarker,buildAgentProjectionBlock,buildAgentProjectionBody,buildAgentProjectionMeta,buildArkRuleFileHints,buildEffectiveArkRules,buildImprovementCompass,buildRulesInventory,buildStatusManifest,canPromoteInvariant,catalogFixForRuleId,catalogWhyForRuleId,classifyArkPolicyDelta,classifyCoverage,classifyResolvedLayerCoverage,classifyStatusWritePath,collectAnalysisConfigWarnings,collectEmptyAppliesToFindings,collectForbiddenCapabilityUses,composeMergePlanesHonesty,countsAsCoverage,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createProjectId,createProjectIdentity,createResolvedCandidateFacts,defaultHonestLabel,demoteExtraPlaneTeethUnderClassificationFloor,deriveArkRuleFileHints,describeCoverage,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,effectiveContractPolicyPayload,elevenLayerProfile,emptyEffectiveArkRules,evaluateArchitectureGraph,evaluateArkOrderSensors,evaluateArkRuleSensors,evaluateArkRunEditorSensors,evaluateArkRunEditorSensorsFromSource,evaluateArkRunSensors,evaluateInvariantCoverage,evaluateStatusBinding,explainViolation,extraMergeTeethAllowed,extractAgentProjectionBlock,extractArkRunDeclarationsFromSource,extractArkRunImportedConstructorNamesFromSource,extractArkRunKernelCallsFromSource,extractArkRunManagedNewsFromSource,extractArkRunValueImportDependenciesFromSource,extractClassShapesFromSource,extractSemanticDependencies,flatSkillTemplateFileRelativePath,formatAgentProjectionCatalogShortList,formatAgentProjectionLayers,formatArkRunDoctorLines,formatImprovementCompassDoctorLines,formatImprovementCompassResidualLabels,getDiagnosticCatalogEntry,inventoryToExtractionCard,isArkOrderRuleId,isArkRunKernelModuleSpecifier,isArkRunRuleId,isArkRunTransportBypassSpecifier,isArkSkillName,isCataloguedOrArkRuleFamily,isExtraPlaneFinding,isFirstClassArkSkillName,isKnownDiagnosticCode,isValidAgentSkillName,loadArkConfigContract,loadArkRulesContract,loadContract,loadResolvedCandidateFacts,mergeAgentProjectionDocument,normalizeExtraMergeTeethClassification,normalizeSkillContent,normalizeStatusImprovementCompass,parseAgentProjectionStamp,parseArkConfigJson,parseArkRulesJson,parseSkillDescriptionVersion,parseSkillDocument,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,primaryImprovementCompassNextAction,projectStatusArkRun,projectStatusImprovementCompass,projectionHasNonEnforcementLabel,projectionMatchesPackageVersion,resolveEffectiveContract,resolveStatusNextAction,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,skillDescriptionVersionPrefix,stableSerialize,stampSkillDescription,statusCompassResidualIsSubsetOfDoctor,stripSkillDescriptionVersion,summarizeArkRunSection,toAdapterDiagnostic,unavailableStatusImprovementCompass,validateAgentSkillDocument,validateAgentSkillsPackage,validateSkillProductCapacity,version});
55
+ `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let p=1;p<o;p+=1){let g=r[p]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let f=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let m=f[1],u=f[2]??"";(u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1)),s[m]=u}let i=r.slice(o+1).join(n),l=typeof s.name=="string"&&s.name.length>0?s.name:null,c=typeof s.description=="string"&&s.description.length>0?s.description:null,d=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:l,description:c,license:d},body:i}}a(Jo,"parseSkillDocument");function Qo(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=Jo(e.content);if(!s.hasFrontmatter||!s.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${o}" is missing YAML frontmatter fences.`,skillName:o||void 0}),r;let{name:i,description:l}=s.frontmatter,c=i??(o||void 0);return!i||!Zo(i)?r.push({code:"INVALID_NAME",message:`Skill name "${i??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):i!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${i}" must match directory name "${o}".`,skillName:i}):t&&!Jr(i)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${i}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:i}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${o}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${o}" is missing a non-empty description.`,skillName:c}),n&&s.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${o}" has an empty instruction body.`,skillName:c}),r}a(Qo,"validateAgentSkillDocument");function Hc(e){let t=[],n=new Set,r=[];for(let o of e){let s=String(o.name??"");if(n.has(s)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${s}".`,skillName:s});continue}n.add(s),r.push(s),t.push(...Qo({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&Xr(o.content)!==Xr(o.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${s}" does not match flat template templates/skills/${s}.md.`,skillName:s})}for(let o of xn)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)Jr(o)||(t.some(s=>s.code==="UNKNOWN_SKILL_NAME"&&s.skillName===o)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:Xo,presentCount:r.length}}a(Hc,"validateAgentSkillsPackage");function fe(e,t){e.push(t)}a(fe,"pushCapacityIssue");function Dc(e,t){return e.includes(t)}a(Dc,"skillMentionsSurface");function Vc(e){let t=[],n=e.skills??{},r=Object.keys(Cn);for(let s of _n)r.includes(s)||fe(t,{code:"CAPACITY_SURFACE_MISSING",surface:s,message:`The capacity table dropped ${s}. Skills must keep covering Layers, ArkRules, ArkRun, ArkOrder plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back on ARK_SKILL_CAPACITY.`});for(let s of r)_n.includes(s)||fe(t,{code:"CAPACITY_SURFACE_UNMAPPED",surface:s,message:`The capacity table lists ${s}, which is not a product surface. Keep the table to Layers, ArkRules, ArkRun, ArkOrder and Contener \xB7 Guiar \xB7 Ordenar.`});for(let s of _n){let i=Cn[s];if(!i||i.length===0)continue;for(let c of i)Yr(c)||fe(t,{code:"CAPACITY_DOOR_NOT_FIRST_CLASS",surface:s,skillName:c,message:`/${c} is listed for ${s} but is not a first-class door. Leftover names are shortcuts. Point ${s} at a first-class skill.`});i.filter(c=>{let d=n[c];return typeof d=="string"&&Dc(d,s)}).length===0&&fe(t,{code:"CAPACITY_BODY_GAP",surface:s,message:`Skills no longer cover ${s}. The product has four parts (Layers, ArkRules, ArkRun, ArkOrder) plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back in a first-class skill${s==="ArkOrder"||s==="Ordenar"?" \u2014 usually /ark-order":s==="ArkRun"?" \u2014 usually /ark-runtime":""} so agents still know when to use it.`})}for(let[s,i]of Object.entries(Yo)){if(!Cn[s]?.includes(i)||!Yr(i)){fe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:i,message:`/${i} is the first-class door for ${s}. Keep it on that surface. Leftover names like /ark-think are shortcuts, not a replacement.`});continue}let c=n[i];(typeof c!="string"||!Dc(c,s))&&fe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:i,message:`/${i} no longer talks about ${s}. That door is how agents reach this part of the product. Put ${s} back in the skill body.`})}for(let s of Zr){let i=n[s];if(typeof i!="string"){fe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is a first-class door but has no skill body in this check. Ship the template so agents know when to use it.`});continue}let l=i.includes(Lc),c=/When \/ not when|\*\*When:\*\*/.test(i),d=/Not when|Do \*\*not\*\* use|Prefer instead/.test(i),p=/Handoff|hand off|`\/ark-/i.test(i);(!l||!c||!d||!p)&&fe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is missing when / not when / handoff or Contener \xB7 Guiar \xB7 Ordenar. First-class skills must say when to use them and which sibling to call next.`}),i.includes($c)&&fe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}let o=e.hubs??{};for(let[s,i]of Object.entries(o)){let l=String(i??"");l.includes("/ark-order")||fe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer names /ark-order. Host instructions must stay at 100% of the product. Add /ark-order back, or you left the order plane behind.`}),l.includes(Lc)||fe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer says Contener \xB7 Guiar \xB7 Ordenar. Keep that filter in the living docs so agents pick the right sibling.`}),l.includes($c)&&fe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}return{ok:t.length===0,issues:t}}a(Vc,"validateSkillProductCapacity");var Qr=/^arkgate@(\S+)\.\s/;function ei(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}a(ei,"skillDescriptionVersionPrefix");function ti(e){return String(e??"").replace(Qr,"")}a(ti,"stripSkillDescriptionVersion");function Kc(e){return String(e??"").match(Qr)?.[1]??null}a(Kc,"parseSkillDescriptionVersion");function Uc(e,t){let n=ti(e),r=typeof t=="string"?t.trim():"";return r?`${ei(r)}${n}`:n}a(Uc,"stampSkillDescription");function Xr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
56
+ `)}a(Xr,"normalizeSkillContent");function ni(e){return`${e}/${qo}`}a(ni,"agentSkillEntryRelativePath");function Gc(e){return`${zo}/${ni(e)}`}a(Gc,"agentSkillPackageFileRelativePath");function Bc(e){return`${Wo}/${e}.md`}a(Bc,"flatSkillTemplateFileRelativePath");0&&(module.exports={ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,AGENT_PROJECTION_BEGIN_MARKER,AGENT_PROJECTION_END_MARKER,AGENT_PROJECTION_ENFORCEMENT_SURFACES,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,AGENT_SKILL_ENTRY_FILENAME,ANALYSIS_IR_SCHEMA_VERSION,ARKORDER_RULE_IDS,ARKORDER_TIER1_SENSOR_IDS,ARKRUN_INTERACTION_NAME_INCOMPLETE,ARKRUN_KERNEL_FACTORY_CALLEES,ARKRUN_KERNEL_INTERACTION_CALLEES,ARKRUN_RULE_IDS,ARKRUN_TIER1_SENSOR_IDS,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,ARK_AGENT_PROJECTION_SCHEMA_VERSION,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_FIRST_CLASS_SKILL_NAMES,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,ARK_PROJECT_IDENTITY_SCHEMA,ARK_PROJECT_IDENTITY_SCHEMA_URL,ARK_PROJECT_IDENTITY_SCHEMA_VERSION,ARK_RULES_SCHEMA,ARK_RULES_SCHEMA_VERSION,ARK_RULE_SENSORS,ARK_RUN_DOCTOR_SCHEMA_VERSION,ARK_SKILL_CAPACITY,ARK_SKILL_CAPACITY_DEDICATED_DOORS,ARK_SKILL_DESCRIPTION_VERSION_PATTERN,ARK_SKILL_NAMES,ARK_SKILL_NAME_COUNT,ARK_SKILL_NORTH_STAR,ARK_SKILL_REQUIRED_SURFACES,ARK_SKILL_STUB_REDIRECTS,ARK_STATUS_MANIFEST_SCHEMA,ARK_STATUS_MANIFEST_SCHEMA_URL,ARK_STATUS_MANIFEST_SCHEMA_VERSION,ArkRulesValidationError,DEFAULT_AGENT_PROJECTION_RULE_IDS,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EXTRA_MERGE_TEETH_GOVERNED_FLOOR,EffectiveContractError,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,IMPROVEMENT_LENS_IDS,MERGE_PLANES_DUAL_STAMP,POLICY_DELTA_SCHEMA_VERSION,PROJECT_BINDING_SCHEMA,PROJECT_EXPECTATION_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,STATUS_COMPASS_FACTS_SOURCES,STATUS_COMPASS_MODES,STATUS_COMPASS_REASON_CODES,adapterDocsCodePath,adapterFindingOccurrenceTargetKeys,adapterFindingRefFromTargetKey,adapterFindingTargetKey,agentProjectionContentIdentity,agentSkillEntryRelativePath,agentSkillPackageFileRelativePath,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,arkRunKernelCallKind,arkSkillStubRedirect,buildAgentProjectionBeginMarker,buildAgentProjectionBlock,buildAgentProjectionBody,buildAgentProjectionMeta,buildArkRuleFileHints,buildEffectiveArkRules,buildImprovementCompass,buildRulesInventory,buildStatusManifest,canPromoteInvariant,catalogFixForRuleId,catalogWhyForRuleId,classifyArkPolicyDelta,classifyCoverage,classifyResolvedLayerCoverage,classifyStatusWritePath,collectAnalysisConfigWarnings,collectEmptyAppliesToFindings,collectForbiddenCapabilityUses,composeMergePlanesHonesty,countsAsCoverage,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createProjectId,createProjectIdentity,createResolvedCandidateFacts,defaultHonestLabel,demoteExtraPlaneTeethUnderClassificationFloor,deriveArkRuleFileHints,describeCoverage,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,effectiveContractPolicyPayload,elevenLayerProfile,emptyEffectiveArkRules,evaluateArchitectureGraph,evaluateArkOrderSensors,evaluateArkRuleSensors,evaluateArkRunEditorSensors,evaluateArkRunEditorSensorsFromSource,evaluateArkRunSensors,evaluateInvariantCoverage,evaluateStatusBinding,explainViolation,extraMergeTeethAllowed,extractAgentProjectionBlock,extractArkRunDeclarationsFromSource,extractArkRunImportedConstructorNamesFromSource,extractArkRunKernelCallsFromSource,extractArkRunManagedNewsFromSource,extractArkRunValueImportDependenciesFromSource,extractClassShapesFromSource,extractSemanticDependencies,flatSkillTemplateFileRelativePath,formatAgentProjectionCatalogShortList,formatAgentProjectionLayers,formatArkRunDoctorLines,formatImprovementCompassDoctorLines,formatImprovementCompassResidualLabels,getDiagnosticCatalogEntry,inventoryToExtractionCard,isArkOrderRuleId,isArkRunKernelModuleSpecifier,isArkRunRuleId,isArkRunTransportBypassSpecifier,isArkSkillName,isCataloguedOrArkRuleFamily,isExtraPlaneFinding,isFirstClassArkSkillName,isKnownDiagnosticCode,isValidAgentSkillName,loadArkConfigContract,loadArkRulesContract,loadContract,loadResolvedCandidateFacts,mergeAgentProjectionDocument,normalizeExtraMergeTeethClassification,normalizeSkillContent,normalizeStatusImprovementCompass,parseAgentProjectionStamp,parseArkConfigJson,parseArkRulesJson,parseSkillDescriptionVersion,parseSkillDocument,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,primaryImprovementCompassNextAction,projectStatusArkRun,projectStatusImprovementCompass,projectionHasNonEnforcementLabel,projectionMatchesPackageVersion,resolveEffectiveContract,resolveStatusNextAction,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,skillDescriptionVersionPrefix,stableSerialize,stampSkillDescription,statusCompassResidualIsSubsetOfDoctor,stripSkillDescriptionVersion,summarizeArkRunSection,toAdapterDiagnostic,unavailableStatusImprovementCompass,validateAgentSkillDocument,validateAgentSkillsPackage,validateSkillProductCapacity,version});