arkgate 4.8.22 → 4.8.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +7 -5
  3. package/bin/ark-check-runtime.mjs +27 -78
  4. package/bin/ark-dashboard.mjs +56 -53
  5. package/bin/ark-layer-match.mjs +1117 -38
  6. package/bin/ark-mcp-runtime.mjs +412 -138
  7. package/bin/ark-mcp.mjs +68 -4
  8. package/bin/ark-shared.mjs +39 -0
  9. package/bin/ark.mjs +65 -97
  10. package/bin/lib/adapter-contract-types.mjs +5 -0
  11. package/bin/lib/adapter-contract.mjs +15 -0
  12. package/bin/lib/agent-projection-command.mjs +5 -1
  13. package/bin/lib/analysis-engine.mjs +15 -11
  14. package/bin/lib/architecture-scan.mjs +50 -6
  15. package/bin/lib/ark-order-doctor.mjs +1 -1
  16. package/bin/lib/ark-order-facts.mjs +410 -15
  17. package/bin/lib/ark-order-invariants.mjs +51 -9
  18. package/bin/lib/ark-order-sensors.mjs +28 -101
  19. package/bin/lib/ark-order-types.mjs +2 -0
  20. package/bin/lib/ark-run-doctor.mjs +14 -0
  21. package/bin/lib/ark-run-facts.mjs +434 -11
  22. package/bin/lib/ark-run-sensors.mjs +5 -3
  23. package/bin/lib/arkgate-pins.mjs +91 -0
  24. package/bin/lib/arkrules-sensors.mjs +50 -249
  25. package/bin/lib/check-args.mjs +23 -1
  26. package/bin/lib/ci-and-commands.mjs +16 -6
  27. package/bin/lib/class-source-scan.mjs +479 -0
  28. package/bin/lib/codex-home.mjs +4 -2
  29. package/bin/lib/config-contract-slices.mjs +701 -0
  30. package/bin/lib/config-contract.mjs +5 -2
  31. package/bin/lib/config-warnings.mjs +32 -0
  32. package/bin/lib/dashboard-cli.mjs +62 -0
  33. package/bin/lib/design-delta.mjs +1 -1
  34. package/bin/lib/diagnostic-catalog.mjs +45 -6
  35. package/bin/lib/doctor-advisories.mjs +84 -1
  36. package/bin/lib/doctor-next-actions.mjs +17 -2
  37. package/bin/lib/doctor-plan.mjs +7 -9
  38. package/bin/lib/effective-contract-load.mjs +121 -59
  39. package/bin/lib/enforcement-honesty.mjs +22 -0
  40. package/bin/lib/enforcement-profiles.mjs +40 -4
  41. package/bin/lib/first-run-help.mjs +3 -2
  42. package/bin/lib/flat-parent-importers.mjs +137 -0
  43. package/bin/lib/flat-parent-pilot.mjs +192 -0
  44. package/bin/lib/gate-files.mjs +29 -2
  45. package/bin/lib/git-change-scope.mjs +109 -0
  46. package/bin/lib/github-enforcement.mjs +1 -1
  47. package/bin/lib/hook-templates.mjs +18 -16
  48. package/bin/lib/host-support-matrix.mjs +3 -1
  49. package/bin/lib/html-report-advisories.mjs +2 -0
  50. package/bin/lib/html-report-depth.mjs +3 -1
  51. package/bin/lib/import-resolve.mjs +13 -1
  52. package/bin/lib/install-migrate.mjs +50 -73
  53. package/bin/lib/invariant-coverage.mjs +59 -11
  54. package/bin/lib/mcp-adoption.mjs +9 -1
  55. package/bin/lib/mcp-hook-payload.mjs +401 -61
  56. package/bin/lib/package-manager.mjs +59 -1
  57. package/bin/lib/passthrough-commands.mjs +83 -0
  58. package/bin/lib/persistence-write-hint.mjs +81 -0
  59. package/bin/lib/physical-cohesion.mjs +16 -18
  60. package/bin/lib/pilot-loop.mjs +21 -8
  61. package/bin/lib/pin-dependent-gates.mjs +117 -0
  62. package/bin/lib/policy-delta-io.mjs +168 -10
  63. package/bin/lib/prepare-change.mjs +120 -6
  64. package/bin/lib/prepare-write.mjs +1 -0
  65. package/bin/lib/presets.mjs +3 -5
  66. package/bin/lib/remediation.mjs +23 -4
  67. package/bin/lib/resolved-candidate-facts.mjs +315 -55
  68. package/bin/lib/rules-inventory.mjs +22 -3
  69. package/bin/lib/rules-under-contract.mjs +179 -5
  70. package/bin/lib/scan-files.mjs +32 -0
  71. package/bin/lib/snippet-analysis.mjs +140 -6
  72. package/bin/lib/source-policy.mjs +34 -0
  73. package/bin/lib/stable-hash.mjs +90 -0
  74. package/bin/lib/start-install-recovery.mjs +71 -1
  75. package/bin/lib/start-preview.mjs +30 -0
  76. package/bin/lib/status-command.mjs +33 -4
  77. package/bin/lib/status-manifest.mjs +32 -4
  78. package/bin/lib/team-parliament-io.mjs +79 -75
  79. package/bin/lib/team-parliament.mjs +6 -1
  80. package/bin/lib/write-path-capabilities.mjs +4 -2
  81. package/dist/chunk-A5EIY3HI.cjs +5 -0
  82. package/dist/chunk-MBXCFLO4.js +16 -0
  83. package/dist/chunk-RNQHRDCQ.cjs +16 -0
  84. package/dist/chunk-SVSQVGFJ.js +5 -0
  85. package/dist/{configTypes-CTELo87-.d.ts → configTypes-BJbaeoj4.d.cts} +53 -4
  86. package/dist/configTypes-BJbaeoj4.d.ts +246 -0
  87. package/dist/eslint/index.cjs +17 -4
  88. package/dist/eslint/index.d.cts +359 -0
  89. package/dist/eslint/index.d.ts +178 -158
  90. package/dist/eslint/index.js +10 -4
  91. package/dist/index.cjs +38 -37
  92. package/dist/index.d.cts +5475 -0
  93. package/dist/index.d.ts +3408 -296
  94. package/dist/index.js +38 -37
  95. package/dist/inspectorListen-6DQVJ4DC.js +1 -0
  96. package/dist/inspectorListen-KGMIQ2TF.cjs +1 -0
  97. package/dist/nestjs/index.cjs +1 -18
  98. package/dist/nestjs/index.d.cts +22 -0
  99. package/dist/nestjs/index.d.ts +1 -3
  100. package/dist/nestjs/index.js +1 -18
  101. package/dist/order/index.cjs +1 -1
  102. package/dist/order/index.d.cts +155 -0
  103. package/dist/order/index.d.ts +15 -3
  104. package/dist/order/index.js +1 -1
  105. package/dist/runtime/index.cjs +13 -30
  106. package/dist/{diagnosticCatalog-WD2TPSwZ.d.ts → runtime/index.d.cts} +814 -290
  107. package/dist/runtime/index.d.ts +2678 -108
  108. package/dist/runtime/index.js +13 -30
  109. package/dist/{types-yDNEQ603.d.ts → types-DRinG-vT.d.cts} +576 -140
  110. package/dist/types-DRinG-vT.d.ts +1792 -0
  111. package/docs/README.md +3 -1
  112. package/docs/agent-guide.md +92 -15
  113. package/docs/ai-gates.md +160 -26
  114. package/docs/arkorder.md +32 -15
  115. package/docs/brownfield-adoption.md +5 -1
  116. package/docs/configuration.md +273 -12
  117. package/docs/develop.md +2 -1
  118. package/docs/diagnostics.md +122 -13
  119. package/docs/package-surface.md +31 -8
  120. package/docs/product-voice.md +1 -1
  121. package/package.json +59 -18
  122. package/schemas/ark.analysis-result.schema.json +15 -0
  123. package/schemas/ark.config.schema.json +163 -4
  124. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  125. package/schemas/ark.status-manifest.schema.json +22 -0
  126. package/server.json +3 -9
  127. package/templates/agent-skills/README.md +1 -1
  128. package/templates/agent-skills/ark-adopt/SKILL.md +4 -1
  129. package/templates/agent-skills/ark-order/SKILL.md +4 -2
  130. package/templates/agent-skills/ark-runtime/SKILL.md +6 -1
  131. package/templates/arkrules/PersistenceAdapters.json +1 -1
  132. package/templates/arkrules/PresentationAdapters.json +1 -1
  133. package/templates/skills/ark-adopt.md +4 -1
  134. package/templates/skills/ark-order.md +4 -2
  135. package/templates/skills/ark-runtime.md +6 -1
  136. package/dist/types-fQ9-KrBj.d.ts +0 -183
package/dist/index.js CHANGED
@@ -1,55 +1,56 @@
1
- var za=Object.defineProperty;var i=(e,t)=>za(e,"name",{value:t,configurable:!0});var Wa="4.8.22";var qa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ya=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ja=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Xa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return qa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ya.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ja.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Xa,"classifyLayerImportKind");function Za(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Xa(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Za,"layerImportNextAction");function Qa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Qa,"arkRunCallSiteName");function ei(e){let t=Qa(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ei,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Za(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return ei(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.`}}i(ye,"deterministicNextAction");var wt="1.5",Pt="docs/diagnostics.md",ss={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function rt(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(rt,"adapterFindingTargetKey");function st(e){let t=new Map;return e.map(n=>{let r=rt(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(st,"adapterFindingOccurrenceTargetKeys");function Lt(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Lt,"adapterFindingRefFromTargetKey");function Dt(e){return`${Pt}#${e}`}i(Dt,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function os(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(os,"positiveInteger");function ti(e,t,n){return ye({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(ti,"nextActionForDiagnostic");function vn(e,t="error",n){let r=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=n??rt(e),l=Lt(a);return{ruleId:r,severity:o,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:os(e.line,1),column:os(e.column,1)},evidence:s,nextAction:O(e.nextAction)??ti(r,s,e),findingRef:l,targetKey:a,docsCodePath:Dt(r)}}i(vn,"toAdapterDiagnostic");function ni(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:O(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(g.message)??`Analysis ${t}: required evidence is incomplete.`,...O(g.file)?{file:O(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=st(s),c=st(a),u=[...s.map((g,f)=>vn(g,"error",l[f])),...a.map((g,f)=>vn(g,"warning",c[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};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}}i(ni,"createAdapterResult");var ri="1.0",as="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Mt="^sha256:[a-f0-9]{64}$",is={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:Mt,description:"Project id previously returned by ark_identity or ark_manifest."}}},ls={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:Mt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},si={$schema:"https://json-schema.org/draft/2020-12/schema",$id:as,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:Mt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Mt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:is,binding:ls}};function oi(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}`}i(oi,"createProjectId");function ai(e){return{schemaVersion:"1.0",...e}}i(ai,"createProjectIdentity");var _n=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),xn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Tn=Object.freeze(Object.keys(xn).sort()),Cn=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"}),On=Object.freeze({process:Object.freeze(["process","node:process"])});function ot(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Cn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Cn[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Cn[e.slice(0,s)]??null}i(ot,"capabilityForModuleSpecifier");function Ce(e,t){for(let n of t)if(On[n]?.includes(e))return n;return null}i(Ce,"forbiddenGlobalForModuleSpecifier");function Ft(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=xn[r];if(o)return o}return null}i(Ft,"capabilityForAmbientName");function je(e){if(e?.pure===!0)return[..._n].sort();let n=(e?.capabilities?.deny??[]).filter(r=>_n.includes(r));return[...new Set(n)].sort()}i(je,"effectiveCapabilityDeny");function at(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(at,"ambientCoveredByForbiddenGlobals");function $t(e){let t=new Set,n=new Set,r=Object.keys(xn);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of On[o]??[])t.add(`import-exact:${a}`)}for(let o of je(e)){if(t.add(`import:${o}`),o==="process")for(let s of On.process)t.add(`import-exact:${s}`);for(let s of r)Ft(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i($t,"loweredLayerCoverage");var cs=new Map;function ds(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ds,"escapeLiteral");function jt(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(jt,"normalizeGlobSeparators");function ii(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(ii,"bracesBalanced");function ke(e){let t=cs.get(e);if(t)return t;let n=jt(e),r=ii(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=ds(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+=ds(c)}let a=new RegExp(`^${o}$`);return cs.set(e,a),a}i(ke,"globToRegExp");function li(e){return jt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(li,"concreteGlobSegments");function wn(e,t){let n=jt(String(e)),r=li(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let u of r){let p=-1;for(let g=l;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;c=p,l=p+1}return(c+1)*1e6+r.length*1e4+o}i(wn,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ke(a).test(n))){for(let a of s.patterns??[])if(ke(a).test(n)){let l=wn(a,n);l>o&&(o=l,r=s.name)}}return r}i(fe,"layerForRelativePath");function Ht(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",o=String(e).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let s=new Set;for(let a of t)if(!(typeof a!="string"||a.length===0)){if(fs(a)){let l=ci(o,a,r);if(l)return l;continue}!a.includes("/")&&!a.includes("\\")&&!a.includes("*")&&s.add(a.toLowerCase())}return fi(o,s)}i(Ht,"sliceIdForPath");function fs(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}i(fs,"isAnchoredSliceEntry");function ci(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=hs(e,r[0]??"");for(let s of o){let a=di(e,r,s,n);if(a)return a}}i(ci,"anchoredSliceId");function di(e,t,n,r="path"){let o=[],s=-1,a=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(a>=e.length-1){for(let u=l;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[a].toLowerCase()),a+=1;continue}if(c==="**"||a>=e.length||e[a].toLowerCase()!==c)return;o.push(e[a].toLowerCase()),s=o.length-1,a+=1}if(o.length!==0)return r==="stars"?s<0?void 0:o.slice(s).join("/"):o.join("/")}i(di,"bindAnchoredSlice");function ms(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 a=ui(s);if(!a)continue;let l=s.split(/[/\\]/).filter(p=>p.length>0).join("/").toLowerCase(),c=o.get(a)??new Set;if(c.has(l))continue;c.add(l),o.set(a,c);let u=r.get(a)??[];u.push(s),r.set(a,u)}for(let[s,a]of r)a.length<2||t.push({from:n.from,to:n.to,stem:s,paths:a,message:pi(n.from,n.to,a,s)})}return t}i(ms,"sliceIdentityCollisions");function ui(e){if(!fs(e))return;let t=e.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),n=-1;for(let o=0;o<t.length;o+=1){let s=t[o]??"";if(s==="**")return;s!=="*"&&(n=o)}if(n<0)return;let r=t.slice(n);if(!r.some((o,s)=>s>0&&o!=="*"))return r.join("/")}i(ui,"starsIdentityStem");function pi(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}.`}i(pi,"formatSliceIdentityCollision");function fi(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()}`}}i(fi,"bareSliceId");function mi(e){let t=new Set;for(let n of e??[]){let o=jt(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(mi,"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 mi(r?.patterns)}i(gs,"resolveSliceFolders");function us(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(us,"normalizeSegments");function ys(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(ys,"trimTrailingSlashes");var gi=["src","app"];function hs(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return gi.includes(n)&&r!==n?[0,1]:[0]}i(hs,"anchorOffsets");function yi(e){let t=ys(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(yi,"isBlanketRoot");function Nn(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=us(n);for(let s of t){if(typeof s!="string"||s.length===0||yi(s))continue;if(s.includes("*")){let c=ys(s.toLowerCase());if(ke(c).test(r)||ke(`${c}/**`).test(r))return!0;continue}let a=us(s);if(a.length===0)continue;let l=hs(o,a[0]??"");for(let c of l){if(c+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[c+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(Nn,"pathUnderSharedRoot");function ps(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(ps,"sliceMatchesDeclaration");function hi(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&ps(r.from,t)&&ps(r.to,n))}i(hi,"crossSliceEdgeAllowed");function Ai(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"}}i(Ai,"peerIsolationDecision");function Ke(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."}}i(Ke,"peerIsolationDenyExplanation");function Kt(e,t,n,r){return Te(e,t,n,r)?.rule}i(Kt,"findDeniedEdgeRule");function Te(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,l=gs(o,t,r?.layers),c=s?Ht(s,l,o.sliceIdentity):void 0,u=a?Ht(a,l,o.sliceIdentity):void 0,p=Ai({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&Nn(s,o.sharedRoots),toShared:!u&&Nn(a,o.sharedRoots),crossSliceAllowed:hi(o.allowedCrossSlice,c,u),sharedImportsSlice:o.sharedImportsSlice});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:c,toSlice:u};continue}if(t!==n)return{rule:o}}}i(Te,"findDeniedEdgeDecision");function As(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let a of e??[]){if(a.from!==t||a.to!==n||a.allowed!==!1||!a.peerIsolation||a.sharedImportsSlice==="deny")continue;let l=gs(a,t,r?.layers),c=Ht(o,l,a.sliceIdentity),u=Ht(s,l,a.sliceIdentity);if(!(c||!u)&&Nn(o,a.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}i(As,"findSharedImportsSliceBridge");function Ve(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ve,"literalText");function Ss(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Ss,"lineOf");function Rs(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(Rs,"isTypeOnlyReference");function Is(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(Is,"singleFileChecker");function Pn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Pn,"symbolAt");function Ln(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Pn(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Ln,"localDeclaration");function Ue(e,t){let n,r=[],o=i((a,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Ss(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",Ve(e,a.moduleSpecifier),Rs(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",Ve(e,a.moduleSpecifier),Rs(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",Ve(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ln(e,n??(n=Is(e,t)),t,a.expression);(l||u)&&o(a,u?"require":"dynamic-import",Ve(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(Ue,"extractSemanticDependencies");function Ri(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=Ve(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(Ri,"staticAccessPath");function ki(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(ki,"runtimeIdentifierReference");function ks(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(ks,"bestForbiddenMatch");function Ge(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Is(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let l=i(f=>{let m=Ri(e,f);if(!m)return;let d=Pn(o,m.root),y=d?s.get(d):void 0;return y?[...y,...m.segments.slice(1)]:Ln(e,o,t,m.root)||a.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 d=l(m.initializer),y=Pn(o,m.name);!d||!y||s.set(y,d)}let c=[],u=new Set,p=i((f,m)=>{let d=Ss(t,m),y=`${f}:${m.getStart(t)}`;u.has(y)||(u.add(y),c.push({name:f,line:d,node:m}))},"flag"),g=i(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 d=l(f),y=d?ks(r,d):void 0;y&&p(y,f)}else e.isIdentifier(f)&&r.has(f.text)&&ki(e,f)&&!Ln(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=l(f.initializer);if(d)for(let y of f.name.elements){if(!e.isIdentifier(y.name))continue;let b=y.propertyName?Ve(e,y.propertyName)??y.propertyName.text:y.name.text,x=ks(r,[...d,b]);x&&p(x,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),c}i(Ge,"collectForbiddenCapabilityUses");function Dn(e,t,n){let r=[];for(let o of n?.dependencies??Ue(e,t)){if(o.typeOnly||!o.specifier)continue;let s=ot(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,Tn)){let s=Ft(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(Dn,"collectCapabilityUses");var Mn={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."},Fn=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 $n(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i($n,"resolveIntentLayer");function Ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ne,"looksLikeArkIntent");function it(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Mn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Mn.PUBLISH_MISSING_SOURCE}),t}i(it,"classifyPublishFacts");function Y(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(Y,"violation");function Be(e,t){return e.slice(0,t).split(`
2
- `).length}i(Be,"lineOf");var Si=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ii(e,t){return e.index+e[0].indexOf(t)}i(Ii,"captureIndex");function Ei(e){let t=[],n=new Set,r=i((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=i(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,Ii(c,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let l=a[1]??"",c=a.index+a[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.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)}i(Ei,"extractQuotedStrings");function bi(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}i(bi,"extractModuleSpecifiers");function vi(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}i(vi,"isSyntaxWrapper");function Hn(e,t){let n=t;for(;n?.parent&&vi(e,n.parent);)n=n.parent;return n}i(Hn,"unwrapWrappers");function jn(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}i(jn,"callCalleeName");function Ci(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Hn(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&jn(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Kn(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Hn(e,s).parent;return!!(l&&e.isCallExpression(l)&&jn(e,l)==="publish")}return!1}i(Ci,"isPublishMetadataSource");function Es(e,t){let n=Hn(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=jn(e,r);if(o&&Si.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Es(e,r);if(e.isPropertyAssignment(r)){let o=Kn(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Ci(e,r))return!0}return!1}i(Es,"isDeclaredIntentSite");function _i(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&Es(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(_i,"extractQuotedStringsAst");function Oi(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}i(Oi,"hasInfrastructureToken");function xi(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(xi,"isKnownInfrastructurePackage");function Ti(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Ti,"layerHasInfrastructureRole");function ct(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ct,"tsStringLiteralText");function Kn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Kn,"tsPropertyName");function bs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Kn(e,r.name)===n)}i(bs,"tsObjectProperty");function dt(e,t,n){return bs(e,t,n)!==void 0}i(dt,"tsObjectHasProperty");function lt(e,t,n){let r=bs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(lt,"tsObjectPropertyValue");function Ni(e,t){let n=lt(e,t,"metadata");return dt(e,n,"source")}i(Ni,"tsObjectHasMetadataSource");function vs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?vs(e,t.name):!1:!1}i(vs,"tsLooksLikeIntentCreatorExpression");function wi(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}i(wi,"tsIsPublishCall");function Pi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=ct(e,n);return r!==void 0&&Ne(r)||dt(e,n,"intent")||vs(e,n)}i(Pi,"tsIsArkPublishCandidate");function Li(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Ni(e,n)||dt(e,r,"source")||dt(e,o,"source")}i(Li,"tsPublishHasSource");function Di(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=lt(e,n,"metadata");return ct(e,lt(e,s,"source"))??ct(e,lt(e,r,"source"))??ct(e,lt(e,o,"source"))}i(Di,"tsPublishSourceLiteral");function Mi(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],u=i(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=i(g=>{if(wi(e,g)){let f=g.arguments[0],m=ct(e,f);for(let y of it({publishCall:!0,rawIntentName:m,objectHasIntent:dt(e,f,"intent"),arkPublishCandidate:Pi(e,g),hasSource:Li(e,g)}))c.push(Y(y.ruleId,y.message,{line:u(g),filePath:a}));let d=Di(e,g);if(r&&l&&d&&Ne(d)){let y=r.resolveLayer(d);y&&y!==l&&c.push(Y("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${y}, but the target file is classified as ${l}.`,{line:u(g),filePath:a,target:d,fromLayer:l,toLayer:y}))}}e.forEachChild(g,p)},"visit");return p(o),c}i(Mi,"analyzePublishAst");function Cs(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let l=[],c=a,u=c?.filePath,p=c?.layer,g=e.typescript,f=g?g.createSourceFile(u??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?Ue(e.typescript,f):void 0,d=m?m.filter(S=>S.specifier!==void 0).map(S=>({value:S.specifier,index:S.node.getStart(f),kind:S.kind,typeOnly:S.typeOnly})):bi(s),y=e.typescript?_i(e.typescript,s):Ei(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let S of m?.filter(({unresolved:E})=>E)??[]){let E=S.kind==="require";l.push(Y(E?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${E?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:S.line,filePath:u}))}let b=p!==void 0&&(r.has(p)||Ti(p)),x=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 E=S.exec(s);S.lastIndex=0,E&&l.push(Y("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${S}`,{line:E.index===void 0?void 0:Be(s,E.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+x}))}else s.includes(S)&&l.push(Y("FORBIDDEN_SUBSTRING",`Forbidden substring: ${S}`,{line:Be(s,s.indexOf(S)),filePath:u}));for(let S of d){let E=e.resolveImportTarget?.(S.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(S.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,D=E?.layer;if(D&&p){let k=Kt(e.architectureProfile?.rules,p,D,{fromPath:C?.relPath,toPath:E?.relPath,layers:e.architectureLayers});if(k){if(S.typeOnly&&!k.peerIsolation)continue;let P=!!k.peerIsolation;l.push(Y("LAYER_IMPORT_VIOLATION",k.message??(P?`Layer "${p}" must not import across slices into "${D}".`:`Layer "${p}" must not import "${D}".`),{line:Be(s,S.index),source:S.value,target:S.value,filePath:u,fromLayer:p,toLayer:D,suggestion:P?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:S.kind,peerIsolation:P,...S.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||S.typeOnly||!Oi(S.value)&&!xi(S.value)||l.push(Y("FORBIDDEN_IMPORT",`Forbidden ${S.kind} target: "${S.value}".`,{line:Be(s,S.index),source:S.value,target:S.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+x,details:{importKind:S.kind}}))}if(e.policies)for(let S of e.policies){let E=S.check({source:s,context:a});if(E!==!0)if(Array.isArray(E))for(let C of E)l.push(Y("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${S.name}".`}));else E===!1?l.push(Y("POLICY_VIOLATION",`Policy ${S.name} failed on generated code`)):l.push(Y("POLICY_VIOLATION",E.message))}if(o&&t.size>0)for(let S of y)Ne(S.value)&&!t.has(S.value)&&l.push(Y("UNKNOWN_INTENT",`Unknown intent reference: "${S.value}"`,{line:Be(s,S.index),filePath:u,target:S.value,suggestion:`Register intent "${S.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let S of y){if(!Ne(S.value))continue;let E=e.architectureProfile.resolveLayer(S.value);if(!E)continue;let C=Te(e.architectureProfile.rules,p,E,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let D=C.rule.peerIsolation?Ke(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,k=`Layer "${p}" must not reference "${E}" through "${S.value}".`,P=D&&C.peerIsolationReason!=="cross-slice"?`${k} ${D}`:C.rule.message?D?`${C.rule.message} (${D})`:C.rule.message:k;l.push(Y("LAYER_REFERENCE_VIOLATION",P,{line:Be(s,S.index),filePath:u,target:S.value,fromLayer:p,toLayer:E,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let S of e.extensions)try{let E=S.analyze(s,a);l.push(...E)}catch(E){l.push(Y("EXTENSION_ERROR",`Extension "${S.name}" failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let S=e.forbiddenGlobals[p];l.push(...Ge(e.typescript,f,S).map(E=>Y("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${E.name}".`,{line:E.line,filePath:u,target:E.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 E of m??[]){if(E.typeOnly||!E.specifier)continue;let C=Ce(E.specifier,S);C&&l.push(Y("FORBIDDEN_GLOBAL",`${p} must not use module "${E.specifier}" because it is the import form of forbidden global "${C}".`,{line:E.line,filePath:u,source:E.specifier,target:E.specifier,fromLayer:p,details:{importKind:E.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(S){l.push(Y("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]),E=e.forbiddenGlobals?.[p]??[];for(let C of Dn(e.typescript,f))S.has(C.capability)&&(C.source==="ambient-global"&&at(C.symbol,E)||C.source==="import-based"&&Ce(C.symbol,E)||l.push(Y("CAPABILITY_VIOLATION",C.source==="import-based"?`${p} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${p} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(S){l.push(Y("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript)try{l.push(...Mi(e.typescript,s,a,e.architectureProfile))}catch(S){l.push(Y("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.length===0,violations:l}}}}i(Cs,"createAICodeGate");var we={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_s={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...we,default:[]},kernelRoots:{...we},managedLayers:{...we,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Os={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...we,default:[]},managedLayers:{...we,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...we,default:[]},appliesTo:{...we,default:[]}}};function ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ut,"isObject");function xs(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)ut(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(xs,"declaredLayerNames");function Ts(e){if(!ut(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Ts,"defaultedArkRun");function Ns(e){if(!ut(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(Ns,"defaultedArkOrder");function ws(e,t){let n=e.arkRun;if(n===void 0||!ut(n))return;let r=xs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(ws,"validateArkRunExtra");function Ps(e,t){let n=e.arkOrder;if(n===void 0||!ut(n))return;let r=xs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Ps,"validateArkOrderExtra");function Vt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(Vt,"normalizeStewardId");function Ls(e){let t=Vt(e);return!t||Vn(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(Ls,"isGitHubHandle");function Fi(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Vn(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(Fi,"isGitHubEmail");function $i(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Ls(t[1])?Vt(t[1]):null}i($i,"githubHandleFromEmail");function Ds(e){let t=$i(e);if(t)return t;let n=Vt(e);return!n||Vn(n)?null:Ls(n)||Fi(n)?n:null}i(Ds,"canonicalStewardId");var Hi=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Vn(e){let t=Vt(e);return!t||Hi.test(t)}i(Vn,"isAutomationAuthor");var ie="1.3",ji=["public","auth","admin","internal"];function Ki(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(Ki,"isFutureHouseLayer");function Vi(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}i(Vi,"layerOwnersList");function Fs(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ki(t)&&!Vi(t)).map(t=>t.name)}i(Fs,"layersMissingRequiredOwners");function $s(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i($s,"missingLayerOwnersNextAction");var Gt="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Ms=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ui=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Gi(){let e=[];for(let t of Ms)for(let n of Ms)t===n||Ui.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Gi,"createDefaultRules");var Bt=Gi(),Un=[{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},Gn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Gt,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:Gt,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:Bt,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:[...ji]},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 the star bindings, 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:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...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:_s,arkOrder:Os}},Se=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ var $l=Object.defineProperty;var a=(e,t)=>$l(e,"name",{value:t,configurable:!0});var Ml="4.8.24";var dr="docs/diagnostics.md",Fl="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 Jt=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.")]),ur=new Map(Jt.map(e=>[e.ruleId,e])),jl=Object.freeze(Jt.map(e=>e.ruleId));function Hl(e){return typeof e=="string"&&e.length>0&&ur.has(e)}a(Hl,"isKnownDiagnosticCode");function Kl(e){return typeof e!="string"||e.length===0?!1:ur.has(e)?!0:e.startsWith("ARKRULE_")}a(Kl,"isCataloguedOrArkRuleFamily");function Qt(e){if(!(typeof e!="string"||e.length===0))return ur.get(e)}a(Qt,"getDiagnosticCatalogEntry");function Qs(e){return`#${Qt(e)?.docsAnchor??e}`}a(Qs,"diagnosticDocsFragment");function Vl(e){return`${dr}${Qs(e)}`}a(Vl,"diagnosticDocsPath");function Ul(){return{schemaVersion:"1.0",docsPath:dr,codes:Jt}}a(Ul,"serializeDiagnosticCatalog");function Gl(e){return Qt(e)?.fix}a(Gl,"catalogFixForRuleId");function Bl(e){return Qt(e)?.why}a(Bl,"catalogWhyForRuleId");var zl=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."})]),Wl=new Map(zl.map(e=>[e.reasonId,e]));function eo(e){if(!(typeof e!="string"||e.length===0))return Wl.get(e)}a(eo,"sliceReasonHint");var ql=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Yl=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Xl=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Zl(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return ql.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Yl.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Xl.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(Zl,"classifyLayerImportKind");function Jl(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}a(Jl,"sliceHintAction");function Ql(e){let t=eo(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${Jl(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=Zl(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(Ql,"layerImportNextAction");function ec(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(ec,"arkRunCallSiteName");function tc(e){let t=ec(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(tc,"arkRunNextAction");function Ae(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ql(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 tc(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(Ae,"deterministicNextAction");var en="1.5",tn="docs/diagnostics.md",to={$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 mt(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(mt,"adapterFindingTargetKey");function ht(e){let t=new Map;return e.map(n=>{let r=mt(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(ht,"adapterFindingOccurrenceTargetKeys");function nn(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(nn,"adapterFindingRefFromTargetKey");function rn(e){return`${tn}#${e}`}a(rn,"adapterDocsCodePath");function _(e){return typeof e=="string"&&e.length>0?e:void 0}a(_,"text");function no(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(no,"positiveInteger");function nc(e,t,n){return Ae({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(nc,"nextActionForDiagnostic");var rc=new Set(["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]);function sc(e){let t=e.details,n=t!==null&&typeof t=="object"?t.reasonId:void 0,r=_(e.reasonId)??_(n);return r&&rc.has(r)?r:void 0}a(sc,"sliceReasonOf");function pr(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=sc(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??mt(e),c=nn(l);return{ruleId:r,severity:o,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:no(e.line,1),column:no(e.column,1)},evidence:i,nextAction:_(e.nextAction)??nc(r,i,e),findingRef:c,targetKey:l,docsCodePath:rn(r)}}a(pr,"toAdapterDiagnostic");function oc(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=ht(s),c=ht(i),d=[...s.map((m,f)=>pr(m,"error",l[f])),...i.map((m,f)=>pr(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(oc,"createAdapterResult");var ic="1.0",ro="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",sn="^sha256:[a-f0-9]{64}$",so={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:sn,description:"Project id previously returned by ark_identity or ark_manifest."}}},oo={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:sn},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},ac={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ro,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:sn},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:sn},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:so,binding:oo}};function lc(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(lc,"createProjectId");function cc(e){return{schemaVersion:"1.0",...e}}a(cc,"createProjectIdentity");var gr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),hr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),yr=Object.freeze(Object.keys(hr).sort()),fr=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"}),mr=Object.freeze({process:Object.freeze(["process","node:process"])});function yt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=fr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=fr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:fr[e.slice(0,s)]??null}a(yt,"capabilityForModuleSpecifier");function we(e,t){for(let n of t)if(mr[n]?.includes(e))return n;return null}a(we,"forbiddenGlobalForModuleSpecifier");function on(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=hr[r];if(o)return o}return null}a(on,"capabilityForAmbientName");function Ye(e){if(e?.pure===!0)return[...gr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>gr.includes(r));return[...new Set(n)].sort()}a(Ye,"effectiveCapabilityDeny");function At(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}a(At,"ambientCoveredByForbiddenGlobals");function an(e){let t=new Set,n=new Set,r=Object.keys(hr);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 mr[o]??[])t.add(`import-exact:${i}`)}for(let o of Ye(e)){if(t.add(`import:${o}`),o==="process")for(let s of mr.process)t.add(`import-exact:${s}`);for(let s of r)on(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(an,"loweredLayerCoverage");function Te(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(Te,"sharedImportsSliceMode");function pn(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(pn,"sharedImportsSliceStopAt");var io=new Map;function ao(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(ao,"escapeLiteral");function fn(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(fn,"normalizeGlobSeparators");function dc(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(dc,"bracesBalanced");function me(e){let t=io.get(e);if(t)return t;let n=fn(e),r=dc(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=ao(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+=ao(c)}let i=new RegExp(`^${o}$`);return io.set(e,i),i}a(me,"globToRegExp");function uc(e){return fn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(uc,"concreteGlobSegments");function kr(e,t){let n=fn(String(e)),r=uc(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(kr,"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=kr(i,n);l>o&&(o=l,r=s.name)}}return r}a(he,"layerForRelativePath");function kt(e,t,n){return ho(e,t,n==="stars"?"stars":"path")}a(kt,"sliceIdForPath");function Rr(e,t){return ho(e,t?[...t]:void 0,mo)}a(Rr,"legacyStarsSliceIdForPath");var mo="stars-4.8.23";function ho(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=pc(s);if(i.anchored){let l=gc(r,i.anchored,n);if(l)return l;continue}i.bare!==void 0&&o.add(i.bare)}return Ac(r,o)}a(ho,"sliceIdWithBinding");var ln=new Map;function pc(e){let t=ln.get(e);if(t)return t;let n={};return yo(e)?n={anchored:fc(e)}:!e.includes("/")&&!e.includes("\\")&&!e.includes("*")&&(n={bare:e.toLowerCase()}),ln.size>=1024&&ln.clear(),ln.set(e,n),n}a(pc,"parsedSliceFolder");function yo(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(yo,"isAnchoredSliceEntry");function fc(e){return e.split(/[/\\]/).filter(t=>t.length>0).map(t=>t.toLowerCase())}a(fc,"anchoredSlicePattern");function gc(e,t,n){let r=So(e,t[0]??"");for(let o of r){let s=mc(e,t,o,n);if(s)return s}}a(gc,"anchoredSliceIdFromPattern");function mc(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===mo?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(mc,"bindAnchoredSlice");function Ao(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(Ao,"starsKeptSegmentIndexes");function Ro(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=hc(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:yc(n.from,n.to,i,s)})}return t}a(Ro,"sliceIdentityCollisions");function hc(e){if(!yo(e))return;let t=e.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(t.some(r=>r==="**"))return;let n=Ao(t);if(n)return n.map(r=>t[r]).join("/")}a(hc,"starsIdentityStem");function yc(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(yc,"formatSliceIdentityCollision");function Ac(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(Ac,"bareSliceId");function Rc(e){let t=new Set;for(let n of e??[]){let o=fn(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(Rc,"inferSliceFoldersFromPatterns");function Ir(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 Rc(r?.patterns)}a(Ir,"resolveSliceFolders");function lo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(lo,"normalizeSegments");function It(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(It,"trimTrailingSlashes");var Sc=["src","app"];function So(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Sc.includes(n)&&r!==n?[0,1]:[0]}a(So,"anchorOffsets");function kc(e){let t=It(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(kc,"isBlanketRoot");function Ze(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=lo(n);for(let s of t){if(typeof s!="string"||s.length===0||kc(s))continue;if(s.includes("*")){let c=It(s.toLowerCase());if(me(c).test(r)||me(`${c}/**`).test(r))return!0;continue}let i=lo(s);if(i.length===0)continue;let l=So(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(Ze,"pathUnderSharedRoot");function co(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(co,"sliceMatchesDeclaration");function cn(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&co(r.from,t)&&co(r.to,n))}a(cn,"crossSliceEdgeAllowed");function Ic(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(Ic,"peerIsolationDecision");function ko(e){return It(e.trim().replace(/\\/g,"/")).toLowerCase()}a(ko,"aliasGlobPattern");function Io(e,t){let n=ko(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=Sr(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(Io,"aliasGlobMatches");function Eo(e,t){return!e||!t?.length?!1:Ze(e,[...t])?!0:t.some(n=>typeof n=="string"&&Io(n,e))}a(Eo,"pathMatchesSharedWalkStop");function Er(e){let t=ko(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(Er,"splitAliasTarget");function bo(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Io(n.from,e))return n;return null}a(bo,"firstSliceAliasEntry");function Ec(e,t){let n=bo(e,t);return n?Er(n.to):null}a(Ec,"firstSliceAlias");function Rt(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=kt(e,r?[...r]:void 0,t.sliceIdentity),s=dn(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=Ec(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Rt,"resolveGovernedSlice");function bc(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=Ao(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(bc,"starsUniverseShapes");function uo(e,t){return e.length===t.length&&e.every((n,r)=>n===null||t[r]==="*"||n===t[r])}a(uo,"literalsMatch");function Xe(e,t){let n=t.split("/").filter(Boolean).map(s=>s.toLowerCase()),r=bc(e);if(n.length===0||r.some(s=>uo(s.literals,n)))return[];let o=new Set;for(let s of r)if(s.legacy.length!==s.literals.length&&uo(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(Xe,"legacyStarsIdTargets");function vo(e,t){if(e.sliceIdentity!=="stars")return;let n=Er(t);if(n)return Xe(e.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(vo,"legacyAliasUniverse");function po(e,t,n){let r=Rt(e,t,n);if(!e||t.sliceIdentity!=="stars")return r;if(r.universeId){let o=bo(e,t);if(!kt(e,[...n],t.sliceIdentity)&&o&&vo(t,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let i=Rr(e,n),l=t.childSlices,c=l?.sliceIdentity==="stars"?Rr(e,l.sliceFolders):void 0;return{...r,...i?{legacyUniverse:i}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(po,"placeForPair");function br(e,t,n,r){let o=po(n,e,t),s=po(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=cn(e.allowedCrossSlice,d.universeId,u.universeId)||e.sliceIdentity==="stars"&&(i!==d.universeId||l!==u.universeId)&&cn(e.allowedCrossSlice,i,l),f=e.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&s.legacyChild!==void 0&&o.legacyChild!==s.legacyChild&&Co(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(br,"resolveGovernedSlicePair");function vc(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(vc,"peerIsolationDenyExplanation");function Cc(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Cc,"crossParentExplanation");function _c(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(_c,"crossSiblingExplanation");function xc(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(xc,"parentImportsChildExplanation");function St(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(St,"universePairLabel");function Oc(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(Oc,"isCommonFolderName");function dn(e,t,n){if(!e||!n?.sliceFolders?.length)return{};let r=kt(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 Oc(i,n.commonFolders)?{}:{childId:r}}a(dn,"resolveChildSliceId");function wc(e){return It(e.trim().replace(/\\/g,"/")).toLowerCase()}a(wc,"siblingEntryKey");function Sr(e){return e.replace(/^(?:src|app)\//,"")}a(Sr,"stripSrcOrApp");function Tc(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=Sr(t);if(!r)return!1;let o=Sr(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(Tc,"pathUnderSubtree");function Lc(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=wc(o);if(!(!s||s.includes("*"))&&(r===s||e&&Tc(e,s)))return!0}return!1}a(Lc,"importerInEnforcedSubtree");function Nc(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!Lc(t,n,e.enforce)}a(Nc,"siblingCrossingAdvisory");function un(e){if(typeof e!="string")return null;let t=It(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(un,"childSlicePatternSegments");function fo(e,t){let n=un(e),r=un(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(fo,"childSlicePatternMatches");function Co(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&fo(r.from,t)&&fo(r.to,n))return!0;return!1}a(Co,"childCrossSliceAllowed");function Pc(e,t){let n=un(e),r=un(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(Pc,"childAllowanceSpansUniverses");function Dc(e){let t=Ic({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:Te(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?Cc(e.fromSlice,e.toSlice):vc(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??dn(e.fromPath,e.fromSlice,n).childId,o=e.toChild??dn(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?e.legacyChildAllowed||Co(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:Nc(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:_c(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:xc(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(Dc,"evaluateNestedSliceWall");function _o(e){return e?.crossing==="cross-sibling"||e?.crossing==="parent-imports-child"}a(_o,"isChildWallCrossing");function gn(e,t){return _o(t)?e?.childSlices?.message:e?.message}a(gn,"sliceConsumerMessage");function Je(e){let t=e.verdict.explanation,n=_o(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(Je,"composeSliceDenialMessage");function Fe(e){if(!e||e.decision==="allow")return{};let t=St(e.fromUniverse),n=St(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Fe,"sliceFindingExtras");function xo(e,t){let n=[],r=new Set,o=new Set;for(let s of e??[])if(s?.peerIsolation&&s.allowed===!1&&n.push(...$c(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=kt(i,s.sliceFolders,s.sliceIdentity),c=dn(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"||!Pc(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(xo,"childSliceConfigFindings");function go(e,t){let n=new Map;if(!e?.length)return n;for(let r of t){if(typeof r!="string")continue;let o=kt(r,[...e],"stars"),s=Rr(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(go,"observedIdsByLegacy");function Ar(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(Ar,"newIdHint");function $c(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=go(e.sliceFolders,t);for(let i of o?.sliceAliases??[]){if(!i||typeof i.to!="string")continue;let l=Er(i.to);if(!l||vo(e,i.to)===void 0)continue;let c=Xe(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 ${Ar(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("/")&&Xe(e.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?Ar(d,Xe(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=go(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=>Xe(o.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?Ar(d,Xe(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($c,"legacyStarsIdFindings");function Oo(e){if(e!==null&&typeof e=="object"){let t=e.ratchet;if(t===!0)return"always";if(t===!1)return"never"}return"auto"}a(Oo,"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=Ir(o,t,r?.layers),c=br(o,l,s,i),d=c.from,u=c.to,m=d.universeId,f=u.universeId,h=Dc({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:m,toSlice:f,fromChild:d.childId,toChild:u.childId,fromShared:!m&&Ze(s,o.sharedRoots),toShared:!f&&Ze(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 wo(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||Te(i.sharedImportsSlice)==="deny")continue;let l=Ir(i,t,r?.layers),c=Rt(o,i,l).universeId,d=Rt(s,i,l).universeId;if(!(c||!d)&&Ze(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:d}}}a(wo,"findSharedImportsSliceBridge");function vr(e,t,n){return Ir(e,t,n)}a(vr,"peerSliceFolders");function Qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Qe,"literalText");function No(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(No,"lineOf");function To(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(To,"isTypeOnlyReference");function Po(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(Po,"singleFileChecker");function Cr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Cr,"symbolAt");function _r(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Cr(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(_r,"localDeclaration");function et(e,t){let n,r=[],o=a((i,l,c,d=!1)=>r.push({specifier:c,kind:l,line:No(t,i),typeOnly:d,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",Qe(e,i.moduleSpecifier),To(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",Qe(e,i.moduleSpecifier),To(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",Qe(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"&&!_r(e,n??(n=Po(e,t)),t,i.expression);(l||d)&&o(i,d?"require":"dynamic-import",Qe(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(et,"extractSemanticDependencies");function Mc(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Qe(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}a(Mc,"staticAccessPath");function Fc(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(Fc,"runtimeIdentifierReference");function Lo(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(Lo,"bestForbiddenMatch");function tt(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Po(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=Mc(e,f);if(!h)return;let p=Cr(o,h.root),y=p?s.get(p):void 0;return y?[...y,...h.segments.slice(1)]:_r(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=Cr(o,h.name);!p||!y||s.set(y,p)}let c=[],d=new Set,u=a((f,h)=>{let p=No(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?Lo(r,p):void 0;y&&u(y,f)}else e.isIdentifier(f)&&r.has(f.text)&&Fc(e,f)&&!_r(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?Qe(e,y.propertyName)??y.propertyName.text:y.name.text,C=Lo(r,[...p,S]);C&&u(C,f.initializer)}}e.forEachChild(f,m)},"visit");return m(t),c}a(tt,"collectForbiddenCapabilityUses");function xr(e,t,n){let r=[];for(let o of n?.dependencies??et(e,t)){if(o.typeOnly||!o.specifier)continue;let s=yt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??tt(e,t,yr)){let s=on(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(xr,"collectCapabilityUses");var Or={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."},Et=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 mn(e){let t=(e.intentPrefixes??[]).filter(n=>n.trim().length>0);return t.length>0?t:Et.find(n=>n.layer===e.name)?.prefixes??[]}a(mn,"effectiveIntentPrefixes");function Do(e){let t=new Set(e.layers.filter(r=>mn(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(Do,"unresolvableLayerFlowLayers");function wr(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(wr,"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 bt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&be(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Or.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Or.PUBLISH_MISSING_SOURCE}),t}a(bt,"classifyPublishFacts");function Z(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(Z,"violation");function jc(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(jc,"peerSuggestion");function nt(e,t){return e.slice(0,t).split(`
2
+ `).length}a(nt,"lineOf");var Hc=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Kc(e,t){return e.index+e[0].indexOf(t)}a(Kc,"captureIndex");function Vc(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,Kc(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(Vc,"extractQuotedStrings");function Uc(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(Uc,"extractModuleSpecifiers");function Gc(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(Gc,"isSyntaxWrapper");function Tr(e,t){let n=t;for(;n?.parent&&Gc(e,n.parent);)n=n.parent;return n}a(Tr,"unwrapWrappers");function Lr(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(Lr,"callCalleeName");function Bc(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Tr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Lr(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Nr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Tr(e,s).parent;return!!(l&&e.isCallExpression(l)&&Lr(e,l)==="publish")}return!1}a(Bc,"isPublishMetadataSource");function $o(e,t){let n=Tr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Lr(e,r);if(o&&Hc.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return $o(e,r);if(e.isPropertyAssignment(r)){let o=Nr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Bc(e,r))return!0}return!1}a($o,"isDeclaredIntentSite");function zc(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&$o(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(zc,"extractQuotedStringsAst");function Wc(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(Wc,"hasInfrastructureToken");function qc(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(qc,"isKnownInfrastructurePackage");function Yc(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(Yc,"layerHasInfrastructureRole");function Ct(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Ct,"tsStringLiteralText");function Nr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(Nr,"tsPropertyName");function Mo(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Nr(e,r.name)===n)}a(Mo,"tsObjectProperty");function _t(e,t,n){return Mo(e,t,n)!==void 0}a(_t,"tsObjectHasProperty");function vt(e,t,n){let r=Mo(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(vt,"tsObjectPropertyValue");function Xc(e,t){let n=vt(e,t,"metadata");return _t(e,n,"source")}a(Xc,"tsObjectHasMetadataSource");function Fo(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Fo(e,t.name):!1:!1}a(Fo,"tsLooksLikeIntentCreatorExpression");function Zc(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(Zc,"tsIsPublishCall");function Jc(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Ct(e,n);return r!==void 0&&be(r)||_t(e,n,"intent")||Fo(e,n)}a(Jc,"tsIsArkPublishCandidate");function Qc(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Xc(e,n)||_t(e,r,"source")||_t(e,o,"source")}a(Qc,"tsPublishHasSource");function ed(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=vt(e,n,"metadata");return Ct(e,vt(e,s,"source"))??Ct(e,vt(e,r,"source"))??Ct(e,vt(e,o,"source"))}a(ed,"tsPublishSourceLiteral");function td(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(Zc(e,m)){let f=m.arguments[0],h=Ct(e,f);for(let y of bt({publishCall:!0,rawIntentName:h,objectHasIntent:_t(e,f,"intent"),arkPublishCandidate:Jc(e,m),hasSource:Qc(e,m)}))c.push(Z(y.ruleId,y.message,{line:d(m),filePath:i}));let p=ed(e,m);if(r&&l&&p&&be(p)){let y=r.resolveLayer(p);y&&y!==l&&c.push(Z("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(td,"analyzePublishAst");function jo(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?et(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})):Uc(s),y=e.typescript?zc(e.typescript,s):Vc(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(d))for(let R of h?.filter(({unresolved:k})=>k)??[]){let k=R.kind==="require";l.push(Z(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)||Yc(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(Z("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:k.index===void 0?void 0:nt(s,k.index),filePath:d,suggestion:"Remove infrastructure imports from domain/application layers."+C}))}else s.includes(R)&&l.push(Z("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:nt(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=Fe($),N=gn(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(Z("LAYER_IMPORT_VIOLATION",M?`${N} ${M}`:N,{line:nt(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:jc(E,P.peerIsolationReason),details:{importKind:R.kind,peerIsolation:E,...R.typeOnly?{typeOnly:!0}:{},...w.reasonId?{reasonId:w.reasonId}:{}}}));continue}continue}S||R.typeOnly||!Wc(R.value)&&!qc(R.value)||l.push(Z("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:nt(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(Z("POLICY_VIOLATION",v.message,{filePath:d,suggestion:`Fix violation of policy "${R.name}".`}));else k===!1?l.push(Z("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(Z("POLICY_VIOLATION",k.message))}if(o&&t.size>0)for(let R of y)be(R.value)&&!t.has(R.value)&&l.push(Z("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:nt(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?Je({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=Fe(H);l.push(Z("LAYER_REFERENCE_VIOLATION",D,{line:nt(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(Z("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(...tt(e.typescript,f,R).map(k=>Z("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=we(k.specifier,R);v&&l.push(Z("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(Z("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 xr(e.typescript,f))R.has(v.capability)&&(v.source==="ambient-global"&&At(v.symbol,k)||v.source==="import-based"&&we(v.symbol,k)||l.push(Z("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(Z("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...td(e.typescript,s,i,e.architectureProfile))}catch(R){l.push(Z("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(jo,"createAICodeGate");var je={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ho={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...je,default:[]},kernelRoots:{...je},managedLayers:{...je,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ko={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...je,default:[]},managedLayers:{...je,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...je,default:[]},appliesTo:{...je,default:[]}}};function xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(xt,"isObject");function Vo(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)xt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Vo,"declaredLayerNames");function Uo(e){if(!xt(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(Uo,"defaultedArkRun");function Go(e){if(!xt(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(Go,"defaultedArkOrder");function Bo(e,t){let n=e.arkRun;if(n===void 0||!xt(n))return;let r=Vo(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(Bo,"validateArkRunExtra");function zo(e,t){let n=e.arkOrder;if(n===void 0||!xt(n))return;let r=Vo(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(zo,"validateArkOrderExtra");var yn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Jo={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:{...yn,minItems:1}}}]},Qo={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:{...yn,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...yn,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:{...yn},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 An(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(An,"propertyPath");function Le(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Le,"trimTrailingSlashes");function ei(e,t){id(e,t),ld(e,t),pd(e,t),Cd(e,t)}a(ei,"validateSliceContract");var Wo='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',qo="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function nd(e){return e==="*"||e==="**"}a(nd,"isWildcardSegment");function ti(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&&nd(t[n-1]??"");)n-=1;let r=t.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(ti,"coveredFolder");function rd(e,t){return e.length<=t.length&&e.every((n,r)=>t[r]===n)}a(rd,"isPrefixOf");function sd(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=ti(u.join("/"));m&&o.push(m)}}return o}a(sd,"ruleLayerFolders");function od(e,t){let n=Le(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 qo;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=ti(n);return o===null?null:o.length===0?qo:t.some(s=>rd(o,s))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(od,"stopAtEntryIssue");function id(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:Wo});return}if(!ue(s)){t.push({path:i,message:Wo});return}for(let u of Object.keys(s))u!=="mode"&&u!=="stopAt"&&t.push({path:An(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=sd(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=od(u,d);if(h){t.push({path:f,message:h});return}let p=Le(u.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(p)){t.push({path:f,message:"duplicate stopAt entry"});return}c.add(p)})})}a(id,"validateSharedImportsSlice");var ad=["deny","advisory"],Yo='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function ld(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"){ad.includes(i)||t.push({path:l,message:Yo});return}if(!ue(i)){t.push({path:l,message:Yo});return}for(let d of Object.keys(i))d!=="default"&&d!=="enforce"&&d!=="ratchet"&&t.push({path:An(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=Le(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(ld,"validateChildSliceSiblings");var cd="must be a slice id with a slash. A bare name is ambiguous across universes.",dd="* matches one whole path segment. ** and a partial segment are not wildcards.";function ud(e){let t=Le(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return cd;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 dd}return null}a(ud,"childCrossSlicePatternIssue");function Xo(e){return Le(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Xo,"childCrossSlicePatternKey");function pd(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:An(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=ud(p);S&&t.push({path:y,message:S})}if(typeof d.from!="string"||typeof d.to!="string")return;let f=`${Xo(d.from)}\0${Xo(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(pd,"validateChildSliceAllowedCrossSlice");var rt="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.",fd="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/*).",gd="overlaps a slice folder. An alias covers only files outside the slice trees.",md="two slice aliases match the same file";function hd(e){return Le(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(hd,"aliasPathSegments");function yd(e){let t=e[e.length-1];return t===void 0||t.includes("*")?[...e]:[...e,"**"]}a(yd,"aliasSegmentsWithSubtree");function ni(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(ni,"concreteGlobPrefix");function Ot(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(Ot,"segmentsArePrefix");function Ad(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(Ad,"anchoredSlicePrefix");function Rd(e,t){let n=ni(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Ot(t,n)||Ot(t,o)?!0:r?Ot(n,t)&&n.length<t.length||Ot(n,["src",...t])&&n.length<t.length+1||Ot(n,["app",...t])&&n.length<t.length+1:!1}a(Rd,"globOverlapsAnchored");function Sd(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(Sd,"globOverlapsBare");function kd(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return Sd(e,n[0]);let r=Ad(t);return r?Rd(e,r):!1}a(kd,"globOverlapsSliceEntry");function Id(e){let t=Le(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(Id,"aliasGlobIssue");function Ed(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(Ed,"universeShapes");function hn(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(hn,"shapeMatches");function bd(e,t){let n=Le(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(s=>s.length===0||s==="."||s==="..")||n.includes("*")||!n.includes("/"))return rt;let r=n.split("/").map(s=>s.toLowerCase());if(t.length===0||t.some(s=>hn(s,r)))return rt;if(t.some(s=>hn(s,r.slice(0,-1))))return null;let o=new Set(t.filter(s=>s.legacy!==void 0&&!hn({literals:s.legacy},r)&&hn({literals:s.legacy},r.slice(0,-1))).map(s=>s.literals.map(i=>i??"*").join("/")));return o.size===1?null:o.size>1?fd:rt}a(bd,"aliasTargetIssue");function Zo(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(Zo,"aliasGlobVariants");function vd(e,t){let n=Zo(e),r=Zo(t);for(let o of n)if(He(o,t,0,0,new Map))return!0;for(let o of r)if(He(e,o,0,0,new Map))return!0;return!1}a(vd,"aliasesCanMatchSameFile");function He(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=He(e,t,n+1,r,o)||r<t.length&&He(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=He(e,t,n,r+1,o)||n<e.length&&He(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=He(e,t,n+1,r+1,o))}return o.set(s,l),l}a(He,"globsCanMatchSame");function Cd(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=Ed(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:An(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=Id(p);if(S)t.push({path:`${h}.from`,message:S});else{let C=yd(hd(p));d.some(R=>kd(C,R))&&t.push({path:`${h}.from`,message:gd});for(let R of u)if(vd(R,C)){t.push({path:h,message:md});break}u.push(C)}}if(typeof y!="string"||y.trim().length===0)t.push({path:`${h}.to`,message:rt});else{let S=bd(y,c);S&&t.push({path:`${h}.to`,message:S})}})})}a(Cd,"validateChildSliceAliases");function Rn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(Rn,"normalizeStewardId");function ri(e){let t=Rn(e);return!t||Pr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(ri,"isGitHubHandle");function _d(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t.includes("@")||t.includes(" ")||Pr(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(_d,"isGitHubEmail");function xd(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&ri(t[1])?Rn(t[1]):null}a(xd,"githubHandleFromEmail");function si(e){let t=xd(e);if(t)return t;let n=Rn(e);return!n||Pr(n)?null:ri(n)||_d(n)?n:null}a(si,"canonicalStewardId");var Od=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Pr(e){let t=Rn(e);return!t||Od.test(t)}a(Pr,"isAutomationAuthor");var ae="1.3",wd=["public","auth","admin","internal"];function Td(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(Td,"isFutureHouseLayer");function Ld(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(Ld,"layerOwnersList");function ii(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Td(t)&&!Ld(t)).map(t=>t.name)}a(ii,"layersMissingRequiredOwners");function ai(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(ai,"missingLayerOwnersNextAction");var kn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",oi=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Nd=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Pd(){let e=[];for(let t of oi)for(let n of oi)t===n||Nd.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Pd,"createDefaultRules");var In=Pd(),Dr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ie={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},$r={$schema:"https://json-schema.org/draft/2020-12/schema",$id:kn,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:kn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ae,default:ae},name:{type:"string",minLength:1},include:{...ie,minItems:1,default:["src"]},exclude:{...ie,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:In,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ie,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ie,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ie,minItems:1},exclude:ie,intentPrefixes:ie,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...wd]},owners:{...ie,minItems:1},forbiddenGlobals:ie,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ie,minItems:1},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:{...ie,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:Jo,childSlices:Qo}},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:{...ie,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:{...ie,minItems:1}}},arkRun:Ho,arkOrder:Ko}},ve=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Hs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Hs,"isObject");function Ut(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Ut,"propertyPath");function ze(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ze,"valueType");function Bi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Bi,"resolveSchemaRef");function pt(e,t,n,r,o){if(t.$ref){let s=Bi(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}pt(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(!Hs(e)){o.push({path:n,message:`must be an object; received ${ze(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Ut(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Ut(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in s||pt(e[l],a,Ut(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&pt(e[a],l,Ut(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${ze(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>pt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${ze(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 ${ze(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${ze(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(pt,"validateNode");function zi(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((a,l)=>{typeof a=="string"&&(Ds(a)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(zi,"validateLayerOwners");function Wi(e){let t={...e,$schema:e.$schema===void 0?Gt: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?Bt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Ts(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ns(e.arkOrder)),t}i(Wi,"defaultedConfig");function qi(e){return e===ie?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(qi,"migratedFromOf");function Yi(){let e=new Set([ie]);for(let t of Un)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Yi,"knownInputVersions");function Ji(e,t="ark.config.json"){if(!Hs(e))throw new Se(t,[{path:"$",message:`must be an object; received ${ze(e)}`}]);let n=Yi(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ie}`}]);if(r!=="unversioned"&&!n.has(r))throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);let o=r,s={...e},a=0;for(;o!==ie&&a<Un.length+1;){a+=1;let l=Un.find(c=>c.from===o);if(!l)throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ie}`}]);o=l.to,s.schemaVersion=o}if(o!==ie)throw new Se(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);return{candidate:Wi(s),migratedFrom:qi(r)}}i(Ji,"migrateArkConfig");function zt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ji(e,t),o=[];if(pt(n,Gn,"$",Gn,o),ws(n,o),Ps(n,o),zi(n,o),o.length>0)throw new Se(t,o);return{config:n,migratedFrom:r}}i(zt,"loadArkConfigContract");function Bn(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Se(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return zt(n,t)}i(Bn,"parseArkConfigJson");function js(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Gt,schemaVersion:ie};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(js,"withArkConfigMetadata");function Xi(e){return e.endsWith(".")?e:`${e}.`}i(Xi,"normalizePrefix");function Zi(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}i(Zi,"byLongestPrefix");function qt(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Xi)})),n=[...t].sort(Zi),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(a=>o.startsWith(a)))?.name}}}i(qt,"createArchitectureProfile");function Ks(e,t={}){return qt({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}i(Ks,"createArchitectureProfileFromArkConfig");var Qi=[{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}],Wt=qt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Qi,rules:Bt.map(e=>({...e}))}),el={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 Vs(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return js({include:e.include??[t],layers:Wt.layers.map(o=>({name:o.name,patterns:(el[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Wt.rules]})}i(Vs,"createElevenLayerArkConfig");function Z(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Z,"deterministicHash");function K(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(K).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${K(t[n])}`).join(",")}}`}i(K,"stableSerialize");var Pe="1.2";var Us=["network","filesystem","clock","randomness","environment","process","persistence"];function J(e,t){let n=K(e),r=K(t);return n<r?-1:n>r?1:0}i(J,"compareCanonical");function Q(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Q,"sortedUnique");function ft(e){let t={schemaVersion:"1.2",include:Q(e.include??[]),exclude:Q(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Q(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:Q(n.patterns??[]),exclude:Q(n.exclude??[]),forbiddenGlobals:Q(n.forbiddenGlobals??[]),intentPrefixes:Q(n.intentPrefixes??[]),capabilityDeny:Q(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(J),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:Q(e.arkRun.compositionRoots),managedLayers:Q(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return Z(K(t))}i(ft,"resolvedFactsEvidenceRequirementsHash");function tl(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(J),n=e.files.map(k=>({...k,typeOnlyExportNames:Q(k.typeOnlyExportNames)})).sort((k,P)=>k.path<P.path?-1:k.path>P.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:Q(k.namedBindings)}:{}})).sort(J),o=e.capabilityUses.map(k=>({...k})).sort(J),s=e.ambientUses.map(k=>({...k})).sort(J),a=e.publishCalls.map(k=>({...k})).sort(J),l=e.intentReferences.map(k=>({...k})).sort(J),c=e.safetyUses.map(k=>({...k})).sort(J),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(P=>({...P}))})).sort(J),p=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(J),g=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(J),f=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(J),m=(e.arkRunDeclarations??[]).map(k=>({...k,uses:Q(k.uses),reactsTo:Q(k.reactsTo),raises:Q(k.raises),sends:Q(k.sends)})).sort(J),d=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(J),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(J),b=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(J),x=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(J),S=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(J),E=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(J),C=e.files.map(({path:k,contentHash:P})=>({path:k,contentHash:P})).sort((k,P)=>k.path<P.path?-1:k.path>P.path?1:0),D=Z(K(C));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:a,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:d,arkOrderGenericUpdates:y,arkOrderRootHits:b,arkOrderXiFieldWrites:x,arkOrderIngestWritesXi:S,arkOrderReleaseKeyCounts:E}}i(tl,"canonicalResolvedFactsInput");function Gs(e){let t=tl(e);return{...t,factsHash:Z(K(t))}}i(Gs,"createCanonicalResolvedCandidateFacts");function zn(e){return Gs(zs($(e,"$"),!1))}i(zn,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i($,"asRecord");function V(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(V,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function Ie(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Ie,"optionalText");function B(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(B,"requiredProjectPath");function z(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(z,"requiredBoolean");function Bs(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(Bs,"requiredInteger");function ne(e,t,n){let r=Bs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(ne,"requiredPositiveInteger");function W(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(W,"requiredArray");function Ee(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Ee,"enumValue");function We(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(We,"parseStringArray");function nl(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(nl,"assertUnique");function zs(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",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ee(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ee(e,"completeness",["complete","partial","unavailable"],"$"),o=W(e,"completenessReasons","$").map((v,_)=>{let h=`$.completenessReasons[${_}]`,R=$(v,h);V(R,["code","message","file"],h);let M=R.file===void 0?void 0:B(R,"file",h);return{code:F(R,"code",h),message:F(R,"message",h),...M?{file:M}:{}}});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=W(e,"files","$").map((v,_)=>{let h=`$.files[${_}]`,R=$(v,h);return V(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:B(R,"path",h),contentHash:F(R,"contentHash",h),parseStatus:Ee(R,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Bs(R,"parseDiagnosticCount",h),exportsOnlyTypes:z(R,"exportsOnlyTypes",h),typeOnlyExportNames:We(R.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:z(R,"hasTopLevelSideEffects",h)}}),a=W(e,"dependencies","$").map((v,_)=>{let h=`$.dependencies[${_}]`,R=$(v,h);V(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let M=Ie(R,"specifier",h),X=Ie(R,"target",h),ve=Ee(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ve==="resolved-project"&&!X)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ve!=="resolved-project"&&X)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ve!=="dynamic"&&!M)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:B(R,"from",h),...M?{specifier:M}:{},kind:Ee(R,"kind",["import","export","dynamic-import","require"],h),typeOnly:z(R,"typeOnly",h),line:ne(R,"line",h),resolution:ve,...X?{target:B(R,"target",h)}:{},...R.namedBindings!==void 0?{namedBindings:We(R.namedBindings,`${h}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:z(R,"targetTypeOnlyExports",h)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:z(R,"sourcePureTypeModule",h)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:z(R,"namedBindingsTypeOnly",h)}:{},...R.portProofEligible!==void 0?{portProofEligible:z(R,"portProofEligible",h)}:{}}}),l=W(e,"capabilityUses","$").map((v,_)=>{let h=`$.capabilityUses[${_}]`,R=$(v,h);return V(R,["file","line","symbol","capability","source"],h),{file:B(R,"file",h),line:ne(R,"line",h),symbol:F(R,"symbol",h),capability:Ee(R,"capability",Us,h),source:Ee(R,"source",["ambient-global","import-based"],h)}}),c=W(e,"ambientUses","$").map((v,_)=>{let h=`$.ambientUses[${_}]`,R=$(v,h);return V(R,["file","line","symbol"],h),{file:B(R,"file",h),line:ne(R,"line",h),symbol:F(R,"symbol",h)}}),u=W(e,"publishCalls","$").map((v,_)=>{let h=`$.publishCalls[${_}]`,R=$(v,h);V(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let M=Ie(R,"rawIntentName",h),X=Ie(R,"sourceIntent",h);return{file:B(R,"file",h),line:ne(R,"line",h),...M?{rawIntentName:M}:{},objectHasIntent:z(R,"objectHasIntent",h),arkPublishCandidate:z(R,"arkPublishCandidate",h),hasSource:z(R,"hasSource",h),...X?{sourceIntent:X}:{}}}),p=W(e,"intentReferences","$").map((v,_)=>{let h=`$.intentReferences[${_}]`,R=$(v,h);return V(R,["file","line","intent"],h),{file:B(R,"file",h),line:ne(R,"line",h),intent:F(R,"intent",h)}}),g=W(e,"safetyUses","$").map((v,_)=>{let h=`$.safetyUses[${_}]`,R=$(v,h);V(R,["file","line","kind","symbol"],h);let M=Ie(R,"symbol",h),X=Ee(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(X==="in-memory-store"&&!M)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(X!=="in-memory-store"&&M)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:B(R,"file",h),line:ne(R,"line",h),kind:X,...M?{symbol:M}:{}}});nl(s,v=>v.path,"$.files");let f=new Set(s.map(v=>v.path));for(let v of s){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:W(e,"arkRunKernelCalls","$")).map((v,_)=>{let h=`$.arkRunKernelCalls[${_}]`,R=$(v,h);V(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let M=Ie(R,"receiver",h),X=Ie(R,"nameLiteral",h);return{file:B(R,"file",h),line:ne(R,"line",h),kind:Ee(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(R,"callee",h),viaImport:z(R,"viaImport",h),...M?{receiver:M}:{},...X?{nameLiteral:X}:{}}}),b=(e.arkRunManagedNews===void 0?[]:W(e,"arkRunManagedNews","$")).map((v,_)=>{let h=`$.arkRunManagedNews[${_}]`,R=$(v,h);V(R,["file","line","typeName","importedFrom"],h);let M=Ie(R,"importedFrom",h);return{file:B(R,"file",h),line:ne(R,"line",h),typeName:F(R,"typeName",h),...M?{importedFrom:M}:{}}}),S=(e.arkRunCompositionRootHits===void 0?[]:W(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let h=`$.arkRunCompositionRootHits[${_}]`,R=$(v,h);return V(R,["file","matchedRoot","hasKernelFactory"],h),{file:B(R,"file",h),matchedRoot:F(R,"matchedRoot",h),hasKernelFactory:z(R,"hasKernelFactory",h)}}),E=e.arkRunDeclarations===void 0?[]:W(e,"arkRunDeclarations","$"),D=(e.arkOrderPlaneCalls===void 0?[]:W(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let h=`$.arkOrderPlaneCalls[${_}]`,R=$(v,h);return V(R,["file","line","callee"],h),{file:B(R,"file",h),line:ne(R,"line",h),callee:F(R,"callee",h)}}),P=(e.arkOrderGenericUpdates===void 0?[]:W(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let h=`$.arkOrderGenericUpdates[${_}]`,R=$(v,h);return V(R,["file","line","method"],h),{file:B(R,"file",h),line:ne(R,"line",h),method:F(R,"method",h)}}),N=(e.arkOrderRootHits===void 0?[]:W(e,"arkOrderRootHits","$")).map((v,_)=>{let h=`$.arkOrderRootHits[${_}]`,R=$(v,h);return V(R,["file","matchedRoot","hasPlaneFactory"],h),{file:B(R,"file",h),matchedRoot:F(R,"matchedRoot",h),hasPlaneFactory:z(R,"hasPlaneFactory",h)}}),L=(e.arkOrderXiFieldWrites===void 0?[]:W(e,"arkOrderXiFieldWrites","$")).map((v,_)=>{let h=`$.arkOrderXiFieldWrites[${_}]`,R=$(v,h);return V(R,["file","line","key"],h),{file:B(R,"file",h),line:ne(R,"line",h),key:F(R,"key",h)}}),G=(e.arkOrderIngestWritesXi===void 0?[]:W(e,"arkOrderIngestWritesXi","$")).map((v,_)=>{let h=`$.arkOrderIngestWritesXi[${_}]`,R=$(v,h);return V(R,["file","line"],h),{file:B(R,"file",h),line:ne(R,"line",h)}}),Re=(e.arkOrderReleaseKeyCounts===void 0?[]:W(e,"arkOrderReleaseKeyCounts","$")).map((v,_)=>{let h=`$.arkOrderReleaseKeyCounts[${_}]`,R=$(v,h);return V(R,["file","line","keyCount"],h),{file:B(R,"file",h),line:ne(R,"line",h),keyCount:ne(R,"keyCount",h)}}),et=E.map((v,_)=>{let h=`$.arkRunDeclarations[${_}]`,R=$(v,h);return V(R,["file","line","uses","reactsTo","raises","sends"],h),{file:B(R,"file",h),line:ne(R,"line",h),uses:We(R.uses,`${h}.uses`),reactsTo:We(R.reactsTo,`${h}.reactsTo`),raises:We(R.raises,`${h}.raises`),sends:We(R.sends,`${h}.sends`)}});for(let[v,_]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",S],["$.arkRunDeclarations",et],["$.arkOrderPlaneCalls",D],["$.arkOrderGenericUpdates",P],["$.arkOrderRootHits",N],["$.arkOrderXiFieldWrites",L],["$.arkOrderIngestWritesXi",G],["$.arkOrderReleaseKeyCounts",Re]])for(let h of _)if(!f.has(h.file))throw new Error(`${v} references missing file ${h.file}.`);let Nt=Ie(e,"projectPackageName","$"),rs=(e.classShapes===void 0?[]:W(e,"classShapes","$")).map((v,_)=>{let h=`$.classShapes[${_}]`,R=$(v,h);V(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let M=W(R,"mutatingMethods",h).map((X,ve)=>{let A=`${h}.mutatingMethods[${ve}]`,se=$(X,A);return V(se,["name","referencesGuardOrPublish"],A),{name:F(se,"name",A),referencesGuardOrPublish:z(se,"referencesGuardOrPublish",A)}});return{file:B(R,"file",h),className:F(R,"className",h),exported:z(R,"exported",h),hasPublicMutableFields:z(R,"hasPublicMutableFields",h),hasPublicSetters:z(R,"hasPublicSetters",h),hasPublicConstructor:z(R,"hasPublicConstructor",h),hasStaticFactory:z(R,"hasStaticFactory",h),mutatingMethods:M,...R.dataOnly===void 0?{}:{dataOnly:z(R,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...Nt?{projectPackageName:Nt}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:p,safetyUses:g,classShapes:rs,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:S,arkRunDeclarations:et,arkOrderPlaneCalls:D,arkOrderGenericUpdates:P,arkOrderRootHits:N,arkOrderXiFieldWrites:L,arkOrderIngestWritesXi:G,arkOrderReleaseKeyCounts:Re}}i(zs,"parseResolvedFactsInput");function _e(e){let t=$(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Gs(zs(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(_e,"loadResolvedCandidateFacts");var rl=["network","filesystem","clock","randomness","environment","process","persistence"],w={type:"string",minLength:1},oe={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Wn={$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:w,message:w,file:q}}},resolverIdentity:w,compilerIdentity:w,compilerOptionsHash:w,tsconfigHash:w,candidateTreeHash:w,evidenceRequirementsHash:w,projectPackageName:w,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:w,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:w},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:q,specifier:w,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:w},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:q,line:oe,symbol:w,capability:{enum:rl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:oe,symbol:w}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:oe,rawIntentName:w,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:w}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:oe,intent:w}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:w},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:q,className:w,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:w,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:q,line:oe,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:w,viaImport:{type:"boolean"},receiver:w,nameLiteral:w}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:q,line:oe,typeName:w,importedFrom:w}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:q,matchedRoot:w,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:q,line:oe,uses:{type:"array",items:w},reactsTo:{type:"array",items:w},raises:{type:"array",items:w},sends:{type:"array",items:w}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:q,line:oe,callee:w}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:q,line:oe,method:w}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:q,matchedRoot:w,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:q,line:oe,key:w}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:q,line:oe}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:q,line:oe,keyCount:{type:"integer",minimum:1}}}},factsHash:w},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}`}i(le,"dependencyKey");function mt(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.`}:{}}}i(mt,"dependencyFinding");function qe(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])),a=new Map(e.candidateDependencies.map(f=>[le(f),f]));for(let f of[...n.values()].sort((m,d)=>m.path.localeCompare(d.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,d)=>m.path.localeCompare(d.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,d)=>le(m).localeCompare(le(d)))){if(a.has(le(f))){t.push(mt("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};a.has(le(m))?(l.add(le(m)),t.push(mt("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(mt("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[...a].sort(([d],[y])=>d.localeCompare(y)))s.has(f)||o.has(f)||l.has(f)||!c.has(m.from)&&!c.has(m.to)||t.push({...mt("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([d],[y])=>d.localeCompare(y)))a.has(f)||u.has(m.from)||u.has(m.to)||!c.has(m.from)&&!c.has(m.to)||t.push({...mt("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}}i(qe,"analyzeArchitectureConvergence");var sl="1.0",Yn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ys=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],ol=["no-anemic-model"],Ws={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Jn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Yn,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:Yn},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:[...Ys]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ws,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:Ws}}}},Le=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function li(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(li,"isObject");function Sn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Sn,"propertyPath");function st(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(st,"valueType");function Dd(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Dd,"resolveSchemaRef");function wt(e,t,n,r,o){if(t.$ref){let s=Dd(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}wt(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(!li(e)){o.push({path:n,message:`must be an object; received ${st(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Sn(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Sn(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||wt(e[l],i,Sn(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&wt(e[i],l,Sn(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${st(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)=>wt(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 ${st(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 ${st(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${st(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(wt,"validateNode");function $d(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"&&(si(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a($d,"validateLayerOwners");function Md(e){let t={...e,$schema:e.$schema===void 0?kn: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?In.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Uo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Go(e.arkOrder)),t}a(Md,"defaultedConfig");function Fd(e){return e===ae?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Fd,"migratedFromOf");function jd(){let e=new Set([ae]);for(let t of Dr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(jd,"knownInputVersions");function Hd(e,t="ark.config.json"){if(!li(e))throw new ve(t,[{path:"$",message:`must be an object; received ${st(e)}`}]);let n=jd(),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 ${ae}`}]);if(r!=="unversioned"&&!n.has(r))throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);let o=r,s={...e},i=0;for(;o!==ae&&i<Dr.length+1;){i+=1;let l=Dr.find(c=>c.from===o);if(!l)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ae}`}]);o=l.to,s.schemaVersion=o}if(o!==ae)throw new ve(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);return{candidate:Md(s),migratedFrom:Fd(r)}}a(Hd,"migrateArkConfig");function En(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Hd(e,t),o=[];if(wt(n,$r,"$",$r,o),Bo(n,o),zo(n,o),$d(n,o),ei(n,o),o.length>0)throw new ve(t,o);return{config:n,migratedFrom:r}}a(En,"loadArkConfigContract");function Mr(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 En(n,t)}a(Mr,"parseArkConfigJson");function ci(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:kn,schemaVersion:ae};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(ci,"withArkConfigMetadata");function Kd(e){return e.endsWith(".")?e:`${e}.`}a(Kd,"normalizePrefix");function Vd(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(Vd,"byLongestPrefix");function vn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Kd)})),n=[...t].sort(Vd),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(vn,"createArchitectureProfile");function di(e,t={}){return vn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:[...mn(n)],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(di,"createArchitectureProfileFromArkConfig");var Ud=[{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}],bn=vn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ud,rules:In.map(e=>({...e}))}),Gd={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 ui(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ci({include:e.include??[t],layers:bn.layers.map(o=>({name:o.name,patterns:(Gd[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...bn.rules]})}a(ui,"createElevenLayerArkConfig");function te(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(te,"deterministicHash");function J(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(J).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${J(t[n])}`).join(",")}}`}a(J,"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 Fr(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")Fr(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"?Fr(i,t):Ce(`${JSON.stringify(i)}`,t)}Ce("}",t)}a(Fr,"feedStable");function jr(e){if(e===null||typeof e!="object")return te(J(e));let t={hash:2166136261};return Fr(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}a(jr,"stableHash");var Ke="1.2";var pi=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e){let t=e.map((n,r)=>({key:J(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 Tt(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 te(J(t))}a(Tt,"resolvedFactsEvidenceRequirementsHash");function Bd(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=jr(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(Bd,"canonicalResolvedFactsInput");function fi(e){let t=Bd(e);return{...t,factsHash:jr(t)}}a(fi,"createCanonicalResolvedCandidateFacts");function Kr(e){return fi(gi(K(e,"$"),!1))}a(Kr,"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 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 Hr(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(Hr,"requiredInteger");function ee(e,t,n){let r=Hr(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 ot(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(ot,"parseStringArray");function zd(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(zd,"assertUnique");function gi(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:Hr(g,"parseDiagnosticCount",A),exportsOnlyTypes:X(g,"exportsOnlyTypes",A),typeOnlyExportNames:ot(g.typeOnlyExportNames,`${A}.typeOnlyExportNames`),hasTopLevelSideEffects:X(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:X(g,"typeOnly",A),line:ee(g,"line",A),resolution:de,...W?{target:U(g,"target",A)}:{},...g.namedBindings!==void 0?{namedBindings:ot(g.namedBindings,`${A}.namedBindings`)}:{},...g.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:X(g,"targetTypeOnlyExports",A)}:{},...g.sourcePureTypeModule!==void 0?{sourcePureTypeModule:X(g,"sourcePureTypeModule",A)}:{},...g.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:X(g,"namedBindingsTypeOnly",A)}:{},...g.portProofEligible!==void 0?{portProofEligible:X(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:ee(g,"line",A),symbol:j(g,"symbol",A),capability:xe(g,"capability",pi,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:ee(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:ee(g,"line",A),...L?{rawIntentName:L}:{},objectHasIntent:X(g,"objectHasIntent",A),arkPublishCandidate:X(g,"arkPublishCandidate",A),hasSource:X(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:ee(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:ee(g,"line",A),kind:W,...L?{symbol:L}:{}}});zd(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:ee(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:X(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:ee(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:X(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:ee(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:ee(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:X(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:ee(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:ee(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:ee(g,"line",A),keyCount:ee(g,"keyCount",A)}}),Yt=(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:ee(g,"line",A),key:j(g,"key",A)}}),ar=(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:ee(g,"line",A),kind:j(g,"kind",A)}}),gt=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:ee(g,"line",A),uses:ot(g.uses,`${A}.uses`),reactsTo:ot(g.reactsTo,`${A}.reactsTo`),raises:ot(g.raises,`${A}.raises`),sends:ot(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",gt],["$.arkOrderPlaneCalls",H],["$.arkOrderGenericUpdates",D],["$.arkOrderRootHits",$],["$.arkOrderXiFieldWrites",N],["$.arkOrderIngestWritesXi",F],["$.arkOrderReleaseKeyCounts",ge],["$.arkOrderXiTtlKeys",Yt],["$.arkOrderBudgetLeaks",ar]])for(let A of O)if(!f.has(A.file))throw new Error(`${b} references missing file ${A.file}.`);let Me=_e(e,"projectPackageName","$"),lr=(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 Zt=`${A}.mutatingMethods[${de}]`,cr=K(W,Zt);return V(cr,["name","referencesGuardOrPublish"],Zt),{name:j(cr,"name",Zt),referencesGuardOrPublish:X(cr,"referencesGuardOrPublish",Zt)}});return{file:U(g,"file",A),className:j(g,"className",A),exported:X(g,"exported",A),hasPublicMutableFields:X(g,"hasPublicMutableFields",A),hasPublicSetters:X(g,"hasPublicSetters",A),hasPublicConstructor:X(g,"hasPublicConstructor",A),hasStaticFactory:X(g,"hasStaticFactory",A),mutatingMethods:L,...g.dataOnly===void 0?{}:{dataOnly:X(g,"dataOnly",A)},...g.truncatedUntil===void 0?{}:{truncatedUntil:Hr(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","$"),...Me?{projectPackageName:Me}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:d,intentReferences:u,safetyUses:m,classShapes:lr,arkRunKernelCalls:p,arkRunManagedNews:S,arkRunCompositionRootHits:R,arkRunDeclarations:gt,arkOrderPlaneCalls:H,arkOrderGenericUpdates:D,arkOrderRootHits:$,arkOrderXiFieldWrites:N,arkOrderIngestWritesXi:F,arkOrderReleaseKeyCounts:ge,arkOrderXiTtlKeys:Yt,arkOrderBudgetLeaks:ar}}a(gi,"parseResolvedFactsInput");function Ne(e){let t=K(e,"$"),n=j(t,"factsHash","$"),r=j(t,"candidateTreeHash","$"),o=fi(gi(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(Ne,"loadResolvedCandidateFacts");var Wd=["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])(?!.*\\/$).+$"},Vr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code: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:Wd},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 Ur="1.0";function le(e){return`${e.from}->${e.to}`}a(le,"dependencyKey");function Lt(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(Lt,"dependencyFinding");function it(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(Lt("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(Lt("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(Lt("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({...Lt("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({...Lt("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(it,"analyzeArchitectureConvergence");var qd="1.0",Gr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",yi=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Yd=["no-anemic-model"],mi={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Br={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Gr,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:Gr},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...yi]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:mi,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:mi}}}},Pe=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 ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ht,"isObject");function Yt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Yt,"propertyPath");function gt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(gt,"valueType");function al(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(al,"resolveSchemaRef");function yt(e,t,n,r,o){if(t.$ref){let s=al(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}yt(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(!ht(e)){o.push({path:n,message:`must be an object; received ${gt(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Yt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Yt(n,a),message:"unknown field"});else if(ht(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in s||yt(e[l],a,Yt(n,l),r,o)}for(let[a,l]of Object.entries(s))e[a]!==void 0&&yt(e[a],l,Yt(n,a),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(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>yt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${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)}`})}i(yt,"validateNode");function il(e){return{...e,$schema:e.$schema===void 0?Yn: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}}i(il,"defaultedArkRules");function qs(e){return e==="enforced"?"enforced":"advisory"}i(qs,"normalizeMode");function ll(e){return ol.includes(e)}i(ll,"isTier2Sensor");function cl(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],o=new Set;n.forEach((s,a)=>{if(!ht(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),typeof s.sensor=="string"&&ll(s.sensor)&&s.mode==="enforced"&&t.push({path:`$.structure[${a}].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[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((s,a)=>{if(!ht(s))return;let l=typeof s.id=="string"?s.id:"";l&&(o.has(l)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),o.add(l)),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}i(cl,"validateSemantics");function Jt(e,t="arkrules.json",n){if(!ht(e))throw new Le(t,[{path:"$",message:`must be an object; received ${gt(e)}`}]);let r=il(e),o=[];if(yt(r,Jn,"$",Jn,o),cl(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 Le(t,o);return{config:r}}i(Jt,"loadArkRulesContract");function dl(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new Le(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return Jt(r,t,n)}i(dl,"parseArkRulesJson");function Xn(e){let t={},n=[],r=[],o=[...e].sort((s,a)=>s.layer.localeCompare(a.layer));for(let s of o){let a=(s.file.structure??[]).map(c=>({...c,mode:qs(c.mode),provenance:{sourceFile:s.sourceFile,ruleId:c.id,layer:s.layer}})),l=(s.file.invariants??[]).map(c=>({...c,mode:qs(c.mode),provenance:{sourceFile:s.sourceFile,ruleId:c.id,layer:s.layer}}));t[s.layer]={sourceFile:s.sourceFile,structure:a,invariants:l},n.push(...a),r.push(...l)}return n.sort((s,a)=>{let l=s.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:s.id.localeCompare(a.id)}),r.sort((s,a)=>{let l=s.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:s.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(Xn,"buildEffectiveArkRules");function De(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(De,"emptyEffectiveArkRules");var Xt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function Dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Dt,"isObject");function Cn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Cn,"propertyPath");function Nt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(Nt,"valueType");function Xd(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Xd,"resolveSchemaRef");function Pt(e,t,n,r,o){if(t.$ref){let s=Xd(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Pt(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(!Dt(e)){o.push({path:n,message:`must be an object; received ${Nt(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Cn(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Cn(n,i),message:"unknown field"});else if(Dt(t.additionalProperties)){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||Pt(e[l],i,Cn(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Pt(e[i],l,Cn(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Nt(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)=>Pt(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 ${Nt(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 ${Nt(e)}`})}a(Pt,"validateNode");function Zd(e){return{...e,$schema:e.$schema===void 0?Gr: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(Zd,"defaultedArkRules");function hi(e){return e==="enforced"?"enforced":"advisory"}a(hi,"normalizeMode");function Jd(e){return Yd.includes(e)}a(Jd,"isTier2Sensor");function Qd(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(!Dt(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"&&Jd(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(!Dt(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(Qd,"validateSemantics");function _n(e,t="arkrules.json",n){if(!Dt(e))throw new Pe(t,[{path:"$",message:`must be an object; received ${Nt(e)}`}]);let r=Zd(e),o=[];if(Pt(r,Br,"$",Br,o),Qd(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 Pe(t,o);return{config:r}}a(_n,"loadArkRulesContract");function eu(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new Pe(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return _n(r,t,n)}a(eu,"parseArkRulesJson");function zr(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:hi(c.mode),provenance:{sourceFile:s.sourceFile,ruleId:c.id,layer:s.layer}})),l=(s.file.invariants??[]).map(c=>({...c,mode:hi(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(zr,"buildEffectiveArkRules");function Ve(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(Ve,"emptyEffectiveArkRules");var xn=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 Js(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Js,"normalizeRel");function ul(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:De(),warnings:r}}let o=new Set(e.config.layers.map(c=>c.name)),s=[],a=[],l=new Set;for(let c of Object.keys(n).sort()){let u=n[c],p=`$.arkRules[${JSON.stringify(c)}]`;if(typeof u!="string"||u.length===0){s.push({path:p,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){s.push({path:p,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(c)){s.push({path:p,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let g=Js(u);l.add(g);let f=e.fileContents[g]??e.fileContents[u];if(f===void 0){s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let m=Jt(JSON.parse(f),g,c);a.push({layer:c,sourceFile:g,file:m.config})}catch(m){if(m instanceof Le)for(let d of m.issues)s.push({path:`${p}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${g}: ${d.message}`});else m instanceof SyntaxError?s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${m.message}`}):s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${m instanceof Error?m.message:String(m)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let u=Js(c);l.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(s.length>0)throw new Xt(t,s);return{config:e.config,arkRules:Xn(a),warnings:r}}i(ul,"resolveEffectiveContract");function Zn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(Zn,"omitLayerDescriptions");function Qn(e){let{stewards:t,...n}=Zn(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(Qn,"effectiveContractPolicyPayload");var pl="INVARIANT_TESTS_PATH_MISSING",fl="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.",ml="INVARIANT_COVERAGE_ROOTS_MISSING",gl="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 Xs(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i(Xs,"formatCoverageDiscards");function eo(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(eo,"isUnderCoverageRoot");function tr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(tr,"escapeRegExp");function Ye(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Ye,"normalizePath");function nr(e,t){let n=[],r=0,o=e.length;for(;r<o;){let s=e[r],a=e[r+1];if(s==="/"&&a==="/"){for(;r<o&&e[r]!==`
9
- `;)n.push(" "),r+=1;continue}if(s==="/"&&a==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Ai(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Ai,"normalizeRel");function tu(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:Ve(),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=Ai(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=_n(JSON.parse(f),m,c);i.push({layer:c,sourceFile:m,file:h.config})}catch(h){if(h instanceof Pe)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=Ai(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 xn(t,s);return{config:e.config,arkRules:zr(i),warnings:r}}a(tu,"resolveEffectiveContract");function Wr(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(Wr,"omitLayerDescriptions");function qr(e){let{stewards:t,...n}=Wr(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(qr,"effectiveContractPolicyPayload");var nu=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),ru=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),su=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function ou(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 su.has(e.slice(o+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:ru.has(r)}a(ou,"slashStartsRegex");function iu(e,t){if(!ou(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(iu,"skipRegexLiteral");function Ue(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 iu(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(Ue,"skipStringOrComment");function Re(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=Ue(e,n);continue}break}return n}a(Re,"skipWsAndComments");function On(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(On,"readIdent");function De(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=Ue(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(De,"skipBalanced");function wn(e){let t=[],n=0,r;for(;n<e.length&&(n=Re(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let u=On(e,s);if(!u||!nu.has(u.ident))break;o.push(u.ident),s=Re(e,u.end)}if(o.length===1&&o[0]==="static"&&e[s]==="{"){let u=De(e,s,"{","}");if(u==null){r=e.length;break}n=u;continue}let i=On(e,s);if(!i){n+=1;continue}if(s=Re(e,i.end),e[s]==="<"){let u=De(e,s,"<",">");if(u==null){r=e.length;break}s=Re(e,u)}if(e[s]==="("){let u=De(e,s,"(",")");if(u==null){r=e.length;break}if(s=Re(e,u),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let m=Ue(e,s);if(m!==s){s=m;continue}s+=1}if(e[s]==="{"){let m=De(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=Ue(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(wn,"scanClassMembers");function Ri(e,t){let n=t;for(;n<e.length;){let r=Re(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=De(e,n,o,o==="<"?">":o==="("?")":"]");if(i==null)return null;n=i;continue}if(o==='"'||o==="'"||o==="`"){n=Ue(e,n);continue}n+=1}return null}a(Ri,"findClassBodyBrace");function Tn(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=Si(e),s;for(;(s=r.exec(o))!==null;){let i=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=Ri(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=De(e,c,"{","}");n.push({name:i,start:s.index,exported:l,bodyStart:c+1,bodyEnd:d==null?null:d-1})}return n}a(Tn,"findClassDeclarations");function Si(e){let t="",n=0;for(;n<e.length;){let r=Ue(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}a(Si,"maskStringsAndComments");function ki(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=Si(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=Ri(e,i.index+i[0].length);else{c="object";let u=Re(e,i.index+i[0].length);l=e[u]==="{"?u:null}if(l==null)continue;let d=De(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:d==null?e.length:d-1})}return n}a(ki,"findMemberContainers");function Ii(e){let t=[],n=0,r=!0;for(;n<e.length;){let o=Ue(e,n);if(o!==n){n=o,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=De(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=On(e,n);for(;i&&(i.ident==="async"||i.ident==="get"||i.ident==="set");){let l=Re(e,i.end);e[l]==="*"&&(l=Re(e,l+1));let c=On(e,l);if(!c)break;i=c}if(i){let l=Re(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(Ii,"objectLiteralMemberNames");var au="INVARIANT_TESTS_PATH_MISSING",lu="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.",cu="INVARIANT_COVERAGE_ROOTS_MISSING",du="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Ei(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}a(Ei,"formatCoverageDiscards");function Ci(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}a(Ci,"isUnderCoverageRoot");function Xr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Xr,"escapeRegExp");function at(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(at,"normalizePath");function Zr(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
+ `;)n.push(" "),r+=1;continue}if(s==="/"&&i==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
10
12
  `?`
11
- `:" "),r+=1;r<o&&(n.push(" "," "),r+=2);continue}if(s==='"'||s==="'"||s==="`"){let l=s;for(n.push(t?" ":s),r+=1;r<o;){let c=e[r];if(c==="\\"){let u=e[r+1];t?n.push(" ",u===void 0?"":" "):(n.push("\\"),u!==void 0&&n.push(u)),r+=u===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
12
- `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}i(nr,"maskNonCode");function yl(e,t){if(!t)return;let n=tr(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(nr(e,!1))?.[2];return s===void 0?void 0:s}i(yl,"matchTestTitle");function hl(e,t){if(!t)return;let n=tr(t),r=nr(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}i(hl,"declarationShape");function Al(e,t){let n=e.lastIndexOf(`
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(Zr,"maskNonCode");function uu(e,t){if(!t)return;let n=Xr(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(Zr(e,!1))?.[2];return s===void 0?void 0:s}a(uu,"matchTestTitle");function _i(e,t){if(!t)return;let n=Xr(t),r=Zr(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(_i,"declarationShape");function pu(e,t,n){let r=a(o=>wn(o).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let o of Tn(e))if(!(o.name!==t||o.bodyStart==null)&&r(e.slice(o.bodyStart,o.bodyEnd??e.length)))return"method";for(let o of ki(e,t)){let s=e.slice(o.bodyStart,o.bodyEnd);if(o.kind==="class-expression"&&r(s)||o.kind==="object"&&Ii(s).includes(n))return"method";if(o.kind==="namespace"){let i=_i(s,n);if(i==="function"||i==="const")return i}}}a(pu,"classMemberShape");function fu(e,t){let n=e.lastIndexOf(`
13
15
  `,t-1)+1,r=e.indexOf(`
14
- `,t);return e.slice(n,r===-1?e.length:r)}i(Al,"lineAt");function Rl(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}i(Rl,"isImportLine");function Zs(e,t,n){if(!t||!e.includes(t))return;let r=new Set,o=0,s=e.length,a=i((l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(Rl(Al(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]!==`
15
- `;)a(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(a(o,"comment"),a(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)a(o,"comment"),o+=1;o<s&&(a(o,"comment"),a(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let u=l;for(a(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){a(o,"string"),e[o+1]!==void 0&&a(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===u){a(o,"string"),o+=1;break}a(o,"string"),o+=1}continue}a(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"}i(Zs,"mentionContext");function to(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}i(to,"symbolNeedle");function kl(e){return to(e.coverage?.symbol)?.name??e.id}i(kl,"declaredLabel");function Qs(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}i(Qs,"sortedContentFiles");function no(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(m=>Ye(m))),s=(t.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),a=e.coverage?.test!==!1&&n,l=to(e.coverage?.symbol??void 0),c,u;if(a){for(let m of r){let d=t.fileContents[m];if(!d)continue;let y=yl(d,e.id);if(y!==void 0){if(s.length===0||eo(m,s)){c={file:m,title:y};break}u??={file:m,title:y}}}c??=u}let p;if(l)for(let m of Qs(t.fileContents)){if(o.has(Ye(m)))continue;let d=t.fileContents[m];if(!d||l.className&&!d.includes(l.className))continue;let y=hl(d,l.name);if(y){p={file:m,shape:y};break}}let g;if(!c&&!p){if(a)for(let m of r){let d=t.fileContents[m];if(!d)continue;let y=Zs(d,e.id,!0);if(y){g={file:m,context:y};break}}if(!g&&l)for(let m of Qs(t.fileContents)){if(o.has(Ye(m)))continue;let d=t.fileContents[m];if(!d)continue;let y=Zs(d,l.name,!1);if(y){g={file:m,context:y};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&&Sl(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...p?{declaration:p}:{}}}i(no,"rankCoverage");function Sl(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${tr(n)}(?=$|[^A-Za-z0-9_$])`),s=Ye(r);for(let a of Object.keys(e)){if(t.has(Ye(a))||Ye(a)===s)continue;let l=e[a];if(l&&o.test(nr(l,!0)))return!0}return!1}i(Sl,"symbolInCodeElsewhere");function Il(e,t){return no(e,t).best}i(Il,"classifyCoverage");function ro(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}i(ro,"countsAsCoverage");function El(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"}}i(El,"mentionWhere");function so(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} ${kl(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${El(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"}}i(so,"describeCoverage");function rr(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=Xs(s),l=Xs(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,g=u.join(", "),f=[],m=[];for(let d of t){let y=d.coverage?.test!==!1,b=d.coverage?.symbol,x=!r&&y,S=no(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},x),E=S.best,C=[];x&&S.testTitle&&C.push("test-title"),S.declaration&&C.push("symbol");let D=ro(E),k,P;x&&S.testTitle&&(k=S.testTitle.file,p&&(P=!eo(k,u)));let ge=S.declaration?.file,N=S.declaration?.shape,L=(d.coverage?.test===!0||!!b||d.coverage===void 0)&&D||d.coverage?.test===!1&&!b?!0:D,j=r&&y&&!D;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:L&&!j,evidence:C,partial:j,description:d.description,...k!==void 0?{testEvidenceFile:k}:{},...ge!==void 0?{symbolEvidenceFile:ge}:{},...N!==void 0?{shape:N}:{},...P!==void 0?{outsideDeclaredRoots:P}:{},coverageRootsDeclared:p}),P===!0&&k!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${k}, 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:k,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!L||j){let G=d.mode==="enforced"&&!j,pe=r||n.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(j?o?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${so(d,E)} (${pe==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(j&&o?l:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:G?"error":"warning",failsStrict:G,kind:pe})}}return{coverage:f,violations:m,partial:f.some(d=>d.partial)}}i(rr,"evaluateInvariantCoverage");function sr(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(sr,"canPromoteInvariant");function er(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}i(er,"nonEmptyPathStrings");function bl(e){return!e||typeof e!="object"?[]:[...er(e.testGlobs),...er(e.coverageRoots)]}i(bl,"configuredInvariantTestsPaths");function vl(e){return bl(e).length>0}i(vl,"hasConfiguredInvariantTestsPath");function or(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(or,"catalogDemandsInvariantTestsPath");function oo(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&or(e.invariants);return e.adopted!==!0||!t?[]:vl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:pl,message:fl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(oo,"collectMissingInvariantTestsPathFindings");function Cl(e){return!e||typeof e!="object"?[]:er(e.coverageRoots)}i(Cl,"configuredCoverageRoots");function _l(e){return Cl(e).length>0}i(_l,"hasConfiguredCoverageRoots");function ar(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(ar,"catalogHasEnforcedInvariant");function ao(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&ar(e.invariants)?_l(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:ml,message:gl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(ao,"collectMissingCoverageRootsFindings");var cr="1.0",Ol="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function T(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Ol}`: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}})}i(T,"addFinding");function ee(e){return[...new Set(e??[])].sort()}i(ee,"sortedUnique");function me(e,t,n,r,o){let s=ee(n),a=ee(r),l=new Set(s),c=new Set(a),u=a.filter(g=>!l.has(g)),p=s.filter(g=>!c.has(g));u.length===0&&p.length===0||(u.length>0&&T(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),p.length>0&&T(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(me,"compareStringSets");function At(e,t,n,r,o,s,a){if(n===r)return;T(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(At,"compareBoolean");function Zt(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(Zt,"keyed");function xl(e,t,n){let r=Zt(t,s=>s.name),o=Zt(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&T(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!a&&l){T(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(a&&!l){T(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;me(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),me(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=$t(a),p=$t(l);me(e,`${c}.forbiddenGlobals`,u.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`,u.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)."}),ee(a.intentPrefixes).join("\0")!==ee(l.intentPrefixes).join("\0")&&T(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:ee(a.intentPrefixes),after:ee(l.intentPrefixes)}),At(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),At(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(xl,"compareLayers");function Tl(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Zt(t,r),s=Zt(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&T(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(a),c=s.values.get(a),u=`$.rules[${a}]`;if(!l&&c){c.allowed===!1?T(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):T(e,{kind:"allow-added",path:u,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&T(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&T(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let p=l.peerIsolation===!0,g=c.peerIsolation===!0;if(p!==g){let d=l.from===l.to&&c.from===c.to;T(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?g?"strengthening":"weakening":"judgment-required",message:d?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})}ee(l.sliceFolders).join("\0")!==ee(c.sliceFolders).join("\0")&&T(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:ee(l.sliceFolders),after:ee(c.sliceFolders)});let f=l.sliceIdentity??"path",m=c.sliceIdentity??"path";if(f!==m&&T(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:m}),!(!p&&!g)&&(lo(e,`${u}.sharedRoots`,"shared-roots",ee(l.sharedRoots),ee(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."),lo(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",ee((l.allowedCrossSlice??[]).map(io)),ee((c.allowedCrossSlice??[]).map(io)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(l.sharedImportsSlice??null)!==(c.sharedImportsSlice??null))){let d=c.sharedImportsSlice==="deny";T(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:d?"strengthening":"weakening",message:d?"A shared root may no longer import a slice.":"A shared root may import a slice again.",before:l.sharedImportsSlice??null,after:c.sharedImportsSlice??null})}}}i(Tl,"compareRules");function io(e){return JSON.stringify([e.from,e.to])}i(io,"crossSliceKey");function lo(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(p=>!r.includes(p)),c=r.filter(p=>!o.includes(p)),u=l.length>0&&c.length>0;T(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:l.length>0?s:a,before:r,after:o})}i(lo,"compareDeclaredExceptions");function Nl(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,l=o[s]??0;a!==l&&T(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])At(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Nl,"compareSafety");function ir(e){return e.mode==="enforced"?"enforced":"advisory"}i(ir,"arkRunMode");function lr(e){return e.mode==="enforced"?"enforced":"advisory"}i(lr,"arkOrderMode");function wl(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){T(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${lr(o)}).`,after:o});return}if(r&&!o){T(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=lr(r),l=lr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";T(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}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."})}i(wl,"compareArkOrder");function Pl(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){T(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${ir(o)}).`,after:o});return}if(r&&!o){T(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=ir(r),l=ir(o);if(a!==l){let c=a==="advisory"&&l==="enforced";T(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}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."}),At(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Pl,"compareArkRun");function Ll(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(Ll,"overallClassification");function co(e,t){return`${e}::${t}`}i(co,"ruleKey");function uo(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(co(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(co(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(uo,"indexEffectiveRules");function Dl(e,t,n,r,o,s){let a=new Map((s??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let f of u){let m=l[f],d=c[f],y=`$.arkRules[${f}]`;if(m===void 0&&d!==void 0){T(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(m!==void 0&&d===void 0){T(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:m});continue}m!==d&&T(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:m,after:d})}let p=uo(r),g=uo(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),d=g.structure.get(f),y=`$.arkRules.structure[${f}]`;if(!m&&d){T(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){T(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!d)){if(m.mode!==d.mode){let b=m.mode==="advisory"&&d.mode==="enforced";T(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}m.sensor!==d.sensor&&T(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:m.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),d=g.invariants.get(f),y=`$.arkRules.invariants[${f}]`;if(!m&&d){T(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){T(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!d)&&m.mode!==d.mode)if(m.mode==="advisory"&&d.mode==="enforced"){let x=a?.get(d.id),S=sr(x);S.ok?T(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:d.mode}):T(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${S.reason}`,before:m.mode,after:d.mode})}else T(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}}i(Dl,"compareArkRules");function dr(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."}),At(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";T(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&T(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}),xl(r,e.layers,t.layers),Tl(r,e.rules,t.rules),Nl(r,e,t),Dl(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Pl(r,e,t),wl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:cr,classification:Ll(r),findings:r}}i(dr,"classifyArkPolicyDelta");function ur(e,t){if(!e||e.schemaVersion!==cr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=ee(e.findingIds),r=ee(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(ur,"policyDeltaAcknowledgementMatches");function Me(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Me,"normalizePath");function po(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(po,"isIdentifierStart");function Qt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(Qt,"isIdentifierCharacter");function ce(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ce,"skipWhitespace");function Rt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Rt,"readString");function de(e,t,n){return e.startsWith(t,n)&&!Qt(e[n-1])&&!Qt(e[n+t.length])}i(de,"isWordAt");function fo(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(!de(e,"type",n))return!1;let o=ce(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||de(e,"as",o)||!po(e[o]))return!1;for(n=o;n<e.length&&Qt(e[n]);)n+=1;if(n=ce(e,n),de(e,"as",n)){if(n=ce(e,n+2),!po(e[n]))return!1;for(;n<e.length&&Qt(e[n]);)n+=1}r=!0}return!1}i(fo,"bracedNamedBindingsAreTypeOnly");function Ml(e,t){if(t=ce(e,t+6),e[t]==="(")return Rt(e,ce(e,t+1));let n=!1;if(de(e,"type",t)){let o=ce(e,t+4);e[o]!==","&&!de(e,"from",o)&&(n=!0)}else fo(e,t)&&(n=!0);let r=mo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Ml,"specifierAfterImport");function Fl(e,t){t=t+6;let n=ce(e,t),r=!1;if(de(e,"type",n)){let s=ce(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else fo(e,n)&&(r=!0);let o=mo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(Fl,"specifierAfterExport");function mo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(de(e,"from",t))return Rt(e,ce(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Rt(e,t);if(t>0&&(de(e,"import",t)||de(e,"export",t)))return}}i(mo,"specifierInStaticStatement");function $l(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i($l,"skipTemplateLiteral");function Hl(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=Rt(e,r);return o?{...o,requireCall:!0}:void 0}i(Hl,"specifierAfterRequire");function jl(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(`
16
- `,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=$l(e,n);continue}if(r==="'"||r==='"'){let s=Rt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&de(e,"import",n)?Ml(e,n):r==="e"&&de(e,"export",n)?Fl(e,n):r==="r"&&de(e,"require",n)?Hl(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(jl,"moduleSpecifiers");function go(e,t){let n=[],r=[];for(let o of jl(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=ot(s);if(!u)continue;let p=e.content.slice(0,o.offset).split(`
17
- `).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:p,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
18
- `).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=Kl(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(go,"moduleFactsFor");function Kl(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(Kl,"resolveSpecifier");function yo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Kt(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(yo,"violationsFor");var Vl={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 Ul(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Ul,"hasActiveArkRules");function Gl(e,t){return Ul(e,t)?Z(K(Qn({config:e,arkRules:t,warnings:[]}))):Z(K(Zn(e)))}i(Gl,"policyHashFor");function en(e,t,n){let r=typeof e=="string"?Bn(e,t):zt(e,t),o=n?.arkRules??De();return{...r,arkRules:o,policyHash:Gl(r.config,o)}}i(en,"loadContract");function ho(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=dr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,a=s&&ur(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(ho,"analyzePolicyDelta");function kt(e){let t=e.files.map(g=>{let f=Me(g.path);return{path:f,content:g.content,contentHash:Z(g.content),layer:fe(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=go(g,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=yo(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),l=new Map(e.contract.config.layers.map(g=>[g.name,new Set(je(g))]));for(let g of o){let f=n.get(g.file)?.layer;if(!f)continue;let m=a.get(f),d=Ce(g.symbol,m?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${d}".`,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",u=c==="complete"?[]:[{...Vl}],p={schemaVersion:qn,policyHash:e.contract.policyHash,compilerOptionsHash:Z(K(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:u,valid:c==="complete"&&s.length===0,ir:p}}i(kt,"analyzeProject");function tn(e){let t=new Map(e.files.map(n=>[Me(n.path),n]));for(let n of e.changes){let r=Me(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return kt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(tn,"analyzeChange");function Ao(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(Ao,"explainViolation");function pr(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let 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 u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==c);u.length>1&&a.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(pr,"detectArchitectureCycles");function Je(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Te(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a){let f=As(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=a.rule,c=!!l.peerIsolation,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=c?Ke(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,g=l.message?p?`${l.message} (${p})`:l.message:p?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${p}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:u?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=pr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(Je,"evaluateArchitectureGraph");function Ro(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}i(Ro,"structureFreezeTarget");var Bl=["no-anemic-model"],vo=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],gr=new RegExp(`\\b(${vo.join("|")})\\b`),Co="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",yr=new RegExp(`\\bthis\\.${Co}\\.push\\s*\\(`),zl=new RegExp(`^this\\.${Co}\\s*=\\s*\\[\\s*\\]`),Wl=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,ql=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,_o="truncatedUntil";function hr(){return`${vo.join(", ")}, or events-array .push(`}i(hr,"expectedDomainInvariantWordsPhrase");function Yl(e){return gr.test(e)||yr.test(e)}i(Yl,"referencesGuardOrPublish");function Ar(e,t,n){let r=e.slice(t);if(zl.test(r))return!0;if(!Wl.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))}i(Ar,"isIdiomaticEventsReset");function Jl(e,t){let n=new RegExp(ql.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!Ar(t,r.index,e))return!0;return!1}i(Jl,"methodAssignsThis");function Xl(e,t){return t==null||Object.defineProperty(e,_o,{value:t,enumerable:!1,configurable:!0}),e}i(Xl,"attachShapeTruncation");function mr(e){let t=Object.getOwnPropertyDescriptor(e,_o)?.value;return typeof t=="number"?t:void 0}i(mr,"shapeTruncatedUntil");function Zl(e){let t=mr(e);return t==null?"":` shape analysed until character ${t}`}i(Zl,"shapeTruncationSuffix");function ko(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ko,"escapeGlobLiteral");function Ql(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+=ko(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ko(o)}return new RegExp(`^${n}$`)}i(Ql,"globToRegExp");function Xe(e,t){return!t||t.length===0?!0:t.some(n=>Ql(n).test(e))}i(Xe,"matchesAppliesTo");function Oo(e){return Bl.includes(e)}i(Oo,"isTier2");function xo(e){return e.mode==="enforced"&&!Oo(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(xo,"severityFor");function Oe(e,t,n,r=1){let{severity:o,failsStrict:s}=xo(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(Oe,"baseViolation");function rn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(rn,"isInRuleLayer");function sn(e,t,n){return t.filter(r=>!(!r.exported||!Xe(r.file,e.appliesTo)||!rn(r.file,e,n)))}i(sn,"shapesForRule");function ec(e,t,n){let r=[];for(let o of sn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Oe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(ec,"evaluateAggregatePrivateState");function tc(e,t,n){let r=[];for(let o of sn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Oe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(tc,"evaluateAlwaysValidFactory");function nc(e,t,n){let r=[],o=hr();for(let s of sn(e,t,n)){let a=Zl(s);mr(s)!=null&&r.push(Oe(e,s.file,`Exported class ${s.className} shape analysed until character ${mr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(Oe(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(nc,"evaluateDomainEventOnMutation");function rc(e,t){let n=[];for(let r of t.files)Xe(r,e.appliesTo)&&rn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Oe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(rc,"evaluateOrchestrationOnly");function sc(e,t){let n=[];for(let r of t.files)Xe(r,e.appliesTo)&&rn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Oe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(sc,"evaluateThinAdapter");function oc(e,t){let n=[];for(let r of t.files)Xe(r,e.appliesTo)&&rn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Oe(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(oc,"evaluateWritesViaAggregate");function ac(e,t,n){let r=[];for(let o of sn(e,t,n))if(o.dataOnly===!0){let s=Oe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(ac,"evaluateNoAnemicModel");function 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(...ec(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...tc(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...nc(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...rc(n,e));break;case"thin-adapter":t.push(...sc(n,e));break;case"writes-via-aggregate":t.push(...oc(n,e));break;case"no-anemic-model":t.push(...ac(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(Rr,"evaluateArkRuleSensors");function kr(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=>Xe(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=xo(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>Xe(l,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(kr,"collectEmptyAppliesToFindings");var So=64;function ic(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(ic,"stripTrailingDots");function lc(e){let t=e.trim(),n=t.length>So?t.slice(0,So):t;return ic(n)}i(lc,"normalizeIntentPrefix");function cc(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(cc,"layerNameLooksDomain");function dc(e){return e.some(t=>{let n=lc(t);return n==="Domain"||n.startsWith("Domain.")})}i(dc,"ownsDomainIntent");function uc(e,t=[]){return cc(e)||dc(t)}i(uc,"isDomainRoleLayerName");function To(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>uc(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=t.find(c=>e.arkRules.byLayer?.[c])??t[0],a=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!Oo(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 ${a}.`,file:a,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:a,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}i(To,"collectEmptyInvariantCatalogFindings");var Io=/\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)/,Eo=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,pc=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function fc(e){return e==="PersistenceAdapters"}i(fc,"isPersistenceDriverLayer");function mc(e,t){if(Io.test(e)||Eo.test(e))return!0;if(!t)return!1;for(let n of t){if(fc(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Io.test(o)||Eo.test(o))return!0}return!1}i(mc,"sourceImportsPersistenceDriver");var gc=/\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*=)/,yc=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,hc=/\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*=/,Ac=/\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=mc(t,n),o=r&&pc.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(hc.source,"g"))??[],a=t.match(new RegExp(Ac.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&l+c>=6,p=gc.test(t)||yc.test(t),g=s.length>=1||a.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!u&&!m&&!o?null:{...u?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(No,"deriveArkRuleFileHints");function Sr(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=No(r,o,t?.[s]);a&&(n[s]=a)}return n}i(Sr,"buildArkRuleFileHints");var Rc=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),kc=new Set(["if","match","when"]);function nn(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
19
- `,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==="'"||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}i(nn,"skipStringOrComment");function St(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=nn(e,n);continue}break}return n}i(St,"skipWsAndComments");function bo(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}}i(bo,"readIdent");function fr(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let a=nn(e,s);if(a!==s){s=a;continue}let l=e[s];l===n?o+=1:l===r&&(o-=1),s+=1}return o===0?s:null}i(fr,"skipBalanced");function Sc(e){let t=[],n=0,r;for(;n<e.length&&(n=St(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=bo(e,s);if(!p||!Rc.has(p.ident))break;o.push(p.ident),s=St(e,p.end)}let a=bo(e,s);if(!a){n+=1;continue}if(s=St(e,a.end),e[s]==="<"){let p=fr(e,s,"<",">");if(p==null){r=e.length;break}s=St(e,p)}if(e[s]==="("){let p=fr(e,s,"(",")");if(p==null){r=e.length;break}if(s=St(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=nn(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=fr(e,s,"{","}");if(g==null){r=e.length;break}t.push({name:a.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,u=0;for(;s<e.length;){let p=nn(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==="[")u+=1;else if(g==="]")u-=1;else if(g===";"&&l===0&&c===0&&u===0){s+=1;break}s+=1}t.push({name:a.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}i(Sc,"scanClassMembers");function Ic(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],a=o.index+o[0].length,l=1,c=a;for(;c<t.length&&l>0;){let k=t[c];k==="{"?l+=1:k==="}"&&(l-=1),c+=1}let u=t.slice(a,c-1),p=l>0,g=Sc(u),f=p?t.length:g.truncatedAt==null?void 0:a+g.truncatedAt,m=g.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"))),d=m.length>0,y=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),b=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),x=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!b,S=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),E=[];for(let k of g.members)k.kind==="method"&&k.name!=="constructor"&&(k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set")||kc.has(k.name)||Jl(k.name,k.body)&&E.push({name:k.name,referencesGuardOrPublish:Yl(k.body)}));let D=g.members.filter(k=>k.kind==="method").length<=1&&m.length>=2&&d;n.push(Xl({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:y,hasPublicConstructor:x,hasStaticFactory:S,mutatingMethods:[...E],dataOnly:D},f))}return n}i(Ic,"extractClassShapesFromSource");var Ec=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}}i(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}i(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}}i(Er,"classifyResolvedLayerCoverage");function br(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(br,"isArkRunRuleId");function wo(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(wo,"isArkOrderRuleId");function Po(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_")}i(Po,"isExtraPlaneFinding");function bc(e,t={}){if(!Array.isArray(e)||Ae(t))return e;for(let n of e)Po(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(bc,"demoteExtraPlaneTeethUnderClassificationFloor");var Lo="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 he(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(he,"countOrZero");function on(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),a=e.arkRules,l=he(a?.structureEnforced),c=he(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?he(a.structureAdvisory):Math.max(0,c-l),p=he(a?.invariantEnforced),g=he(a?.invariantTotal),f=typeof a?.invariantAdvisory=="number"?he(a.invariantAdvisory):Math.max(0,g-p),m=l>0||p>0,d=e.arkRun?.present===!0,y=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=he(e.arkRun?.residualCount),x=d&&y==="enforced",S=x&&s,E=e.arkOrder?.present===!0,C=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,D=he(e.arkOrder?.residualCount),k=E&&C==="enforced",P=k&&s,ge=m||x||k,N=ge&&s,H=ge&&o&&!s,L;if(N){let G=[];m&&G.push("enforced structure/invariant findings"),x&&G.push("enforced ArkRun skip findings"),k&&G.push("enforced ArkOrder skip findings"),L=`Layer graph failures plus ${G.join(" and ")} (advisory extras never fail merge alone).`}else if(H)L=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,x?"ArkRun":null,k?"ArkOrder":null].filter(pe=>!!pe).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 G=d?y==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",pe=E?C==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";L="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+G+pe}let j={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:u,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:he(a?.covered),uncovered:he(a?.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:d,mode:y,residualCount:b,extraMergeTeeth:S,note:d?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:E,mode:C,residualCount:D,extraMergeTeeth:P,note:E?C==="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:N,dualPlaneStamp:Lo,failMergeWhen:L};return o&&(j.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),j}i(on,"composeMergePlanesHonesty");var Mo=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],vc=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Cc=new Set(Mo),_c=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"]),Oc=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function bt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(bt,"isArkRunKernelModuleSpecifier");var Fo=["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"],vr=new Set(Fo);function _r(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(vr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(vr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:vr.has(e.slice(0,r))}i(_r,"isArkRunTransportBypassSpecifier");function Cr(e){if(Cc.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}}i(Cr,"arkRunKernelCallKind");function Et(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(Et,"lineAt");function vt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(vt,"stripCommentsPreservingLines");function xc(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}i(xc,"firstStringLiteralArg");function Do(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)}i(Do,"keywordBefore");function an(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]??"")}i(an,"parseValueImportClause");function Tc(e,t){an(vt(e),t)}i(Tc,"forEachArkRunValueImportClause");function Or(e,t){let n=vt(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:Et(t,s.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=a.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:Et(t,s.index),resolution:"resolved-external"})}return r}i(Or,"extractArkRunValueImportDependenciesFromSource");function xr(e){let t=[];return Tc(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 a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),l=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],c=a?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),It(t)}i(xr,"extractArkRunImportedConstructorNamesFromSource");function Nc(e){let t=new Map,n=new Set;return an(e,(r,o)=>{if(!bt(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let l=/\{([^}]*)\}/.exec(r);if(l?.[1])for(let c of l[1].split(",")){let u=c.trim();if(!u||u.startsWith("type "))continue;let p=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(p){t.set(p[2],p[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:n}}i(Nc,"collectKernelImportBindings");function wc(e,t){let n=new Set(t);return an(e,(r,o)=>{let s=/\{([^}]*)\}/.exec(r);if(s?.[1])for(let a of s[1].split(",")){let l=a.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),u=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],p=c?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(bt(o)||t.has(p)||t.has(u))&&(n.add(u),n.add(p))}}),n}i(wc,"collectImportedConstructors");function Pc(e,t){let n;return an(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}i(Pc,"importedFromForName");function Tr(e,t){let n=vt(t),r=Nc(n),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=s.exec(n))!==null;){let l=a[1],c=a.index;if(Do(n,c,"function")||Do(n,c,"class"))continue;let p=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=r.named.get(l)??l,f=Cr(g)??Cr(l);if(!f)continue;let m=r.named.has(l)||p!==void 0&&r.namespaces.has(p);if(f!=="factory"&&(!m&&p===void 0||p&&Oc.has(p)&&!m))continue;let d=xc(n,c+a[0].length);o.push({file:e,line:Et(t,c),kind:f,callee:l,viaImport:m,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}i(Tr,"extractArkRunKernelCallsFromSource");function Nr(e,t,n){let r=vt(t),o=wc(r,n),s=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=a.exec(r))!==null;){let c=l[1];if(_c.has(c)||!o.has(c))continue;let u=Pc(r,c);s.push({file:e,line:Et(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return s}i(Nr,"extractArkRunManagedNewsFromSource");function Lc(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}i(Lc,"matchingBracketEnd");function Dc(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=s.exec(r))!==null;){let l=a[2]??"";l.length>0&&o.push(l)}return o}i(Dc,"stringLiteralsInList");function It(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(It,"uniqueSorted");function Mc(e,t){let n=vt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],a=[],l=[],c,u;for(;(u=r.exec(n))!==null;){let p=n.slice(u.index+u[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=u.index+u[0].length+(g[0].length-1),m=Lc(n,f);if(m<0)continue;let d=Dc(n,f,m);if(d.length===0)continue;c===void 0&&(c=u.index);let y=u[1];y==="uses"?o.push(...d):y==="reactsTo"?s.push(...d):y==="raises"?a.push(...d):l.push(...d)}return c===void 0?[]:[{file:e,line:Et(t,c),uses:It(o),reactsTo:It(s),raises:It(a),sends:It(l)}]}i(Mc,"extractArkRunDeclarationsFromSource");var Fc=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],$c=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Hc=new Set($c);function jc(e){return Hc.has(e)}i(jc,"isArkRunEditorSensor");var wr={"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"},jo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ko(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Ko,"isDomainRoleLayer");function Kc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Kc,"compareFindings");function be(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:wr[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:wr[t],fromLayer:s?.fromLayer,target:s?.target})}}i(be,"finding");function Vc(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(Vc,"bagForFile");function $o(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i($o,"emitKinds");function Ho(e){return e==="subscribe"||e==="register-handler"}i(Ho,"handleKinds");function Uc(e){return e==="resolve"||e==="resolve-singleton"}i(Uc,"dependKinds");function Gc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(be(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let l=s.get(a.matchedRoot)??[];l.push(a),s.set(a.matchedRoot,l)}for(let a of o){let l=[...s.get(a)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(l.length===0){r.push(be(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(be(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(Gc,"evaluateMissingRoot");function Bc(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!bt(c))continue;let u=r(l.from);u&&Ko(u,s.get(u)??[])&&a.push(be(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return a}i(Bc,"evaluateKernelInDomain");function zc(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.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)),u=[];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||!a.has(f)||Ko(f,l.get(f)??[])||u.push(be(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 u}i(zc,"evaluateDirectNew");function Wc(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:a};for(let c of t){if(!$o(c.kind)&&!Ho(c.kind)&&!Uc(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:jo,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let p=Vc(n,c.file);if($o(c.kind)){if(p.raises.has(c.nameLiteral)||p.sends.has(c.nameLiteral))continue;s.push(be(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},o));continue}if(Ho(c.kind)){if(p.reactsTo.has(c.nameLiteral))continue;s.push(be(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},o));continue}p.uses.has(c.nameLiteral)||s.push(be(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(Wc,"evaluateUndeclared");function qc(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!_r(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(be(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}i(qc,"evaluateTransportBypass");function ln(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Ae(e.classification),r=Wc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Gc(t,e.compositionRootHits,n),...Bc(t,e.layers,e.dependencies,e.layerForFile,n),...zc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...qc(t,e.dependencies,e.layerForFile,n)].sort(Kc),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}i(ln,"evaluateArkRunSensors");function Vo(e){return{findings:ln(e).findings.filter(n=>jc(n.sensor)),completenessReasons:[]}}i(Vo,"evaluateArkRunEditorSensors");function Yc(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}/`))}i(Yc,"fileMatchesCompositionRoot");function Jc(e,t,n){let r=Tr(t,n).some(a=>a.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let a of s)Yc(a,t)&&o.push({file:t,matchedRoot:a,hasKernelFactory:r});return o}i(Jc,"compositionRootHitsForSource");function Xc(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(xr(e.source));return Vo({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Nr(e.file,e.source,n),compositionRootHits:Jc(t,e.file,e.source),declarations:[],dependencies:Or(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Xc,"evaluateArkRunEditorSensorsFromSource");function Uo(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Uo,"isArkOrderModuleSpecifier");var Go=new Map;function Bo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Bo,"escapeAppliesToLiteral");function Zc(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(Zc,"normalizeAppliesToGlob");function Qc(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(Qc,"appliesToBracesBalanced");function ed(e){let t=Go.get(e);if(t)return t;let n=Zc(e),r=Qc(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Bo(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+=Bo(c)}let a=new RegExp(`^${o}$`);return Go.set(e,a),a}i(ed,"globToRegExp");var td=["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"],Pr={"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 nd(e,t){return!t||t.length===0?!0:t.some(n=>ed(n).test(e))}i(nd,"matchesArkOrderAppliesTo");function rd(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(rd,"isDomainRoleLayer");function xe(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Pr[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:Pr[t],fromLayer:s?.fromLayer,target:s?.target})}}i(xe,"finding");function Lr(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(xe(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let u of e.planeRootHits){let p=c.get(u.matchedRoot)??[];p.push(u),c.set(u.matchedRoot,p)}for(let u of o){let p=c.get(u)??[];if(p.length===0){r.push(xe(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}p.some(g=>g.hasPlaneFactory)||r.push(xe(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!Uo(u))continue;let p=e.layerForFile(c.from);p&&rd(p,s.get(p)??[])&&r.push(xe(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let c of e.genericUpdates)r.push(xe(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(xe(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(xe(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||nd(c.file,t.appliesTo)&&r.push(xe(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}i(Lr,"evaluateArkOrderSensors");function te(e,t,n={}){return{ruleId:e,message:t,...n}}i(te,"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(d=>typeof d!="string"))&&s.push(te("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(te("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let y=t.safety[d];y!==void 0&&(!Number.isInteger(y)||y<0)&&s.push(te("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...a.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);a.length===0&&s.push(te("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of a){if(!d.name){s.push(te("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="string"))&&s.push(te("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let y=Array.isArray(d.patterns)?d.patterns:[];if(y.length===0){s.push(te("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let b of y){let x;try{x=ke(b)}catch(E){s.push(te("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${E instanceof Error?E.message:String(E)}`,{layer:d.name,pattern:b}));continue}let S=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(E=>x.test(E))&&!S&&s.push(te("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of p)s.push(te("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&s.push(te("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&s.push(te("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let g=new Set;if(a.length>1)for(let d of r){let y=-1,b=[];for(let x of a)for(let S of x.patterns??[]){if(!ke(S).test(d))continue;let E=wn(S,d);E>y?(y=E,b=[x.name]):E===y&&!b.includes(x.name)&&b.push(x.name)}b.length>1&&g.add([...b].sort().join(" + "))}g.size>0&&s.push(te("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(d=>!fe(d,a));f.length>0&&s.push(te("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 d of ms(n))s.push(te("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));let m=Fs(t);if(m.length>0){let d=m[0]??"this layer";s.push(te("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:m,nextAction:$s(d)}))}return s}i(cn,"collectAnalysisConfigWarnings");function zo(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:Ro({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(zo,"toArkRuleEngineViolation");function sd(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(sd,"arkRulesMapIsOn");function Wo(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.`}i(Wo,"arkRuleFindingNextAction");function od(e,t){return t.some(n=>{try{return ke(n).test(e)}catch{return!1}})}i(od,"matchesAny");function ad(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:b})=>({file:y,line:b})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:b})=>({file:y,line:b})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!od(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),u=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"})),p=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})),g={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],m=c.filter(y=>y.kind==="import");if(m.length>0){let y=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(y=>y.kind==="require");if(d.length>0){let y=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];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(u.length>0){let y=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return 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}}i(ad,"evaluateSafety");function id(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(id,"ambientForbiddenGlobal");function qo(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return $n(e,n.length>0?n:Fn.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(qo,"intentLayer");function ld(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!id(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let l=o.get(a),c=l?.forbiddenGlobals??[],u=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"&&at(s.symbol,c))){if(s.source==="import-based"){let p=Ce(s.symbol,c);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}je(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let c of it({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!s.sourceIntent)continue;let l=qo(s.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let l=qo(s.intent,e.contract);if(!l)continue;let c=Te(e.contract.config.rules,a,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?Ke(c.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,p=`${a} must not reference ${l} intent ${s.intent}.`,g=u&&c.peerIsolationReason!=="cross-slice"?`${p} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:g})}return r}i(ld,"contentViolations");function cd(e){let{facts:t}=e,n=ft(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((A,se)=>{let tt=`${A.code}\0${A.file??""}\0${A.message}`,nt=`${se.code}\0${se.file??""}\0${se.message}`;return tt<nt?-1:tt>nt?1:0}),a=t.files.map(A=>({...A,layer:fe(A.path,e.contract.config.layers)??null})),l=new Map(a.map(A=>[A.path,A.layer])),c=t.dependencies.map(A=>{let se=A.target?l.get(A.target)??fe(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:l.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...se?{toLayer:se}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),u=cn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(A=>A.path)}),p=ad(e,t),g=e.contract.arkRules??De(),f=a.map(A=>A.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Sr(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=i(A=>l.get(A)??fe(A,e.contract.config.layers),"resolveLayer"),b=[...Rr({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:y,fileHints:d}),...kr(g,f),...To({arkRulesActive:sd(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(A=>({path:A,layer:y(A)}))})],x=(g.invariants?.length??0)>0,S=ao({hasEnforcedInvariant:ar(g.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),E=S.length>0?[]:oo({adopted:e.adopted===!0,hasDomainInvariants:or(g.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),C=[...S.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.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})),...E.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.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}))],D=b.filter(A=>A.failsStrict).map(A=>zo(A,Wo(A,!1))),k=b.filter(A=>!A.failsStrict).map(A=>({...zo(A,Wo(A,!0)),failsStrict:!1})),P=x?rr({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},ge=P.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),N=P.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${A.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),H=Er(a),L=ln({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(A=>l.get(A)??fe(A,e.contract.config.layers),"layerForFile"),classification:H}),j=e.contract.config.arkRun?.mode,G=L.findings.filter(()=>j==="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:A.failsStrict,...A.severity?{severity:A.severity}:{}})),pe=L.findings.filter(()=>j!=="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:!1})),Re=Lr({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(A=>l.get(A)??fe(A,e.contract.config.layers),"layerForFile"),classification:H}),et=e.contract.config.arkOrder?.mode,Nt=Re.findings.filter(()=>et==="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:A.failsStrict,...A.severity?{severity:A.severity}:{}})),ns=Re.findings.filter(()=>et!=="enforced").map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,target:A.target,nextAction:A.nextAction,sensor:A.sensor,failsStrict:!1})),v=[...P.partial&&P.coverage.some(A=>A.mode==="enforced"&&A.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."}]:[],...L.completenessReasons,...Re.completenessReasons],_=Je({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(A=>A.layer).map(A=>A.path),contentViolations:[...ld(e,t,l),...D,...C,...ge,...G,...Nt],edges:c,warnings:[...u,...p.warnings,...k,...N,...pe,...ns],safety:p.report}),h=o==="complete"&&v.length>0?"partial":o,R=h==="complete"?s:[...s,...v].sort((A,se)=>{let tt=`${A.code}\0${A.file??""}\0${A.message}`,nt=`${se.code}\0${se.file??""}\0${se.message}`;return tt<nt?-1:tt>nt?1:0}),M=_.violations.filter(A=>A.failsStrict!==!1),X=h==="complete"&&M.length===0,ve=X&&_.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:h,completenessReasons:R,valid:X,strictValid:ve,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:a,layers:e.contract.config.layers.map(A=>A.name),edges:c,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}i(cd,"analyzeCanonicalResolvedProject");function Ct(e){return cd({contract:e.contract,facts:_e(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(Ct,"analyzeResolvedProject");function Yo(e){return Z(K(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Yo,"analysisTreeHash");function Jo(e){let t=kt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let y=d.path.replace(/\\/g,"/"),b=Me(d.path);if(!b||b===".."||b.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=tn({...e,changes:r}),l=new Map(a.ir.files.map(d=>[d.path,d])),c=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let y=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:d.message}}),u=Je({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:c,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(d=>{let y=Me(d.path),b=n.get(y),x=l.get(y);return{path:y,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...x?{candidateContentHash:x.contentHash}:{}}}).sort((d,y)=>d.path.localeCompare(y.path)),g=[...s,...u.violations].map(d=>({...d,nextAction:ye(d)})),f=g.filter(d=>d.failsStrict!==!1),m=e.changeMap?qe({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Yo(t.ir.files),candidateTreeHash:Yo(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:u.warnings}}i(Jo,"preflightChange");function dd(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(dd,"canonicalChangePath");function ud(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(ud,"identityViolations");function pd(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(pd,"preparedChange");function Xo(e){let t=_e(e.baseFacts),n=_e(e.candidateFacts),r=Ct({contract:e.contract,facts:t}),o=Ct({contract:e.contract,facts:n}),s=new Map(t.files.map(m=>[m.path,m])),a=new Map(n.files.map(m=>[m.path,m])),l=ud(t,n),c=new Map,u=[];for(let m of e.changes){let d=dd(m.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,m);let y=s.get(d),b=a.get(d);if("delete"in m&&m.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let x="content"in m?m.content:"",S=Z(x);b?b.contentHash!==S&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:S,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(pd(m,d,s,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let m of new Set([...s.keys(),...a.keys()])){if(c.has(m))continue;let d=s.get(m),y=a.get(m);d&&y&&K(d)===K(y)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:m,line:1,message:`Candidate facts change ${m}, but the atomic change set does not declare it.`})}let p=e.changeMap?qe({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:o.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0,g=[...l,...o.ir.violations].map(m=>({...m,nextAction:ye(m)})),f=g.filter(m=>m.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&f.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:u.sort((m,d)=>m.path<d.path?-1:m.path>d.path?1:0),violations:g,warnings:o.ir.warnings}}i(Xo,"preflightResolvedChange");var Zo="1.0",fd=12,md="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",gd="Next: /ark-runtime to wire one candidate.";function Qo(e){return e==="enforced"||e==="advisory"?e:null}i(Qo,"closedMode");function yd(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)}i(yd,"uniqueArkRunRuleIds");function hd(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Qo(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}i(hd,"extraFromConfig");function Ad(e={}){let t=hd(e.arkRun),n=t.present?yd(e.findings):[],r=n.slice(0,fd),o=n.length,s=on({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:o}}),a=t.present&&t.mode==="enforced"&&Ae(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?l="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":l="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":l="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:Zo,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:r},extraMergeTeeth:a,failMergeWhen:s.failMergeWhen,note:l,mergePlanes:s}}i(Ad,"summarizeArkRunSection");function Dr(e={}){let t=e.present===!0,n=Qo(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}}i(Dr,"projectStatusArkRun");function Rd(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=[md,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let o=e.residual.ruleIds.join(", "),s=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${o}${s}`),r.push(gd)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");return e.failMergeWhen&&r.push(e.failMergeWhen),r}i(Rd,"formatArkRunDoctorLines");function dn(e,t){return e.slice(0,t).split(`
20
- `).length}i(dn,"lineOf");function ea(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(ea,"normalizeInventoryPath");function na(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}i(na,"ownsIntent");function ta(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||na(t,["Domain"])}i(ta,"isDomainLayer");function kd(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||na(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(kd,"isControllerEligibleLayer");function Sd(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)}i(Sd,"isNonPilotSurface");function Id(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[ea(c),u])),o=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),s=(e.layerContexts??[]).find(c=>ta(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([p],[g])=>p.localeCompare(g))){let p=ea(c);if(Sd(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let g=r.has(p),f=r.get(p),m=f?o.get(f)??[]:[],d=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(p)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(p)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(p),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),x=/controller|handler|resolver/i.test(c)||y||b||/route\.(?:ts|js|tsx|jsx)$/i.test(p)&&!d||/@(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),S=g?!!(f&&kd(f,m)&&x):x,E=g?!!(f&&ta(f,m)):/domain|entity|aggregate|model/i.test(c),C=!g||E||S;if(S&&!d){let N=/\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,H;for(;(H=N.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:dn(u,H.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let D=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,k,P=i(N=>/^(?: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(N)||/^(?: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(N)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(N)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(N)||/^(?: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(N)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(N)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(N)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(N)||/_(?:OID|OIDS)$/i.test(N)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(N)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(N),"isInfraMagicName"),ge=i((N,H)=>{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(N)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(N))return!0;let L=H.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(H)&&(/\s/.test(L)||/[.!?…]$/.test(L))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(N))},"isUxMessageConstant");for(;(k=D.exec(u))!==null;){let N=k[2],H=k[3]??"";!C||P(N)||ge(N,H)||d&&!E||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!E||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:dn(u,k.index),message:`Magic business constant ${N} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${N}`},neverMechanicalSafe:!0}))}if(E){let N=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,H;for(;(H=N.exec(u))!==null;){let L=H[2]??"",j=(L.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(L.match(/:\s*[A-Za-z]/g)??[]).length>=2&&j<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:dn(u,H.index),message:`Class ${H[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(E&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let H=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,L;for(;(L=H.exec(u))!==null;){let j=u.lastIndexOf("class ",L.index),G=j>=0?u.indexOf("{",j):-1,pe=j>=0&&G>=j&&G<L.index?u.slice(j,G):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(pe)||Ar(u,L.index))continue;let Re=u.slice(Math.max(0,L.index-200),L.index+200);if(!gr.test(Re)&&!yr.test(Re)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:dn(u,L.index),message:`Domain field mutation without nearby ${hr()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((c,u)=>+(u.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(u.file)||c.line-u.line||c.kind.localeCompare(u.kind)||c.id.localeCompare(u.id));let l=t.filter(c=>c.suggestedArkRule?.invariantId&&a.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&a.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Id,"buildRulesInventory");function Ed(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."}}i(Ed,"inventoryToExtractionCard");var bd="1.1";var vd="1.0";var Mr="docs/diagnostics.md",Cd="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(I,"entry");var un=Object.freeze([I("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),I("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),I("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),I("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),I("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),I("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),I("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),I("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),I("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),I("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),I("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),I("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),I("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),I("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),I("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),I("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),I("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),I("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),I("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),I("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),I("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),I("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),I("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),I("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),I("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),I("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),I("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),I("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),I("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),I("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),I("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),I("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),I("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),I("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),I("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),I("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),I("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),I("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),I("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),I("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),I("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),I("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),I("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),I("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),I("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),I("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),I("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),I("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),I("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),I("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),I("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),I("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),I("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),I("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),I("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),I("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),I("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),I("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),I("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),I("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),I("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),I("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),I("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),I("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),I("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),I("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),I("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),I("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),I("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),I("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),I("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),I("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),I("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),I("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),I("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),I("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),I("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),I("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Fr=new Map(un.map(e=>[e.ruleId,e])),_d=Object.freeze(un.map(e=>e.ruleId));function Od(e){return typeof e=="string"&&e.length>0&&Fr.has(e)}i(Od,"isKnownDiagnosticCode");function xd(e){return typeof e!="string"||e.length===0?!1:Fr.has(e)?!0:e.startsWith("ARKRULE_")}i(xd,"isCataloguedOrArkRuleFamily");function pn(e){if(!(typeof e!="string"||e.length===0))return Fr.get(e)}i(pn,"getDiagnosticCatalogEntry");function ra(e){return`#${pn(e)?.docsAnchor??e}`}i(ra,"diagnosticDocsFragment");function Td(e){return`${Mr}${ra(e)}`}i(Td,"diagnosticDocsPath");function Nd(){return{schemaVersion:"1.0",docsPath:Mr,codes:un}}i(Nd,"serializeDiagnosticCatalog");function wd(e){return pn(e)?.fix}i(wd,"catalogFixForRuleId");function Pd(e){return pn(e)?.why}i(Pd,"catalogWhyForRuleId");function Ld(e){return e==="enforced"||e==="advisory"?e:null}i(Ld,"closedMode");function sa(e={}){let t=e.present===!0,n=Ld(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}}i(sa,"projectStatusArkOrder");var $r="1.0",oa="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",aa=["full","subset","unavailable"],ia=["doctor-facts","report-snapshot","none"],fn={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},la=/^sha256:[a-f0-9]{64}$/;function ca(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"||!la.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."}}i(ca,"evaluateStatusBinding");function da(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"}i(da,"classifyStatusWritePath");function ua(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)."}i(ua,"defaultHonestLabel");function pa(e,t,n,r,o){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{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)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?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 (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}: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".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(pa,"resolveStatusNextAction");function Dd(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&la.test(e.projectId)?e.projectId:null,r=ca({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,a=da({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():ua(a,s),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:_t(e.activeViolations),frozenResidual:_t(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:_t(e.rulesInventoried),underContract:_t(e.rulesUnderContract),frozenResidual:_t(e.rulesFrozenResidual)},p={writePath:a,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:$r,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:c,rules:u,nextAction:pa(e,r,p,c,u)},m=ma(e.improvementCompass);return m&&(f.improvementCompass=m),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Dr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=sa(e.arkOrder)),f}i(Dd,"buildStatusManifest");var fa=new Set(aa),Md=new Set(ia);function Hr(e){let t=fa.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Md.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 a={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:fn.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&&(a.contractHash=r),a}let o=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.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:fn.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}i(Hr,"projectStatusImprovementCompass");function Fd(e={}){return Hr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??fn.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --doctor or --report for residual lenses. Status never invents green.",factsSource:"none",contractHash:e.contractHash})}i(Fd,"unavailableStatusImprovementCompass");function ma(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"&&fa.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})}i(ma,"normalizeStatusImprovementCompass");function $d(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}i($d,"statusCompassResidualIsSubsetOfDoctor");function _t(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(_t,"numberOrNull");var Hd={$schema:"https://json-schema.org/draft/2020-12/schema",$id:oa,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:$r},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}}},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 mn="1.0",gn=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],yn=5,Fe=["scalability","resilience","security"],Ze=new Set(Fe),jr={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},Kr={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"},Vr={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 Ur(e){return Kr[e]??e}i(Ur,"improvementCompassHumanLabel");function Gr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Gr,"smellIdOf");function Br(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Br,"violationRuleId");function U(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)}i(U,"pushEvidence");function re(e,t,n){Ze.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(re,"markResidual");function ga(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`${Kr[e]} \u2014 no residual from current sensors.`}}i(ga,"defaultOkSummary");function ya(){return gn.map(e=>Ze.has(e)?{id:e,status:"out-of-scope",summary:Vr[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:ga(e),evidence:[]}:{id:e,status:"ok",summary:ga(e),evidence:[]})}i(ya,"createInitialImprovementCompassLenses");function jd(e,t){for(let n of t){let r=Gr(n);if(!r)continue;let o=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((p,g,f)=>{let m=e.get(p);!m||Ze.has(p)||(U(m,"designSmells",r,o),a&&U(m,"designSmells",a,r),re(m,g,f))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={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.",u);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.",u),l("testability","Direct I/O under application code hurts pure unit testing.",u);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}}}i(jd,"mapDesignSmells");function Kd(e){return e.failsStrict===!1||e.typeOnly===!0}i(Kd,"isTypeOnlyPlacementDebt");function Vd(e,t){for(let n of t){let r=Br(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),a=i((c,u,p)=>{let g=e.get(c);!g||Ze.has(c)||(U(g,"violations",r,o),n.file&&U(g,"violations",n.file,r),re(g,u,p))},"attach");if(Kd(n)){a("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"){a("coupling","Import graph edges violate the layer contract.",l);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",l);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){a("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_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("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"){a("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)."}),a("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"){a("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."}),a("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}}}i(Vd,"mapViolations");function Ud(e,t){let n=Number(t.cycleCount)||0;if(n>0){let m=e.get("coupling");U(m,"cycles",`count:${n}`),re(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");U(m,"peerIsolation",`count:${r}`),re(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");U(m,"physicalCohesion",`findings:${o}`),re(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 d=e.get("srp");U(d,"physicalCohesion",`findings:${o}`),re(d,"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,a=Number(t.forbiddenGlobalResidual)||0;if(s>0||a>0){let m=e.get("dip");s>0&&U(m,"capability",`residual:${s}`),a>0&&U(m,"forbiddenGlobals",`residual:${a}`),re(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let d=e.get("testability");s>0&&U(d,"capability",`residual:${s}`),a>0&&U(d,"forbiddenGlobals",`residual:${a}`),re(d,"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");U(m,"arkRules",`structureResidual:${l}`),re(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 d=e.get("domain");U(d,"arkRules",`structureResidual:${l}`),re(d,"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");U(m,"designFitness","design-weak"),re(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&&U(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&U(m,"baseline",`stale:${t.baselineStale}`),re(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");U(m,"baseline",`frozen:${c}`),re(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 u=Number(t.ungovernedDirCount)||0,p=Number(t.emptyLayerCount)||0;if(u>0||p>0){let m=e.get("modularity");u>0&&U(m,"coverage",`ungovernedDirs:${u}`),p>0&&U(m,"coverage",`emptyLayers:${p}`),re(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");U(m,"goldenPattern","absent"),re(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."})}i(Ud,"mapCountsAndFlags");function ha(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>Gr(r).localeCompare(Gr(o)));jd(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=Br(r).localeCompare(Br(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});Vd(e,n)}Ud(e,t)}i(ha,"projectImprovementCompassFacts");function Aa(e){for(let t of Fe){let n=e.get(t);n.status="out-of-scope",n.summary=Vr[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."}}}i(Aa,"lockImprovementCompassOutOfScope");function Ra(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)})}i(Ra,"sortImprovementCompassEvidence");function ka(e){return e.filter(n=>n.status==="residual"&&!Ze.has(n.id)).slice().sort((n,r)=>{let o=jr[n.id]??150,s=jr[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(ka,"finalizeImprovementCompassTopResidual");function Gd(e={}){let t=ya(),n=new Map(t.map(o=>[o.id,o]));ha(n,e),Aa(n),Ra(t);let r=ka(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(a=>({...a}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}i(Gd,"buildImprovementCompass");function Sa(e){return e.topResidual.map(t=>Ur(t))}i(Sa,"formatImprovementCompassResidualLabels");function Ia(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}i(Ia,"primaryImprovementCompassNextAction");function Bd(e){let t=Sa(e),n=Fe.map(s=>Ur(s)),r=Ia(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}i(Bd,"formatImprovementCompassDoctorLines");var $e="1.0",Ea="<!-- arkgate:agent-projection:begin",hn="<!-- arkgate:agent-projection:end -->",An="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",Ot=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ba=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 Qe(e){let t=String(e??"").replace(/\r\n/g,`
21
- `),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")}`}i(Qe,"agentProjectionContentIdentity");function xt(e){return String(e??"").replace(/\r\n/g,`
22
- `)}i(xt,"normalizeNewlines");function He(e){let t=xt(e);return t.endsWith(`
16
+ `,t);return e.slice(n,r===-1?e.length:r)}a(fu,"lineAt");function gu(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(gu,"isImportLine");function bi(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(gu(fu(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(bi,"mentionContext");function xi(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(xi,"symbolNeedle");function mu(e){return xi(e.coverage?.symbol)?.name??e.id}a(mu,"declaredLabel");function vi(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(vi,"sortedContentFiles");function Oi(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(h=>at(h))),s=(t.coverageRoots??[]).filter(h=>typeof h=="string"&&h.length>0),i=e.coverage?.test!==!1&&n,l=xi(e.coverage?.symbol??void 0),c,d;if(i){for(let h of r){let p=t.fileContents[h];if(!p)continue;let y=uu(p,e.id);if(y!==void 0){if(s.length===0||Ci(h,s)){c={file:h,title:y};break}d??={file:h,title:y}}}c??=d}let u;if(l)for(let h of vi(t.fileContents)){if(o.has(at(h)))continue;let p=t.fileContents[h];if(!p)continue;let y=l.className?pu(p,l.className,l.name):_i(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=bi(p,e.id,!0);if(y){m={file:h,context:y};break}}if(!m&&l)for(let h of vi(t.fileContents)){if(o.has(at(h)))continue;let p=t.fileContents[h];if(!p)continue;let y=bi(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&&hu(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...u?{declaration:u}:{}}}a(Oi,"rankCoverage");function hu(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${Xr(n)}(?=$|[^A-Za-z0-9_$])`),s=at(r);for(let i of Object.keys(e)){if(t.has(at(i))||at(i)===s)continue;let l=e[i];if(l&&o.test(Zr(l,!0)))return!0}return!1}a(hu,"symbolInCodeElsewhere");function yu(e,t){return Oi(e,t).best}a(yu,"classifyCoverage");function wi(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(wi,"countsAsCoverage");function Au(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(Au,"mentionWhere");function Ti(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} ${mu(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Au(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(Ti,"describeCoverage");function Jr(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,i=Ei(s),l=Ei(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",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=Oi(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=wi(k),P,D;C&&R.testTitle&&(P=R.testTitle.file,u&&(D=!Ci(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}: ${Ti(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(Jr,"evaluateInvariantCoverage");function Qr(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(Qr,"canPromoteInvariant");function Yr(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(Yr,"nonEmptyPathStrings");function Ru(e){return!e||typeof e!="object"?[]:[...Yr(e.testGlobs),...Yr(e.coverageRoots)]}a(Ru,"configuredInvariantTestsPaths");function Su(e){return Ru(e).length>0}a(Su,"hasConfiguredInvariantTestsPath");function es(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(es,"catalogDemandsInvariantTestsPath");function Li(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&es(e.invariants);return e.adopted!==!0||!t?[]:Su(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:au,message:lu,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(Li,"collectMissingInvariantTestsPathFindings");function ku(e){return!e||typeof e!="object"?[]:Yr(e.coverageRoots)}a(ku,"configuredCoverageRoots");function Iu(e){return ku(e).length>0}a(Iu,"hasConfiguredCoverageRoots");function ts(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(ts,"catalogHasEnforcedInvariant");function Ni(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&ts(e.invariants)?Iu(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:cu,message:du,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(Ni,"collectMissingCoverageRootsFindings");var os="1.0",Eu="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 ${Eu}`: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 $t(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($t,"compareBoolean");function Nn(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(Nn,"keyed");function bu(e,t,n){let r=Nn(t,s=>s.name),o=Nn(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=an(i),u=an(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)}),$t(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."),$t(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(bu,"compareLayers");function vu(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=Nn(t,r),s=Nn(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;Ln(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."),Ln(e,`${d}.allowedCrossSlice`,"cross-slice-allowance",z((l.allowedCrossSlice??[]).map(ss)),z((c.allowedCrossSlice??[]).map(ss)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let p=Te(l.sharedImportsSlice)??null,y=Te(c.sharedImportsSlice)??null;if(p!==y){let S=Ui(y)>Ui(p);x(e,{kind:"shared-imports-slice",path:`${d}.sharedImportsSlice`,classification:S?"strengthening":"weakening",message:Fu(p,y),before:p,after:y})}else y==="deny-cross-parent"&&Ln(e,`${d}.sharedImportsSlice.stopAt`,"shared-walk-stop",Di(l.sharedImportsSlice),Di(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.");_u(e,d,l,c)}}a(vu,"compareRules");function Pi(e){let t=e.childSlices;return t?JSON.stringify([z(t.sliceFolders??[]),t.sliceIdentity??"path",z(t.commonFolders??[])]):""}a(Pi,"childSliceFoldersKey");function Di(e){return z(pn(e).map(t=>Mt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Di,"stopAtKeys");function $i(e){return e==="always"?2:e==="auto"?1:0}a($i,"siblingRatchetRank");function Cu(e){return z((e??[]).map(t=>Mt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Cu,"enforceKeys");function Mi(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:Cu(t.enforce),ratchet:Oo(t)}}a(Mi,"childSliceSiblingPolicy");function _u(e,t,n,r){let o=Mi(n),s=Mi(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(Pi(n)!==Pi(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"&&(xu(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce),o.ratchet!==s.ratchet)){let c=$i(s.ratchet)>$i(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}),Lu(e,t,n,r),Tu(e,t,n,r)}a(_u,"compareChildSlices");function xu(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(xu,"compareSiblingEnforceList");function ss(e){return JSON.stringify([e.from,e.to])}a(ss,"crossSliceKey");function Fi(e){return z((e.childSlices?.allowedCrossSlice??[]).map(ss))}a(Fi,"childCrossSliceKeys");function lt(e){return Mt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(lt,"allowanceSegments");function ji(e,t){let n=lt(e),r=lt(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(ji,"patternWidens");function Ou(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=lt(n[0]).join("/")===lt(r[0]).join("/"),s=lt(n[1]).join("/")===lt(r[1]).join("/"),i=ji(n[0],r[0]),l=ji(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(Ou,"allowanceWidens");function wu(e){return JSON.stringify([Mt(e.from.trim().replace(/\\/g,"/")).toLowerCase(),Mt(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(wu,"aliasEntryKey");function Hi(e){return z((e.childSlices?.sliceAliases??[]).map(wu))}a(Hi,"sliceAliasKeys");function Tu(e,t,n,r){let o=Hi(n),s=Hi(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(Tu,"compareSliceAliases");function Lu(e,t,n,r){let o=Fi(n),s=Fi(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=>Ou(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}Ln(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(Lu,"compareChildCrossSliceAllowances");function Ln(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(Ln,"compareDeclaredExceptions");function Nu(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"])$t(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(Nu,"compareSafety");function ns(e){return e.mode==="enforced"?"enforced":"advisory"}a(ns,"arkRunMode");function rs(e){return e.mode==="enforced"?"enforced":"advisory"}a(rs,"arkOrderMode");function Pu(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 (${rs(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=rs(r),l=rs(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(Pu,"compareArkOrder");function Du(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 (${ns(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=ns(r),l=ns(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."}),$t(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Du,"compareArkRun");function $u(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($u,"overallClassification");function Ki(e,t){return`${e}::${t}`}a(Ki,"ruleKey");function Vi(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Ki(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Ki(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Vi,"indexEffectiveRules");function Mu(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=Vi(r),m=Vi(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=Qr(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(Mu,"compareArkRules");function is(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."}),$t(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}),bu(r,e.layers,t.layers),vu(r,e.rules,t.rules),Nu(r,e,t),Mu(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Du(r,e,t),Pu(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:os,classification:$u(r),findings:r}}a(is,"classifyArkPolicyDelta");function as(e,t){if(!e||e.schemaVersion!==os||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(as,"policyDeltaAcknowledgementMatches");function Mt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Mt,"trimTrailingSlashes");function Ui(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(Ui,"sharedImportsSliceRank");function Fu(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(Fu,"sharedImportsSliceMessage");function Ge(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(Ge,"normalizePath");function Gi(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(Gi,"isIdentifierStart");function Pn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(Pn,"isIdentifierCharacter");function ce(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ce,"skipWhitespace");function Ft(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(Ft,"readString");function pe(e,t,n){return e.startsWith(t,n)&&!Pn(e[n-1])&&!Pn(e[n+t.length])}a(pe,"isWordAt");function Bi(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)||!Gi(e[o]))return!1;for(n=o;n<e.length&&Pn(e[n]);)n+=1;if(n=ce(e,n),pe(e,"as",n)){if(n=ce(e,n+2),!Gi(e[n]))return!1;for(;n<e.length&&Pn(e[n]);)n+=1}r=!0}return!1}a(Bi,"bracedNamedBindingsAreTypeOnly");function ju(e,t){if(t=ce(e,t+6),e[t]==="(")return Ft(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 Bi(e,t)&&(n=!0);let r=zi(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(ju,"specifierAfterImport");function Hu(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 Bi(e,n)&&(r=!0);let o=zi(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(Hu,"specifierAfterExport");function zi(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(pe(e,"from",t))return Ft(e,ce(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ft(e,t);if(t>0&&(pe(e,"import",t)||pe(e,"export",t)))return}}a(zi,"specifierInStaticStatement");function Ku(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(Ku,"skipTemplateLiteral");function Vu(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=Ft(e,r);return o?{...o,requireCall:!0}:void 0}a(Vu,"specifierAfterRequire");function Uu(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=Ku(e,n);continue}if(r==="'"||r==='"'){let s=Ft(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&pe(e,"import",n)?ju(e,n):r==="e"&&pe(e,"export",n)?Hu(e,n):r==="r"&&pe(e,"require",n)?Vu(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(Uu,"moduleSpecifiers");function Wi(e,t){let n=[],r=[];for(let o of Uu(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let d=yt(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=Gu(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(Wi,"moduleFactsFor");function Gu(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(Gu,"resolveSpecifier");function qi(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:gn(s,o.sliceVerdict)??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(qi,"violationsFor");var Bu={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 zu(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(zu,"hasActiveArkRules");function Wu(e,t){return zu(e,t)?te(J(qr({config:e,arkRules:t,warnings:[]}))):te(J(Wr(e)))}a(Wu,"policyHashFor");function Dn(e,t,n){let r=typeof e=="string"?Mr(e,t):En(e,t),o=n?.arkRules??Ve();return{...r,arkRules:o,policyHash:Wu(r.config,o)}}a(Dn,"loadContract");function Yi(e){let t=Dn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Dn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=is(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&&as(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(Yi,"analyzePolicyDelta");function jt(e){let t=e.files.map(m=>{let f=Ge(m.path);return{path:f,content:m.content,contentHash:te(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=Wi(m,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=qi(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(Ye(m))]));for(let m of o){let f=n.get(m.file)?.layer;if(!f)continue;let h=i.get(f),p=we(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"?[]:[{...Bu}],u={schemaVersion:Ur,policyHash:e.contract.policyHash,compilerOptionsHash:te(J(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(jt,"analyzeProject");function $n(e){let t=new Map(e.files.map(n=>[Ge(n.path),n]));for(let n of e.changes){let r=Ge(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return jt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a($n,"analyzeChange");function Xi(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(Xi,"explainViolation");function cs(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(cs,"detectArchitectureCycles");function ct(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=wo(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?Je({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}:{},...Fe(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(...Xu(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=cs(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(ct,"evaluateArchitectureGraph");var qu="CROSS_PARENT_VIA_SHARED",Yu="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function Zi(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&Te(r.sharedImportsSlice)==="deny-cross-parent")return r}a(Zi,"denyingCrossParentRule");function ls(e,t,n,r){let o=Rt(n,e,vr(e,t,r)).universeId;return o?{kind:"slice",id:o}:Ze(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(ls,"placeFile");function Ji(e,t){return Eo(t,pn(e.sharedImportsSlice))}a(Ji,"isWalkStop");function Xu(e){let t=e.rules??[];if(!t.some(s=>Te(s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=Zu(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=Zi(t,s.fromLayer,s.toLayer);if(!i)continue;let l=ls(i,s.fromLayer,s.from,e.config.layers),c=ls(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||Ji(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=Zi(t,f.fromLayer,f.toLayer);if(!h)continue;let p=ls(h,f.fromLayer,f.to,e.config.layers);if(p.kind==="shared"){if(u.has(f.to)||Ji(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()||cn(i.allowedCrossSlice,l.id,p.id))continue;if(i.sliceIdentity==="stars"){let k=br(i,vr(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=St(s.fromSlice),l=St(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:qu,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}. ${Yu}`}})}a(Xu,"crossParentViaSharedViolations");function Zu(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(Zu,"valueHop");function Qi(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(Qi,"structureFreezeTarget");var Ju=/\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)/,Qu=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,ep=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,tp=["db","tx","client","prisma","prismaClient","drizzle"],np="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",rp="\\bINSERT\\s+INTO\\b|\\bUPDATE\\s+[A-Za-z_][\\w.]*\\s+SET\\b|\\bDELETE\\s+FROM\\b",ea="\\((?:[^()]|\\([^()]*\\))*\\)",sp=`\\bnew\\s+PrismaClient\\s*${ea}|\\bdrizzle\\s*${ea}`,op=/(?<![\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,ip=/(?<![\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 ap(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(ap,"escapeRegExp");function Mn(e){return Ju.test(e)||Qu.test(e)}a(Mn,"sourceImportsPersistenceDriverText");function ta(e,t,n){let r=new RegExp(e.source,"g"),o;for(;(o=r.exec(t))!==null;)o[1]&&n.add(o[1])}a(ta,"collectFirstGroup");function lp(e){let t=new Set;ta(op,e,t),ta(ip,e,t);let n=new RegExp(ep.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(lp,"persistenceClientBindings");function ds(e){let t=[...tp,...lp(e)].map(ap).join("|");return new RegExp(`(?:\\b(?:${t})(?![\\w$])|${sp})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${np}\\s*\\(|${rp}`,"i").test(e)}a(ds,"sourceHasPersistenceWrite");var cp=["no-anemic-model"],oa=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],us=new RegExp(`\\b(${oa.join("|")})\\b`),ia="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",ps=new RegExp(`\\bthis\\.${ia}\\.push\\s*\\(`),dp=new RegExp(`^this\\.${ia}\\s*=\\s*\\[\\s*\\]`),up=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,pp=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g;function fs(){return`${oa.join(", ")}, or events-array .push(`}a(fs,"expectedDomainInvariantWordsPhrase");function fp(e){return us.test(e)||ps.test(e)}a(fp,"referencesGuardOrPublish");function gs(e,t,n){let r=e.slice(t);if(dp.test(r))return!0;if(!up.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(gs,"isIdiomaticEventsReset");function gp(e,t){let n=new RegExp(pp.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!gs(t,r.index,e))return!0;return!1}a(gp,"methodAssignsThis");function na(e,t){return t==null?e:{...e,truncatedUntil:t}}a(na,"attachShapeTruncation");function aa(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}a(aa,"shapeTruncatedUntil");function mp(e){let t=aa(e);return t==null?"":` shape analysed until character ${t}`}a(mp,"shapeTruncationSuffix");function ra(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(ra,"escapeGlobLiteral");function hp(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+=ra(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ra(o)}return new RegExp(`^${n}$`)}a(hp,"globToRegExp");function dt(e,t){return!t||t.length===0?!0:t.some(n=>hp(n).test(e))}a(dt,"matchesAppliesTo");function la(e){return cp.includes(e)}a(la,"isTier2");function ca(e){return e.mode==="enforced"&&!la(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(ca,"severityFor");function $e(e,t,n,r=1){let{severity:o,failsStrict:s}=ca(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($e,"baseViolation");function Fn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(Fn,"isInRuleLayer");function jn(e,t,n){return t.filter(r=>!(!r.exported||!dt(r.file,e.appliesTo)||!Fn(r.file,e,n)))}a(jn,"shapesForRule");function ms(e,t,n){let r=aa(t);if(r!=null)return $e(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}a(ms,"truncatedShapeViolation");function yp(e,t,n){let r=[];for(let o of jn(e,t,n)){let s=ms(e,o,"members");s&&r.push(s),(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push($e(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}a(yp,"evaluateAggregatePrivateState");function Ap(e,t,n){let r=[];for(let o of jn(e,t,n)){let s=ms(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($e(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}a(Ap,"evaluateAlwaysValidFactory");function Rp(e,t,n){let r=[],o=fs();for(let s of jn(e,t,n)){let i=mp(s),l=ms(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push($e(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(Rp,"evaluateDomainEventOnMutation");function Sp(e,t){let n=[];for(let r of t.files)dt(r,e.appliesTo)&&Fn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push($e(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(Sp,"evaluateOrchestrationOnly");function kp(e,t){let n=[];for(let r of t.files)dt(r,e.appliesTo)&&Fn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push($e(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(kp,"evaluateThinAdapter");function Ip(e,t){let n=[];for(let r of t.files)dt(r,e.appliesTo)&&Fn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push($e(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(Ip,"evaluateWritesViaAggregate");function Ep(e,t,n){let r=[];for(let o of jn(e,t,n))if(o.dataOnly===!0){let s=$e(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(Ep,"evaluateNoAnemicModel");function hs(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(...yp(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Ap(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Rp(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Sp(n,e));break;case"thin-adapter":t.push(...kp(n,e));break;case"writes-via-aggregate":t.push(...Ip(n,e));break;case"no-anemic-model":t.push(...Ep(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(hs,"evaluateArkRuleSensors");function ys(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=>dt(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=ca(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=>dt(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(ys,"collectEmptyAppliesToFindings");var sa=64;function bp(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(bp,"stripTrailingDots");function vp(e){let t=e.trim(),n=t.length>sa?t.slice(0,sa):t;return bp(n)}a(vp,"normalizeIntentPrefix");function Cp(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(Cp,"layerNameLooksDomain");function _p(e){return e.some(t=>{let n=vp(t);return n==="Domain"||n.startsWith("Domain.")})}a(_p,"ownsDomainIntent");function xp(e,t=[]){return Cp(e)||_p(t)}a(xp,"isDomainRoleLayerName");function da(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>xp(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)&&!la(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(da,"collectEmptyInvariantCatalogFindings");function Op(e){return e==="PersistenceAdapters"}a(Op,"isPersistenceDriverLayer");function wp(e,t){if(Mn(e))return!0;if(!t)return!1;for(let n of t){if(Op(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Mn(o))return!0}return!1}a(wp,"sourceImportsPersistenceDriver");var Tp=/\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*=)/,Lp=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Np=/\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*=/,Pp=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function ua(e,t,n){if(!t)return null;let r=wp(t,n),o=r&&ds(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Np.source,"g"))??[],i=t.match(new RegExp(Pp.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=Tp.test(t)||Lp.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(ua,"deriveArkRuleFileHints");function As(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=ua(r,o,t?.[s]);i&&(n[s]=i)}return n}a(As,"buildArkRuleFileHints");var Dp=new Set(["if","match","when"]);function $p(e,t){let n=[];for(let r of Tn(t,{exportedOnly:!0})){let o=r.name;if(r.bodyStart==null){n.push(na({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=wn(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")||Dp.has(k.name)||gp(k.name,k.body)&&S.push({name:k.name,referencesGuardOrPublish:fp(k.body)}));let R=c.members.filter(k=>k.kind==="method").length<=1&&u.length>=2&&m;n.push(na({file:e,className:o,exported:!0,hasPublicMutableFields:m,hasPublicSetters:f,hasPublicConstructor:p,hasStaticFactory:y,mutatingMethods:[...S],dataOnly:R},d))}return n}a($p,"extractClassShapesFromSource");var Mp=50;function Rs(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(Rs,"normalizeExtraMergeTeethClassification");function ke(e){let t=Rs(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(ke,"extraMergeTeethAllowed");function Ss(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(Ss,"classifyResolvedLayerCoverage");function ks(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}a(ks,"isArkRunRuleId");function pa(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}a(pa,"isArkOrderRuleId");function fa(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(fa,"isExtraPlaneFinding");function Fp(e,t={}){if(!Array.isArray(e)||ke(t))return e;for(let n of e)fa(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}a(Fp,"demoteExtraPlaneTeethUnderClassificationFloor");var ga="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 Se(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}a(Se,"countOrZero");function Hn(e={}){let t=Rs(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=ke(t),i=e.arkRules,l=Se(i?.structureEnforced),c=Se(i?.structureTotal),d=typeof i?.structureAdvisory=="number"?Se(i.structureAdvisory):Math.max(0,c-l),u=Se(i?.invariantEnforced),m=Se(i?.invariantTotal),f=typeof i?.invariantAdvisory=="number"?Se(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=Se(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=Se(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:Se(i?.covered),uncovered:Se(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:ga,failMergeWhen:N};return o&&(M.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),M}a(Hn,"composeMergePlanesHonesty");var ya=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"],jp="ArkModule",Hp=["forRoot","forRootAsync"],Kp=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"],Aa=new Set(["eventBus"]),Vp=new Set(["publisher","eventBus"]),Up=new Set(Hp),Gp=new Set(Kp),Bp=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Kn=new Set(ya),zp=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"]),Ra=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function ut(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}a(ut,"isArkRunKernelModuleSpecifier");var Sa=["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"],Is=new Set(Sa);function Es(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Is.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Is.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Is.has(e.slice(0,r))}a(Es,"isArkRunTransportBypassSpecifier");function Vn(e){if(Kn.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(Vn,"arkRunKernelCallKind");function Kt(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}a(Kt,"lineAt");function Vt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}a(Vt,"stripCommentsPreservingLines");function Wp(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(Wp,"firstStringLiteralArg");function ma(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(ma,"keywordBefore");function Ut(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(Ut,"parseValueImportClause");function qp(e,t){Ut(Vt(e),t)}a(qp,"forEachArkRunValueImportClause");function bs(e,t){let n=Vt(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:Kt(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:Kt(t,s.index),resolution:"resolved-external"})}return r}a(bs,"extractArkRunValueImportDependenciesFromSource");function vs(e){let t=[];return qp(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)}}),Ht(t)}a(vs,"extractArkRunImportedConstructorNamesFromSource");function Yp(e){let t=new Map,n=new Set;return Ut(e,(r,o)=>{if(!ut(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(Yp,"collectKernelImportBindings");function Xp(e,t){let n=new Set(t);return Ut(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)||(ut(o)||t.has(u)||t.has(d))&&(n.add(d),n.add(u))}}),n}a(Xp,"collectImportedConstructors");function Zp(e,t){let n;return Ut(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}a(Zp,"importedFromForName");function Jp(e){let t=new Set,n=/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;){if(!ut(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;Gp.has(c)&&t.add(d)}}return t}a(Jp,"collectKernelTypeNames");function Qp(e,t){let n=e.split(".");if(n.length===2)return t.namespaces.has(n[0])&&Kn.has(n[1]);if(n.length!==1)return!1;let r=t.named.get(n[0]);return r!==void 0&&Kn.has(r)}a(Qp,"isFactoryCalleeExpression");function ef(e,t,n,r){Ut(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(ef,"addRootModuleImports");function tf(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])&&(!Vp.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(Aa.has(f)){if(n.has(h))continue;n.add(h),d=!0}else Vn(f)&&!Kn.has(f)&&r.add(h)}}}a(tf,"addDerivedReceivers");function nf(e,t,n){let r={receivers:new Set,calleeBindings:new Set,rootNamespaces:new Set};n&&ef(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;)Qp(s[2].replace(/\s+/g,""),t)&&r.receivers.add(s[1]);let i=Jp(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 tf(e,r),r}a(nf,"traceKernelReceivers");function rf(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(rf,"matchingOpenParen");function ha(e){let t=e.split(".").map(n=>n.trim()).filter(n=>n.length>0);return t[0]==="this"?t.slice(1):t}a(ha,"chainParts");function sf(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:ha(r[1].replace(/\?/g,"")),viaPublisherCall:!1}}let o=/\)\s*\??\.\s*$/.exec(n);if(!o)return;let s=t-n.length+o.index,i=rf(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:ha(c[1].replace(/\?/g,"")),viaPublisherCall:!0}:{parts:["<expr>"],viaPublisherCall:!1}}a(sf,"receiverChainBefore");function of(e,t,n){let[r,...o]=e.parts;return r?o.length===0&&t.namespaces.has(r)?!0:Ra.has(r)||!n.receivers.has(r)?!1:(n.rootNamespaces.has(r)?o.slice(1):o).every(i=>Aa.has(i)):!1}a(of,"chainReachesKernel");function af(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(af,"collectDefinedIntentNames");function lf(e,t){return/^\s*([A-Za-z_$][\w$]*)\s*[,)]/.exec(e.slice(t))?.[1]}a(lf,"firstIdentifierArg");function cf(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(cf,"carriesIntentPrefix");function df(e){if(!e)return;if(e.viaPublisherCall)return"publisher";let t=e.parts[e.parts.length-1];return t==="<expr>"?void 0:t}a(df,"receiverName");function uf(e,t,n){if(!e||t===void 0||!cf(t,n))return!1;let r=e.parts[0];return r!==void 0&&r!=="<expr>"&&!Ra.has(r)}a(uf,"untracedKernelNameEvidence");function Cs(e,t,n={}){let r=Vt(t),o=Yp(r),s=nf(r,o,n.isKernelRootSpecifier),i=af(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(ma(r,m,"function")||ma(r,m,"class"))continue;let f=sf(r,m),h=df(f),p=o.named.get(u)??u,y=Vn(p)??Vn(u),S=o.named.has(u)||s.calleeBindings.has(u)||f?.parts.length===1&&o.namespaces.has(f.parts[0]);if(!y&&Up.has(u)&&f?.parts.length===1&&o.named.get(f.parts[0])===jp&&(y="factory",S=!0),!y||y==="factory"&&f!==void 0&&!S)continue;let C=m+d[0].length,R=Wp(r,C);if(y!=="factory"&&(f===void 0?!S:!of(f,o,s))&&!uf(f,R,n.intentPrefixes))continue;let k=lf(r,C),v=R??(k?i.get(k):void 0);l.push({file:e,line:Kt(t,m),kind:y,callee:u,viaImport:S,...h?{receiver:h}:{},...v?{nameLiteral:v}:{}})}return l}a(Cs,"extractArkRunKernelCallsFromSource");function _s(e,t,n){let r=Vt(t),o=Xp(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(zp.has(c)||!o.has(c))continue;let d=Zp(r,c);s.push({file:e,line:Kt(t,l.index),typeName:c,...d?{importedFrom:d}:{}})}return s}a(_s,"extractArkRunManagedNewsFromSource");function pf(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(pf,"matchingBracketEnd");function ff(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(ff,"stringLiteralsInList");function Ht(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(Ht,"uniqueSorted");function gf(e,t){let n=Vt(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=pf(n,f);if(h<0)continue;let p=ff(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:Kt(t,c),uses:Ht(o),reactsTo:Ht(s),raises:Ht(i),sends:Ht(l)}]}a(gf,"extractArkRunDeclarationsFromSource");var mf=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],hf=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],yf=new Set(hf);function Af(e){return yf.has(e)}a(Af,"isArkRunEditorSensor");var xs={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},Ea="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ba(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(ba,"isDomainRoleLayer");function Rf(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Rf,"compareFindings");function Oe(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:xs[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:Ae({ruleId:xs[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Oe,"finding");function Sf(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(Sf,"bagForFile");function ka(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(ka,"emitKinds");function Ia(e){return e==="subscribe"||e==="register-handler"}a(Ia,"handleKinds");function kf(e){return e==="resolve"||e==="resolve-singleton"}a(kf,"dependKinds");function If(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Oe(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(Oe(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(Oe(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(If,"evaluateMissingRoot");function Ef(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||!ut(c))continue;let d=r(l.from);d&&ba(d,s.get(d)??[])&&i.push(Oe(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(Ef,"evaluateKernelInDomain");function bf(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)||ba(f,l.get(f)??[])||d.push(Oe(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(bf,"evaluateDirectNew");function vf(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(!ka(c.kind)&&!Ia(c.kind)&&!kf(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:Ea,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=Sf(n,c.file);if(ka(c.kind)){if(u.raises.has(c.nameLiteral)||u.sends.has(c.nameLiteral))continue;s.push(Oe(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(Ia(c.kind)){if(u.reactsTo.has(c.nameLiteral))continue;s.push(Oe(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(Oe(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(vf,"evaluateUndeclared");function Cf(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||!Es(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(Oe(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(Cf,"evaluateTransportBypass");function Un(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=ke(e.classification),r=vf(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...If(t,e.compositionRootHits,n),...Ef(t,e.layers,e.dependencies,e.layerForFile,n),...bf(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Cf(t,e.dependencies,e.layerForFile,n)].sort(Rf),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(Un,"evaluateArkRunSensors");function va(e){return{findings:Un(e).findings.filter(n=>Af(n.sensor)),completenessReasons:[]}}a(va,"evaluateArkRunEditorSensors");function _f(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(_f,"fileMatchesCompositionRoot");function xf(e,t,n){let r=Cs(t,n).some(i=>i.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let i of s)_f(i,t)&&o.push({file:t,matchedRoot:i,hasKernelFactory:r});return o}a(xf,"compositionRootHitsForSource");function Of(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(vs(e.source));return va({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:_s(e.file,e.source,n),compositionRootHits:xf(t,e.file,e.source),declarations:[],dependencies:bs(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}a(Of,"evaluateArkRunEditorSensorsFromSource");var Ca=new Map;function _a(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(_a,"escapeAppliesToLiteral");function wf(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(wf,"normalizeAppliesToGlob");function Tf(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(Tf,"appliesToBracesBalanced");function xa(e){let t=Ca.get(e);if(t)return t;let n=wf(e),r=Tf(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=_a(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+=_a(c)}let i=new RegExp(`^${o}$`);return Ca.set(e,i),i}a(xa,"arkOrderGlobToRegExp");function Oa(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Oa,"isArkOrderModuleSpecifier");var Lf=["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"],Os={"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 Nf(e,t){return!t||t.length===0?!0:t.some(n=>xa(n).test(e))}a(Nf,"matchesArkOrderAppliesTo");function Pf(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(Pf,"isDomainRoleLayer");function Ie(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Os[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:Ae({ruleId:Os[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Ie,"finding");function ws(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=ke(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||!Oa(d))continue;let u=e.layerForFile(c.from);u&&Pf(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)||Nf(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(ws,"evaluateArkOrderSensors");var Ts="4.8.24";function Ls(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}a(Ls,"childSlicesOf");var wa=Object.freeze([{key:"sharedImportsSlice.stopAt",minVersion:Ts,uses:a(e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:Ts,uses:a(e=>Ls(e)?.message!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:Ts,uses:a(e=>{let t=Ls(e)?.siblings;return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:a(e=>Ls(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 Gn(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}a(Gn,"versionCore");function Gt(e,t){let n=Gn(e),r=Gn(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(Gt,"compareArkgateVersion");function Ta(e,t){return t&&Gn(t)&&Gt(t,e)<0?t.replace(/^v/,""):e}a(Ta,"effectiveFloor");function Df(e,t){let n=[],r=null;for(let o of wa){if(!(e??[]).some(i=>i&&o.uses(i)))continue;n.push(o.key);let s=Ta(o.minVersion,t);(!r||Gt(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}a(Df,"configVersionFloors");function La(e){let t=Df(e.rules,e.runningVersion);if(!t||!e.pins?.length)return[];let n=e.runningVersion,r=n&&Gn(n)&&Gt(n,t.required)>0?n.replace(/^v/,""):t.required,o=a(l=>wa.filter(c=>t.keys.includes(c.key)&&Gt(l.version,Ta(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,i=[];for(let l of e.pins){if(Gt(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(La,"configVersionPinFindings");function Q(e,t,n={}){return{ruleId:e,message:t,...n}}a(Q,"configWarning");function Bn(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=kr(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 Ro(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 xo(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 La({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=ii(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:ai(p)}))}return s}a(Bn,"collectAnalysisConfigWarnings");function Na(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:Qi({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(Na,"toArkRuleEngineViolation");function $f(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a($f,"arkRulesMapIsOn");function Pa(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(Pa,"arkRuleFindingNextAction");function Mf(e,t){return t.some(n=>{try{return me(n).test(e)}catch{return!1}})}a(Mf,"matchesAny");function Ff(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")&&!Mf(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(Ff,"evaluateSafety");function jf(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(jf,"ambientForbiddenGlobal");function Da(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return wr(e,n.length>0?n:Et.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Da,"intentLayer");function Hf(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||!jf(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"&&At(s.symbol,c))){if(s.source==="import-based"){let u=we(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}}Ye(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 bt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=Da(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=Da(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?Je({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}:{},...Fe(d),message:m})}return r}a(Hf,"contentViolations");function zn(e){let{facts:t}=e,n=Tt(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=Bn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(g=>g.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),u=Ff(e,t),m=e.contract.arkRules??Ve(),f=i.map(g=>g.path),p={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?As(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=a(g=>l.get(g)??he(g,e.contract.config.layers),"resolveLayer"),S=[...hs({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:y,fileHints:p}),...ys(m,f),...da({arkRulesActive:$f(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=Ni({hasEnforcedInvariant:ts(m.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),k=R.length>0?[]:Li({adopted:e.adopted===!0,hasDomainInvariants:es(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=>Na(g,Pa(g,!1))),P=S.filter(g=>!g.failsStrict).map(g=>({...Na(g,Pa(g,!0)),failsStrict:!1})),D=C?Jr({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=Ss(i),N=Un({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=ws({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,xiTtlKeys:t.arkOrderXiTtlKeys,budgetLeaks:t.arkOrderBudgetLeaks,dependencies:t.dependencies,layerForFile:a(g=>l.get(g)??he(g,e.contract.config.layers),"layerForFile"),classification:w}),qe=e.contract.config.arkOrder?.mode,Yt=ge.findings.filter(()=>qe==="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}:{}})),Js=ge.findings.filter(()=>qe!=="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})),gt=[...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],Me=ct({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(g=>g.layer).map(g=>g.path),contentViolations:[...Hf(e,t,l),...H,...v,...E,...F,...Yt],edges:c,warnings:[...d,...u.warnings,...P,...$,...oe,...Js],safety:u.report}),Xt=o==="complete"&&gt.length>0?"partial":o,lr=Xt==="complete"?s:[...s,...gt].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=Me.violations.filter(g=>g.failsStrict!==!1),O=Xt==="complete"&&b.length===0,A=O&&Me.warnings.every(g=>g.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Xt,completenessReasons:lr,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:Me.violations,warnings:Me.warnings}}}a(zn,"analyzeCanonicalResolvedProject");function $a(e){return zn({contract:e.contract,facts:Ne(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent,arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion})}a($a,"analyzeResolvedProject");function Ma(e){return te(J(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Ma,"analysisTreeHash");function Fa(e){let t=jt(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=Ge(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=$n({...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=ct({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=Ge(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:Ae(p)})),f=m.filter(p=>p.failsStrict!==!1),h=e.changeMap?it({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:Ma(t.ir.files),candidateTreeHash:Ma(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(Fa,"preflightChange");function Kf(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(Kf,"canonicalChangePath");function Vf(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(Vf,"identityViolations");function Uf(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(Uf,"preparedChange");function Wn(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}a(Wn,"isArkRulesPlaneRule");function ja(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,e.file??"",t,e.target??e.message].join("|")}a(ja,"ratchetKey");function Ha(e,t){let n=new Map;for(let r of e){if(!Wn(r.ruleId)||r.failsStrict===!1)continue;let o=ja(r);n.set(o,(n.get(o)??0)+1)}return t.map(r=>{if(!Wn(r.ruleId))return r;let o=ja(r),s=n.get(o)??0;return s===0?r:(n.set(o,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}a(Ha,"ratchetPreExistingArkRules");function Gf(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>Wn(n.ruleId)),warnings:e.ir.warnings.filter(n=>Wn(n.ruleId))}}}a(Gf,"baseAnalysisSummary");function Ka(e){return Bf(e,Ne(e.baseFacts),Ne(e.candidateFacts))}a(Ka,"preflightResolvedChange");function Bf(e,t,n){let r=Gf(zn({...e.baseAnalysisInputs??{},contract:e.contract,facts:t}),e.changeMap!==void 0),o=zn({...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=Vf(t,n),c=new Map,d=[];for(let y of e.changes){let S=Kf(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=te(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(Uf(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&&J(S)===J(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?it({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=Ha(r.ir.violations,o.ir.violations),f=Ha(r.ir.warnings,o.ir.warnings),h=[...l,...m].map(y=>({...y,nextAction:Ae(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(Bf,"preflightCanonicalChange");var Va="1.0",zf=12,Wf="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",qf="Next: /ark-runtime to wire one candidate.";function Ua(e){return e==="enforced"||e==="advisory"?e:null}a(Ua,"closedMode");function Yf(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!ks(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}a(Yf,"uniqueArkRunRuleIds");function Xf(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Ua(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(Xf,"extraFromConfig");function Zf(e={}){let t=Xf(e.arkRun),n=t.present&&Array.isArray(e.layerFlow?.layers)?Do({layers:e.layerFlow.layers,rules:Array.isArray(e.layerFlow.rules)?e.layerFlow.rules:[]}):[],r=t.present?Yf(e.findings):[],o=r.slice(0,zf),s=r.length,i=Hn({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"&&ke(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:Va,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(Zf,"summarizeArkRunSection");function Ns(e={}){let t=e.present===!0,n=Ua(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(Ns,"projectStatusArkRun");function Jf(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=[Wf,`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(qf)}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(Jf,"formatArkRunDoctorLines");function Qf(e){let t=e.split("|",1)[0]??"";return t.startsWith("ARKRULE_")||t.startsWith("INVARIANT_")}a(Qf,"isArkRulesFrozenKey");function qn(e,t){return e.slice(0,t).split(`
21
+ `).length}a(qn,"lineOf");function Ga(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Ga,"normalizeInventoryPath");function za(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}a(za,"ownsIntent");function Ba(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||za(t,["Domain"])}a(Ba,"isDomainLayer");function eg(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||za(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}a(eg,"isControllerEligibleLayer");function tg(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(tg,"isNonPilotSurface");function ng(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,u])=>[Ga(d),u])),o=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),s=(e.layerContexts??[]).find(d=>Ba(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,u]of Object.entries(e.fileContents).sort(([m],[f])=>m.localeCompare(f))){let m=Ga(d);if(tg(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&&eg(h,p)&&R):R,v=f?!!(h&&Ba(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:qn(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:qn(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:qn(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)||gs(u,M.index))continue;let qe=u.slice(Math.max(0,M.index-200),M.index+200);if(!us.test(qe)&&!ps.test(qe)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:qn(u,M.index),message:`Domain field mutation without nearby ${fs()}.`,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(Qf).length,notAScore:!0}}a(ng,"buildRulesInventory");function rg(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(rg,"inventoryToExtractionCard");var sg="1.1";var og="1.0";function ig(e){return e==="enforced"||e==="advisory"?e:null}a(ig,"closedMode");function Wa(e={}){let t=e.present===!0,n=ig(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(Wa,"projectStatusArkOrder");var Ps="1.0",qa="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Ya=["full","subset","unavailable"],Xa=["doctor-facts","report-snapshot","none"],Yn={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Za=/^sha256:[a-f0-9]{64}$/;function Ja(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"||!Za.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(Ja,"evaluateStatusBinding");function Qa(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(Qa,"classifyStatusWritePath");function el(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(el,"defaultHonestLabel");function tl(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(tl,"normalizedConfigErrors");function nl(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=tl(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(nl,"resolveStatusNextAction");function ag(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Za.test(e.projectId)?e.projectId:null,r=Ja({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=Qa({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():el(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:Bt(e.activeViolations),frozenResidual:Bt(e.frozenResidual)},d={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Bt(e.rulesInventoried),underContract:Bt(e.rulesUnderContract),frozenResidual:Bt(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:Ps,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:u,lastCheck:c,rules:d,nextAction:nl(e,r,u,c,d)},h=tl(e.configErrors);m.resolvedConfigPath&&h.length>0&&(f.contract={valid:!1,errors:h});let p=sl(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=Ns(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=Wa(e.arkOrder)),f}a(ag,"buildStatusManifest");var rl=new Set(Ya),lg=new Set(Xa);function Ds(e){let t=rl.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&lg.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:Yn.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:Yn.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(Ds,"projectStatusImprovementCompass");function cg(e={}){return Ds({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??Yn.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(cg,"unavailableStatusImprovementCompass");function sl(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"&&rl.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Ds({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(sl,"normalizeStatusImprovementCompass");function dg(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(dg,"statusCompassResidualIsSubsetOfDoctor");function Bt(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}a(Bt,"numberOrNull");var ug={$schema:"https://json-schema.org/draft/2020-12/schema",$id:qa,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:Ps},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 Xn="1.0",Zn=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Jn=5,Be=["scalability","resilience","security"],pt=new Set(Be),$s={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},Ms={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"},Fs={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 js(e){return Ms[e]??e}a(js,"improvementCompassHumanLabel");function Hs(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}a(Hs,"smellIdOf");function Ks(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}a(Ks,"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){pt.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}a(se,"markResidual");function ol(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`${Ms[e]} \u2014 no residual from current sensors.`}}a(ol,"defaultOkSummary");function il(){return Zn.map(e=>pt.has(e)?{id:e,status:"out-of-scope",summary:Fs[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:ol(e),evidence:[]}:{id:e,status:"ok",summary:ol(e),evidence:[]})}a(il,"createInitialImprovementCompassLenses");function pg(e,t){for(let n of t){let r=Hs(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||pt.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(pg,"mapDesignSmells");function fg(e){return e.failsStrict===!1||e.typeOnly===!0}a(fg,"isTypeOnlyPlacementDebt");function gg(e,t){for(let n of t){let r=Ks(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),i=a((c,d,u)=>{let m=e.get(c);!m||pt.has(c)||(Y(m,"violations",r,o),n.file&&Y(m,"violations",n.file,r),se(m,d,u))},"attach");if(fg(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(gg,"mapViolations");function mg(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(mg,"mapCountsAndFlags");function al(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>Hs(r).localeCompare(Hs(o)));pg(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=Ks(r).localeCompare(Ks(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});gg(e,n)}mg(e,t)}a(al,"projectImprovementCompassFacts");function ll(e){for(let t of Be){let n=e.get(t);n.status="out-of-scope",n.summary=Fs[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(ll,"lockImprovementCompassOutOfScope");function cl(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(cl,"sortImprovementCompassEvidence");function dl(e){return e.filter(n=>n.status==="residual"&&!pt.has(n.id)).slice().sort((n,r)=>{let o=$s[n.id]??150,s=$s[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}a(dl,"finalizeImprovementCompassTopResidual");function hg(e={}){let t=il(),n=new Map(t.map(o=>[o.id,o]));al(n,e),ll(n),cl(t);let r=dl(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(hg,"buildImprovementCompass");function ul(e){return e.topResidual.map(t=>js(t))}a(ul,"formatImprovementCompassResidualLabels");function pl(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(pl,"primaryImprovementCompassNextAction");function yg(e){let t=ul(e),n=Be.map(s=>js(s)),r=pl(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(yg,"formatImprovementCompassDoctorLines");var ze="1.0",fl="<!-- arkgate:agent-projection:begin",Qn="<!-- arkgate:agent-projection:end -->",er="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",zt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),gl=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 ft(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(ft,"agentProjectionContentIdentity");function Wt(e){return String(e??"").replace(/\r\n/g,`
23
+ `)}a(Wt,"normalizeNewlines");function We(e){let t=Wt(e);return t.endsWith(`
23
24
  `)?t:`${t}
24
- `}i(He,"ensureTrailingNewline");function Tt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(Tt,"safeVersion");function va(e){return e==="compact"?"compact":"full"}i(va,"resolveProfile");function zr(e){let t=Tt(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}i(zr,"buildAgentProjectionBeginMarker");function Rn(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(We,"ensureTrailingNewline");function qt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}a(qt,"safeVersion");function ml(e){return e==="compact"?"compact":"full"}a(ml,"resolveProfile");function Vs(e){let t=qt(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(Vs,"buildAgentProjectionBeginMarker");function tr(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
26
  |-------|----------|-----------------|
26
- ${e.map(n=>{let r=n.name?.trim()||"Unknown",o=n.patterns??[],s=n.intentPrefixes??[],a=o.map(c=>`\`${c}\``).join(", ")||"\u2014",l=s.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${a} | ${l} |`}).join(`
27
- `)}`}i(Rn,"formatAgentProjectionLayers");function Wr(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(`
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(tr,"formatAgentProjectionLayers");function Us(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
29
  `)}
29
30
 
30
- Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(Wr,"formatAgentProjectionCatalogShortList");function kn(e){let t=Tt(e.arkgateVersion),n=va(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():"",a=s&&s!=="unknown"?s:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",An,"","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}\`${a?` \xB7 **host:** \`${a}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?u.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)","",Rn(l),""):u.push("### Contract layers","",Rn(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)","",Wr(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`).",""),u.push("### Enforcement surfaces (authoritative)","",Ot.map(p=>`- \`${p}\``).join(`
31
- `),""),u.join(`
31
+ Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}a(Us,"formatAgentProjectionCatalogShortList");function nr(e){let t=qt(e.arkgateVersion),n=ml(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","",er,"","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)","",tr(l),""):d.push("### Contract layers","",tr(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)","",Us(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)","",zt.map(u=>`- \`${u}\``).join(`
32
+ `),""),d.join(`
32
33
  `).replace(/\n{3,}/g,`
33
34
 
34
35
  `).trimEnd()+`
35
- `}i(kn,"buildAgentProjectionBody");function Ca(e){let t=kn(e);return`${zr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
36
- ${t}${hn}
37
- `}i(Ca,"buildAgentProjectionBlock");function _a(e){let t=kn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Tt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...Ot],contentIdentity:Qe(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:va(e.profile)}}i(_a,"buildAgentProjectionMeta");var qr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Oa=/<!--\s*arkgate:agent-projection:end\s*-->/i,zd=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Wd=/\bschema=([A-Za-z0-9._+-]+)/i;function Sn(e){let t=xt(e??""),n=qr.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),a=Oa.exec(s);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=a.index,c=l+a[0].length,u=s.slice(0,l);u.startsWith(`
38
- `)&&(u=u.slice(1));let p=t.slice(r,o+c),g=s.slice(c);return{block:p,body:u,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}i(Sn,"extractAgentProjectionBlock");function Yr(e){let t=String(e??""),r=qr.exec(t)?.[1]??t,o=zd.exec(r),s=Wd.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:a}}i(Yr,"parseAgentProjectionStamp");function xa(e,t){let n=Yr(e).arkgateVersion;return n?n===Tt(t):!1}i(xa,"projectionMatchesPackageVersion");function Ta(e){return String(e??"").includes("non-authoritative")}i(Ta,"projectionHasNonEnforcementLabel");function Na(e,t){let n=He(xt(t)),o=Sn(n).body??n.replace(qr,"").replace(Oa,"").trim()+`
39
- `,s=Qe(o);if(e==null||!String(e).trim())return{content:He(`# Ark Enforcement
36
+ `}a(nr,"buildAgentProjectionBody");function hl(e){let t=nr(e);return`${Vs({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
37
+ ${t}${Qn}
38
+ `}a(hl,"buildAgentProjectionBlock");function yl(e){let t=nr(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:qt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...zt],contentIdentity:ft(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:ml(e.profile)}}a(yl,"buildAgentProjectionMeta");var Gs=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Al=/<!--\s*arkgate:agent-projection:end\s*-->/i,Ag=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Rg=/\bschema=([A-Za-z0-9._+-]+)/i;function rr(e){let t=Wt(e??""),n=Gs.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=Al.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(rr,"extractAgentProjectionBlock");function Bs(e){let t=String(e??""),r=Gs.exec(t)?.[1]??t,o=Ag.exec(r),s=Rg.exec(r),i=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:i}}a(Bs,"parseAgentProjectionStamp");function Rl(e,t){let n=Bs(e).arkgateVersion;return n?n===qt(t):!1}a(Rl,"projectionMatchesPackageVersion");function Sl(e){return String(e??"").includes("non-authoritative")}a(Sl,"projectionHasNonEnforcementLabel");function kl(e,t){let n=We(Wt(t)),o=rr(n).body??n.replace(Gs,"").replace(Al,"").trim()+`
40
+ `,s=ft(o);if(e==null||!String(e).trim())return{content:We(`# Ark Enforcement
40
41
 
41
- ${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let a=xt(e),l=Sn(a);if(l.block!=null){let u=l.body??"";if(Qe(u)===s)return{content:He(a),action:"unchanged",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0};let p=l.before.replace(/\s*$/,`
42
+ ${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let i=Wt(e),l=rr(i);if(l.block!=null){let d=l.body??"";if(ft(d)===s)return{content:We(i),action:"unchanged",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0};let u=l.before.replace(/\s*$/,`
42
43
 
43
- `),g=l.after.replace(/^\s*/,`
44
- `);return{content:He(`${p}${n.trimEnd()}
45
- ${g}`),action:"block-replaced",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(a);if(c&&c.index!=null){let u=c.index+c[1].length,p=a.slice(0,u).replace(/\s*$/,`
44
+ `),m=l.after.replace(/^\s*/,`
45
+ `);return{content:We(`${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*$/,`
46
47
 
47
- `),g=a.slice(u).replace(/^\s*/,`
48
- `);return{content:He(`${p}${n.trimEnd()}
49
- ${g}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:He(`${n.trimEnd()}
48
+ `),m=i.slice(d).replace(/^\s*/,`
49
+ `);return{content:We(`${u}${n.trimEnd()}
50
+ ${m}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:We(`${n.trimEnd()}
50
51
 
51
- ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}i(Na,"mergeAgentProjectionDocument");var qd="1.0",Da="templates/agent-skills",Ma="templates/skills",Fa="SKILL.md",Yd=Object.freeze(["Contener","Guiar","Ordenar"]),Qr=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),Jr=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"]),$a=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),wa="Contener \xB7 Guiar \xB7 Ordenar",Pa="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"]),Ha=bn.length,Jd=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ja(e){return typeof e!="string"||e.length<1||e.length>64?!1:Jd.test(e)}i(ja,"isValidAgentSkillName");function es(e){return bn.includes(e)}i(es,"isArkSkillName");function Xr(e){return Qr.includes(e)}i(Xr,"isFirstClassArkSkillName");function Xd(e){return e in Jr?Jr[e]:null}i(Xd,"arkSkillStubRedirect");function Ka(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
52
+ ${i.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}a(kl,"mergeAgentProjectionDocument");var Sg="1.0",vl="templates/agent-skills",Cl="templates/skills",_l="SKILL.md",kg=Object.freeze(["Contener","Guiar","Ordenar"]),Ys=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),zs=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),sr=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"]}),or=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),xl=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),Il="Contener \xB7 Guiar \xB7 Ordenar",El="Do not invent `/ark-order`",ir=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"]),Ol=ir.length,Ig=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function wl(e){return typeof e!="string"||e.length<1||e.length>64?!1:Ig.test(e)}a(wl,"isValidAgentSkillName");function Xs(e){return ir.includes(e)}a(Xs,"isArkSkillName");function Ws(e){return Ys.includes(e)}a(Ws,"isFirstClassArkSkillName");function Eg(e){return e in zs?zs[e]:null}a(Eg,"arkSkillStubRedirect");function Tl(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
52
53
  `)?`\r
53
54
  `:`
54
- `,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],d=f[2]??"";(d.startsWith('"')&&d.endsWith('"')&&d.length>=2||d.startsWith("'")&&d.endsWith("'")&&d.length>=2)&&(d=d.slice(1,-1)),s[m]=d}let a=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,u=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:l,description:c,license:u},body:a}}i(Ka,"parseSkillDocument");function Va(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=Ka(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:a,description:l}=s.frontmatter,c=a??(o||void 0);return!a||!ja(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):a!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${o}".`,skillName:a}):t&&!es(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:a}),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}i(Va,"validateAgentSkillDocument");function Zd(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(...Va({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)es(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:Ha,presentCount:r.length}}i(Zd,"validateAgentSkillsPackage");function ue(e,t){e.push(t)}i(ue,"pushCapacityIssue");function La(e,t){return e.includes(t)}i(La,"skillMentionsSurface");function Qd(e){let t=[],n=e.skills??{},r=Object.keys(In);for(let s of En)r.includes(s)||ue(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)||ue(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 a=In[s];if(!a||a.length===0)continue;for(let c of a)Xr(c)||ue(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.`});a.filter(c=>{let u=n[c];return typeof u=="string"&&La(u,s)}).length===0&&ue(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,a]of Object.entries($a)){if(!In[s]?.includes(a)||!Xr(a)){ue(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} 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[a];(typeof c!="string"||!La(c,s))&&ue(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} 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 Qr){let a=n[s];if(typeof a!="string"){ue(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=a.includes(wa),c=/When \/ not when|\*\*When:\*\*/.test(a),u=/Not when|Do \*\*not\*\* use|Prefer instead/.test(a),p=/Handoff|hand off|`\/ark-/i.test(a);(!l||!c||!u||!p)&&ue(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.`}),a.includes(Pa)&&ue(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,a]of Object.entries(o)){let l=String(a??"");l.includes("/ark-order")||ue(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(wa)||ue(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(Pa)&&ue(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}}i(Qd,"validateSkillProductCapacity");var ts=/^arkgate@(\S+)\.\s/;function Ua(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(Ua,"skillDescriptionVersionPrefix");function Ga(e){return String(e??"").replace(ts,"")}i(Ga,"stripSkillDescriptionVersion");function eu(e){return String(e??"").match(ts)?.[1]??null}i(eu,"parseSkillDescriptionVersion");function tu(e,t){let n=Ga(e),r=typeof t=="string"?t.trim():"";return r?`${Ua(r)}${n}`:n}i(tu,"stampSkillDescription");function Zr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
55
- `)}i(Zr,"normalizeSkillContent");function Ba(e){return`${e}/${Fa}`}i(Ba,"agentSkillEntryRelativePath");function nu(e){return`${Da}/${Ba(e)}`}i(nu,"agentSkillPackageFileRelativePath");function ru(e){return`${Ma}/${e}.md`}i(ru,"flatSkillTemplateFileRelativePath");export{Pt as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,Ea as AGENT_PROJECTION_BEGIN_MARKER,hn as AGENT_PROJECTION_END_MARKER,Ot as AGENT_PROJECTION_ENFORCEMENT_SURFACES,An as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,Da as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,Fa as AGENT_SKILL_ENTRY_FILENAME,qn as ANALYSIS_IR_SCHEMA_VERSION,Pr as ARKORDER_RULE_IDS,td as ARKORDER_TIER1_SENSOR_IDS,jo as ARKRUN_INTERACTION_NAME_INCOMPLETE,Mo as ARKRUN_KERNEL_FACTORY_CALLEES,vc as ARKRUN_KERNEL_INTERACTION_CALLEES,wr as ARKRUN_RULE_IDS,Fc as ARKRUN_TIER1_SENSOR_IDS,Fo as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,$e as ARK_AGENT_PROJECTION_SCHEMA_VERSION,qd as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,ss as ARK_ANALYSIS_RESULT_SCHEMA,wt as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Gn as ARK_CONFIG_SCHEMA,ie as ARK_CONFIG_SCHEMA_VERSION,vd as ARK_DESIGN_DELTA_SCHEMA_VERSION,bd as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Qr as ARK_FIRST_CLASS_SKILL_NAMES,mn as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,si as ARK_PROJECT_IDENTITY_SCHEMA,as as ARK_PROJECT_IDENTITY_SCHEMA_URL,ri as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,Jn as ARK_RULES_SCHEMA,sl as ARK_RULES_SCHEMA_VERSION,Ys as ARK_RULE_SENSORS,Zo as ARK_RUN_DOCTOR_SCHEMA_VERSION,In as ARK_SKILL_CAPACITY,$a as ARK_SKILL_CAPACITY_DEDICATED_DOORS,ts as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,bn as ARK_SKILL_NAMES,Ha as ARK_SKILL_NAME_COUNT,Yd as ARK_SKILL_NORTH_STAR,En as ARK_SKILL_REQUIRED_SURFACES,Jr as ARK_SKILL_STUB_REDIRECTS,Hd as ARK_STATUS_MANIFEST_SCHEMA,oa as ARK_STATUS_MANIFEST_SCHEMA_URL,$r as ARK_STATUS_MANIFEST_SCHEMA_VERSION,ba as DEFAULT_AGENT_PROJECTION_RULE_IDS,un as DIAGNOSTIC_CATALOG,Cd as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Mr as DIAGNOSTIC_DOCS_RELATIVE_PATH,_d as DIAGNOSTIC_RULE_IDS,Ec as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,Xt as EffectiveContractError,Ma as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Fe as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,yn as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,gn as IMPROVEMENT_LENS_IDS,Lo as MERGE_PLANES_DUAL_STAMP,cr as POLICY_DELTA_SCHEMA_VERSION,ls as PROJECT_BINDING_SCHEMA,is as PROJECT_EXPECTATION_SCHEMA,Wn as RESOLVED_CANDIDATE_FACTS_SCHEMA,Pe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ia as STATUS_COMPASS_FACTS_SOURCES,aa as STATUS_COMPASS_MODES,fn as STATUS_COMPASS_REASON_CODES,Dt as adapterDocsCodePath,st as adapterFindingOccurrenceTargetKeys,Lt as adapterFindingRefFromTargetKey,rt as adapterFindingTargetKey,Qe as agentProjectionContentIdentity,Ba as agentSkillEntryRelativePath,nu as agentSkillPackageFileRelativePath,qe as analyzeArchitectureConvergence,tn as analyzeChange,ho as analyzePolicyDelta,kt as analyzeProject,Ct as analyzeResolvedProject,Cr as arkRunKernelCallKind,Xd as arkSkillStubRedirect,zr as buildAgentProjectionBeginMarker,Ca as buildAgentProjectionBlock,kn as buildAgentProjectionBody,_a as buildAgentProjectionMeta,Sr as buildArkRuleFileHints,Xn as buildEffectiveArkRules,Gd as buildImprovementCompass,Id as buildRulesInventory,Dd as buildStatusManifest,sr as canPromoteInvariant,wd as catalogFixForRuleId,Pd as catalogWhyForRuleId,dr as classifyArkPolicyDelta,Il as classifyCoverage,Er as classifyResolvedLayerCoverage,da as classifyStatusWritePath,cn as collectAnalysisConfigWarnings,kr as collectEmptyAppliesToFindings,Ge as collectForbiddenCapabilityUses,on as composeMergePlanesHonesty,ro as countsAsCoverage,Cs as createAICodeGate,ni as createAdapterResult,qt as createArchitectureProfile,Ks as createArchitectureProfileFromArkConfig,Vs as createElevenLayerArkConfig,oi as createProjectId,ai as createProjectIdentity,zn as createResolvedCandidateFacts,ua as defaultHonestLabel,bc as demoteExtraPlaneTeethUnderClassificationFloor,No as deriveArkRuleFileHints,so as describeCoverage,pr as detectArchitectureCycles,Z as deterministicHash,ra as diagnosticDocsFragment,Td as diagnosticDocsPath,Qn as effectiveContractPolicyPayload,Wt as elevenLayerProfile,De as emptyEffectiveArkRules,Je as evaluateArchitectureGraph,Lr as evaluateArkOrderSensors,Rr as evaluateArkRuleSensors,Vo as evaluateArkRunEditorSensors,Xc as evaluateArkRunEditorSensorsFromSource,ln as evaluateArkRunSensors,rr as evaluateInvariantCoverage,ca as evaluateStatusBinding,Ao as explainViolation,Ae as extraMergeTeethAllowed,Sn as extractAgentProjectionBlock,Mc as extractArkRunDeclarationsFromSource,xr as extractArkRunImportedConstructorNamesFromSource,Tr as extractArkRunKernelCallsFromSource,Nr as extractArkRunManagedNewsFromSource,Or as extractArkRunValueImportDependenciesFromSource,Ic as extractClassShapesFromSource,Ue as extractSemanticDependencies,ru as flatSkillTemplateFileRelativePath,Wr as formatAgentProjectionCatalogShortList,Rn as formatAgentProjectionLayers,Rd as formatArkRunDoctorLines,Bd as formatImprovementCompassDoctorLines,Sa as formatImprovementCompassResidualLabels,pn as getDiagnosticCatalogEntry,Ed as inventoryToExtractionCard,wo as isArkOrderRuleId,bt as isArkRunKernelModuleSpecifier,br as isArkRunRuleId,_r as isArkRunTransportBypassSpecifier,es as isArkSkillName,xd as isCataloguedOrArkRuleFamily,Po as isExtraPlaneFinding,Xr as isFirstClassArkSkillName,Od as isKnownDiagnosticCode,ja as isValidAgentSkillName,zt as loadArkConfigContract,Jt as loadArkRulesContract,en as loadContract,_e as loadResolvedCandidateFacts,Na as mergeAgentProjectionDocument,Ir as normalizeExtraMergeTeethClassification,Zr as normalizeSkillContent,ma as normalizeStatusImprovementCompass,Yr as parseAgentProjectionStamp,Bn as parseArkConfigJson,dl as parseArkRulesJson,eu as parseSkillDescriptionVersion,Ka as parseSkillDocument,ur as policyDeltaAcknowledgementMatches,Jo as preflightChange,Xo as preflightResolvedChange,Ia as primaryImprovementCompassNextAction,Dr as projectStatusArkRun,Hr as projectStatusImprovementCompass,Ta as projectionHasNonEnforcementLabel,xa as projectionMatchesPackageVersion,ul as resolveEffectiveContract,pa as resolveStatusNextAction,ft as resolvedFactsEvidenceRequirementsHash,Nd as serializeDiagnosticCatalog,Ua as skillDescriptionVersionPrefix,K as stableSerialize,tu as stampSkillDescription,$d as statusCompassResidualIsSubsetOfDoctor,Ga as stripSkillDescriptionVersion,Ad as summarizeArkRunSection,vn as toAdapterDiagnostic,Fd as unavailableStatusImprovementCompass,Va as validateAgentSkillDocument,Zd as validateAgentSkillsPackage,Qd as validateSkillProductCapacity,Wa as 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 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(Tl,"parseSkillDocument");function Ll(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=Tl(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||!wl(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&&!Xs(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(Ll,"validateAgentSkillDocument");function bg(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(...Ll({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&qs(o.content)!==qs(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 ir)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)Xs(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:Ol,presentCount:r.length}}a(bg,"validateAgentSkillsPackage");function fe(e,t){e.push(t)}a(fe,"pushCapacityIssue");function bl(e,t){return e.includes(t)}a(bl,"skillMentionsSurface");function vg(e){let t=[],n=e.skills??{},r=Object.keys(sr);for(let s of or)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)or.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 or){let i=sr[s];if(!i||i.length===0)continue;for(let c of i)Ws(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"&&bl(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(xl)){if(!sr[s]?.includes(i)||!Ws(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"||!bl(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 Ys){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(Il),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(El)&&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(Il)||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(El)&&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(vg,"validateSkillProductCapacity");var Zs=/^arkgate@(\S+)\.\s/;function Nl(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}a(Nl,"skillDescriptionVersionPrefix");function Pl(e){return String(e??"").replace(Zs,"")}a(Pl,"stripSkillDescriptionVersion");function Cg(e){return String(e??"").match(Zs)?.[1]??null}a(Cg,"parseSkillDescriptionVersion");function _g(e,t){let n=Pl(e),r=typeof t=="string"?t.trim():"";return r?`${Nl(r)}${n}`:n}a(_g,"stampSkillDescription");function qs(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
56
+ `)}a(qs,"normalizeSkillContent");function Dl(e){return`${e}/${_l}`}a(Dl,"agentSkillEntryRelativePath");function xg(e){return`${vl}/${Dl(e)}`}a(xg,"agentSkillPackageFileRelativePath");function Og(e){return`${Cl}/${e}.md`}a(Og,"flatSkillTemplateFileRelativePath");export{tn as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,fl as AGENT_PROJECTION_BEGIN_MARKER,Qn as AGENT_PROJECTION_END_MARKER,zt as AGENT_PROJECTION_ENFORCEMENT_SURFACES,er as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,vl as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,_l as AGENT_SKILL_ENTRY_FILENAME,Ur as ANALYSIS_IR_SCHEMA_VERSION,Os as ARKORDER_RULE_IDS,Lf as ARKORDER_TIER1_SENSOR_IDS,Ea as ARKRUN_INTERACTION_NAME_INCOMPLETE,ya as ARKRUN_KERNEL_FACTORY_CALLEES,Bp as ARKRUN_KERNEL_INTERACTION_CALLEES,xs as ARKRUN_RULE_IDS,mf as ARKRUN_TIER1_SENSOR_IDS,Sa as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,ze as ARK_AGENT_PROJECTION_SCHEMA_VERSION,Sg as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,to as ARK_ANALYSIS_RESULT_SCHEMA,en as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,$r as ARK_CONFIG_SCHEMA,ae as ARK_CONFIG_SCHEMA_VERSION,og as ARK_DESIGN_DELTA_SCHEMA_VERSION,sg as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Ys as ARK_FIRST_CLASS_SKILL_NAMES,Xn as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,ac as ARK_PROJECT_IDENTITY_SCHEMA,ro as ARK_PROJECT_IDENTITY_SCHEMA_URL,ic as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,Br as ARK_RULES_SCHEMA,qd as ARK_RULES_SCHEMA_VERSION,yi as ARK_RULE_SENSORS,Va as ARK_RUN_DOCTOR_SCHEMA_VERSION,sr as ARK_SKILL_CAPACITY,xl as ARK_SKILL_CAPACITY_DEDICATED_DOORS,Zs as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,ir as ARK_SKILL_NAMES,Ol as ARK_SKILL_NAME_COUNT,kg as ARK_SKILL_NORTH_STAR,or as ARK_SKILL_REQUIRED_SURFACES,zs as ARK_SKILL_STUB_REDIRECTS,ug as ARK_STATUS_MANIFEST_SCHEMA,qa as ARK_STATUS_MANIFEST_SCHEMA_URL,Ps as ARK_STATUS_MANIFEST_SCHEMA_VERSION,Pe as ArkRulesValidationError,gl as DEFAULT_AGENT_PROJECTION_RULE_IDS,Jt as DIAGNOSTIC_CATALOG,Fl as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,dr as DIAGNOSTIC_DOCS_RELATIVE_PATH,jl as DIAGNOSTIC_RULE_IDS,Mp as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,xn as EffectiveContractError,Cl as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,Be as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,Jn as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,Zn as IMPROVEMENT_LENS_IDS,ga as MERGE_PLANES_DUAL_STAMP,os as POLICY_DELTA_SCHEMA_VERSION,oo as PROJECT_BINDING_SCHEMA,so as PROJECT_EXPECTATION_SCHEMA,Vr as RESOLVED_CANDIDATE_FACTS_SCHEMA,Ke as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Xa as STATUS_COMPASS_FACTS_SOURCES,Ya as STATUS_COMPASS_MODES,Yn as STATUS_COMPASS_REASON_CODES,rn as adapterDocsCodePath,ht as adapterFindingOccurrenceTargetKeys,nn as adapterFindingRefFromTargetKey,mt as adapterFindingTargetKey,ft as agentProjectionContentIdentity,Dl as agentSkillEntryRelativePath,xg as agentSkillPackageFileRelativePath,it as analyzeArchitectureConvergence,$n as analyzeChange,Yi as analyzePolicyDelta,jt as analyzeProject,$a as analyzeResolvedProject,Vn as arkRunKernelCallKind,Eg as arkSkillStubRedirect,Vs as buildAgentProjectionBeginMarker,hl as buildAgentProjectionBlock,nr as buildAgentProjectionBody,yl as buildAgentProjectionMeta,As as buildArkRuleFileHints,zr as buildEffectiveArkRules,hg as buildImprovementCompass,ng as buildRulesInventory,ag as buildStatusManifest,Qr as canPromoteInvariant,Gl as catalogFixForRuleId,Bl as catalogWhyForRuleId,is as classifyArkPolicyDelta,yu as classifyCoverage,Ss as classifyResolvedLayerCoverage,Qa as classifyStatusWritePath,Bn as collectAnalysisConfigWarnings,ys as collectEmptyAppliesToFindings,tt as collectForbiddenCapabilityUses,Hn as composeMergePlanesHonesty,wi as countsAsCoverage,jo as createAICodeGate,oc as createAdapterResult,vn as createArchitectureProfile,di as createArchitectureProfileFromArkConfig,ui as createElevenLayerArkConfig,lc as createProjectId,cc as createProjectIdentity,Kr as createResolvedCandidateFacts,el as defaultHonestLabel,Fp as demoteExtraPlaneTeethUnderClassificationFloor,ua as deriveArkRuleFileHints,Ti as describeCoverage,cs as detectArchitectureCycles,te as deterministicHash,Qs as diagnosticDocsFragment,Vl as diagnosticDocsPath,qr as effectiveContractPolicyPayload,bn as elevenLayerProfile,Ve as emptyEffectiveArkRules,ct as evaluateArchitectureGraph,ws as evaluateArkOrderSensors,hs as evaluateArkRuleSensors,va as evaluateArkRunEditorSensors,Of as evaluateArkRunEditorSensorsFromSource,Un as evaluateArkRunSensors,Jr as evaluateInvariantCoverage,Ja as evaluateStatusBinding,Xi as explainViolation,ke as extraMergeTeethAllowed,rr as extractAgentProjectionBlock,gf as extractArkRunDeclarationsFromSource,vs as extractArkRunImportedConstructorNamesFromSource,Cs as extractArkRunKernelCallsFromSource,_s as extractArkRunManagedNewsFromSource,bs as extractArkRunValueImportDependenciesFromSource,$p as extractClassShapesFromSource,et as extractSemanticDependencies,Og as flatSkillTemplateFileRelativePath,Us as formatAgentProjectionCatalogShortList,tr as formatAgentProjectionLayers,Jf as formatArkRunDoctorLines,yg as formatImprovementCompassDoctorLines,ul as formatImprovementCompassResidualLabels,Qt as getDiagnosticCatalogEntry,rg as inventoryToExtractionCard,pa as isArkOrderRuleId,ut as isArkRunKernelModuleSpecifier,ks as isArkRunRuleId,Es as isArkRunTransportBypassSpecifier,Xs as isArkSkillName,Kl as isCataloguedOrArkRuleFamily,fa as isExtraPlaneFinding,Ws as isFirstClassArkSkillName,Hl as isKnownDiagnosticCode,wl as isValidAgentSkillName,En as loadArkConfigContract,_n as loadArkRulesContract,Dn as loadContract,Ne as loadResolvedCandidateFacts,kl as mergeAgentProjectionDocument,Rs as normalizeExtraMergeTeethClassification,qs as normalizeSkillContent,sl as normalizeStatusImprovementCompass,Bs as parseAgentProjectionStamp,Mr as parseArkConfigJson,eu as parseArkRulesJson,Cg as parseSkillDescriptionVersion,Tl as parseSkillDocument,as as policyDeltaAcknowledgementMatches,Fa as preflightChange,Ka as preflightResolvedChange,pl as primaryImprovementCompassNextAction,Ns as projectStatusArkRun,Ds as projectStatusImprovementCompass,Sl as projectionHasNonEnforcementLabel,Rl as projectionMatchesPackageVersion,tu as resolveEffectiveContract,nl as resolveStatusNextAction,Tt as resolvedFactsEvidenceRequirementsHash,Ul as serializeDiagnosticCatalog,Nl as skillDescriptionVersionPrefix,J as stableSerialize,_g as stampSkillDescription,dg as statusCompassResidualIsSubsetOfDoctor,Pl as stripSkillDescriptionVersion,Zf as summarizeArkRunSection,pr as toAdapterDiagnostic,cg as unavailableStatusImprovementCompass,Ll as validateAgentSkillDocument,bg as validateAgentSkillsPackage,vg as validateSkillProductCapacity,Ml as version};