arkgate 4.8.23 → 4.8.25
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.
- package/CHANGELOG.md +153 -0
- package/README.md +7 -5
- package/bin/ark-check-runtime.mjs +41 -91
- package/bin/ark-dashboard.mjs +56 -53
- package/bin/ark-layer-match.mjs +707 -121
- package/bin/ark-mcp-runtime.mjs +448 -169
- package/bin/ark-mcp.mjs +68 -4
- package/bin/ark-shared.mjs +42 -22
- package/bin/ark.mjs +65 -97
- package/bin/lib/adapter-contract-types.mjs +5 -0
- package/bin/lib/adapter-contract.mjs +15 -0
- package/bin/lib/adoption-stance.mjs +2 -2
- package/bin/lib/adr-path.mjs +3 -3
- package/bin/lib/agent-gates.mjs +0 -61
- package/bin/lib/agent-homes.mjs +12 -21
- package/bin/lib/agent-projection-command.mjs +9 -5
- package/bin/lib/ambient-state.mjs +9 -30
- package/bin/lib/analysis-engine.mjs +15 -11
- package/bin/lib/architecture-scan.mjs +61 -15
- package/bin/lib/ark-order-doctor.mjs +4 -29
- package/bin/lib/ark-order-facts.mjs +319 -17
- package/bin/lib/ark-order-sensors.mjs +28 -101
- package/bin/lib/ark-order-types.mjs +3 -2
- package/bin/lib/ark-run-doctor.mjs +17 -28
- package/bin/lib/ark-run-facts.mjs +461 -48
- package/bin/lib/ark-run-sensors.mjs +6 -4
- package/bin/lib/arkgate-pins.mjs +91 -0
- package/bin/lib/arkrule-file-hints.mjs +2 -47
- package/bin/lib/arkrules-contract.mjs +124 -133
- package/bin/lib/arkrules-sensors.mjs +55 -252
- package/bin/lib/check-args.mjs +85 -1
- package/bin/lib/ci-and-commands.mjs +24 -78
- package/bin/lib/ci-merge-boundary.mjs +1 -1
- package/bin/lib/class-source-scan.mjs +479 -0
- package/bin/lib/clone-detection.mjs +474 -0
- package/bin/lib/codex-home.mjs +5 -3
- package/bin/lib/config-contract-slices.mjs +739 -0
- package/bin/lib/config-contract.mjs +42 -607
- package/bin/lib/config-extras.mjs +16 -22
- package/bin/lib/config-warnings.mjs +32 -0
- package/bin/lib/contract-smells.mjs +33 -15
- package/bin/lib/core-ratchet.mjs +0 -2
- package/bin/lib/dashboard-cli.mjs +62 -0
- package/bin/lib/deep-module-coach.mjs +2 -4
- package/bin/lib/deploy-path.mjs +13 -38
- package/bin/lib/design-delta.mjs +1 -1
- package/bin/lib/design-smells.mjs +2 -2
- package/bin/lib/diagnostic-catalog.mjs +23 -9
- package/bin/lib/doctor-advisories.mjs +78 -8
- package/bin/lib/doctor-green-cite.mjs +1 -1
- package/bin/lib/doctor-human.mjs +1 -1
- package/bin/lib/doctor-next-actions.mjs +19 -4
- package/bin/lib/doctor-plan.mjs +9 -13
- package/bin/lib/duplication-io.mjs +572 -0
- package/bin/lib/effective-contract-load.mjs +282 -83
- package/bin/lib/enforcement-profiles.mjs +40 -4
- package/bin/lib/entry-points-io.mjs +424 -0
- package/bin/lib/extra-merge-teeth.mjs +36 -0
- package/bin/lib/field-install.mjs +38 -14
- package/bin/lib/first-run-help.mjs +10 -5
- package/bin/lib/flat-parent-importers.mjs +139 -0
- package/bin/lib/flat-parent-pilot.mjs +40 -100
- package/bin/lib/gate-files.mjs +58 -90
- package/bin/lib/git-change-scope.mjs +109 -0
- package/bin/lib/github-enforcement.mjs +166 -29
- package/bin/lib/golden-pattern.mjs +1 -1
- package/bin/lib/hook-templates.mjs +17 -15
- package/bin/lib/host-support-matrix.mjs +3 -1
- package/bin/lib/html-report-advisories.mjs +4 -0
- package/bin/lib/html-report-depth.mjs +2 -2
- package/bin/lib/html-report.mjs +2 -2
- package/bin/lib/import-graph-projection.mjs +112 -0
- package/bin/lib/import-resolve.mjs +13 -1
- package/bin/lib/improvement-compass-doctor.mjs +1 -24
- package/bin/lib/install-migrate.mjs +50 -73
- package/bin/lib/invariant-coverage-io.mjs +4 -3
- package/bin/lib/invariant-coverage.mjs +85 -11
- package/bin/lib/invariant-probe-cli.mjs +347 -0
- package/bin/lib/invariant-probe-io.mjs +165 -0
- package/bin/lib/invariant-probe-runner.mjs +268 -0
- package/bin/lib/invariant-probe-sites.mjs +174 -0
- package/bin/lib/invariant-probe-workspace.mjs +183 -0
- package/bin/lib/invariant-probe.mjs +461 -0
- package/bin/lib/invariant-tests-path.mjs +16 -22
- package/bin/lib/literal-path-drift.mjs +4 -2
- package/bin/lib/managed-upgrade.mjs +2 -8
- package/bin/lib/mcp-adoption.mjs +13 -6
- package/bin/lib/mcp-hook-payload.mjs +403 -63
- package/bin/lib/orphan-modules-io.mjs +458 -0
- package/bin/lib/orphan-modules.mjs +251 -0
- package/bin/lib/outside-importers.mjs +197 -0
- package/bin/lib/package-manager.mjs +60 -2
- package/bin/lib/parse-health.mjs +1 -1
- package/bin/lib/passthrough-commands.mjs +83 -0
- package/bin/lib/persistence-write-hint.mjs +106 -0
- package/bin/lib/pin-dependent-gates.mjs +117 -0
- package/bin/lib/policy-delta-io.mjs +219 -14
- package/bin/lib/post-green-path.mjs +1 -1
- package/bin/lib/prepare-change.mjs +115 -7
- package/bin/lib/prepare-write.mjs +2 -2
- package/bin/lib/presets.mjs +59 -73
- package/bin/lib/product-copy.mjs +1 -6
- package/bin/lib/project-root.mjs +31 -62
- package/bin/lib/remediation.mjs +23 -4
- package/bin/lib/resolved-candidate-facts.mjs +405 -117
- package/bin/lib/rules-inventory.mjs +22 -3
- package/bin/lib/rules-under-contract.mjs +247 -9
- package/bin/lib/scan-files.mjs +36 -4
- package/bin/lib/schema-validation.mjs +130 -0
- package/bin/lib/sensor-promote-cli.mjs +2 -11
- package/bin/lib/sensor-promote-io.mjs +33 -22
- package/bin/lib/sensor-promotion.mjs +1 -1
- package/bin/lib/skill-catalog-apply.mjs +1 -1
- package/bin/lib/skill-install.mjs +42 -38
- package/bin/lib/snippet-analysis.mjs +140 -6
- package/bin/lib/source-policy.mjs +34 -0
- package/bin/lib/start-install-recovery.mjs +72 -2
- package/bin/lib/start-preview.mjs +31 -1
- package/bin/lib/states-transitions-presence.mjs +3 -3
- package/bin/lib/status-command.mjs +35 -22
- package/bin/lib/status-manifest.mjs +50 -30
- package/bin/lib/status-transition-catalog.mjs +0 -6
- package/bin/lib/suggestions.mjs +3 -3
- package/bin/lib/team-parliament-io.mjs +76 -88
- package/bin/lib/team-parliament.mjs +21 -10
- package/bin/lib/upgrade-behavior-changes.mjs +2 -2
- package/bin/lib/upgrade-command.mjs +2 -24
- package/bin/lib/upgrade-outcome.mjs +1 -1
- package/bin/lib/upstream-report.mjs +21 -10
- package/bin/lib/violations.mjs +10 -9
- package/bin/lib/weakest-link.mjs +13 -0
- package/bin/lib/write-path-capabilities.mjs +6 -4
- package/dist/chunk-A5EIY3HI.cjs +5 -0
- package/dist/chunk-AHACEKSV.js +16 -0
- package/dist/chunk-SVSQVGFJ.js +5 -0
- package/dist/chunk-UN5EH4QV.cjs +16 -0
- package/dist/{configTypes-Bbf_MFGe.d.ts → configTypes-GPvvdleM.d.cts} +30 -4
- package/dist/configTypes-GPvvdleM.d.ts +257 -0
- package/dist/eslint/index.cjs +18 -5
- package/dist/eslint/index.d.cts +368 -0
- package/dist/eslint/index.d.ts +139 -156
- package/dist/eslint/index.js +11 -5
- package/dist/index.cjs +36 -35
- package/dist/index.d.cts +5547 -0
- package/dist/index.d.ts +3283 -198
- package/dist/index.js +36 -35
- package/dist/inspectorListen-6DQVJ4DC.js +1 -0
- package/dist/inspectorListen-KGMIQ2TF.cjs +1 -0
- package/dist/nestjs/index.cjs +1 -18
- package/dist/nestjs/index.d.cts +22 -0
- package/dist/nestjs/index.d.ts +1 -3
- package/dist/nestjs/index.js +1 -18
- package/dist/order/index.cjs +1 -1
- package/dist/order/index.d.cts +155 -0
- package/dist/order/index.d.ts +15 -3
- package/dist/order/index.js +1 -1
- package/dist/runtime/index.cjs +13 -30
- package/dist/{diagnosticCatalog-35mrwAHe.d.ts → runtime/index.d.cts} +828 -276
- package/dist/runtime/index.d.ts +2741 -133
- package/dist/runtime/index.js +13 -30
- package/dist/{types-Bdj32QwA.d.ts → types-CnauMQQL.d.cts} +607 -163
- package/dist/types-CnauMQQL.d.ts +1800 -0
- package/docs/README.md +3 -1
- package/docs/agent-guide.md +217 -16
- package/docs/ai-gates.md +174 -26
- package/docs/arkorder.md +32 -15
- package/docs/brownfield-adoption.md +5 -1
- package/docs/configuration.md +230 -31
- package/docs/develop.md +2 -1
- package/docs/diagnostics.md +212 -19
- package/docs/package-surface.md +35 -9
- package/docs/product-voice.md +7 -1
- package/package.json +69 -19
- package/schemas/ark.analysis-result.schema.json +15 -0
- package/schemas/ark.config.schema.json +77 -12
- package/schemas/ark.invariant-probe.schema.json +368 -0
- package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
- package/schemas/ark.status-manifest.schema.json +22 -0
- package/server.json +3 -9
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +5 -1
- package/templates/agent-skills/ark-contract/SKILL.md +17 -0
- package/templates/agent-skills/ark-coverage/SKILL.md +2 -0
- package/templates/agent-skills/ark-explore/SKILL.md +7 -0
- package/templates/agent-skills/ark-fix/SKILL.md +20 -0
- package/templates/agent-skills/ark-order/SKILL.md +4 -2
- package/templates/agent-skills/ark-place/SKILL.md +8 -0
- package/templates/agent-skills/ark-runtime/SKILL.md +6 -1
- package/templates/arkrules/PersistenceAdapters.json +1 -1
- package/templates/arkrules/PresentationAdapters.json +1 -1
- package/templates/skills/ark-adopt.md +5 -1
- package/templates/skills/ark-contract.md +17 -0
- package/templates/skills/ark-coverage.md +2 -0
- package/templates/skills/ark-explore.md +7 -0
- package/templates/skills/ark-fix.md +20 -0
- package/templates/skills/ark-order.md +4 -2
- package/templates/skills/ark-place.md +8 -0
- package/templates/skills/ark-runtime.md +6 -1
- package/bin/lib/ark-order-error.mjs +0 -18
- package/bin/lib/ark-order-invariants.mjs +0 -346
- package/dist/types-Ik_OakcI.d.ts +0 -183
package/dist/index.js
CHANGED
|
@@ -1,55 +1,56 @@
|
|
|
1
|
-
var Ia=Object.defineProperty;var a=(e,t)=>Ia(e,"name",{value:t,configurable:!0});var Ea="4.8.23";var ba=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,va=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ca=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function _a(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return ba.test(n)?"pure-shared":r==="PersistenceAdapters"&&(va.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ca.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(_a,"classifyLayerImportKind");function Oa(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=_a(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}a(Oa,"layerImportNextAction");function xa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(xa,"arkRunCallSiteName");function Ta(e){let t=xa(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(Ta,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Oa(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 Ta(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(ye,"deterministicNextAction");var Gt="1.5",Bt="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 ut(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(ut,"adapterFindingTargetKey");function pt(e){let t=new Map;return e.map(n=>{let r=ut(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(pt,"adapterFindingOccurrenceTargetKeys");function zt(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(zt,"adapterFindingRefFromTargetKey");function Wt(e){return`${Bt}#${e}`}a(Wt,"adapterDocsCodePath");function w(e){return typeof e=="string"&&e.length>0?e:void 0}a(w,"text");function Is(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(Is,"positiveInteger");function wa(e,t,n){return ye({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}a(wa,"nextActionForDiagnostic");function Fn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},i=n??ut(e),l=zt(i);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:Is(e.line,1),column:Is(e.column,1)},evidence:s,nextAction:w(e.nextAction)??wa(r,s,e),findingRef:l,targetKey:i,docsCodePath:Wt(r)}}a(Fn,"toAdapterDiagnostic");function Na(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:w(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(m.message)??`Analysis ${t}: required evidence is incomplete.`,...w(m.file)?{file:w(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let 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=pt(s),c=pt(i),u=[...s.map((m,f)=>Fn(m,"error",l[f])),...i.map((m,f)=>Fn(m,"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 m={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...m}:{...p,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}a(Na,"createAdapterResult");var La="1.0",Es="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",qt="^sha256:[a-f0-9]{64}$",bs={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:qt,description:"Project id previously returned by ark_identity or ark_manifest."}}},vs={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:qt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Pa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Es,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:qt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:qt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:bs,binding:vs}};function Da(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(Da,"createProjectId");function Ma(e){return{schemaVersion:"1.0",...e}}a(Ma,"createProjectIdentity");var Hn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Vn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Kn=Object.freeze(Object.keys(Vn).sort()),$n=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"}),jn=Object.freeze({process:Object.freeze(["process","node:process"])});function ft(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=$n[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=$n[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:$n[e.slice(0,s)]??null}a(ft,"capabilityForModuleSpecifier");function _e(e,t){for(let n of t)if(jn[n]?.includes(e))return n;return null}a(_e,"forbiddenGlobalForModuleSpecifier");function Yt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Vn[r];if(o)return o}return null}a(Yt,"capabilityForAmbientName");function Ge(e){if(e?.pure===!0)return[...Hn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Hn.includes(r));return[...new Set(n)].sort()}a(Ge,"effectiveCapabilityDeny");function gt(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(gt,"ambientCoveredByForbiddenGlobals");function Jt(e){let t=new Set,n=new Set,r=Object.keys(Vn);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 jn[o]??[])t.add(`import-exact:${i}`)}for(let o of Ge(e)){if(t.add(`import:${o}`),o==="process")for(let s of jn.process)t.add(`import-exact:${s}`);for(let s of r)Yt(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(Jt,"loweredLayerCoverage");var Cs="4.8.22",_s=new Map;function Os(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Os,"escapeLiteral");function Qt(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(Qt,"normalizeGlobSeparators");function Fa(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(Fa,"bracesBalanced");function Ae(e){let t=_s.get(e);if(t)return t;let n=Qt(e),r=Fa(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Os(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+=Os(c)}let i=new RegExp(`^${o}$`);return _s.set(e,i),i}a(Ae,"globToRegExp");function $a(e){return Qt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a($a,"concreteGlobSegments");function Gn(e,t){let n=Qt(String(e)),r=$a(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let u of r){let p=-1;for(let m=l;m<i.length;m+=1)if(i[m]===u){p=m;break}if(p<0)return s;c=p,l=p+1}return(c+1)*1e6+r.length*1e4+o}a(Gn,"patternSpecificity");function ge(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>Ae(i).test(n))){for(let i of s.patterns??[])if(Ae(i).test(n)){let l=Gn(i,n);l>o&&(o=l,r=s.name)}}return r}a(ge,"layerForRelativePath");function Bn(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",o=String(e).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let s=new Set;for(let i of t)if(!(typeof i!="string"||i.length===0)){if(Ns(i)){let l=Ha(o,i,r);if(l)return l;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&s.add(i.toLowerCase())}return Ua(o,s)}a(Bn,"sliceIdForPath");function Ns(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Ns,"isAnchoredSliceEntry");function Ha(e,t,n){let r=t.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),o=Ps(e,r[0]??"");for(let s of o){let i=ja(e,r,s,n);if(i)return i}}a(Ha,"anchoredSliceId");function ja(e,t,n,r="path"){let o=[],s=-1,i=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(i>=e.length-1){for(let u=l;u<t.length;u+=1)if(t[u]!=="*")return;break}o.push(e[i].toLowerCase()),i+=1;continue}if(c==="**"||i>=e.length||e[i].toLowerCase()!==c)return;o.push(e[i].toLowerCase()),s=o.length-1,i+=1}if(o.length!==0)return r==="stars"?s<0?void 0:o.slice(s).join("/"):o.join("/")}a(ja,"bindAnchoredSlice");function Ls(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=Va(s);if(!i)continue;let l=s.split(/[/\\]/).filter(p=>p.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let u=r.get(i)??[];u.push(s),r.set(i,u)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:Ka(n.from,n.to,i,s)})}return t}a(Ls,"sliceIdentityCollisions");function Va(e){if(!Ns(e))return;let t=e.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),n=-1;for(let o=0;o<t.length;o+=1){let s=t[o]??"";if(s==="**")return;s!=="*"&&(n=o)}if(n<0)return;let r=t.slice(n);if(!r.some((o,s)=>s>0&&o!=="*"))return r.join("/")}a(Va,"starsIdentityStem");function Ka(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(Ka,"formatSliceIdentityCollision");function Ua(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(Ua,"bareSliceId");function Ga(e){let t=new Set;for(let n of e??[]){let o=Qt(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(Ga,"inferSliceFoldersFromPatterns");function zn(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 Ga(r?.patterns)}a(zn,"resolveSliceFolders");function xs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(xs,"normalizeSegments");function yt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(yt,"trimTrailingSlashes");var Ba=["src","app"];function Ps(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Ba.includes(n)&&r!==n?[0,1]:[0]}a(Ps,"anchorOffsets");function za(e){let t=yt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(za,"isBlanketRoot");function mt(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=xs(n);for(let s of t){if(typeof s!="string"||s.length===0||za(s))continue;if(s.includes("*")){let c=yt(s.toLowerCase());if(Ae(c).test(r)||Ae(`${c}/**`).test(r))return!0;continue}let i=xs(s);if(i.length===0)continue;let l=Ps(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let u=!0;for(let p=0;p<i.length;p+=1)if(o[c+p]!==i[p]){u=!1;break}if(u)return!0}}return!1}a(mt,"pathUnderSharedRoot");function Ts(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(Ts,"sliceMatchesDeclaration");function Wa(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Ts(r.from,t)&&Ts(r.to,n))}a(Wa,"crossSliceEdgeAllowed");function qa(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(qa,"peerIsolationDecision");function Ds(e){return yt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ds,"aliasGlobPattern");function Ya(e,t){let n=Ds(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=Un(r),s=Ae(n);return s.test(r)||o!==r&&s.test(o)}a(Ya,"aliasGlobMatches");function Ja(e){let t=Ds(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(Ja,"splitAliasTarget");function Xa(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Ya(n.from,e))return Ja(n.to);return null}a(Xa,"firstSliceAlias");function Be(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=Bn(e,r?[...r]:void 0,t.sliceIdentity),s=Xt(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=Xa(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Be,"resolveGovernedSlice");function Za(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(Za,"peerIsolationDenyExplanation");function Qa(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Qa,"crossParentExplanation");function el(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(el,"crossSiblingExplanation");function tl(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(tl,"parentImportsChildExplanation");function ht(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(ht,"universePairLabel");function nl(e){return String(e).split(/[/\\]/).filter(Boolean).slice(0,-1)}a(nl,"directorySegments");function rl(e,t){if(!t?.length)return!1;let n=new Set;for(let r of t)typeof r=="string"&&r.length>0&&n.add(r.toLowerCase());return n.size===0?!1:nl(e).some(r=>n.has(r.toLowerCase()))}a(rl,"pathHasCommonFolder");function Xt(e,t,n){if(!e||!n?.sliceFolders?.length)return{};if(rl(e,n.commonFolders))return{};let r=Bn(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let o=r.toLowerCase(),s=t.toLowerCase();return o===s?{}:o.startsWith(`${s}/`)?{childId:r}:{mismatched:{childId:r,universeId:t}}}a(Xt,"resolveChildSliceId");function sl(e){return yt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(sl,"siblingEntryKey");function Un(e){return e.replace(/^(?:src|app)\//,"")}a(Un,"stripSrcOrApp");function ol(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=Un(t);if(!r)return!1;let o=Un(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(ol,"pathUnderSubtree");function il(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=sl(o);if(!(!s||s.includes("*"))&&(r===s||e&&ol(e,s)))return!0}return!1}a(il,"importerInEnforcedSubtree");function al(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!il(t,n,e.enforce)}a(al,"siblingCrossingAdvisory");function Zt(e){if(typeof e!="string")return null;let t=yt(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(Zt,"childSlicePatternSegments");function ws(e,t){let n=Zt(e),r=Zt(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(ws,"childSlicePatternMatches");function ll(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&ws(r.from,t)&&ws(r.to,n))return!0;return!1}a(ll,"childCrossSliceAllowed");function cl(e,t){let n=Zt(e),r=Zt(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(cl,"childAllowanceSpansUniverses");function dl(e){let t=qa({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: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?Qa(e.fromSlice,e.toSlice):Za(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??Xt(e.fromPath,e.fromSlice,n).childId,o=e.toChild??Xt(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?ll(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:al(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:el(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:tl(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(dl,"evaluateNestedSliceWall");function ze(e){let t=e.verdict.explanation;if(e.surface==="intent"){let n=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return e.verdict.reasonId&&t?`${n} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${n} ${t}`:e.ruleMessage?t?`${e.ruleMessage} (${t})`:e.ruleMessage:n}if(e.ruleMessage)return t?`${e.ruleMessage} (${t})`:e.ruleMessage;if(t){let n=e.kind??"import";return`${e.fromLayer} must not ${n} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(ze,"composeSliceDenialMessage");function Ne(e){if(!e||e.decision==="allow")return{};let t=ht(e.fromUniverse),n=ht(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Ne,"sliceFindingExtras");function Ms(e,t){let n=[],r=!1,o=new Set,s=new Set;for(let i of e??[])if(i?.childSlices&&(r||(r=!0,n.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,message:`childSlices needs an arkgate newer than ${Cs}. Version ${Cs} and older reject the key because the rule schema sets additionalProperties: false.`})),!!i.peerIsolation)){for(let l of t){let c=Bn(l,i.sliceFolders,i.sliceIdentity),u=Xt(l,c,i.childSlices);if(!u.mismatched)continue;let p=`${i.from}\0${i.to}\0${u.mismatched.universeId}\0${u.mismatched.childId}`;o.has(p)||(o.add(p),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:i.from,toLayer:i.to,path:l,message:`${i.from} \u2192 ${i.to}: child id ${u.mismatched.childId} does not extend universe id ${u.mismatched.universeId} (${l}).`}))}for(let l of i.childSlices.allowedCrossSlice??[]){if(!l||typeof l.from!="string"||typeof l.to!="string"||!cl(l.from,l.to))continue;let c=`${l.from.trim().toLowerCase()}\0${l.to.trim().toLowerCase()}`;s.has(c)||(s.add(c),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`childSlices.allowedCrossSlice ${l.from} \u2192 ${l.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(Ms,"childSliceConfigFindings");function Fs(e,t,n,r){return Oe(e,t,n,r)?.rule}a(Fs,"findDeniedEdgeRule");function Oe(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=zn(o,t,r?.layers),c=Be(s,o,l),u=Be(i,o,l),p=c.universeId,m=u.universeId,f=dl({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:p,toSlice:m,fromChild:c.childId,toChild:u.childId,fromShared:!p&&mt(s,o.sharedRoots),toShared:!m&&mt(i,o.sharedRoots),crossSliceAllowed:Wa(o.allowedCrossSlice,p,m)});if(f.decision!=="allow")return{rule:o,peerIsolationReason:f.peerIsolationReason,fromSlice:p,toSlice:m,sliceVerdict:f};continue}if(t!==n)return{rule:o}}}a(Oe,"findDeniedEdgeDecision");function $s(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let i of e??[]){if(i.from!==t||i.to!==n||i.allowed!==!1||!i.peerIsolation||i.sharedImportsSlice==="deny")continue;let l=zn(i,t,r?.layers),c=Be(o,i,l).universeId,u=Be(s,i,l).universeId;if(!(c||!u)&&mt(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}a($s,"findSharedImportsSliceBridge");function Hs(e,t,n){return zn(e,t,n)}a(Hs,"peerSliceFolders");function We(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(We,"literalText");function Ks(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(Ks,"lineOf");function js(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(js,"isTypeOnlyReference");function Us(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}a(Us,"singleFileChecker");function Wn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Wn,"symbolAt");function qn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Wn(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(qn,"localDeclaration");function qe(e,t){let n,r=[],o=a((i,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Ks(t,i),typeOnly:u,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",We(e,i.moduleSpecifier),js(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",We(e,i.moduleSpecifier),js(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",We(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!qn(e,n??(n=Us(e,t)),t,i.expression);(l||u)&&o(i,u?"require":"dynamic-import",We(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(qe,"extractSemanticDependencies");function ul(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=We(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(ul,"staticAccessPath");function pl(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(pl,"runtimeIdentifierReference");function Vs(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(Vs,"bestForbiddenMatch");function Ye(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Us(e,t),s=new Map,i=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let g of f.declarationList.declarations)e.isIdentifier(g.name)&&i.add(g.name.text);let l=a(f=>{let g=ul(e,f);if(!g)return;let d=Wn(o,g.root),h=d?s.get(d):void 0;return h?[...h,...g.segments.slice(1)]:qn(e,o,t,g.root)||i.has(g.root.text)?void 0:g.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let g of f.declarationList.declarations){if(!g.initializer||!e.isIdentifier(g.name))continue;let d=l(g.initializer),h=Wn(o,g.name);!d||!h||s.set(h,d)}let c=[],u=new Set,p=a((f,g)=>{let d=Ks(t,g),h=`${f}:${g.getStart(t)}`;u.has(h)||(u.add(h),c.push({name:f,line:d,node:g}))},"flag"),m=a(f=>{let g=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!g){let d=l(f),h=d?Vs(r,d):void 0;h&&p(h,f)}else e.isIdentifier(f)&&r.has(f.text)&&pl(e,f)&&!qn(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 h of f.name.elements){if(!e.isIdentifier(h.name))continue;let E=h.propertyName?We(e,h.propertyName)??h.propertyName.text:h.name.text,_=Vs(r,[...d,E]);_&&p(_,f.initializer)}}e.forEachChild(f,m)},"visit");return m(t),c}a(Ye,"collectForbiddenCapabilityUses");function Yn(e,t,n){let r=[];for(let o of n?.dependencies??qe(e,t)){if(o.typeOnly||!o.specifier)continue;let s=ft(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ye(e,t,Kn)){let s=Yt(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(Yn,"collectCapabilityUses");var Jn={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."},Xn=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 Zn(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(Zn,"resolveIntentLayer");function Le(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(Le,"looksLikeArkIntent");function At(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Le(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Jn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Jn.PUBLISH_MISSING_SOURCE}),t}a(At,"classifyPublishFacts");function X(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(X,"violation");function Je(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}a(Je,"lineOf");var fl=new Set(["publish","subscribe","defineIntent","registerHandler"]);function gl(e,t){return e.index+e[0].indexOf(t)}a(gl,"captureIndex");function ml(e){let t=[],n=new Set,r=a((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=a(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,gl(c,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,i;for(;(i=s.exec(e))!==null;){let l=i[1]??"",c=i.index+i[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.exec(l))!==null;){let m=p[1];m&&r(m,c+p.index+p[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(ml,"extractQuotedStrings");function hl(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(hl,"extractModuleSpecifiers");function yl(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(yl,"isSyntaxWrapper");function Qn(e,t){let n=t;for(;n?.parent&&yl(e,n.parent);)n=n.parent;return n}a(Qn,"unwrapWrappers");function er(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(er,"callCalleeName");function Al(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Qn(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&er(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&tr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Qn(e,s).parent;return!!(l&&e.isCallExpression(l)&&er(e,l)==="publish")}return!1}a(Al,"isPublishMetadataSource");function Gs(e,t){let n=Qn(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=er(e,r);if(o&&fl.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return Gs(e,r);if(e.isPropertyAssignment(r)){let o=tr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Al(e,r))return!0}return!1}a(Gs,"isDeclaredIntentSite");function Rl(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&Gs(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(Rl,"extractQuotedStringsAst");function kl(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(kl,"hasInfrastructureToken");function Sl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(Sl,"isKnownInfrastructurePackage");function Il(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(Il,"layerHasInfrastructureRole");function kt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(kt,"tsStringLiteralText");function tr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(tr,"tsPropertyName");function Bs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:tr(e,r.name)===n)}a(Bs,"tsObjectProperty");function St(e,t,n){return Bs(e,t,n)!==void 0}a(St,"tsObjectHasProperty");function Rt(e,t,n){let r=Bs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Rt,"tsObjectPropertyValue");function El(e,t){let n=Rt(e,t,"metadata");return St(e,n,"source")}a(El,"tsObjectHasMetadataSource");function zs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?zs(e,t.name):!1:!1}a(zs,"tsLooksLikeIntentCreatorExpression");function bl(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(bl,"tsIsPublishCall");function vl(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=kt(e,n);return r!==void 0&&Le(r)||St(e,n,"intent")||zs(e,n)}a(vl,"tsIsArkPublishCandidate");function Cl(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return El(e,n)||St(e,r,"source")||St(e,o,"source")}a(Cl,"tsPublishHasSource");function _l(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Rt(e,n,"metadata");return kt(e,Rt(e,s,"source"))??kt(e,Rt(e,r,"source"))??kt(e,Rt(e,o,"source"))}a(_l,"tsPublishSourceLiteral");function Ol(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],u=a(m=>o.getLineAndCharacterOfPosition(m.getStart(o)).line+1,"lineForNode"),p=a(m=>{if(bl(e,m)){let f=m.arguments[0],g=kt(e,f);for(let h of At({publishCall:!0,rawIntentName:g,objectHasIntent:St(e,f,"intent"),arkPublishCandidate:vl(e,m),hasSource:Cl(e,m)}))c.push(X(h.ruleId,h.message,{line:u(m),filePath:i}));let d=_l(e,m);if(r&&l&&d&&Le(d)){let h=r.resolveLayer(d);h&&h!==l&&c.push(X("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${h}, but the target file is classified as ${l}.`,{line:u(m),filePath:i,target:d,fromLayer:l,toLayer:h}))}}e.forEachChild(m,p)},"visit");return p(o),c}a(Ol,"analyzePublishAst");function Ws(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,u=c?.filePath,p=c?.layer,m=e.typescript,f=m?m.createSourceFile(u??"generated.ts",s,m.ScriptTarget.Latest,!0):void 0,g=f?qe(e.typescript,f):void 0,d=g?g.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(f),kind:k.kind,typeOnly:k.typeOnly})):hl(s),h=e.typescript?Rl(e.typescript,s):ml(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of g?.filter(({unresolved:b})=>b)??[]){let b=k.kind==="require";l.push(X(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:u}))}let E=p!==void 0&&(r.has(p)||Il(p)),_=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 k of n)if(k instanceof RegExp){k.lastIndex=0;let b=k.exec(s);k.lastIndex=0,b&&l.push(X("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:b.index===void 0?void 0:Je(s,b.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+_}))}else s.includes(k)&&l.push(X("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:Je(s,s.indexOf(k)),filePath:u}));for(let k of d){let b=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),O=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,D=b?.layer;if(D&&p){let S=Oe(e.architectureProfile?.rules,p,D,{fromPath:O?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(S){let L=S.rule;if(k.typeOnly&&!L.peerIsolation)continue;let j=!!L.peerIsolation,T=Ne(S.sliceVerdict),M=L.message??(j?`Layer "${p}" must not import across slices into "${D}".`:`Layer "${p}" must not import "${D}".`),P=T.reasonId||j&&!S.peerIsolationReason?S.sliceVerdict?.explanation:void 0;l.push(X("LAYER_IMPORT_VIOLATION",P?`${M} ${P}`:M,{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:p,toLayer:D,...T.reasonId?{reasonId:T.reasonId}:{},...T.failsStrict===!1?{failsStrict:!1}:{},suggestion:j?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:k.kind,peerIsolation:j,...k.typeOnly?{typeOnly:!0}:{},...T.reasonId?{reasonId:T.reasonId}:{}}}));continue}continue}E||k.typeOnly||!kl(k.value)&&!Sl(k.value)||l.push(X("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+_,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let b=k.check({source:s,context:i});if(b!==!0)if(Array.isArray(b))for(let O of b)l.push(X("POLICY_VIOLATION",O.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else b===!1?l.push(X("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):l.push(X("POLICY_VIOLATION",b.message))}if(o&&t.size>0)for(let k of h)Le(k.value)&&!t.has(k.value)&&l.push(X("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:Je(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let k of h){if(!Le(k.value))continue;let b=e.architectureProfile.resolveLayer(k.value);if(!b)continue;let O=Oe(e.architectureProfile.rules,p,b,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(O){let D=O.sliceVerdict,S=`Layer "${p}" must not reference "${b}" through "${k.value}".`,L=D?ze({surface:"intent",verdict:D,fromLayer:p,toLayer:b,fromPath:typeof u=="string"?u:void 0,ruleMessage:O.rule.message,defaultMessage:S}):O.rule.message??S,j=Ne(D);l.push(X("LAYER_REFERENCE_VIOLATION",L,{line:Je(s,k.index),filePath:u,target:k.value,fromLayer:p,toLayer:b,...j.reasonId?{reasonId:j.reasonId}:{},...j.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O.rule,peerIsolationReason:O.peerIsolationReason,...j.reasonId?{reasonId:j.reasonId}:{}}}))}}if(e.extensions)for(let k of e.extensions)try{let b=k.analyze(s,i);l.push(...b)}catch(b){l.push(X("EXTENSION_ERROR",`Extension "${k.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let k=e.forbiddenGlobals[p];l.push(...Ye(e.typescript,f,k).map(b=>X("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${b.name}".`,{line:b.line,filePath:u,target:b.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 b of g??[]){if(b.typeOnly||!b.specifier)continue;let O=_e(b.specifier,k);O&&l.push(X("FORBIDDEN_GLOBAL",`${p} must not use module "${b.specifier}" because it is the import form of forbidden global "${O}".`,{line:b.line,filePath:u,source:b.specifier,target:b.specifier,fromLayer:p,details:{importKind:b.kind,forbiddenGlobal:O},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let k=new Set(e.capabilityWalls[p]),b=e.forbiddenGlobals?.[p]??[];for(let O of Yn(e.typescript,f))k.has(O.capability)&&(O.source==="ambient-global"&>(O.symbol,b)||O.source==="import-based"&&_e(O.symbol,b)||l.push(X("CAPABILITY_VIOLATION",O.source==="import-based"?`${p} denies the ${O.capability} capability; found import of "${O.symbol}".`:`${p} denies the ${O.capability} capability; found ambient "${O.symbol}".`,{line:O.line,filePath:u,target:O.symbol,capability:O.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{l.push(...Ol(e.typescript,s,i,e.architectureProfile))}catch(k){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:!l.some(k=>k.failsStrict!==!1),violations:l}}}}a(Ws,"createAICodeGate");var Pe={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Pe,default:[]},kernelRoots:{...Pe},managedLayers:{...Pe,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ys={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Pe,default:[]},managedLayers:{...Pe,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Pe,default:[]},appliesTo:{...Pe,default:[]}}};function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(It,"isObject");function Js(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)It(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Js,"declaredLayerNames");function Xs(e){if(!It(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}a(Xs,"defaultedArkRun");function Zs(e){if(!It(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}a(Zs,"defaultedArkOrder");function Qs(e,t){let n=e.arkRun;if(n===void 0||!It(n))return;let r=Js(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(Qs,"validateArkRunExtra");function eo(e,t){let n=e.arkOrder;if(n===void 0||!It(n))return;let r=Js(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(eo,"validateArkOrderExtra");function en(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(en,"normalizeStewardId");function to(e){let t=en(e);return!t||nr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(to,"isGitHubHandle");function xl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||nr(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}a(xl,"isGitHubEmail");function Tl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&to(t[1])?en(t[1]):null}a(Tl,"githubHandleFromEmail");function no(e){let t=Tl(e);if(t)return t;let n=en(e);return!n||nr(n)?null:to(n)||xl(n)?n:null}a(no,"canonicalStewardId");var wl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function nr(e){let t=en(e);return!t||wl.test(t)}a(nr,"isAutomationAuthor");var le="1.3",Nl=["public","auth","admin","internal"];function Ll(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(Ll,"isFutureHouseLayer");function Pl(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(Pl,"layerOwnersList");function lo(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ll(t)&&!Pl(t)).map(t=>t.name)}a(lo,"layersMissingRequiredOwners");function co(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(co,"missingLayerOwnersNextAction");var tn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",ro=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Dl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ml(){let e=[];for(let t of ro)for(let n of ro)t===n||Dl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Ml,"createDefaultRules");var nn=Ml(),rr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ne={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},sr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:tn,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:tn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:le,default:le},name:{type:"string",minLength:1},include:{...ne,minItems:1,default:["src"]},exclude:{...ne,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:nn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ne,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ne,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ne,minItems:1},exclude:ne,intentPrefixes:ne,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Nl]},owners:{...ne,minItems:1},forbiddenGlobals:ne,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ne,minItems:1},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:{...ne,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny","deny-cross-parent"],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. arkgate 4.8.22 and older reject deny-cross-parent."},childSlices:{type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Absent keeps today's universe wall. sliceFolders names children. commonFolders and flat files are universe common. siblings is "deny" (default), "advisory", or { default, enforce }. parentMayImportChild defaults to false. 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:{...ne,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...ne,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce } so listed subtrees are errors while the default stays advisory. A string-enum build rejects the object at config load (must be one of deny, advisory).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...ne}}}]},parentMayImportChild:{type:"boolean"},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 bare name, a universe id alone, an unknown universe, and a wildcard in to are rejected. 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}}}}}}}},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:{...ne,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:{...ne,minItems:1}}},arkRun:qs,arkOrder:Ys}},Ie=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
1
|
+
var Ql=Object.defineProperty;var a=(e,t)=>Ql(e,"name",{value:t,configurable:!0});var ec="4.8.25";var gr="docs/diagnostics.md",tc="1.0";function b(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(b,"entry");var rn=Object.freeze([b("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),b("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),b("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),b("SHARED_IMPORTS_SLICE","layer","A shared root imports a slice",'A declared shared root imports a slice directly. That hop is allowed while sharedImportsSlice is unset or "deny-cross-parent", so this is advisory: the universe wall is direct-only.','Move the code the shared root needs into the shared root, or invert the dependency. Set sharedImportsSlice: "deny" to make these edges errors. With "deny-cross-parent", a slice that reaches another universe through a shared root is reported as LAYER_IMPORT_VIOLATION with reasonId CROSS_PARENT_VIA_SHARED. This warning does not fail the check.',{oftenAdvisory:!0}),b("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),b("CROSS_WALL_DUPLICATE","layer","Code copied across a wall","Near-identical code sits on two sides of a slice wall (or in two layers that may not import each other). The wall would deny the import, so the code was copied instead. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; they never enter the check, so the verdict does not change. Same-slice copies are counted, never listed.","Move one copy to a shared home the wall allows \u2014 a declared shared root, the universe common folder, or a layer both sides may import \u2014 then import it from both sides. One move at a time, through the write gate (/ark-place names the destination). Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("CROSS_LAYER_DUPLICATE","layer","Code copied in two layers","Near-identical code sits in two layers, and at least one of them may import the other. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; the verdict does not change.","Keep one copy in the lower layer both sides may import, and import it from the other. One move at a time, through the write gate. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),b("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),b("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),b("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),b("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),b("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),b("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),b("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),b("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),b("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),b("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),b("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),b("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),b("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),b("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),b("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),b("ARKRULE_FILE_UNREFERENCED","arkrules","ArkRules file not referenced","A JSON file under arkrules/, or a slice file named arkrules.<Layer>.json beside governed code, is not in the effective catalog, so none of its rules are enforced. Drift looks like governance until someone notices.","Reference a central file from arkRules, set childSlices.arkRulesFile so a slice file is discovered, or delete it. Advisory only: it never fails the check.",{oftenAdvisory:!0}),b("ARKRULE_DUPLICATE_ID","arkrules","ArkRule id declared more than once","Two ArkRules files in one layer declare the same effective id. Central ids stay bare. A slice file is namespaced as <childId>#<localId>, so the same local id in two slices is not a duplicate.","Rename one id, or split the files onto different slices. Config load fails closed. The catalog is not enforced until the id is unique."),b("ARKRULE_SCOPE_ESCAPES_SLICE","arkrules","Slice ArkRule appliesTo leaves its slice","A file discovered from childSlices.arkRulesFile set appliesTo to a glob that can match outside that child slice. The default, when appliesTo is omitted, is the slice directory.","Narrow appliesTo to the slice directory, or omit it. Config load fails closed. The escaping rule is not enforced."),b("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),b("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),b("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),b("INVARIANT_PROBE_SURVIVED","arkrules","Covering tests do not pin the invariant","The committed invariant probe (.ark/invariant-probe.json, written by arkgate-check --probe-invariants --write) shows, for files that have not changed since, that the covering tests still pass with the invariant's symbol broken on purpose (survived) or never call it (not reached). The test names the rule but does not pin it. A status and inventory line only: it never enters the check, so the verdict does not change.","Add a test case that fails when the rule is broken (the line names the change that went unnoticed), then re-run arkgate-check --probe-invariants --write and commit the file. Promotion to enforced refuses while the fresh artifact says survived or not reached; a stale, killed, inconclusive or missing result changes nothing.",{oftenAdvisory:!0}),b("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present. Not freezable."),b("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),b("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel, their *FromConfig variants, or ArkModule.forRoot / forRootAsync imported from arkgate/nestjs) was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),b("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, arkgate/nestjs, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),b("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),b("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),b("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),b("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call on a receiver traced to the kernel names a component that is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),b("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),b("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),b("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),b("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),b("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),b("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),b("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),b("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),b("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),b("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),b("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),b("ARKORDER_STALE_PROPOSAL","arkorder","Proposal is not bound to the current Release","apply() got a ProposeResult computed against another Release (another apply landed first), one missing its base binding, or one whose reviewed blast radius is not the transition that would commit. The binding is data, not a capability: a proposal that states the current base and the exact transition applies whoever built it.","Run proposeRelease again against the current Release, review the new blast radius, then apply that proposal. Never mechanical-safe."),b("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),b("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),b("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),b("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),b("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),b("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),b("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),b("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),b("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),b("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),b("WRITE_GATE_UNAVAILABLE","preflight","Write gate could not run","The write gate could not load its own inputs (ark.config.json missing, unreadable, or invalid; a referenced ArkRules file missing or invalid; or the built library missing), so it cannot judge this governed source write (existing files included), or a write would leave ark.config.json or a referenced ArkRules file unloadable. No checker, no write: the hook blocks instead of letting the write through unchecked.","Fix the reported input (repair ark.config.json or the ArkRules file, or run `npm run build` / reinstall arkgate from npm), then retry the same write. Do not remove the hook to get past it."),b("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),b("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),b("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","For a complete verdict, run `npx arkgate-check --root . --config ark.config.json` (or ark_prepare_change over MCP with the full candidate batch). Read lexicalValid for the one-file result."),b("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),b("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),b("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),b("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),b("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),b("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),b("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),b("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),b("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),b("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),b("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),b("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),b("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),b("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),b("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),b("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),b("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),b("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),b("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),b("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),b("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),b("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),b("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),b("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),b("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),b("CONFIG_CHILD_SLICES_VERSION","config","Config needs a newer arkgate than a pinned copy",'ark.config.json uses a slice key (childSlices, sharedImportsSlice "deny-cross-parent" or its object form, sliceIdentity, sharedImportsSlice, childSlices.message, siblings.ratchet) that an arkgate pinned in this repo rejects at config load. Emitted only with evidence of that pin: an exact package.json dependency, the installed node_modules/arkgate, package-lock.json, a scripts/*hook* or host hook command, or a CI workflow. Silent otherwise.',"Bump the named file to the version the finding gives (or newer), then run Ark again. This warning does not fail the check.",{oftenAdvisory:!0}),b("CONFIG_CHILD_SLICE_EXTENDS","config","Child slice id does not extend its universe","A path resolved a child id that is not the universe id plus a further segment. The child wall does not treat that id as a child, so the edge is universe common until the folders line up.","Point childSlices.sliceFolders at children under the same universe id the outer sliceFolders already names. Doctor names the path.",{oftenAdvisory:!0}),b("CONFIG_CHILD_SLICE_CROSS_UNIVERSE","config","Child slice allowance cannot cross the universe wall","childSlices.allowedCrossSlice names a pattern that can match two universes. That list clears only a sibling crossing inside one universe. The universe wall still denies the edge.","Narrow the pattern so both sides share one universe prefix (features/projects/* to features/projects/d2d-item), or remove the entry. This warning does not fail the check.",{oftenAdvisory:!0}),b("CONFIG_CHILD_SLICES_INERT","config","childSlices on a rule that cannot run it","A rule sets childSlices without peerIsolation: true and allowed: false. The child wall runs only inside a universe wall, so on this rule childSlices enforces nothing. Config load still accepts it (arkgate 4.8.23 did too).",'Add "peerIsolation": true and "allowed": false to the same rule so the child wall runs, or remove childSlices. This warning does not fail the check.',{oftenAdvisory:!0}),b("CONFIG_SLICE_LEGACY_STARS_ID","config","Slice id written in the 4.8.23 stars form",'Under sliceIdentity "stars", a sliceAliases target or an allowedCrossSlice entry names the 4.8.23 stars id, which dropped a star binding before the last literal (modules/*/api/* bound api/v1). The id now keeps that binding (orders/api/v1). For one release the entry keeps its 4.8.23 meaning, so verdicts do not change.',"Rewrite the entry with the new id the warning names (for example orders/api/v1/x instead of api/v1/x). A sliceAliases target that maps to more than one universe shape is rejected at config load. This warning does not fail the check.",{oftenAdvisory:!0}),b("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),b("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),b("ORPHAN_MODULE","drift","File nothing imports","No governed file, test or entry point imports this module. It is the leftover an agent leaves when a rewrite lands next to the old file. Status reads it from the import facts the check already resolved, so it never changes the verdict. When a dynamic import, an unresolved import or an unmapped entry could reach the file, the item says so (maybe-dynamic, maybe-unresolved) and the list is partial.","Delete the file through the write gate, one file at a time. If a framework, a script or a runtime loader uses it, add a glob with a reason to .ark/entry-points.json (optional reviewBy) instead. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("UNUSED_EXPORT","drift","Export nothing imports by name","An export no governed file or test imports by name. Listed only in status details (`--doctor --all`) and the report. Default, namespace, star, dynamic and require use count as using every export, so those files are skipped.","Drop the export keyword (or the code) if nothing outside the file needs it, or keep it when it is public API an entry point exposes. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),b("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),mr=new Map(rn.map(e=>[e.ruleId,e])),nc=Object.freeze(rn.map(e=>e.ruleId));function rc(e){return typeof e=="string"&&e.length>0&&mr.has(e)}a(rc,"isKnownDiagnosticCode");function sc(e){return typeof e!="string"||e.length===0?!1:mr.has(e)?!0:e.startsWith("ARKRULE_")}a(sc,"isCataloguedOrArkRuleFamily");function sn(e){if(!(typeof e!="string"||e.length===0))return mr.get(e)}a(sn,"getDiagnosticCatalogEntry");function ro(e){return`#${sn(e)?.docsAnchor??e}`}a(ro,"diagnosticDocsFragment");function oc(e){return`${gr}${ro(e)}`}a(oc,"diagnosticDocsPath");function ic(){return{schemaVersion:"1.0",docsPath:gr,codes:rn}}a(ic,"serializeDiagnosticCatalog");function ac(e){return sn(e)?.fix}a(ac,"catalogFixForRuleId");function lc(e){return sn(e)?.why}a(lc,"catalogWhyForRuleId");var cc=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."})]),dc=new Map(cc.map(e=>[e.reasonId,e]));function so(e){if(!(typeof e!="string"||e.length===0))return dc.get(e)}a(so,"sliceReasonHint");var uc=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,pc=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,fc=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function gc(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return uc.test(n)?"pure-shared":r==="PersistenceAdapters"&&(pc.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":fc.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(gc,"classifyLayerImportKind");function mc(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}a(mc,"sliceHintAction");function hc(e){let t=so(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${mc(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=gc(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(hc,"layerImportNextAction");function yc(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(yc,"arkRunCallSiteName");function Ac(e){let t=yc(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(Ac,"arkRunNextAction");function he(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return hc(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 Ac(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(he,"deterministicNextAction");var on="1.5",an="docs/diagnostics.md",oo={$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 kt(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(kt,"adapterFindingTargetKey");function It(e){let t=new Map;return e.map(n=>{let r=kt(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(It,"adapterFindingOccurrenceTargetKeys");function ln(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(ln,"adapterFindingRefFromTargetKey");function cn(e){return`${an}#${e}`}a(cn,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}a(x,"text");function io(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(io,"positiveInteger");function Rc(e,t,n){return he({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0,reasonId:x(t.reasonId)??void 0})}a(Rc,"nextActionForDiagnostic");var Sc=new Set(["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]);function kc(e){let t=e.details,n=t!==null&&typeof t=="object"?t.reasonId:void 0,r=x(e.reasonId)??x(n);return r&&Sc.has(r)?r:void 0}a(kc,"sliceReasonOf");function hr(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s=kc(e),i={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{},...s?{reasonId:s}:{},...s&&x(e.universeFrom)?{universeFrom:x(e.universeFrom)}:{},...s&&x(e.universeTo)?{universeTo:x(e.universeTo)}:{}},l=n??kt(e),c=ln(l);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:io(e.line,1),column:io(e.column,1)},evidence:i,nextAction:x(e.nextAction)??Rc(r,i,e),findingRef:c,targetKey:l,docsCodePath:cn(r)}}a(hr,"toAdapterDiagnostic");function Ic(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(g=>({code:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],i=e.warnings??[],l=It(s),c=It(i),d=[...s.map((g,f)=>hr(g,"error",l[f])),...i.map((g,f)=>hr(g,"warning",c[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:d};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}a(Ic,"createAdapterResult");var He={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ao={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...He,default:[]},kernelRoots:{...He},managedLayers:{...He,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},lo={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...He,default:[]},managedLayers:{...He,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...He,default:[]},appliesTo:{...He,default:[]}}};function bt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(bt,"isObject");function bc(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)bt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(bc,"declaredLayerNames");function co(e){if(!bt(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(co,"defaultedArkRun");function uo(e){if(!bt(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(uo,"defaultedArkOrder");function po(e,t,n,r){if(!Array.isArray(t))return;let o=bc(e);t.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!o.has(s)&&r.push({path:`$.${n}.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})})}a(po,"validateManagedLayersDeclared");function fo(e,t){let n=e.arkRun;if(n===void 0||!bt(n))return;let r=n.managedLayers;if(po(e,r,"arkRun",t),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(r)||r.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(fo,"validateArkRunExtra");function go(e,t){let n=e.arkOrder;if(n===void 0||!bt(n))return;let r=n.managedLayers;if(po(e,r,"arkOrder",t),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(r)||r.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(go,"validateArkOrderExtra");var un={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ko={description:'deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. The object form { mode: "deny-cross-parent", stopAt } names composition roots (bootstrap, DI registrations) the whole-graph walk never starts at or passes through; a stop file must still sit under sharedRoots, and stopAt does not silence the direct SHARED_IMPORTS_SLICE warning. arkgate 4.8.22 and older reject deny-cross-parent. arkgate 4.8.23 and older reject the object form (must be one of deny, deny-cross-parent).',oneOf:[{type:"string",enum:["deny","deny-cross-parent"]},{type:"object",additionalProperties:!1,required:["mode","stopAt"],properties:{mode:{type:"string",enum:["deny-cross-parent"]},stopAt:{...un,minItems:1}}}]},Io={type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Runs only on a rule with peerIsolation: true and allowed: false; elsewhere it is inert and ark-check warns CONFIG_CHILD_SLICES_INERT (config load still accepts it, as 4.8.23 did). Absent keeps today's universe wall. sliceFolders names children. Flat files are universe common, and so is a commonFolders directory directly under the universe (a folder of that name inside a child belongs to that child). siblings is "deny" (default), "advisory", or { default, enforce, ratchet }. parentMayImportChild defaults to false. message is the text for inner-wall findings. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...un,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...un,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce, ratchet } so listed subtrees are errors while the default stays advisory. ratchet absent: a new advisory crossing fails only when the baseline in use already records an advisory crossing of this rule. ratchet true: any unrecorded advisory crossing fails when a baseline is in use. ratchet false: measure only, never fails. A string-enum build rejects the object at config load (must be one of deny, advisory). arkgate 4.8.23 and older reject ratchet (unknown field).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...un},ratchet:{type:"boolean"}}}]},parentMayImportChild:{type:"boolean"},message:{type:"string",minLength:1,description:"Text for inner-wall findings (CROSS_SIBLING_SLICE and universe common importing a child). The rule message stays the universe-wall text (CROSS_PARENT_SLICE and fail-closed denies). Absent: ArkGate default text, never the rule message. arkgate 4.8.23 and older reject this field (unknown field)."},arkRulesFile:{type:"string",minLength:1,description:"Filename read at each child slice root this wall already resolved. The only token is <Layer>, replaced with a declared layer name (arkrules.<Layer>.json). No slash and no wildcard. A discovered file that omits appliesTo is scoped to that slice directory. Explicit appliesTo outside the slice fails config load (ARKRULE_SCOPE_ESCAPES_SLICE). The effective id is <childId>#<localId>. A build that rejects unknown childSlices fields fails at config load (unknown field)."},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A path without a wildcard also covers everything under it, as sharedRoots does. A bare name, a universe id alone, a target outside every universe shape, and a wildcard in to are rejected. Under stars identity a target written against the 4.8.23 stars id (star bindings before the last literal dropped, e.g. api/v1/x for modules/*/api/*) still loads when it maps to one universe shape, and ark-check warns CONFIG_SLICE_LEGACY_STARS_ID with the new id; it is rejected only when it maps to more than one shape. Config load checks only the shape; doctor reports a target universe no file belongs to. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each unpinned alias as an owed move. pinned true lists the alias separately and does not count it as debt. reason is a doctor label and does not pin by itself. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},pinned:{type:"boolean",description:"True when a framework forces the path to stay. The alias is not an owed move and does not clear other honesty debt."},reason:{type:"string",minLength:1,description:"Doctor label, such as framework-route. A label alone does not pin."}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}};function ie(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ie,"isObject");function pn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(pn,"propertyPath");function we(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(we,"trimTrailingSlashes");function bo(e,t){xc(e,t),wc(e,t),Lc(e,t),Yc(e,t),qc(e,t)}a(bo,"validateSliceContract");var mo='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',ho="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function vc(e){return e==="*"||e==="**"}a(vc,"isWildcardSegment");function vo(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&&vc(t[n-1]??"");)n-=1;let r=t.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(vo,"coveredFolder");function Ec(e,t){return e.length<=t.length&&e.every((n,r)=>t[r]===n)}a(Ec,"isPrefixOf");function Cc(e,t){let n=e.layers;if(!Array.isArray(n))return[];let r=new Set([t.from,t.to].filter(s=>typeof s=="string")),o=[];for(let s of n){if(!ie(s)||typeof s.name!="string"||!r.has(s.name))continue;let i=Array.isArray(s.patterns)?s.patterns:[];for(let l of i){if(typeof l!="string")continue;let c=l.replace(/\\/g,"/").split("/"),d=c.findIndex(f=>f.includes("*")),p=d===-1?c:c.slice(0,d),g=vo(p.join("/"));g&&o.push(g)}}return o}a(Cc,"ruleLayerFolders");function _c(e,t){let n=we(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 ho;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=vo(n);return o===null?null:o.length===0?ho:t.some(s=>Ec(o,s))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(_c,"stopAtEntryIssue");function xc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r)||r.sharedImportsSlice===void 0)return;let s=r.sharedImportsSlice,i=`$.rules[${o}].sharedImportsSlice`;if(typeof s=="string"){s!=="deny"&&s!=="deny-cross-parent"&&t.push({path:i,message:mo});return}if(!ie(s)){t.push({path:i,message:mo});return}for(let p of Object.keys(s))p!=="mode"&&p!=="stopAt"&&t.push({path:pn(i,p),message:"unknown field"});s.mode===void 0?t.push({path:`${i}.mode`,message:"is required"}):s.mode!=="deny-cross-parent"&&t.push({path:`${i}.mode`,message:'must be deny-cross-parent. stopAt has no meaning for deny; use the string "deny".'});let l=s.stopAt;if(l===void 0){t.push({path:`${i}.stopAt`,message:"is required"});return}if(!Array.isArray(l)||l.length===0){t.push({path:`${i}.stopAt`,message:"must be a non-empty array of paths or globs"});return}let c=new Set,d=Cc(e,r);l.forEach((p,g)=>{let f=`${i}.stopAt[${g}]`;if(typeof p!="string"){t.push({path:f,message:"must be a non-empty path or glob"});return}let m=_c(p,d);if(m){t.push({path:f,message:m});return}let u=we(p.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(u)){t.push({path:f,message:"duplicate stopAt entry"});return}c.add(u)})})}a(xc,"validateSharedImportsSlice");var Oc=["deny","advisory"],yo='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function wc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){Oc.includes(i)||t.push({path:l,message:yo});return}if(!ie(i)){t.push({path:l,message:yo});return}for(let d of Object.keys(i))d!=="default"&&d!=="enforce"&&d!=="ratchet"&&t.push({path:pn(l,d),message:"unknown field"});if(i.ratchet!==void 0&&typeof i.ratchet!="boolean"&&t.push({path:`${l}.ratchet`,message:"must be a boolean"}),i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((d,p)=>{let g=`${l}.enforce[${p}]`;if(typeof d!="string"||d.trim().length===0){t.push({path:g,message:"must be a non-empty child slice id or subtree path"});return}let f=we(d.trim().replace(/\\/g,"/"));if(f.split("/").some(m=>m.length===0||m==="."||m==="..")){t.push({path:g,message:"must be a child slice id or subtree path without . or .."});return}if(f.includes("*")){t.push({path:g,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(f)){t.push({path:g,message:"duplicate enforce entry"});return}c.add(f)})})}a(wc,"validateChildSliceSiblings");var Tc="must be a slice id with a slash. A bare name is ambiguous across universes.",Pc="* matches one whole path segment. ** and a partial segment are not wildcards.";function Nc(e){let t=we(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return Tc;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 Pc}return null}a(Nc,"childCrossSlicePatternIssue");function Ao(e){return we(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ao,"childCrossSlicePatternKey");function Lc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.allowedCrossSlice===void 0)return;let i=s.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((d,p)=>{let g=`${l}[${p}]`;if(!ie(d)){t.push({path:g,message:"must be an object with from and to"});return}for(let m of Object.keys(d))m!=="from"&&m!=="to"&&t.push({path:pn(g,m),message:"unknown field"});for(let m of["from","to"]){let u=d[m],h=`${g}.${m}`;if(typeof u!="string"||u.trim().length===0){t.push({path:h,message:"must be a non-empty slice id"});continue}let k=Nc(u);k&&t.push({path:h,message:k})}if(typeof d.from!="string"||typeof d.to!="string")return;let f=`${Ao(d.from)}\0${Ao(d.to)}`;if(!f.startsWith("\0")&&!f.endsWith("\0")){if(c.has(f)){t.push({path:g,message:"duplicate child slice allowance"});return}c.add(f)}})})}a(Lc,"validateChildSliceAllowedCrossSlice");var Je="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.",$c="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/*).",Dc="overlaps a slice folder. An alias covers only files outside the slice trees.",Fc="two slice aliases match the same file";function Mc(e){return we(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Mc,"aliasPathSegments");function jc(e){let t=e[e.length-1];return t===void 0||t.includes("*")?[...e]:[...e,"**"]}a(jc,"aliasSegmentsWithSubtree");function Eo(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(Eo,"concreteGlobPrefix");function vt(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(vt,"segmentsArePrefix");function Hc(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(Hc,"anchoredSlicePrefix");function Vc(e,t){let n=Eo(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return vt(t,n)||vt(t,o)?!0:r?vt(n,t)&&n.length<t.length||vt(n,["src",...t])&&n.length<t.length+1||vt(n,["app",...t])&&n.length<t.length+1:!1}a(Vc,"globOverlapsAnchored");function Kc(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=Eo(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(Kc,"globOverlapsBare");function Uc(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return Kc(e,n[0]);let r=Hc(t);return r?Vc(e,r):!1}a(Uc,"globOverlapsSliceEntry");function Gc(e){let t=we(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(Gc,"aliasGlobIssue");function Bc(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let o of e){if(typeof o!="string"||o.length===0)continue;let s=o.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(s.length===1&&s[0]&&!s[0].includes("*")){n.push({literals:[s[0],null]});continue}if(!s.some(i=>i==="**"||i.includes("*")&&i!=="*")&&s.includes("*")){if(r){let i=-1;for(let d=0;d<s.length;d+=1)s[d]!=="*"&&(i=d);if(i<0)continue;let l=s.filter((d,p)=>p>=i||d==="*").map(d=>d==="*"?null:d),c=s.slice(i).map(d=>d==="*"?null:d);n.push(c.length===l.length?{literals:l}:{literals:l,legacy:c});continue}n.push({literals:s.map(i=>i==="*"?null:i)})}}return n}a(Bc,"universeShapes");function dn(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(dn,"shapeMatches");function zc(e,t){let n=we(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(s=>s.length===0||s==="."||s==="..")||n.includes("*")||!n.includes("/"))return Je;let r=n.split("/").map(s=>s.toLowerCase());if(t.length===0||t.some(s=>dn(s,r)))return Je;if(t.some(s=>dn(s,r.slice(0,-1))))return null;let o=new Set(t.filter(s=>s.legacy!==void 0&&!dn({literals:s.legacy},r)&&dn({literals:s.legacy},r.slice(0,-1))).map(s=>s.literals.map(i=>i??"*").join("/")));return o.size===1?null:o.size>1?$c:Je}a(zc,"aliasTargetIssue");function Ro(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(Ro,"aliasGlobVariants");function Wc(e,t){let n=Ro(e),r=Ro(t);for(let o of n)if(Ve(o,t,0,0,new Map))return!0;for(let o of r)if(Ve(e,o,0,0,new Map))return!0;return!1}a(Wc,"aliasesCanMatchSameFile");function Ve(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=Ve(e,t,n+1,r,o)||r<t.length&&Ve(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=Ve(e,t,n,r+1,o)||n<e.length&&Ve(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=Ve(e,t,n+1,r+1,o))}return o.set(s,l),l}a(Ve,"globsCanMatchSame");var So="must be a filename with exactly one <Layer> token and no slash or wildcard (arkrules.<Layer>.json)";function qc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.arkRulesFile===void 0)return;let i=`$.rules[${o}].childSlices.arkRulesFile`,l=s.arkRulesFile;if(typeof l!="string"||l.length===0){t.push({path:i,message:So});return}(l.split("<Layer>").length!==2||/[*\\/]/.test(l)||l.includes(".."))&&t.push({path:i,message:So})})}a(qc,"validateChildSliceArkRulesFile");function Yc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ie(r))return;let s=r.childSlices;if(!ie(s)||s.sliceAliases===void 0)return;let i=s.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=Bc(r.sliceFolders,r.sliceIdentity),d=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(g=>typeof g=="string"&&g.length>0),p=[];i.forEach((g,f)=>{let m=`${l}[${f}]`;if(!ie(g)){t.push({path:m,message:"must be an object with from and to"});return}for(let k of Object.keys(g))k!=="from"&&k!=="to"&&k!=="pinned"&&k!=="reason"&&t.push({path:pn(m,k),message:"unknown field"});let u=g.from,h=g.to;if(typeof u!="string"||u.trim().length===0)t.push({path:`${m}.from`,message:"must be a non-empty path glob"});else{let k=Gc(u);if(k)t.push({path:`${m}.from`,message:k});else{let C=jc(Mc(u));d.some(S=>Uc(C,S))&&t.push({path:`${m}.from`,message:Dc});for(let S of p)if(Wc(S,C)){t.push({path:m,message:Fc});break}p.push(C)}}if(typeof h!="string"||h.trim().length===0)t.push({path:`${m}.to`,message:Je});else{let k=zc(h,c);k&&t.push({path:`${m}.to`,message:k})}})})}a(Yc,"validateChildSliceAliases");function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Pe,"isObject");function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Qe,"propertyPath");function Ie(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(Ie,"valueType");function Xc(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Xc,"resolveSchemaRef");function Te(e,t,n,r,o){if(t.$ref){let s=Xc(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Te(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(!Pe(e)){o.push({path:n,message:`must be an object; received ${Ie(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Qe(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Qe(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||Te(e[l],i,Qe(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Te(e[i],l,Qe(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Ie(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>Te(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${Ie(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${Ie(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${Ie(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(Te,"validateSchemaNode");function fn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(fn,"normalizeStewardId");function Co(e){let t=fn(e);return!t||yr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Co,"isGitHubHandle");function Zc(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t.includes("@")||t.includes(" ")||yr(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(Zc,"isGitHubEmail");function Jc(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Co(t[1])?fn(t[1]):null}a(Jc,"githubHandleFromEmail");function _o(e){let t=Jc(e);if(t)return t;let n=fn(e);return!n||yr(n)?null:Co(n)||Zc(n)?n:null}a(_o,"canonicalStewardId");var Qc=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function yr(e){let t=fn(e);return!t||Qc.test(t)}a(yr,"isAutomationAuthor");var le="1.3",ed=["public","auth","admin","internal"];function td(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(td,"isFutureHouseLayer");function nd(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(nd,"layerOwnersList");function Oo(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!td(t)&&!nd(t)).map(t=>t.name)}a(Oo,"layersMissingRequiredOwners");function wo(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(wo,"missingLayerOwnersNextAction");var gn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",xo=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],rd=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function sd(){let e=[];for(let t of xo)for(let n of xo)t===n||rd.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(sd,"createDefaultRules");var mn=sd(),Ar=[{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},Rr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:gn,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:gn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:le,default:le},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:mn,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:{description:"A project-relative ArkRules path, or a list of paths merged into one catalog for this layer. A string keeps today's behaviour. An older build that types this value as a string rejects an array at config load.",oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1}}]},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...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:[...ed]},owners:{...ae,minItems:1},forbiddenGlobals:ae,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ae,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus every star binding (a star before the last literal is kept too), so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...ae,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:ko,childSlices:Io}},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:ao,arkOrder:lo}},be=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
2
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(me,"isObject");function Me(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Me,"propertyPath");function Xe(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(Xe,"valueType");function Fl(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Fl,"resolveSchemaRef");function bt(e,t,n,r,o){if(t.$ref){let s=Fl(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}bt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!me(e)){o.push({path:n,message:`must be an object; received ${Xe(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Me(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Me(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||bt(e[l],i,Me(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&bt(e[i],l,Me(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Xe(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>bt(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${Xe(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 ${Xe(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${Xe(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(bt,"validateNode");var $l=["deny","advisory"],so='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"] }';function Hl(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!me(r))return;let s=r.childSlices;if(!me(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){$l.includes(i)||t.push({path:l,message:so});return}if(!me(i)){t.push({path:l,message:so});return}for(let u of Object.keys(i))u!=="default"&&u!=="enforce"&&t.push({path:Me(l,u),message:"unknown field"});if(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((u,p)=>{let m=`${l}.enforce[${p}]`;if(typeof u!="string"||u.trim().length===0){t.push({path:m,message:"must be a non-empty child slice id or subtree path"});return}let f=Qe(u.trim().replace(/\\/g,"/"));if(f.split("/").some(g=>g.length===0||g==="."||g==="..")){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(Hl,"validateChildSliceSiblings");var jl="must be a slice id with a slash. A bare name is ambiguous across universes.",Vl="* matches one whole path segment. ** and a partial segment are not wildcards.";function Kl(e){let t=Qe(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return jl;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 Vl}return null}a(Kl,"childCrossSlicePatternIssue");function oo(e){return Qe(e.trim().replace(/\\/g,"/")).toLowerCase()}a(oo,"childCrossSlicePatternKey");function Ul(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!me(r))return;let s=r.childSlices;if(!me(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((u,p)=>{let m=`${l}[${p}]`;if(!me(u)){t.push({path:m,message:"must be an object with from and to"});return}for(let g of Object.keys(u))g!=="from"&&g!=="to"&&t.push({path:Me(m,g),message:"unknown field"});for(let g of["from","to"]){let d=u[g],h=`${m}.${g}`;if(typeof d!="string"||d.trim().length===0){t.push({path:h,message:"must be a non-empty slice id"});continue}let E=Kl(d);E&&t.push({path:h,message:E})}if(typeof u.from!="string"||typeof u.to!="string")return;let f=`${oo(u.from)}\0${oo(u.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(Ul,"validateChildSliceAllowedCrossSlice");var Ze="must be a child of an existing universe (the universe id this rule already names, plus one child segment). A bare name, a universe id alone, an unknown universe, and a wildcard are rejected.",Gl="overlaps a slice folder. An alias covers only files outside the slice trees.",Bl="two slice aliases match the same file";function zl(e){return Qe(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(zl,"aliasPathSegments");function uo(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(uo,"concreteGlobPrefix");function Et(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(Et,"segmentsArePrefix");function Wl(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(Wl,"anchoredSlicePrefix");function ql(e,t){let n=uo(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Et(t,n)||Et(t,o)?!0:r?Et(n,t)&&n.length<t.length||Et(n,["src",...t])&&n.length<t.length+1||Et(n,["app",...t])&&n.length<t.length+1:!1}a(ql,"globOverlapsAnchored");function Yl(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=uo(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(Yl,"globOverlapsBare");function Jl(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return Yl(e,n[0]);let r=Wl(t);return r?ql(e,r):!1}a(Jl,"globOverlapsSliceEntry");function Xl(e){let t=Qe(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(Xl,"aliasGlobIssue");function Zl(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 l=0;l<s.length;l+=1)s[l]!=="*"&&(i=l);if(i<0)continue;n.push({literals:s.slice(i).map(l=>l==="*"?null:l)});continue}n.push({literals:s.map(i=>i==="*"?null:i)})}}return n}a(Zl,"universeShapes");function io(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(io,"shapeMatches");function Ql(e,t){let n=Qe(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(o=>o.length===0||o==="."||o==="..")||n.includes("*")||!n.includes("/"))return Ze;let r=n.split("/").map(o=>o.toLowerCase());return t.length===0||t.some(o=>io(o,r))?Ze:t.some(o=>io(o,r.slice(0,-1)))?null:Ze}a(Ql,"aliasTargetIssue");function ao(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(ao,"aliasGlobVariants");function ec(e,t){let n=ao(e),r=ao(t);for(let o of n)if(De(o,t,0,0,new Map))return!0;for(let o of r)if(De(e,o,0,0,new Map))return!0;return!1}a(ec,"aliasesCanMatchSameFile");function De(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=De(e,t,n+1,r,o)||r<t.length&&De(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=De(e,t,n,r+1,o)||n<e.length&&De(e,t,n+1,r,o);else if(n<e.length&&r<t.length){let c=e[n],u=t[r];(c===u||c==="*"||u==="*")&&(l=De(e,t,n+1,r+1,o))}return o.set(s,l),l}a(De,"globsCanMatchSame");function tc(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!me(r))return;let s=r.childSlices;if(!me(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=Zl(r.sliceFolders,r.sliceIdentity),u=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(m=>typeof m=="string"&&m.length>0),p=[];i.forEach((m,f)=>{let g=`${l}[${f}]`;if(!me(m)){t.push({path:g,message:"must be an object with from and to"});return}for(let E of Object.keys(m))E!=="from"&&E!=="to"&&t.push({path:Me(g,E),message:"unknown field"});let d=m.from,h=m.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${g}.from`,message:"must be a non-empty path glob"});else{let E=Xl(d);if(E)t.push({path:`${g}.from`,message:E});else{let _=zl(d);u.some(k=>Jl(_,k))&&t.push({path:`${g}.from`,message:Gl});for(let k of p)if(ec(k,_)){t.push({path:g,message:Bl});break}p.push(_)}}if(typeof h!="string"||h.trim().length===0)t.push({path:`${g}.to`,message:Ze});else{let E=Ql(h,c);E&&t.push({path:`${g}.to`,message:E})}})})}a(tc,"validateChildSliceAliases");function nc(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"&&(no(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(nc,"validateLayerOwners");function rc(e){let t={...e,$schema:e.$schema===void 0?tn:e.$schema,schemaVersion:e.schemaVersion===void 0?le:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?nn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Xs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Zs(e.arkOrder)),t}a(rc,"defaultedConfig");function sc(e){return e===le?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(sc,"migratedFromOf");function oc(){let e=new Set([le]);for(let t of rr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(oc,"knownInputVersions");function ic(e,t="ark.config.json"){if(!me(e))throw new Ie(t,[{path:"$",message:`must be an object; received ${Xe(e)}`}]);let n=oc(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${le}`}]);if(r!=="unversioned"&&!n.has(r))throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);let o=r,s={...e},i=0;for(;o!==le&&i<rr.length+1;){i+=1;let l=rr.find(c=>c.from===o);if(!l)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${le}`}]);o=l.to,s.schemaVersion=o}if(o!==le)throw new Ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);return{candidate:rc(s),migratedFrom:sc(r)}}a(ic,"migrateArkConfig");function rn(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ic(e,t),o=[];if(bt(n,sr,"$",sr,o),Qs(n,o),eo(n,o),nc(n,o),Hl(n,o),Ul(n,o),tc(n,o),o.length>0)throw new Ie(t,o);return{config:n,migratedFrom:r}}a(rn,"loadArkConfigContract");function or(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Ie(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return rn(n,t)}a(or,"parseArkConfigJson");function po(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:tn,schemaVersion:le};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(po,"withArkConfigMetadata");function Qe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Qe,"trimTrailingSlashes");function ac(e){return e.endsWith(".")?e:`${e}.`}a(ac,"normalizePrefix");function lc(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(lc,"byLongestPrefix");function on(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(ac)})),n=[...t].sort(lc),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(on,"createArchitectureProfile");function fo(e,t={}){return on({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(fo,"createArchitectureProfileFromArkConfig");var cc=[{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}],sn=on({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:cc,rules:nn.map(e=>({...e}))}),dc={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 go(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return po({include:e.include??[t],layers:sn.layers.map(o=>({name:o.name,patterns:(dc[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...sn.rules]})}a(go,"createElevenLayerArkConfig");function ee(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(ee,"deterministicHash");function 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(",")}}`}a(K,"stableSerialize");var Fe="1.2";var mo=["network","filesystem","clock","randomness","environment","process","persistence"];function Z(e,t){let n=K(e),r=K(t);return n<r?-1:n>r?1:0}a(Z,"compareCanonical");function re(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(re,"sortedUnique");function vt(e){let t={schemaVersion:"1.2",include:re(e.include??[]),exclude:re(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:re(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:re(n.patterns??[]),exclude:re(n.exclude??[]),forbiddenGlobals:re(n.forbiddenGlobals??[]),intentPrefixes:re(n.intentPrefixes??[]),capabilityDeny:re(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(Z),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:re(e.arkRun.compositionRoots),managedLayers:re(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return ee(K(t))}a(vt,"resolvedFactsEvidenceRequirementsHash");function uc(e){let t=e.completenessReasons.map(S=>({code:S.code,message:S.message,...S.file?{file:S.file}:{}})).sort(Z),n=e.files.map(S=>({...S,typeOnlyExportNames:re(S.typeOnlyExportNames)})).sort((S,L)=>S.path<L.path?-1:S.path>L.path?1:0),r=e.dependencies.map(S=>({...S,...S.namedBindings?{namedBindings:re(S.namedBindings)}:{}})).sort(Z),o=e.capabilityUses.map(S=>({...S})).sort(Z),s=e.ambientUses.map(S=>({...S})).sort(Z),i=e.publishCalls.map(S=>({...S})).sort(Z),l=e.intentReferences.map(S=>({...S})).sort(Z),c=e.safetyUses.map(S=>({...S})).sort(Z),u=(e.classShapes??[]).map(S=>({...S,mutatingMethods:[...S.mutatingMethods??[]].map(L=>({...L}))})).sort(Z),p=(e.arkRunKernelCalls??[]).map(S=>({...S})).sort(Z),m=(e.arkRunManagedNews??[]).map(S=>({...S})).sort(Z),f=(e.arkRunCompositionRootHits??[]).map(S=>({...S})).sort(Z),g=(e.arkRunDeclarations??[]).map(S=>({...S,uses:re(S.uses),reactsTo:re(S.reactsTo),raises:re(S.raises),sends:re(S.sends)})).sort(Z),d=(e.arkOrderPlaneCalls??[]).map(S=>({...S})).sort(Z),h=(e.arkOrderGenericUpdates??[]).map(S=>({...S})).sort(Z),E=(e.arkOrderRootHits??[]).map(S=>({...S})).sort(Z),_=(e.arkOrderXiFieldWrites??[]).map(S=>({...S})).sort(Z),k=(e.arkOrderIngestWritesXi??[]).map(S=>({...S})).sort(Z),b=(e.arkOrderReleaseKeyCounts??[]).map(S=>({...S})).sort(Z),O=e.files.map(({path:S,contentHash:L})=>({path:S,contentHash:L})).sort((S,L)=>S.path<L.path?-1:S.path>L.path?1:0),D=ee(K(O));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:u,arkRunKernelCalls:p,arkRunManagedNews:m,arkRunCompositionRootHits:f,arkRunDeclarations:g,arkOrderPlaneCalls:d,arkOrderGenericUpdates:h,arkOrderRootHits:E,arkOrderXiFieldWrites:_,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:b}}a(uc,"canonicalResolvedFactsInput");function ho(e){let t=uc(e);return{...t,factsHash:ee(K(t))}}a(ho,"createCanonicalResolvedCandidateFacts");function ir(e){return ho(Ao(H(e,"$"),!1))}a(ir,"createResolvedCandidateFacts");function H(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(H,"asRecord");function U(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}a(U,"assertOnlyKeys");function $(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($,"requiredText");function Ee(e,t,n){if(e[t]!==void 0)return $(e,t,n)}a(Ee,"optionalText");function W(e,t,n){let r=$(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(W,"requiredProjectPath");function q(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(q,"requiredBoolean");function yo(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(yo,"requiredInteger");function se(e,t,n){let r=yo(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(se,"requiredPositiveInteger");function Y(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(Y,"requiredArray");function be(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(be,"enumValue");function et(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(et,"parseStringArray");function pc(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(pc,"assertUnique");function Ao(e,t){U(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=be(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=be(e,"completeness",["complete","partial","unavailable"],"$"),o=Y(e,"completenessReasons","$").map((v,x)=>{let y=`$.completenessReasons[${x}]`,R=H(v,y);U(R,["code","message","file"],y);let F=R.file===void 0?void 0:W(R,"file",y);return{code:$(R,"code",y),message:$(R,"message",y),...F?{file:F}:{}}});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=Y(e,"files","$").map((v,x)=>{let y=`$.files[${x}]`,R=H(v,y);return U(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:W(R,"path",y),contentHash:$(R,"contentHash",y),parseStatus:be(R,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:yo(R,"parseDiagnosticCount",y),exportsOnlyTypes:q(R,"exportsOnlyTypes",y),typeOnlyExportNames:et(R.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:q(R,"hasTopLevelSideEffects",y)}}),i=Y(e,"dependencies","$").map((v,x)=>{let y=`$.dependencies[${x}]`,R=H(v,y);U(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let F=Ee(R,"specifier",y),Q=Ee(R,"target",y),Ce=be(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(Ce==="resolved-project"&&!Q)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(Ce!=="resolved-project"&&Q)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(Ce!=="dynamic"&&!F)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:W(R,"from",y),...F?{specifier:F}:{},kind:be(R,"kind",["import","export","dynamic-import","require"],y),typeOnly:q(R,"typeOnly",y),line:se(R,"line",y),resolution:Ce,...Q?{target:W(R,"target",y)}:{},...R.namedBindings!==void 0?{namedBindings:et(R.namedBindings,`${y}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:q(R,"targetTypeOnlyExports",y)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:q(R,"sourcePureTypeModule",y)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:q(R,"namedBindingsTypeOnly",y)}:{},...R.portProofEligible!==void 0?{portProofEligible:q(R,"portProofEligible",y)}:{}}}),l=Y(e,"capabilityUses","$").map((v,x)=>{let y=`$.capabilityUses[${x}]`,R=H(v,y);return U(R,["file","line","symbol","capability","source"],y),{file:W(R,"file",y),line:se(R,"line",y),symbol:$(R,"symbol",y),capability:be(R,"capability",mo,y),source:be(R,"source",["ambient-global","import-based"],y)}}),c=Y(e,"ambientUses","$").map((v,x)=>{let y=`$.ambientUses[${x}]`,R=H(v,y);return U(R,["file","line","symbol"],y),{file:W(R,"file",y),line:se(R,"line",y),symbol:$(R,"symbol",y)}}),u=Y(e,"publishCalls","$").map((v,x)=>{let y=`$.publishCalls[${x}]`,R=H(v,y);U(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let F=Ee(R,"rawIntentName",y),Q=Ee(R,"sourceIntent",y);return{file:W(R,"file",y),line:se(R,"line",y),...F?{rawIntentName:F}:{},objectHasIntent:q(R,"objectHasIntent",y),arkPublishCandidate:q(R,"arkPublishCandidate",y),hasSource:q(R,"hasSource",y),...Q?{sourceIntent:Q}:{}}}),p=Y(e,"intentReferences","$").map((v,x)=>{let y=`$.intentReferences[${x}]`,R=H(v,y);return U(R,["file","line","intent"],y),{file:W(R,"file",y),line:se(R,"line",y),intent:$(R,"intent",y)}}),m=Y(e,"safetyUses","$").map((v,x)=>{let y=`$.safetyUses[${x}]`,R=H(v,y);U(R,["file","line","kind","symbol"],y);let F=Ee(R,"symbol",y),Q=be(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(Q==="in-memory-store"&&!F)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(Q!=="in-memory-store"&&F)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:W(R,"file",y),line:se(R,"line",y),kind:Q,...F?{symbol:F}:{}}});pc(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 i)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:Y(e,"arkRunKernelCalls","$")).map((v,x)=>{let y=`$.arkRunKernelCalls[${x}]`,R=H(v,y);U(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let F=Ee(R,"receiver",y),Q=Ee(R,"nameLiteral",y);return{file:W(R,"file",y),line:se(R,"line",y),kind:be(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:$(R,"callee",y),viaImport:q(R,"viaImport",y),...F?{receiver:F}:{},...Q?{nameLiteral:Q}:{}}}),E=(e.arkRunManagedNews===void 0?[]:Y(e,"arkRunManagedNews","$")).map((v,x)=>{let y=`$.arkRunManagedNews[${x}]`,R=H(v,y);U(R,["file","line","typeName","importedFrom"],y);let F=Ee(R,"importedFrom",y);return{file:W(R,"file",y),line:se(R,"line",y),typeName:$(R,"typeName",y),...F?{importedFrom:F}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:Y(e,"arkRunCompositionRootHits","$")).map((v,x)=>{let y=`$.arkRunCompositionRootHits[${x}]`,R=H(v,y);return U(R,["file","matchedRoot","hasKernelFactory"],y),{file:W(R,"file",y),matchedRoot:$(R,"matchedRoot",y),hasKernelFactory:q(R,"hasKernelFactory",y)}}),b=e.arkRunDeclarations===void 0?[]:Y(e,"arkRunDeclarations","$"),D=(e.arkOrderPlaneCalls===void 0?[]:Y(e,"arkOrderPlaneCalls","$")).map((v,x)=>{let y=`$.arkOrderPlaneCalls[${x}]`,R=H(v,y);return U(R,["file","line","callee"],y),{file:W(R,"file",y),line:se(R,"line",y),callee:$(R,"callee",y)}}),L=(e.arkOrderGenericUpdates===void 0?[]:Y(e,"arkOrderGenericUpdates","$")).map((v,x)=>{let y=`$.arkOrderGenericUpdates[${x}]`,R=H(v,y);return U(R,["file","line","method"],y),{file:W(R,"file",y),line:se(R,"line",y),method:$(R,"method",y)}}),T=(e.arkOrderRootHits===void 0?[]:Y(e,"arkOrderRootHits","$")).map((v,x)=>{let y=`$.arkOrderRootHits[${x}]`,R=H(v,y);return U(R,["file","matchedRoot","hasPlaneFactory"],y),{file:W(R,"file",y),matchedRoot:$(R,"matchedRoot",y),hasPlaneFactory:q(R,"hasPlaneFactory",y)}}),P=(e.arkOrderXiFieldWrites===void 0?[]:Y(e,"arkOrderXiFieldWrites","$")).map((v,x)=>{let y=`$.arkOrderXiFieldWrites[${x}]`,R=H(v,y);return U(R,["file","line","key"],y),{file:W(R,"file",y),line:se(R,"line",y),key:$(R,"key",y)}}),z=(e.arkOrderIngestWritesXi===void 0?[]:Y(e,"arkOrderIngestWritesXi","$")).map((v,x)=>{let y=`$.arkOrderIngestWritesXi[${x}]`,R=H(v,y);return U(R,["file","line"],y),{file:W(R,"file",y),line:se(R,"line",y)}}),Se=(e.arkOrderReleaseKeyCounts===void 0?[]:Y(e,"arkOrderReleaseKeyCounts","$")).map((v,x)=>{let y=`$.arkOrderReleaseKeyCounts[${x}]`,R=H(v,y);return U(R,["file","line","keyCount"],y),{file:W(R,"file",y),line:se(R,"line",y),keyCount:se(R,"keyCount",y)}}),lt=b.map((v,x)=>{let y=`$.arkRunDeclarations[${x}]`,R=H(v,y);return U(R,["file","line","uses","reactsTo","raises","sends"],y),{file:W(R,"file",y),line:se(R,"line",y),uses:et(R.uses,`${y}.uses`),reactsTo:et(R.reactsTo,`${y}.reactsTo`),raises:et(R.raises,`${y}.raises`),sends:et(R.sends,`${y}.sends`)}});for(let[v,x]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",m],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",lt],["$.arkOrderPlaneCalls",D],["$.arkOrderGenericUpdates",L],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",P],["$.arkOrderIngestWritesXi",z],["$.arkOrderReleaseKeyCounts",Se]])for(let y of x)if(!f.has(y.file))throw new Error(`${v} references missing file ${y.file}.`);let Ut=Ee(e,"projectPackageName","$"),ks=(e.classShapes===void 0?[]:Y(e,"classShapes","$")).map((v,x)=>{let y=`$.classShapes[${x}]`,R=H(v,y);U(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],y);let F=Y(R,"mutatingMethods",y).map((Q,Ce)=>{let A=`${y}.mutatingMethods[${Ce}]`,ie=H(Q,A);return U(ie,["name","referencesGuardOrPublish"],A),{name:$(ie,"name",A),referencesGuardOrPublish:q(ie,"referencesGuardOrPublish",A)}});return{file:W(R,"file",y),className:$(R,"className",y),exported:q(R,"exported",y),hasPublicMutableFields:q(R,"hasPublicMutableFields",y),hasPublicSetters:q(R,"hasPublicSetters",y),hasPublicConstructor:q(R,"hasPublicConstructor",y),hasStaticFactory:q(R,"hasStaticFactory",y),mutatingMethods:F,...R.dataOnly===void 0?{}:{dataOnly:q(R,"dataOnly",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:$(e,"resolverIdentity","$"),compilerIdentity:$(e,"compilerIdentity","$"),compilerOptionsHash:$(e,"compilerOptionsHash","$"),tsconfigHash:$(e,"tsconfigHash","$"),evidenceRequirementsHash:$(e,"evidenceRequirementsHash","$"),...Ut?{projectPackageName:Ut}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:p,safetyUses:m,classShapes:ks,arkRunKernelCalls:d,arkRunManagedNews:E,arkRunCompositionRootHits:k,arkRunDeclarations:lt,arkOrderPlaneCalls:D,arkOrderGenericUpdates:L,arkOrderRootHits:T,arkOrderXiFieldWrites:P,arkOrderIngestWritesXi:z,arkOrderReleaseKeyCounts:Se}}a(Ao,"parseResolvedFactsInput");function xe(e){let t=H(e,"$"),n=$(t,"factsHash","$"),r=$(t,"candidateTreeHash","$"),o=ho(Ao(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(xe,"loadResolvedCandidateFacts");var fc=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},ae={type:"integer",minimum:1},J={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ar={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:N,message:N,file:J}}},resolverIdentity:N,compilerIdentity:N,compilerOptionsHash:N,tsconfigHash:N,candidateTreeHash:N,evidenceRequirementsHash:N,projectPackageName:N,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:J,contentHash:N,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:N},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:J,specifier:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ae,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:J,namedBindings:{type:"array",items:N},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:J,line:ae,symbol:N,capability:{enum:fc},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:J,line:ae,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:J,line:ae,rawIntentName:N,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:N}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:J,line:ae,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:J,line:ae,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:N},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:J,className:N,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:N,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:J,line:ae,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:N,viaImport:{type:"boolean"},receiver:N,nameLiteral:N}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:J,line:ae,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:J,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:J,line:ae,uses:{type:"array",items:N},reactsTo:{type:"array",items:N},raises:{type:"array",items:N},sends:{type:"array",items:N}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:J,line:ae,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:J,line:ae,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:J,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:J,line:ae,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:J,line:ae}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:J,line:ae,keyCount:{type:"integer",minimum:1}}}},factsHash:N},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 lr="1.0";function ce(e){return`${e.from}->${e.to}`}a(ce,"dependencyKey");function Ct(e,t,n,r="dependency"){return{id:`${e}:${r}:${ce(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ce(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ce(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ce(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ce(t)} from the candidate, then preflight again.`}:{}}}a(Ct,"dependencyFinding");function tt(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=>[ce(f),f])),s=new Map(e.baseDependencies.map(f=>[ce(f),f])),i=new Map(e.candidateDependencies.map(f=>[ce(f),f]));for(let f of[...n.values()].sort((g,d)=>g.path.localeCompare(d.path))){let g=r.get(f.path);g?g.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:g.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${g.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:g.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((g,d)=>g.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((g,d)=>ce(g).localeCompare(ce(d)))){if(i.has(ce(f))){t.push(Ct("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let g={from:f.to,to:f.from};i.has(ce(g))?(l.add(ce(g)),t.push(Ct("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ct("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,g]of[...i].sort(([d],[h])=>d.localeCompare(h)))s.has(f)||o.has(f)||l.has(f)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ct("unplanned",g,`${g.from} -> ${g.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,g]of[...s].sort(([d],[h])=>d.localeCompare(h)))i.has(f)||u.has(g.from)||u.has(g.to)||!c.has(g.from)&&!c.has(g.to)||t.push({...Ct("unplanned",g,`${g.from} -> ${g.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,g)=>p[f.classification]-p[g.classification]||(f.subject===g.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(g.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(tt,"analyzeArchitectureConvergence");var gc="1.0",cr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",So=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],mc=["no-anemic-model"],Ro={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},dr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:cr,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:cr},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:[...So]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ro,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:Ro}}}},$e=class extends Error{static{a(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
3
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function od(e,t){let n=e.arkRules;if(!(n===void 0||!Pe(n)))for(let[r,o]of Object.entries(n)){let s=Qe("$.arkRules",r);if(typeof o=="string"){o.length===0&&t.push({path:s,message:"must be a non-empty relative path string"});continue}if(!Array.isArray(o)||o.length===0){t.push({path:s,message:"must be a non-empty path string or an array of paths"});continue}let i=new Set;o.forEach((l,c)=>{let d=`${s}[${c}]`;if(typeof l!="string"||l.length===0){t.push({path:d,message:"must be a non-empty relative path string"});return}i.has(l)&&t.push({path:d,message:"duplicate path"}),i.add(l)})}}a(od,"validateArkRulesRefs");function id(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"&&(_o(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(id,"validateLayerOwners");function ad(e){let t={...e,$schema:e.$schema===void 0?gn:e.$schema,schemaVersion:e.schemaVersion===void 0?le:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?mn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=co(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=uo(e.arkOrder)),t}a(ad,"defaultedConfig");function ld(e){return e===le?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(ld,"migratedFromOf");function cd(){let e=new Set([le]);for(let t of Ar)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(cd,"knownInputVersions");function dd(e,t="ark.config.json"){if(!Pe(e))throw new be(t,[{path:"$",message:`must be an object; received ${Ie(e)}`}]);let n=cd(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${le}`}]);if(r!=="unversioned"&&!n.has(r))throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);let o=r,s={...e},i=0;for(;o!==le&&i<Ar.length+1;){i+=1;let l=Ar.find(c=>c.from===o);if(!l)throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${le}`}]);o=l.to,s.schemaVersion=o}if(o!==le)throw new be(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${le}`}]);return{candidate:ad(s),migratedFrom:ld(r)}}a(dd,"migrateArkConfig");function hn(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=dd(e,t),o=[];if(Te(n,Rr,"$",Rr,o),fo(n,o),go(n,o),id(n,o),bo(n,o),od(n,o),o.length>0)throw new be(t,o);return{config:n,migratedFrom:r}}a(hn,"loadArkConfigContract");function Sr(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new be(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return hn(n,t)}a(Sr,"parseArkConfigJson");function To(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:gn,schemaVersion:le};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(To,"withArkConfigMetadata");var kr={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 yn(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(yn,"effectiveIntentPrefixes");function Po(e){let t=new Set(e.layers.filter(r=>yn(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(Po,"unresolvableLayerFlowLayers");function Ir(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(Ir,"resolveIntentLayer");function ve(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(ve,"looksLikeArkIntent");function Ct(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ve(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:kr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:kr.PUBLISH_MISSING_SOURCE}),t}a(Ct,"classifyPublishFacts");function ud(e){return e.endsWith(".")?e:`${e}.`}a(ud,"normalizePrefix");function pd(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(pd,"byLongestPrefix");function Rn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(ud)})),n=[...t].sort(pd),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(Rn,"createArchitectureProfile");function No(e,t={}){return Rn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:[...yn(n)],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}a(No,"createArchitectureProfileFromArkConfig");var fd=[{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}],An=Rn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:fd,rules:mn.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 Lo(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return To({include:e.include??[t],layers:An.layers.map(o=>({name:o.name,patterns:(gd[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...An.rules]})}a(Lo,"createElevenLayerArkConfig");var vr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Cr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),_r=Object.freeze(Object.keys(Cr).sort()),br=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"}),Er=Object.freeze({process:Object.freeze(["process","node:process"])});function _t(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=br[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=br[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:br[e.slice(0,s)]??null}a(_t,"capabilityForModuleSpecifier");function Ne(e,t){for(let n of t)if(Er[n]?.includes(e))return n;return null}a(Ne,"forbiddenGlobalForModuleSpecifier");function Sn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=Cr[r];if(o)return o}return null}a(Sn,"capabilityForAmbientName");function et(e){if(e?.pure===!0)return[...vr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>vr.includes(r));return[...new Set(n)].sort()}a(et,"effectiveCapabilityDeny");function xt(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(xt,"ambientCoveredByForbiddenGlobals");function kn(e){let t=new Set,n=new Set,r=Object.keys(Cr);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 Er[o]??[])t.add(`import-exact:${i}`)}for(let o of et(e)){if(t.add(`import:${o}`),o==="process")for(let s of Er.process)t.add(`import-exact:${s}`);for(let s of r)Sn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(kn,"loweredLayerCoverage");function Le(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(Le,"sharedImportsSliceMode");function Cn(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(Cn,"sharedImportsSliceStopAt");var $o=new Map;function Do(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Do,"escapeLiteral");function _n(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(_n,"normalizeGlobSeparators");function md(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(md,"bracesBalanced");function ce(e){let t=$o.get(e);if(t)return t;let n=_n(e),r=md(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Do(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+=Do(c)}let i=new RegExp(`^${o}$`);return $o.set(e,i),i}a(ce,"globToRegExp");function hd(e){return _n(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(hd,"concreteGlobSegments");function wr(e,t){let n=_n(String(e)),r=hd(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let d of r){let p=-1;for(let g=l;g<i.length;g+=1)if(i[g]===d){p=g;break}if(p<0)return s;c=p,l=p+1}return(c+1)*1e6+r.length*1e4+o}a(wr,"patternSpecificity");function ge(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>ce(i).test(n))){for(let i of s.patterns??[])if(ce(i).test(n)){let l=wr(i,n);l>o&&(o=l,r=s.name)}}return r}a(ge,"layerForRelativePath");function rt(e,t,n){return Go(e,t,n==="stars"?"stars":"path")}a(rt,"sliceIdForPath");function Or(e,t){return Go(e,t?[...t]:void 0,Uo)}a(Or,"legacyStarsSliceIdForPath");var Uo="stars-4.8.23";function Go(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=yd(s);if(i.anchored){let l=Rd(r,i.anchored,n);if(l)return l;continue}i.bare!==void 0&&o.add(i.bare)}return bd(r,o)}a(Go,"sliceIdWithBinding");var In=new Map;function yd(e){let t=In.get(e);if(t)return t;let n={};return Bo(e)?n={anchored:Ad(e)}:!e.includes("/")&&!e.includes("\\")&&!e.includes("*")&&(n={bare:e.toLowerCase()}),In.size>=1024&&In.clear(),In.set(e,n),n}a(yd,"parsedSliceFolder");function Bo(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(Bo,"isAnchoredSliceEntry");function Ad(e){return e.split(/[/\\]/).filter(t=>t.length>0).map(t=>t.toLowerCase())}a(Ad,"anchoredSlicePattern");function Rd(e,t,n){let r=Wo(e,t[0]??"");for(let o of r){let s=Sd(e,t,o,n);if(s)return s}}a(Rd,"anchoredSliceIdFromPattern");function Sd(e,t,n,r="path"){let o=[],s=[],i=-1,l=n;for(let c=0;c<t.length;c+=1){let d=t[c];if(d==="*"){if(l>=e.length-1){for(let p=c;p<t.length;p+=1)if(t[p]!=="*")return;break}o.push(e[l].toLowerCase()),s.push(!0),l+=1;continue}if(d==="**"||l>=e.length||e[l].toLowerCase()!==d)return;o.push(e[l].toLowerCase()),s.push(!1),i=o.length-1,l+=1}if(o.length!==0)return r===Uo?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(Sd,"bindAnchoredSlice");function Tr(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(Tr,"starsKeptSegmentIndexes");function zo(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=kd(s);if(!i)continue;let l=s.split(/[/\\]/).filter(p=>p.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let d=r.get(i)??[];d.push(s),r.set(i,d)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:Id(n.from,n.to,i,s)})}return t}a(zo,"sliceIdentityCollisions");function kd(e){if(!Bo(e))return;let t=e.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(t.some(r=>r==="**"))return;let n=Tr(t);if(n)return n.map(r=>t[r]).join("/")}a(kd,"starsIdentityStem");function Id(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(Id,"formatSliceIdentityCollision");function bd(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(bd,"bareSliceId");function vd(e){let t=new Set;for(let n of e??[]){let o=_n(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(vd,"inferSliceFoldersFromPatterns");function Pr(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 vd(r?.patterns)}a(Pr,"resolveSliceFolders");function Fo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(Fo,"normalizeSegments");function Pt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Pt,"trimTrailingSlashes");var Ed=["src","app"];function Wo(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Ed.includes(n)&&r!==n?[0,1]:[0]}a(Wo,"anchorOffsets");function Cd(e){let t=Pt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Cd,"isBlanketRoot");function nt(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Fo(n);for(let s of t){if(typeof s!="string"||s.length===0||Cd(s))continue;if(s.includes("*")){let c=Pt(s.toLowerCase());if(ce(c).test(r)||ce(`${c}/**`).test(r))return!0;continue}let i=Fo(s);if(i.length===0)continue;let l=Wo(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let d=!0;for(let p=0;p<i.length;p+=1)if(o[c+p]!==i[p]){d=!1;break}if(d)return!0}}return!1}a(nt,"pathUnderSharedRoot");function Mo(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(Mo,"sliceMatchesDeclaration");function bn(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Mo(r.from,t)&&Mo(r.to,n))}a(bn,"crossSliceEdgeAllowed");function _d(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(_d,"peerIsolationDecision");function qo(e){return Pt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(qo,"aliasGlobPattern");function Yo(e,t){let n=qo(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=vn(r),s=ce(n),l=(n.split("/").pop()??"").includes("*")?null:ce(`${n}/**`),c=a(d=>s.test(d)||l!==null&&l.test(d),"hit");return c(r)||o!==r&&c(o)}a(Yo,"aliasGlobMatches");function Xo(e,t){return!e||!t?.length?!1:nt(e,[...t])?!0:t.some(n=>typeof n=="string"&&Yo(n,e))}a(Xo,"pathMatchesSharedWalkStop");function Nr(e){let t=qo(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(Nr,"splitAliasTarget");function Zo(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Yo(n.from,e))return n;return null}a(Zo,"firstSliceAliasEntry");function xd(e,t){let n=Zo(e,t);return n?Nr(n.to):null}a(xd,"firstSliceAlias");function Ot(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=rt(e,r?[...r]:void 0,t.sliceIdentity),s=Tt(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=xd(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Ot,"resolveGovernedSlice");function Od(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=Tr(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(Od,"starsUniverseShapes");function jo(e,t){return e.length===t.length&&e.every((n,r)=>n===null||t[r]==="*"||n===t[r])}a(jo,"literalsMatch");function tt(e,t){let n=t.split("/").filter(Boolean).map(s=>s.toLowerCase()),r=Od(e);if(n.length===0||r.some(s=>jo(s.literals,n)))return[];let o=new Set;for(let s of r)if(s.legacy.length!==s.literals.length&&jo(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(tt,"legacyStarsIdTargets");function Jo(e,t){if(e.sliceIdentity!=="stars")return;let n=Nr(t);if(n)return tt(e.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(Jo,"legacyAliasUniverse");function Ho(e,t,n){let r=Ot(e,t,n);if(!e||t.sliceIdentity!=="stars")return r;if(r.universeId){let o=Zo(e,t);if(!rt(e,[...n],t.sliceIdentity)&&o&&Jo(t,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let i=Or(e,n),l=t.childSlices,c=l?.sliceIdentity==="stars"?Or(e,l.sliceFolders):void 0;return{...r,...i?{legacyUniverse:i}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(Ho,"placeForPair");function Lr(e,t,n,r){let o=Ho(n,e,t),s=Ho(r,e,t),i=o.legacyUniverse,l=s.legacyUniverse,c=a((u,h)=>{if(!u.legacyAlias||h.legacyAlias||!h.universeId||h.legacyUniverse?.toLowerCase()!==u.universeId?.toLowerCase())return u;let k=u.childId?.split("/").pop();return{...u,universeId:h.universeId,...k?{childId:`${h.universeId}/${k}`}:{}}},"adopt"),d=c(o,s),p=c(s,o),g=bn(e.allowedCrossSlice,d.universeId,p.universeId)||e.sliceIdentity==="stars"&&(i!==d.universeId||l!==p.universeId)&&bn(e.allowedCrossSlice,i,l),f=e.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&s.legacyChild!==void 0&&o.legacyChild!==s.legacyChild&&ei(e.childSlices.allowedCrossSlice,o.legacyChild,s.legacyChild),m=a(u=>({...u.universeId?{universeId:u.universeId}:{},...u.childId?{childId:u.childId}:{}}),"strip");return{from:m(d),to:m(p),crossSliceAllowed:g,legacyChildAllowed:f}}a(Lr,"resolveGovernedSlicePair");function wd(e,t,n){let r=e.split(/[/\\]/).filter(Boolean).map(s=>s.toLowerCase()),o=t.split("/").filter(Boolean).map(s=>s.toLowerCase());if(r.length===0||o.length===0||r.some(s=>s==="**"||s.includes("*")&&s!=="*"))return null;if(n==="stars"){let s=Tr(r);if(!s||s.length!==o.length)return null;let i=[...r];for(let l=0;l<s.length;l+=1){let c=s[l]??0;if(r[c]!=="*"&&r[c]!==o[l])return null;i[c]=o[l]??""}return i.join("/")}if(r.length!==o.length)return null;for(let s=0;s<r.length;s+=1)if(r[s]!=="*"&&r[s]!==o[s])return null;return o.join("/")}a(wd,"childPatternDirectory");function Td(e,t){let n=vn(e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase()).split("/"),r=t.split("/"),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}a(Td,"sharedDirectoryPrefix");function Pd(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase();return n.startsWith("src/")&&!t.startsWith("src/")?`src/${t}`:n.startsWith("app/")&&!t.startsWith("app/")?`app/${t}`:t}a(Pd,"withSourcePrefix");function Nd(e,t,n){let r=null;for(let o of n.sliceFolders){if(typeof o!="string")continue;let s=wd(o,t,n.sliceIdentity);if(!s)continue;let i=Td(e,s);(!r||i>r.score||i===r.score&&s.length<r.dir.length)&&(r={dir:s,score:i})}return r?Pd(e,r.dir):""}a(Nd,"sliceAliasDestination");var Ld="<Layer>";function $d(e,t){let n=Ld;if(!e.includes(n)||e.split(n).length!==2||/[*\\/]/.test(e))return null;let r=e.replace(n,t);return!r||r.includes("..")?null:r}a($d,"sliceRuleFileName");function Qo(e){let t=[...new Set(e.layers.filter(o=>typeof o=="string"&&o.length>0))].sort(),n=[],r=new Set;for(let o of e.rules??[]){let s=o?.childSlices,i=s?.arkRulesFile;if(!s||typeof i!="string")continue;let l=new Map;for(let c of e.files){if(typeof c!="string"||c.length===0)continue;let d=o.sliceFolders?.length?rt(c,o.sliceFolders,o.sliceIdentity):void 0,p=Tt(c,d,s);if(!p.childId||l.has(p.childId))continue;let g=Nd(c,p.childId,s);g&&l.set(p.childId,g)}for(let[c,d]of[...l.entries()].sort((p,g)=>p[0].localeCompare(g[0])))for(let p of t){let g=$d(i,p);if(!g)continue;let f=`${d}/${g}`.replace(/\\/g,"/");r.has(`${p}\0${f}`)||(r.add(`${p}\0${f}`),n.push({path:f,childId:c,layer:p,defaultAppliesTo:[`${d}/**`]}))}}return n}a(Qo,"resolveSliceRulePlan");function Dd(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(Dd,"peerIsolationDenyExplanation");function Fd(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Fd,"crossParentExplanation");function Md(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(Md,"crossSiblingExplanation");function jd(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(jd,"parentImportsChildExplanation");function wt(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(wt,"universePairLabel");function Hd(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(Hd,"isCommonFolderName");function Tt(e,t,n){if(!e||!n?.sliceFolders?.length)return{};let r=rt(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 Hd(i,n.commonFolders)?{}:{childId:r}}a(Tt,"resolveChildSliceId");function Vd(e){return Pt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Vd,"siblingEntryKey");function vn(e){return e.replace(/^(?:src|app)\//,"")}a(vn,"stripSrcOrApp");function Kd(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=vn(t);if(!r)return!1;let o=vn(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(Kd,"pathUnderSubtree");function Ud(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=Vd(o);if(!(!s||s.includes("*"))&&(r===s||e&&Kd(e,s)))return!0}return!1}a(Ud,"importerInEnforcedSubtree");function Gd(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!Ud(t,n,e.enforce)}a(Gd,"siblingCrossingAdvisory");function En(e){if(typeof e!="string")return null;let t=Pt(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(En,"childSlicePatternSegments");function Vo(e,t){let n=En(e),r=En(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(Vo,"childSlicePatternMatches");function ei(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&Vo(r.from,t)&&Vo(r.to,n))return!0;return!1}a(ei,"childCrossSliceAllowed");function Bd(e,t){let n=En(e),r=En(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(Bd,"childAllowanceSpansUniverses");function zd(e){let t=_d({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:Le(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?Fd(e.fromSlice,e.toSlice):Dd(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??Tt(e.fromPath,e.fromSlice,n).childId,o=e.toChild??Tt(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?e.legacyChildAllowed||ei(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:Gd(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:Md(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:jd(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(zd,"evaluateNestedSliceWall");function ti(e){return e?.crossing==="cross-sibling"||e?.crossing==="parent-imports-child"}a(ti,"isChildWallCrossing");function xn(e,t){return ti(t)?e?.childSlices?.message:e?.message}a(xn,"sliceConsumerMessage");function st(e){let t=e.verdict.explanation,n=ti(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(st,"composeSliceDenialMessage");function Ke(e){if(!e||e.decision==="allow")return{};let t=wt(e.fromUniverse),n=wt(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Ke,"sliceFindingExtras");function ni(e,t){let n=[],r=new Set,o=new Set;for(let s of e??[])if(s?.peerIsolation&&s.allowed===!1&&n.push(...Wd(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=rt(i,s.sliceFolders,s.sliceIdentity),c=Tt(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"||!Bd(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(ni,"childSliceConfigFindings");function Ko(e,t){let n=new Map;if(!e?.length)return n;for(let r of t){if(typeof r!="string")continue;let o=rt(r,[...e],"stars"),s=Or(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(Ko,"observedIdsByLegacy");function xr(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(xr,"newIdHint");function Wd(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=Ko(e.sliceFolders,t);for(let i of o?.sliceAliases??[]){if(!i||typeof i.to!="string")continue;let l=Nr(i.to);if(!l||Jo(e,i.to)===void 0)continue;let c=tt(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 ${xr(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("/")&&tt(e.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?xr(d,tt(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=Ko(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=>tt(o.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?xr(d,tt(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(Wd,"legacyStarsIdFindings");function ri(e){if(e!==null&&typeof e=="object"){let t=e.ratchet;if(t===!0)return"always";if(t===!1)return"never"}return"auto"}a(ri,"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=Pr(o,t,r?.layers),c=Lr(o,l,s,i),d=c.from,p=c.to,g=d.universeId,f=p.universeId,m=zd({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:g,toSlice:f,fromChild:d.childId,toChild:p.childId,fromShared:!g&&nt(s,o.sharedRoots),toShared:!f&&nt(i,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(m.decision!=="allow")return{rule:o,peerIsolationReason:m.peerIsolationReason,fromSlice:g,toSlice:f,sliceVerdict:m};continue}if(t!==n)return{rule:o}}}a(Ee,"findDeniedEdgeDecision");function si(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||Le(i.sharedImportsSlice)==="deny")continue;let l=Pr(i,t,r?.layers),c=Ot(o,i,l).universeId,d=Ot(s,i,l).universeId;if(!(c||!d)&&nt(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:d}}}a(si,"findSharedImportsSliceBridge");function $r(e,t,n){return Pr(e,t,n)}a($r,"peerSliceFolders");function ot(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(ot,"literalText");function ai(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(ai,"lineOf");function oi(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(oi,"isTypeOnlyReference");function li(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(li,"singleFileChecker");function Dr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Dr,"symbolAt");function Fr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Dr(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Fr,"localDeclaration");function it(e,t){let n,r=[],o=a((i,l,c,d=!1)=>r.push({specifier:c,kind:l,line:ai(t,i),typeOnly:d,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",ot(e,i.moduleSpecifier),oi(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",ot(e,i.moduleSpecifier),oi(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",ot(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"&&!Fr(e,n??(n=li(e,t)),t,i.expression);(l||d)&&o(i,d?"require":"dynamic-import",ot(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(it,"extractSemanticDependencies");function qd(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=ot(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(qd,"staticAccessPath");function Yd(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(Yd,"runtimeIdentifierReference");function ii(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(ii,"bestForbiddenMatch");function at(e,t,n){if(n.length===0)return[];let r=new Set(n),o=li(e,t),s=new Map,i=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&i.add(m.name.text);let l=a(f=>{let m=qd(e,f);if(!m)return;let u=Dr(o,m.root),h=u?s.get(u):void 0;return h?[...h,...m.segments.slice(1)]:Fr(e,o,t,m.root)||i.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let u=l(m.initializer),h=Dr(o,m.name);!u||!h||s.set(h,u)}let c=[],d=new Set,p=a((f,m)=>{let u=ai(t,m),h=`${f}:${m.getStart(t)}`;d.has(h)||(d.add(h),c.push({name:f,line:u,node:m}))},"flag"),g=a(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let u=l(f),h=u?ii(r,u):void 0;h&&p(h,f)}else e.isIdentifier(f)&&r.has(f.text)&&Yd(e,f)&&!Fr(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let u=l(f.initializer);if(u)for(let h of f.name.elements){if(!e.isIdentifier(h.name))continue;let k=h.propertyName?ot(e,h.propertyName)??h.propertyName.text:h.name.text,C=ii(r,[...u,k]);C&&p(C,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),c}a(at,"collectForbiddenCapabilityUses");function Mr(e,t,n){let r=[];for(let o of n?.dependencies??it(e,t)){if(o.typeOnly||!o.specifier)continue;let s=_t(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??at(e,t,_r)){let s=Sn(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(Mr,"collectCapabilityUses");function X(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(X,"violation");function Xd(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(Xd,"peerSuggestion");function lt(e,t){return e.slice(0,t).split(`
|
|
4
|
+
`).length}a(lt,"lineOf");var Zd=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Jd(e,t){return e.index+e[0].indexOf(t)}a(Jd,"captureIndex");function Qd(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,Jd(c,d))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,i;for(;(i=s.exec(e))!==null;){let l=i[1]??"",c=i.index+i[0].indexOf(l),d=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=d.exec(l))!==null;){let g=p[1];g&&r(g,c+p.index+p[0].indexOf(g))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}a(Qd,"extractQuotedStrings");function eu(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(eu,"extractModuleSpecifiers");function tu(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(tu,"isSyntaxWrapper");function jr(e,t){let n=t;for(;n?.parent&&tu(e,n.parent);)n=n.parent;return n}a(jr,"unwrapWrappers");function Hr(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(Hr,"callCalleeName");function nu(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=jr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Hr(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Vr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=jr(e,s).parent;return!!(l&&e.isCallExpression(l)&&Hr(e,l)==="publish")}return!1}a(nu,"isPublishMetadataSource");function ci(e,t){let n=jr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Hr(e,r);if(o&&Zd.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return ci(e,r);if(e.isPropertyAssignment(r)){let o=Vr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&nu(e,r))return!0}return!1}a(ci,"isDeclaredIntentSite");function ru(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&ci(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(ru,"extractQuotedStringsAst");function su(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(su,"hasInfrastructureToken");function ou(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(ou,"isKnownInfrastructurePackage");function iu(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(iu,"layerHasInfrastructureRole");function Lt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Lt,"tsStringLiteralText");function Vr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(Vr,"tsPropertyName");function di(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Vr(e,r.name)===n)}a(di,"tsObjectProperty");function $t(e,t,n){return di(e,t,n)!==void 0}a($t,"tsObjectHasProperty");function Nt(e,t,n){let r=di(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Nt,"tsObjectPropertyValue");function au(e,t){let n=Nt(e,t,"metadata");return $t(e,n,"source")}a(au,"tsObjectHasMetadataSource");function ui(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?ui(e,t.name):!1:!1}a(ui,"tsLooksLikeIntentCreatorExpression");function lu(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(lu,"tsIsPublishCall");function cu(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Lt(e,n);return r!==void 0&&ve(r)||$t(e,n,"intent")||ui(e,n)}a(cu,"tsIsArkPublishCandidate");function du(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return au(e,n)||$t(e,r,"source")||$t(e,o,"source")}a(du,"tsPublishHasSource");function uu(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Nt(e,n,"metadata");return Lt(e,Nt(e,s,"source"))??Lt(e,Nt(e,r,"source"))??Lt(e,Nt(e,o,"source"))}a(uu,"tsPublishSourceLiteral");function pu(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],d=a(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=a(g=>{if(lu(e,g)){let f=g.arguments[0],m=Lt(e,f);for(let h of Ct({publishCall:!0,rawIntentName:m,objectHasIntent:$t(e,f,"intent"),arkPublishCandidate:cu(e,g),hasSource:du(e,g)}))c.push(X(h.ruleId,h.message,{line:d(g),filePath:i}));let u=uu(e,g);if(r&&l&&u&&ve(u)){let h=r.resolveLayer(u);h&&h!==l&&c.push(X("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${h}, but the target file is classified as ${l}.`,{line:d(g),filePath:i,target:u,fromLayer:l,toLayer:h}))}}e.forEachChild(g,p)},"visit");return p(o),c}a(pu,"analyzePublishAst");function pi(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,i){let l=[],c=i,d=c?.filePath,p=c?.layer,g=e.typescript,f=g?g.createSourceFile(d??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?it(e.typescript,f):void 0,u=m?m.filter(S=>S.specifier!==void 0).map(S=>({value:S.specifier,index:S.node.getStart(f),kind:S.kind,typeOnly:S.typeOnly})):eu(s),h=e.typescript?ru(e.typescript,s):Qd(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(d))for(let S of m?.filter(({unresolved:I})=>I)??[]){let I=S.kind==="require";l.push(X(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:S.line,filePath:d}))}let k=p!==void 0&&(r.has(p)||iu(p)),C=p!==void 0?` If "${p}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let S of n)if(S instanceof RegExp){S.lastIndex=0;let I=S.exec(s);S.lastIndex=0,I&&l.push(X("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${S}`,{line:I.index===void 0?void 0:lt(s,I.index),filePath:d,suggestion:"Remove infrastructure imports from domain/application layers."+C}))}else s.includes(S)&&l.push(X("FORBIDDEN_SUBSTRING",`Forbidden substring: ${S}`,{line:lt(s,s.indexOf(S)),filePath:d}));for(let S of u){let I=e.resolveImportTarget?.(S.value,d)??(e.resolveImportLayer?{layer:e.resolveImportLayer(S.value,d)}:void 0),E=typeof d=="string"?e.resolveImportTarget?.(d)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,H=I?.layer;if(H&&p){let N=Ee(e.architectureProfile?.rules,p,H,{fromPath:E?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(N){let $=N.rule;if(S.typeOnly&&!$.peerIsolation)continue;let v=!!$.peerIsolation,D=N.sliceVerdict,w=Ke(D),P=xn($,D)??(v?`Layer "${p}" must not import across slices into "${H}".`:`Layer "${p}" must not import "${H}".`),M=v&&D?.explanation&&(w.reasonId||N.peerIsolationReason!=="cross-slice")?D.explanation:void 0;l.push(X("LAYER_IMPORT_VIOLATION",M?`${P} ${M}`:P,{line:lt(s,S.index),source:S.value,target:S.value,filePath:d,fromLayer:p,toLayer:H,...v?{peerIsolation:!0}:{},...w.reasonId?{reasonId:w.reasonId}:{},...w.universeFrom?{universeFrom:w.universeFrom}:{},...w.universeTo?{universeTo:w.universeTo}:{},...w.failsStrict===!1?{failsStrict:!1}:{},suggestion:Xd(v,N.peerIsolationReason),details:{importKind:S.kind,peerIsolation:v,...S.typeOnly?{typeOnly:!0}:{},...w.reasonId?{reasonId:w.reasonId}:{}}}));continue}continue}k||S.typeOnly||!su(S.value)&&!ou(S.value)||l.push(X("FORBIDDEN_IMPORT",`Forbidden ${S.kind} target: "${S.value}".`,{line:lt(s,S.index),source:S.value,target:S.value,filePath:d,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+C,details:{importKind:S.kind}}))}if(e.policies)for(let S of e.policies){let I=S.check({source:s,context:i});if(I!==!0)if(Array.isArray(I))for(let E of I)l.push(X("POLICY_VIOLATION",E.message,{filePath:d,suggestion:`Fix violation of policy "${S.name}".`}));else I===!1?l.push(X("POLICY_VIOLATION",`Policy ${S.name} failed on generated code`)):l.push(X("POLICY_VIOLATION",I.message))}if(o&&t.size>0)for(let S of h)ve(S.value)&&!t.has(S.value)&&l.push(X("UNKNOWN_INTENT",`Unknown intent reference: "${S.value}"`,{line:lt(s,S.index),filePath:d,target:S.value,suggestion:`Register intent "${S.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let S of h){if(!ve(S.value))continue;let I=e.architectureProfile.resolveLayer(S.value);if(!I)continue;let E=Ee(e.architectureProfile.rules,p,I,{fromPath:typeof d=="string"?d:void 0,layers:e.architectureLayers});if(E){let H=E.sliceVerdict,N=`Layer "${p}" must not reference "${I}" through "${S.value}".`,$=H?st({surface:"intent",verdict:H,fromLayer:p,toLayer:I,fromPath:typeof d=="string"?d:void 0,ruleMessage:E.rule.message,childMessage:E.rule.childSlices?.message,defaultMessage:N}):E.rule.message??N,v=Ke(H);l.push(X("LAYER_REFERENCE_VIOLATION",$,{line:lt(s,S.index),filePath:d,target:S.value,fromLayer:p,toLayer:I,...v.reasonId?{reasonId:v.reasonId}:{},...v.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:E.rule,peerIsolationReason:E.peerIsolationReason,...v.reasonId?{reasonId:v.reasonId}:{}}}))}}if(e.extensions)for(let S of e.extensions)try{let I=S.analyze(s,i);l.push(...I)}catch(I){l.push(X("EXTENSION_ERROR",`Extension "${S.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let S=e.forbiddenGlobals[p];l.push(...at(e.typescript,f,S).map(I=>X("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${I.name}".`,{line:I.line,filePath:d,target:I.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of m??[]){if(I.typeOnly||!I.specifier)continue;let E=Ne(I.specifier,S);E&&l.push(X("FORBIDDEN_GLOBAL",`${p} must not use module "${I.specifier}" because it is the import form of forbidden global "${E}".`,{line:I.line,filePath:d,source:I.specifier,target:I.specifier,fromLayer:p,details:{importKind:I.kind,forbiddenGlobal:E},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(S){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let S=new Set(e.capabilityWalls[p]),I=e.forbiddenGlobals?.[p]??[];for(let E of Mr(e.typescript,f))S.has(E.capability)&&(E.source==="ambient-global"&&xt(E.symbol,I)||E.source==="import-based"&&Ne(E.symbol,I)||l.push(X("CAPABILITY_VIOLATION",E.source==="import-based"?`${p} denies the ${E.capability} capability; found import of "${E.symbol}".`:`${p} denies the ${E.capability} capability; found ambient "${E.symbol}".`,{line:E.line,filePath:d,target:E.symbol,capability:E.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(S){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript)try{l.push(...pu(e.typescript,s,i,e.architectureProfile))}catch(S){l.push(X("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${S instanceof Error?S.message:String(S)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:!l.some(S=>S.failsStrict!==!1),violations:l}}}}a(pi,"createAICodeGate");function ee(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(ee,"deterministicHash");function Z(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Z).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Z(t[n])}`).join(",")}}`}a(Z,"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 Kr(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")Kr(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"?Kr(i,t):Ce(`${JSON.stringify(i)}`,t)}Ce("}",t)}a(Kr,"feedStable");function Ur(e){if(e===null||typeof e!="object")return ee(Z(e));let t={hash:2166136261};return Kr(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}a(Ur,"stableHash");var Ue="1.2",fi=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e){let t=e.map((n,r)=>({key:Z(n),index:r}));return t.sort((n,r)=>n.key<r.key?-1:n.key>r.key?1:n.index-r.index),t.map(({index:n})=>e[n])}a(W,"sortCanonical");function te(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(te,"sortedUnique");function Dt(e){let t={schemaVersion:"1.2",include:te(e.include??[]),exclude:te(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:te(e.dynamicImportAllowlist??[]),layers:W(e.layers.map(n=>({name:n.name,patterns:te(n.patterns??[]),exclude:te(n.exclude??[]),forbiddenGlobals:te(n.forbiddenGlobals??[]),intentPrefixes:te(n.intentPrefixes??[]),capabilityDeny:te(n.capabilities?.deny??[]),pure:n.pure===!0}))),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:te(e.arkRun.compositionRoots),managedLayers:te(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return ee(Z(t))}a(Dt,"resolvedFactsEvidenceRequirementsHash");function fu(e){let t=W(e.completenessReasons.map(v=>({code:v.code,message:v.message,...v.file?{file:v.file}:{}}))),n=e.files.map(v=>({...v,typeOnlyExportNames:te(v.typeOnlyExportNames)})).sort((v,D)=>v.path<D.path?-1:v.path>D.path?1:0),r=W(e.dependencies.map(v=>({...v,...v.namedBindings?{namedBindings:te(v.namedBindings)}:{}}))),o=W(e.capabilityUses.map(v=>({...v}))),s=W(e.ambientUses.map(v=>({...v}))),i=W(e.publishCalls.map(v=>({...v}))),l=W(e.intentReferences.map(v=>({...v}))),c=W(e.safetyUses.map(v=>({...v}))),d=W((e.classShapes??[]).map(v=>({...v,mutatingMethods:[...v.mutatingMethods??[]].map(D=>({...D}))}))),p=W((e.arkRunKernelCalls??[]).map(v=>({...v}))),g=W((e.arkRunManagedNews??[]).map(v=>({...v}))),f=W((e.arkRunCompositionRootHits??[]).map(v=>({...v}))),m=W((e.arkRunDeclarations??[]).map(v=>({...v,uses:te(v.uses),reactsTo:te(v.reactsTo),raises:te(v.raises),sends:te(v.sends)}))),u=W((e.arkOrderPlaneCalls??[]).map(v=>({...v}))),h=W((e.arkOrderGenericUpdates??[]).map(v=>({...v}))),k=W((e.arkOrderRootHits??[]).map(v=>({...v}))),C=W((e.arkOrderXiFieldWrites??[]).map(v=>({...v}))),S=W((e.arkOrderIngestWritesXi??[]).map(v=>({...v}))),I=W((e.arkOrderReleaseKeyCounts??[]).map(v=>({...v}))),E=W((e.arkOrderXiTtlKeys??[]).map(v=>({...v}))),H=W((e.arkOrderBudgetLeaks??[]).map(v=>({...v}))),N=e.files.map(({path:v,contentHash:D})=>({path:v,contentHash:D})).sort((v,D)=>v.path<D.path?-1:v.path>D.path?1:0),$=Ur(N);return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:$,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:d,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:u,arkOrderGenericUpdates:h,arkOrderRootHits:k,arkOrderXiFieldWrites:C,arkOrderIngestWritesXi:S,arkOrderReleaseKeyCounts:I,arkOrderXiTtlKeys:E,arkOrderBudgetLeaks:H}}a(fu,"canonicalResolvedFactsInput");function gi(e){let t=fu(e);return{...t,factsHash:Ur(t)}}a(gi,"createCanonicalResolvedCandidateFacts");function Br(e){return gi(mi(V(e,"$"),!1))}a(Br,"createResolvedCandidateFacts");function V(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(V,"asRecord");function K(e,t,n){let r=Object.keys(e).find(o=>!t.includes(o));if(r)throw new Error(`${n}.${r} is not part of schema ${"1.2"}.`)}a(K,"assertOnlyKeys");function j(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}a(j,"requiredText");function _e(e,t,n){if(e[t]!==void 0)return j(e,t,n)}a(_e,"optionalText");function U(e,t,n){let r=j(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(U,"requiredProjectPath");function Y(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(Y,"requiredBoolean");function Gr(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(Gr,"requiredInteger");function Q(e,t,n){let r=Gr(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(Q,"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 ct(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(ct,"parseStringArray");function gu(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(gu,"assertUnique");function mi(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts","arkOrderXiTtlKeys","arkOrderBudgetLeaks",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=xe(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=xe(e,"completeness",["complete","partial","unavailable"],"$"),o=G(e,"completenessReasons","$").map((_,R)=>{let y=`$.completenessReasons[${R}]`,A=V(_,y);K(A,["code","message","file"],y);let L=A.file===void 0?void 0:U(A,"file",y);return{code:j(A,"code",y),message:j(A,"message",y),...L?{file:L}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=G(e,"files","$").map((_,R)=>{let y=`$.files[${R}]`,A=V(_,y);return K(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:U(A,"path",y),contentHash:j(A,"contentHash",y),parseStatus:xe(A,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Gr(A,"parseDiagnosticCount",y),exportsOnlyTypes:Y(A,"exportsOnlyTypes",y),typeOnlyExportNames:ct(A.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:Y(A,"hasTopLevelSideEffects",y)}}),i=G(e,"dependencies","$").map((_,R)=>{let y=`$.dependencies[${R}]`,A=V(_,y);K(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let L=_e(A,"specifier",y),se=_e(A,"target",y),Ze=xe(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(Ze==="resolved-project"&&!se)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(Ze!=="resolved-project"&&se)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(Ze!=="dynamic"&&!L)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:U(A,"from",y),...L?{specifier:L}:{},kind:xe(A,"kind",["import","export","dynamic-import","require"],y),typeOnly:Y(A,"typeOnly",y),line:Q(A,"line",y),resolution:Ze,...se?{target:U(A,"target",y)}:{},...A.namedBindings!==void 0?{namedBindings:ct(A.namedBindings,`${y}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:Y(A,"targetTypeOnlyExports",y)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:Y(A,"sourcePureTypeModule",y)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:Y(A,"namedBindingsTypeOnly",y)}:{},...A.portProofEligible!==void 0?{portProofEligible:Y(A,"portProofEligible",y)}:{}}}),l=G(e,"capabilityUses","$").map((_,R)=>{let y=`$.capabilityUses[${R}]`,A=V(_,y);return K(A,["file","line","symbol","capability","source"],y),{file:U(A,"file",y),line:Q(A,"line",y),symbol:j(A,"symbol",y),capability:xe(A,"capability",fi,y),source:xe(A,"source",["ambient-global","import-based"],y)}}),c=G(e,"ambientUses","$").map((_,R)=>{let y=`$.ambientUses[${R}]`,A=V(_,y);return K(A,["file","line","symbol"],y),{file:U(A,"file",y),line:Q(A,"line",y),symbol:j(A,"symbol",y)}}),d=G(e,"publishCalls","$").map((_,R)=>{let y=`$.publishCalls[${R}]`,A=V(_,y);K(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let L=_e(A,"rawIntentName",y),se=_e(A,"sourceIntent",y);return{file:U(A,"file",y),line:Q(A,"line",y),...L?{rawIntentName:L}:{},objectHasIntent:Y(A,"objectHasIntent",y),arkPublishCandidate:Y(A,"arkPublishCandidate",y),hasSource:Y(A,"hasSource",y),...se?{sourceIntent:se}:{}}}),p=G(e,"intentReferences","$").map((_,R)=>{let y=`$.intentReferences[${R}]`,A=V(_,y);return K(A,["file","line","intent"],y),{file:U(A,"file",y),line:Q(A,"line",y),intent:j(A,"intent",y)}}),g=G(e,"safetyUses","$").map((_,R)=>{let y=`$.safetyUses[${R}]`,A=V(_,y);K(A,["file","line","kind","symbol"],y);let L=_e(A,"symbol",y),se=xe(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(se==="in-memory-store"&&!L)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(se!=="in-memory-store"&&L)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:U(A,"file",y),line:Q(A,"line",y),kind:se,...L?{symbol:L}:{}}});gu(s,_=>_.path,"$.files");let f=new Set(s.map(_=>_.path));for(let _ of s){if(_.parseStatus==="parsed"&&_.parseDiagnosticCount!==0)throw new Error(`$.files[${_.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(_.parseStatus==="invalid"&&_.parseDiagnosticCount===0)throw new Error(`$.files[${_.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(_=>_.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let _ of i)if(!f.has(_.from))throw new Error(`$.dependencies references missing source file ${_.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((_,R)=>{let y=`$.arkRunKernelCalls[${R}]`,A=V(_,y);K(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let L=_e(A,"receiver",y),se=_e(A,"nameLiteral",y);return{file:U(A,"file",y),line:Q(A,"line",y),kind:xe(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:j(A,"callee",y),viaImport:Y(A,"viaImport",y),...L?{receiver:L}:{},...se?{nameLiteral:se}:{}}}),k=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((_,R)=>{let y=`$.arkRunManagedNews[${R}]`,A=V(_,y);K(A,["file","line","typeName","importedFrom"],y);let L=_e(A,"importedFrom",y);return{file:U(A,"file",y),line:Q(A,"line",y),typeName:j(A,"typeName",y),...L?{importedFrom:L}:{}}}),S=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((_,R)=>{let y=`$.arkRunCompositionRootHits[${R}]`,A=V(_,y);return K(A,["file","matchedRoot","hasKernelFactory"],y),{file:U(A,"file",y),matchedRoot:j(A,"matchedRoot",y),hasKernelFactory:Y(A,"hasKernelFactory",y)}}),I=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),H=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((_,R)=>{let y=`$.arkOrderPlaneCalls[${R}]`,A=V(_,y);return K(A,["file","line","callee"],y),{file:U(A,"file",y),line:Q(A,"line",y),callee:j(A,"callee",y)}}),$=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((_,R)=>{let y=`$.arkOrderGenericUpdates[${R}]`,A=V(_,y);return K(A,["file","line","method"],y),{file:U(A,"file",y),line:Q(A,"line",y),method:j(A,"method",y)}}),D=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((_,R)=>{let y=`$.arkOrderRootHits[${R}]`,A=V(_,y);return K(A,["file","matchedRoot","hasPlaneFactory"],y),{file:U(A,"file",y),matchedRoot:j(A,"matchedRoot",y),hasPlaneFactory:Y(A,"hasPlaneFactory",y)}}),P=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((_,R)=>{let y=`$.arkOrderXiFieldWrites[${R}]`,A=V(_,y);return K(A,["file","line","key"],y),{file:U(A,"file",y),line:Q(A,"line",y),key:j(A,"key",y)}}),F=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((_,R)=>{let y=`$.arkOrderIngestWritesXi[${R}]`,A=V(_,y);return K(A,["file","line"],y),{file:U(A,"file",y),line:Q(A,"line",y)}}),ke=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((_,R)=>{let y=`$.arkOrderReleaseKeyCounts[${R}]`,A=V(_,y);return K(A,["file","line","keyCount"],y),{file:U(A,"file",y),line:Q(A,"line",y),keyCount:Q(A,"keyCount",y)}}),ur=(e.arkOrderXiTtlKeys===void 0?[]:G(e,"arkOrderXiTtlKeys","$")).map((_,R)=>{let y=`$.arkOrderXiTtlKeys[${R}]`,A=V(_,y);return K(A,["file","line","key"],y),{file:U(A,"file",y),line:Q(A,"line",y),key:j(A,"key",y)}}),je=(e.arkOrderBudgetLeaks===void 0?[]:G(e,"arkOrderBudgetLeaks","$")).map((_,R)=>{let y=`$.arkOrderBudgetLeaks[${R}]`,A=V(_,y);return K(A,["file","line","kind"],y),{file:U(A,"file",y),line:Q(A,"line",y),kind:j(A,"kind",y)}}),Xe=I.map((_,R)=>{let y=`$.arkRunDeclarations[${R}]`,A=V(_,y);return K(A,["file","line","uses","reactsTo","raises","sends"],y),{file:U(A,"file",y),line:Q(A,"line",y),uses:ct(A.uses,`${y}.uses`),reactsTo:ct(A.reactsTo,`${y}.reactsTo`),raises:ct(A.raises,`${y}.raises`),sends:ct(A.sends,`${y}.sends`)}});for(let[_,R]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",d],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",k],["$.arkRunCompositionRootHits",S],["$.arkRunDeclarations",Xe],["$.arkOrderPlaneCalls",H],["$.arkOrderGenericUpdates",$],["$.arkOrderRootHits",D],["$.arkOrderXiFieldWrites",P],["$.arkOrderIngestWritesXi",F],["$.arkOrderReleaseKeyCounts",ke],["$.arkOrderXiTtlKeys",ur],["$.arkOrderBudgetLeaks",je]])for(let y of R)if(!f.has(y.file))throw new Error(`${_} references missing file ${y.file}.`);let en=_e(e,"projectPackageName","$"),tn=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((_,R)=>{let y=`$.classShapes[${R}]`,A=V(_,y);K(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],y);let L=G(A,"mutatingMethods",y).map((se,Ze)=>{let nn=`${y}.mutatingMethods[${Ze}]`,fr=V(se,nn);return K(fr,["name","referencesGuardOrPublish"],nn),{name:j(fr,"name",nn),referencesGuardOrPublish:Y(fr,"referencesGuardOrPublish",nn)}});return{file:U(A,"file",y),className:j(A,"className",y),exported:Y(A,"exported",y),hasPublicMutableFields:Y(A,"hasPublicMutableFields",y),hasPublicSetters:Y(A,"hasPublicSetters",y),hasPublicConstructor:Y(A,"hasPublicConstructor",y),hasStaticFactory:Y(A,"hasStaticFactory",y),mutatingMethods:L,...A.dataOnly===void 0?{}:{dataOnly:Y(A,"dataOnly",y)},...A.truncatedUntil===void 0?{}:{truncatedUntil:Gr(A,"truncatedUntil",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:j(e,"resolverIdentity","$"),compilerIdentity:j(e,"compilerIdentity","$"),compilerOptionsHash:j(e,"compilerOptionsHash","$"),tsconfigHash:j(e,"tsconfigHash","$"),evidenceRequirementsHash:j(e,"evidenceRequirementsHash","$"),...en?{projectPackageName:en}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:d,intentReferences:p,safetyUses:g,classShapes:tn,arkRunKernelCalls:u,arkRunManagedNews:k,arkRunCompositionRootHits:S,arkRunDeclarations:Xe,arkOrderPlaneCalls:H,arkOrderGenericUpdates:$,arkOrderRootHits:D,arkOrderXiFieldWrites:P,arkOrderIngestWritesXi:F,arkOrderReleaseKeyCounts:ke,arkOrderXiTtlKeys:ur,arkOrderBudgetLeaks:je}}a(mi,"parseResolvedFactsInput");function $e(e){let t=V(e,"$"),n=j(t,"factsHash","$"),r=j(t,"candidateTreeHash","$"),o=gi(mi(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($e,"loadResolvedCandidateFacts");var mu=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},ne={type:"integer",minimum:1},B={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},zr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:T,message:T,file:B}}},resolverIdentity:T,compilerIdentity:T,compilerOptionsHash:T,tsconfigHash:T,candidateTreeHash:T,evidenceRequirementsHash:T,projectPackageName:T,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:B,contentHash:T,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:T},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:B,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ne,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:B,namedBindings:{type:"array",items:T},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:B,line:ne,symbol:T,capability:{enum:mu},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:B,line:ne,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:B,line:ne,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:B,line:ne,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:ne,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:B,className:T,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},truncatedUntil:{type:"integer",minimum:0},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:T,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:B,line:ne,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:T,viaImport:{type:"boolean"},receiver:T,nameLiteral:T}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:B,line:ne,typeName:T,importedFrom:T}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:B,matchedRoot:T,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:B,line:ne,uses:{type:"array",items:T},reactsTo:{type:"array",items:T},raises:{type:"array",items:T},sends:{type:"array",items:T}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:B,line:ne,callee:T}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:B,line:ne,method:T}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:B,matchedRoot:T,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:ne,key:T}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:B,line:ne}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:B,line:ne,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:ne,key:T}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:ne,kind:T}}},factsHash:T},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Wr="1.0";function hi(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(hi,"canonicalProjectPath");function dt(e){return e.flatMap(t=>t.to?[{from:t.from,to:t.to}]:[])}a(dt,"resolvedEdgeDependencies");function de(e){return`${e.from}->${e.to}`}a(de,"dependencyKey");function Ft(e,t,n,r="dependency"){return{id:`${e}:${r}:${de(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${de(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${de(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${de(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${de(t)} from the candidate, then preflight again.`}:{}}}a(Ft,"dependencyFinding");function ut(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[de(f),f])),s=new Map(e.baseDependencies.map(f=>[de(f),f])),i=new Map(e.candidateDependencies.map(f=>[de(f),f]));for(let f of[...n.values()].sort((m,u)=>m.path.localeCompare(u.path))){let m=r.get(f.path);m?m.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${m.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((m,u)=>m.path.localeCompare(u.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let l=new Set;for(let f of[...o.values()].sort((m,u)=>de(m).localeCompare(de(u)))){if(i.has(de(f))){t.push(Ft("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};i.has(de(m))?(l.add(de(m)),t.push(Ft("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ft("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,m]of[...i].sort(([u],[h])=>u.localeCompare(h)))s.has(f)||o.has(f)||l.has(f)||!c.has(m.from)&&!c.has(m.to)||t.push({...Ft("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let d=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([u],[h])=>u.localeCompare(h)))i.has(f)||d.has(m.from)||d.has(m.to)||!c.has(m.from)&&!c.has(m.to)||t.push({...Ft("unplanned",m,`${m.from} -> ${m.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,m)=>p[f.classification]-p[m.classification]||(f.subject===m.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(m.id));let g={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}a(ut,"analyzeArchitectureConvergence");var pt="1.0",qr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",ki=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],hu=["no-anemic-model"],yi={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Yr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:qr,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:qr},schemaVersion:{type:"string",const:pt,default:pt},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...ki]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:yi,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:yi}}}},De=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
|
|
6
|
+
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function yu(e){return{...e,$schema:e.$schema===void 0?qr:e.$schema,schemaVersion:e.schemaVersion===void 0?pt:e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}a(yu,"defaultedArkRules");function Ai(e){return e==="enforced"?"enforced":"advisory"}a(Ai,"normalizeMode");function Au(e){return hu.includes(e)}a(Au,"isTier2Sensor");function Ru(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(!Pe(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"&&Au(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(!Pe(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(Ru,"validateSemantics");function Mt(e,t="arkrules.json",n){if(!Pe(e))throw new De(t,[{path:"$",message:`must be an object; received ${Ie(e)}`}]);let r=yu(e),o=[];if(Te(r,Yr,"$",Yr,o),Ru(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 De(t,o);return{config:r}}a(Mt,"loadArkRulesContract");function Su(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new De(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return Mt(r,t,n)}a(Su,"parseArkRulesJson");function On(e,t){return e.childId?`${e.childId}#${t}`:t}a(On,"effectiveRuleId");function Ri(e,t){if(t&&t.length>0)return[...t];if(e.childId&&e.defaultAppliesTo&&e.defaultAppliesTo.length>0)return[...e.defaultAppliesTo]}a(Ri,"effectiveAppliesTo");function Si(e,t){return{sourceFile:e.sourceFile,ruleId:On(e,t),layer:e.layer,...e.childId?{childId:e.childId}:{}}}a(Si,"provenanceFor");function Ii(e,t){let n=t.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase(),r=e.trim().replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase();if(!r||!n||r.includes(".."))return!1;if(r===n||r===`${n}/**`||r===`${n}/*`)return!0;if(r.startsWith(`${n}/`)){let i=r.slice(n.length+1).split("/"),l=i.indexOf("**");return l!==-1&&l!==i.length-1?!1:i.every(c=>c.length>0)}let o=n.replace(/^(?:src|app)\//,""),s=r.replace(/^(?:src|app)\//,"");return o!==n||s!==r?Ii(s,o):!1}a(Ii,"appliesToPatternInsideSlice");function bi(e){if(!e.childId||!e.defaultAppliesTo?.length)return[];let t=String(e.defaultAppliesTo[0]).replace(/\/\*\*$/,""),n=[],r=[...e.file.structure??[],...e.file.invariants??[]];for(let o of r)for(let s of o.appliesTo??[])Ii(s,t)||n.push({id:o.id,pattern:s});return n}a(bi,"sliceScopeEscapes");function vi(e){let t=new Map,n=new Map;for(let r of e){let o=[...(r.file.structure??[]).map(s=>s.id),...(r.file.invariants??[]).map(s=>s.id)];for(let s of o){let i=On(r,s),l=`${r.layer}\0${i}`,c=t.get(l);if(!c){t.set(l,{id:i,layer:r.layer,sourceFiles:[r.sourceFile]});continue}let d=n.get(l)??{id:i,layer:r.layer,sourceFiles:[...c.sourceFiles]};d.sourceFiles.includes(r.sourceFile)||d.sourceFiles.push(r.sourceFile),n.set(l,d)}}return[...n.values()]}a(vi,"duplicateArkRuleIds");function Xr(e){let t={},n=[],r=[],o=[...e].sort((s,i)=>s.layer.localeCompare(i.layer)||s.sourceFile.localeCompare(i.sourceFile));for(let s of o){let i=(s.file.structure??[]).map(d=>{let p=Ri(s,d.appliesTo);return{...d,id:On(s,d.id),...p?{appliesTo:p}:{appliesTo:void 0},mode:Ai(d.mode),provenance:Si(s,d.id)}}),l=(s.file.invariants??[]).map(d=>{let p=Ri(s,d.appliesTo);return{...d,id:On(s,d.id),...p?{appliesTo:p}:{appliesTo:void 0},mode:Ai(d.mode),provenance:Si(s,d.id)}}),c=t[s.layer];c?(c.sourceFiles||(c.sourceFiles=[c.sourceFile]),c.sourceFiles.includes(s.sourceFile)||c.sourceFiles.push(s.sourceFile),c.structure.push(...i),c.invariants.push(...l)):t[s.layer]={sourceFile:s.sourceFile,sourceFiles:[s.sourceFile],structure:i,invariants:l},n.push(...i),r.push(...l)}return n.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),r.sort((s,i)=>{let l=s.provenance.layer.localeCompare(i.provenance.layer);return l!==0?l:s.id.localeCompare(i.id)}),{schemaVersion:pt,byLayer:t,structure:n,invariants:r}}a(Xr,"buildEffectiveArkRules");function Ge(){return{schemaVersion:pt,byLayer:{},structure:[],invariants:[]}}a(Ge,"emptyEffectiveArkRules");var wn=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
|
|
8
|
+
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Ei(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Ei,"normalizeRel");function ku(e,t="ark.config.json"){let n=e.config.arkRules??{},r=[],o=Object.keys(n).length>0,s=!!(e.governedFiles&&e.governedFiles.length>0);if(!o&&!s){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let g of[...e.discoveredArkRulesFiles].sort())r.push({path:g,message:`ArkRules file ${JSON.stringify(g)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:Ge(),warnings:r}}let i=new Set(e.config.layers.map(g=>g.name)),l=[],c=[],d=new Set,p=a((g,f,m)=>{if(m instanceof De){for(let u of m.issues)l.push({path:`${g}${u.path==="$"?"":u.path.replace(/^\$/,"")}`,message:`${f}: ${u.message}`});return}if(m instanceof SyntaxError){l.push({path:g,message:`referenced ArkRules file ${JSON.stringify(f)} is not valid JSON: ${m.message}`});return}l.push({path:g,message:`referenced ArkRules file ${JSON.stringify(f)} failed to load: ${m instanceof Error?m.message:String(m)}`})},"pushLoadIssue");for(let g of Object.keys(n).sort()){let f=n[g],m=`$.arkRules[${JSON.stringify(g)}]`,u=Array.isArray(f)?f:typeof f=="string"?[f]:null;if(!u||u.length===0||u.some(h=>typeof h!="string"||h.length===0)){l.push({path:m,message:"must be a non-empty path string or an array of paths"});continue}if(!i.has(g)){l.push({path:m,message:`layer ${JSON.stringify(g)} is not declared in layers[]`});continue}u.forEach((h,k)=>{let C=u.length===1&&typeof f=="string"?m:`${m}[${k}]`;if(h.startsWith("/")||/^[A-Za-z]:[\\/]/.test(h)){l.push({path:C,message:"must be a project-relative path (absolute paths are not allowed)"});return}let S=Ei(h);d.add(S);let I=e.fileContents[S]??e.fileContents[h];if(I===void 0){l.push({path:C,message:`referenced ArkRules file ${JSON.stringify(S)} is missing`});return}try{let E=Mt(JSON.parse(I),S,g);c.push({layer:g,sourceFile:S,file:E.config})}catch(E){p(C,S,E)}})}if(e.governedFiles&&e.governedFiles.length>0){let g=Qo({files:e.governedFiles,rules:e.config.rules,layers:[...i]});for(let f of g){let m=e.fileContents[f.path];if(m!==void 0){d.add(f.path);try{let u=Mt(JSON.parse(m),f.path,f.layer),h={layer:f.layer,sourceFile:f.path,file:u.config,childId:f.childId,defaultAppliesTo:f.defaultAppliesTo},k=bi(h);if(k.length>0){l.push({path:f.path,message:`ARKRULE_SCOPE_ESCAPES_SLICE: ${f.path} appliesTo ${k.map(C=>C.pattern).join(", ")} escapes ${f.childId}`});continue}c.push(h)}catch(u){p(f.path,f.path,u)}}}}for(let g of vi(c))l.push({path:`$.arkRules[${JSON.stringify(g.layer)}]`,message:`ARKRULE_DUPLICATE_ID: ${g.id} is declared in ${g.sourceFiles.join(", ")}`});if(e.discoveredArkRulesFiles)for(let g of[...e.discoveredArkRulesFiles].sort()){let f=Ei(g);d.has(f)||r.push({path:f,message:`ArkRules file ${JSON.stringify(f)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(l.length>0)throw new wn(t,l);return{config:e.config,arkRules:Xr(c),warnings:r}}a(ku,"resolveEffectiveContract");function Zr(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(Zr,"omitLayerDescriptions");function Jr(e){let{stewards:t,...n}=Zr(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(Jr,"effectiveContractPolicyPayload");var Iu=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),bu=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),vu=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function Eu(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 vu.has(e.slice(o+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:bu.has(r)}a(Eu,"slashStartsRegex");function Cu(e,t){if(!Eu(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(Cu,"skipRegexLiteral");function Be(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 Cu(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(Be,"skipStringOrComment");function ye(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=Be(e,n);continue}break}return n}a(ye,"skipWsAndComments");function Tn(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(Tn,"readIdent");function Fe(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=Be(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(Fe,"skipBalanced");function Pn(e){let t=[],n=0,r;for(;n<e.length&&(n=ye(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=Tn(e,s);if(!p||!Iu.has(p.ident))break;o.push(p.ident),s=ye(e,p.end)}if(o.length===1&&o[0]==="static"&&e[s]==="{"){let p=Fe(e,s,"{","}");if(p==null){r=e.length;break}n=p;continue}let i=Tn(e,s);if(!i){n+=1;continue}if(s=ye(e,i.end),e[s]==="<"){let p=Fe(e,s,"<",">");if(p==null){r=e.length;break}s=ye(e,p)}if(e[s]==="("){let p=Fe(e,s,"(",")");if(p==null){r=e.length;break}if(s=ye(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=Be(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=Fe(e,s,"{","}");if(g==null){r=e.length;break}t.push({name:i.ident,modifiers:o,kind:"method",body:e.slice(s+1,g-1)}),n=g;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,d=0;for(;s<e.length;){let p=Be(e,s);if(p!==s){s=p;continue}let g=e[s];if(g==="{")l+=1;else if(g==="}"){if(l===0)break;l-=1}else if(g==="(")c+=1;else if(g===")")c-=1;else if(g==="[")d+=1;else if(g==="]")d-=1;else if(g===";"&&l===0&&c===0&&d===0){s+=1;break}s+=1}s>=e.length&&(l>0||c>0||d>0)&&(r=e.length),t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(Pn,"scanClassMembers");function Ci(e,t){let n=t;for(;n<e.length;){let r=ye(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=Fe(e,n,o,o==="<"?">":o==="("?")":"]");if(i==null)return null;n=i;continue}if(o==='"'||o==="'"||o==="`"){n=Be(e,n);continue}n+=1}return null}a(Ci,"findClassBodyBrace");function Nn(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=_i(e),s;for(;(s=r.exec(o))!==null;){let i=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=Ci(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=Fe(e,c,"{","}");n.push({name:i,start:s.index,exported:l,bodyStart:c+1,bodyEnd:d==null?null:d-1})}return n}a(Nn,"findClassDeclarations");function _i(e){let t="",n=0;for(;n<e.length;){let r=Be(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}a(_i,"maskStringsAndComments");function xi(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=_i(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=Ci(e,i.index+i[0].length);else{c="object";let p=ye(e,i.index+i[0].length);l=e[p]==="{"?p:null}if(l==null)continue;let d=Fe(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:d==null?e.length:d-1})}return n}a(xi,"findMemberContainers");function Oi(e){let t=[],n=0,r=!0;for(;n<e.length;){let o=Be(e,n);if(o!==n){n=o,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=Fe(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=Tn(e,n);for(;i&&(i.ident==="async"||i.ident==="get"||i.ident==="set");){let l=ye(e,i.end);e[l]==="*"&&(l=ye(e,l+1));let c=Tn(e,l);if(!c)break;i=c}if(i){let l=ye(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(Oi,"objectLiteralMemberNames");function wi(e){return e==="survived"||e==="not-reached"}a(wi,"verdictRefusesPromotion");function _u(e){switch(e.operator){case"negate-guard":return"the guard is negated";case"drop-throw":return"the throw is removed";case"flip-comparison":return`\`${e.original}\` becomes \`${e.replacement}\``;case"boundary-shift":return`the boundary moves (\`${e.original}\` becomes \`${e.replacement}\`)`;case"const-shift":return`\`${e.original}\` becomes \`${e.replacement}\``}}a(_u,"changeText");function Ti(e,t){if(t.verdict==="not-reached")return`Invariant ${e}: the covering tests load the file but never call the declared symbol (mutation probe: not reached); add a test that calls it and re-run --probe-invariants --write before promoting.`;let n=t.survivors[0],r=n?` (${_u(n)} at line ${n.line})`:"";return`Invariant ${e}: the mutation probe shows the covering tests do not pin it${r}; strengthen the test and re-run --probe-invariants --write before promoting.`}a(Ti,"probeRefusalReason");var xu="INVARIANT_TESTS_PATH_MISSING",Ou="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.",wu="INVARIANT_COVERAGE_ROOTS_MISSING",Tu="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 Pi(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(Pi,"formatCoverageDiscards");function $i(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($i,"isUnderCoverageRoot");function es(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(es,"escapeRegExp");function ft(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(ft,"normalizePath");function ts(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]!==`
|
|
9
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
|
|
12
|
-
`?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(
|
|
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(ts,"maskNonCode");function Pu(e,t){if(!t)return;let n=es(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(ts(e,!1))?.[2];return s===void 0?void 0:s}a(Pu,"matchTestTitle");function Di(e,t){if(!t)return;let n=es(t),r=ts(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(Di,"declarationShape");function Nu(e,t,n){let r=a(o=>Pn(o).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let o of Nn(e))if(!(o.name!==t||o.bodyStart==null)&&r(e.slice(o.bodyStart,o.bodyEnd??e.length)))return"method";for(let o of xi(e,t)){let s=e.slice(o.bodyStart,o.bodyEnd);if(o.kind==="class-expression"&&r(s)||o.kind==="object"&&Oi(s).includes(n))return"method";if(o.kind==="namespace"){let i=Di(s,n);if(i==="function"||i==="const")return i}}}a(Nu,"classMemberShape");function Lu(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)}a(
|
|
15
|
-
`;)i(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(i(o,"comment"),i(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)i(o,"comment"),o+=1;o<s&&(i(o,"comment"),i(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let u=l;for(i(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===u){i(o,"string"),o+=1;break}i(o,"string"),o+=1}continue}i(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(bo,"mentionContext");function _o(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}a(_o,"symbolNeedle");function Tc(e){return _o(e.coverage?.symbol)?.name??e.id}a(Tc,"declaredLabel");function vo(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(vo,"sortedContentFiles");function Oo(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(g=>nt(g))),s=(t.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),i=e.coverage?.test!==!1&&n,l=_o(e.coverage?.symbol??void 0),c,u;if(i){for(let g of r){let d=t.fileContents[g];if(!d)continue;let h=Cc(d,e.id);if(h!==void 0){if(s.length===0||Co(g,s)){c={file:g,title:h};break}u??={file:g,title:h}}}c??=u}let p;if(l)for(let g of vo(t.fileContents)){if(o.has(nt(g)))continue;let d=t.fileContents[g];if(!d||l.className&&!d.includes(l.className))continue;let h=_c(d,l.name);if(h){p={file:g,shape:h};break}}let m;if(!c&&!p){if(i)for(let g of r){let d=t.fileContents[g];if(!d)continue;let h=bo(d,e.id,!0);if(h){m={file:g,context:h};break}}if(!m&&l)for(let g of vo(t.fileContents)){if(o.has(nt(g)))continue;let d=t.fileContents[g];if(!d)continue;let h=bo(d,l.name,!1);if(h){m={file:g,context:h};break}}}let f=c?{kind:"test-title",file:c.file,title:c.title}:p?{kind:"declaration",file:p.file,shape:p.shape}:m?{kind:"mention-only",file:m.file,context:m.context}:{kind:"none"};return f.kind==="mention-only"&&f.context==="comment"&&l&&wc(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...p?{declaration:p}:{}}}a(Oo,"rankCoverage");function wc(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${mr(n)}(?=$|[^A-Za-z0-9_$])`),s=nt(r);for(let i of Object.keys(e)){if(t.has(nt(i))||nt(i)===s)continue;let l=e[i];if(l&&o.test(hr(l,!0)))return!0}return!1}a(wc,"symbolInCodeElsewhere");function Nc(e,t){return Oo(e,t).best}a(Nc,"classifyCoverage");function xo(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(xo,"countsAsCoverage");function Lc(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(Lc,"mentionWhere");function To(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} ${Tc(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Lc(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(To,"describeCoverage");function yr(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=Eo(s),l=Eo(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,m=u.join(", "),f=[],g=[];for(let d of t){let h=d.coverage?.test!==!1,E=d.coverage?.symbol,_=!r&&h,k=Oo(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},_),b=k.best,O=[];_&&k.testTitle&&O.push("test-title"),k.declaration&&O.push("symbol");let D=xo(b),S,L;_&&k.testTitle&&(S=k.testTitle.file,p&&(L=!Co(S,u)));let j=k.declaration?.file,T=k.declaration?.shape,P=(d.coverage?.test===!0||!!E||d.coverage===void 0)&&D||d.coverage?.test===!1&&!E?!0:D,V=r&&h&&!D;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:P&&!V,evidence:O,partial:V,description:d.description,...S!==void 0?{testEvidenceFile:S}:{},...j!==void 0?{symbolEvidenceFile:j}:{},...T!==void 0?{shape:T}:{},...L!==void 0?{outsideDeclaredRoots:L}:{},coverageRootsDeclared:p}),L===!0&&S!==void 0&&g.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${S}, 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:S,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!P||V){let z=d.mode==="enforced"&&!V,fe=r||n.length===0?"never-had-tests":"tests-disappeared";g.push({ruleId:"INVARIANT_UNCOVERED",message:(V?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}: ${To(d,b)} (${fe==="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.`)+(V&&o?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:z?"error":"warning",failsStrict:z,kind:fe})}}return{coverage:f,violations:g,partial:f.some(d=>d.partial)}}a(yr,"evaluateInvariantCoverage");function Ar(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a(Ar,"canPromoteInvariant");function gr(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(gr,"nonEmptyPathStrings");function Pc(e){return!e||typeof e!="object"?[]:[...gr(e.testGlobs),...gr(e.coverageRoots)]}a(Pc,"configuredInvariantTestsPaths");function Dc(e){return Pc(e).length>0}a(Dc,"hasConfiguredInvariantTestsPath");function Rr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Rr,"catalogDemandsInvariantTestsPath");function wo(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Rr(e.invariants);return e.adopted!==!0||!t?[]:Dc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Ic,message:Ec,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(wo,"collectMissingInvariantTestsPathFindings");function Mc(e){return!e||typeof e!="object"?[]:gr(e.coverageRoots)}a(Mc,"configuredCoverageRoots");function Fc(e){return Mc(e).length>0}a(Fc,"hasConfiguredCoverageRoots");function kr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(kr,"catalogHasEnforcedInvariant");function No(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&kr(e.invariants)?Fc(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:bc,message:vc,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(No,"collectMissingCoverageRootsFindings");var vr="1.0",$c="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function C(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${$c}`: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(C,"addFinding");function G(e){return[...new Set(e??[])].sort()}a(G,"sortedUnique");function he(e,t,n,r,o){let s=G(n),i=G(r),l=new Set(s),c=new Set(i),u=i.filter(m=>!l.has(m)),p=s.filter(m=>!c.has(m));u.length===0&&p.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),p.length>0&&C(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(he,"compareStringSets");function Tt(e,t,n,r,o,s,i){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(Tt,"compareBoolean");function dn(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(dn,"keyed");function Hc(e,t,n){let r=dn(t,s=>s.name),o=dn(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after: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){C(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){C(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;he(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."}),he(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=Jt(i),p=Jt(l);he(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."}),he(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)."}),G(i.intentPrefixes).join("\0")!==G(l.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:G(i.intentPrefixes),after:G(l.intentPrefixes)}),Tt(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."),Tt(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(Hc,"compareLayers");function jc(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=dn(t,r),s=dn(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),u=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):C(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&&C(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&&C(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,m=c.peerIsolation===!0;if(p!==m){let d=l.from===l.to&&c.from===c.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?m?"strengthening":"weakening":"judgment-required",message:d?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:p,after:m})}G(l.sliceFolders).join("\0")!==G(c.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:G(l.sliceFolders),after:G(c.sliceFolders)});let f=l.sliceIdentity??"path",g=c.sliceIdentity??"path";if(f!==g&&C(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:g}),!(!p&&!m)){if(br(e,`${u}.sharedRoots`,"shared-roots",G(l.sharedRoots),G(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."),br(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",G((l.allowedCrossSlice??[]).map(Er)),G((c.allowedCrossSlice??[]).map(Er)),"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=l.sharedImportsSlice??null,h=c.sharedImportsSlice??null,E=jo(h)>jo(d);C(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:E?"strengthening":"weakening",message:Qc(d,h),before:d,after:h})}Kc(e,u,l,c)}}}a(jc,"compareRules");function Lo(e){let t=e.childSlices;return t?JSON.stringify([G(t.sliceFolders??[]),t.sliceIdentity??"path",G(t.commonFolders??[])]):""}a(Lo,"childSliceFoldersKey");function Vc(e){return G((e??[]).map(t=>un(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Vc,"enforceKeys");function Po(e){if(!e.childSlices)return null;let t=e.childSlices.siblings;return t==null||t==="deny"?{mode:"deny",enforce:[]}:t==="advisory"?{mode:"advisory",enforce:[]}:t.default==="deny"?{mode:"deny",enforce:[]}:{mode:"advisory",enforce:Vc(t.enforce)}}a(Po,"childSliceSiblingPolicy");function Kc(e,t,n,r){let o=Po(n),s=Po(r);if(o===null&&s===null)return;if(o===null&&s!==null){C(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:s.mode==="advisory"?"judgment-required":"strengthening",message:s.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(o!==null&&s===null){C(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(Lo(n)!==Lo(r)){C(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(o===null||s===null)return;if(o.mode!==s.mode){let c=s.mode==="advisory";C(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?s.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:o.mode,after:s.mode})}else o.mode==="advisory"&&Uc(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce);let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&C(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:i,after:l}),Wc(e,t,n,r),zc(e,t,n,r)}a(Kc,"compareChildSlices");function Uc(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;C(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(Uc,"compareSiblingEnforceList");function Er(e){return JSON.stringify([e.from,e.to])}a(Er,"crossSliceKey");function Do(e){return G((e.childSlices?.allowedCrossSlice??[]).map(Er))}a(Do,"childCrossSliceKeys");function rt(e){return un(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(rt,"allowanceSegments");function Mo(e,t){let n=rt(e),r=rt(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(Mo,"patternWidens");function Gc(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=rt(n[0]).join("/")===rt(r[0]).join("/"),s=rt(n[1]).join("/")===rt(r[1]).join("/"),i=Mo(n[0],r[0]),l=Mo(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(Gc,"allowanceWidens");function Bc(e){return JSON.stringify([un(e.from.trim().replace(/\\/g,"/")).toLowerCase(),un(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Bc,"aliasEntryKey");function Fo(e){return G((e.childSlices?.sliceAliases??[]).map(Bc))}a(Fo,"sliceAliasKeys");function zc(e,t,n,r){let o=Fo(n),s=Fo(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(u=>!o.includes(u)),l=o.filter(u=>!s.includes(u)),c=i.length>0&&l.length>0;C(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(zc,"compareSliceAliases");function Wc(e,t,n,r){let o=Do(n),s=Do(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(u=>!i.some(p=>Gc(p,u))).length===0){C(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:o,after:s});return}br(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(Wc,"compareChildCrossSliceAllowances");function br(e,t,n,r,o,s,i){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;C(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(br,"compareDeclaredExceptions");function qc(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&&C(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"])Tt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(qc,"compareSafety");function Sr(e){return e.mode==="enforced"?"enforced":"advisory"}a(Sr,"arkRunMode");function Ir(e){return e.mode==="enforced"?"enforced":"advisory"}a(Ir,"arkOrderMode");function Yc(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){C(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Ir(o)}).`,after:o});return}if(r&&!o){C(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Ir(r),l=Ir(o);if(i!==l){let c=i==="advisory"&&l==="enforced";C(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}he(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."}),he(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(Yc,"compareArkOrder");function Jc(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){C(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Sr(o)}).`,after:o});return}if(r&&!o){C(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Sr(r),l=Sr(o);if(i!==l){let c=i==="advisory"&&l==="enforced";C(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}he(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."}),he(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."}),Tt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Jc,"compareArkRun");function Xc(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(Xc,"overallClassification");function $o(e,t){return`${e}::${t}`}a($o,"ruleKey");function Ho(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set($o(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set($o(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Ho,"indexEffectiveRules");function Zc(e,t,n,r,o,s){let i=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 g=l[f],d=c[f],h=`$.arkRules[${f}]`;if(g===void 0&&d!==void 0){C(e,{kind:"arkrules-ref-added",path:h,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(g!==void 0&&d===void 0){C(e,{kind:"arkrules-ref-removed",path:h,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:g});continue}g!==d&&C(e,{kind:"arkrules-ref-path-changed",path:h,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:g,after:d})}let p=Ho(r),m=Ho(o);for(let f of[...new Set([...p.structure.keys(),...m.structure.keys()])].sort()){let g=p.structure.get(f),d=m.structure.get(f),h=`$.arkRules.structure[${f}]`;if(!g&&d){C(e,{kind:"arkrule-structure-added",path:h,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){C(e,{kind:"arkrule-structure-removed",path:h,classification:"weakening",message:`Structure ArkRule ${g.id} was removed.`,before:g});continue}if(!(!g||!d)){if(g.mode!==d.mode){let E=g.mode==="advisory"&&d.mode==="enforced";C(e,{kind:E?"arkrule-promoted":"arkrule-demoted",path:`${h}.mode`,classification:E?"strengthening":"weakening",message:E?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}g.sensor!==d.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${h}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:g.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...m.invariants.keys()])].sort()){let g=p.invariants.get(f),d=m.invariants.get(f),h=`$.arkRules.invariants[${f}]`;if(!g&&d){C(e,{kind:"arkrule-invariant-added",path:h,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(g&&!d){C(e,{kind:"arkrule-invariant-removed",path:h,classification:"weakening",message:`Invariant ${g.id} was removed.`,before:g});continue}if(!(!g||!d)&&g.mode!==d.mode)if(g.mode==="advisory"&&d.mode==="enforced"){let _=i?.get(d.id),k=Ar(_);k.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${h}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:g.mode,after:d.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${h}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:g.mode,after:d.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${h}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:g.mode,after:d.mode})}}a(Zc,"compareArkRules");function Cr(e,t,n){let r=[];he(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),he(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."}),he(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."}),Tt(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";C(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)&&C(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}),Hc(r,e.layers,t.layers),jc(r,e.rules,t.rules),qc(r,e,t),Zc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Jc(r,e,t),Yc(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:vr,classification:Xc(r),findings:r}}a(Cr,"classifyArkPolicyDelta");function _r(e,t){if(!e||e.schemaVersion!==vr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=G(e.findingIds),r=G(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}a(_r,"policyDeltaAcknowledgementMatches");function un(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(un,"trimTrailingSlashes");function jo(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(jo,"sharedImportsSliceRank");function Qc(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(Qc,"sharedImportsSliceMessage");function je(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(je,"normalizePath");function Vo(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(Vo,"isIdentifierStart");function pn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(pn,"isIdentifierCharacter");function de(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(de,"skipWhitespace");function wt(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(wt,"readString");function ue(e,t,n){return e.startsWith(t,n)&&!pn(e[n-1])&&!pn(e[n+t.length])}a(ue,"isWordAt");function Ko(e,t){let n=de(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=de(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ue(e,"type",n))return!1;let o=de(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ue(e,"as",o)||!Vo(e[o]))return!1;for(n=o;n<e.length&&pn(e[n]);)n+=1;if(n=de(e,n),ue(e,"as",n)){if(n=de(e,n+2),!Vo(e[n]))return!1;for(;n<e.length&&pn(e[n]);)n+=1}r=!0}return!1}a(Ko,"bracedNamedBindingsAreTypeOnly");function ed(e,t){if(t=de(e,t+6),e[t]==="(")return wt(e,de(e,t+1));let n=!1;if(ue(e,"type",t)){let o=de(e,t+4);e[o]!==","&&!ue(e,"from",o)&&(n=!0)}else Ko(e,t)&&(n=!0);let r=Uo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(ed,"specifierAfterImport");function td(e,t){t=t+6;let n=de(e,t),r=!1;if(ue(e,"type",n)){let s=de(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Ko(e,n)&&(r=!0);let o=Uo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(td,"specifierAfterExport");function Uo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ue(e,"from",t))return wt(e,de(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return wt(e,t);if(t>0&&(ue(e,"import",t)||ue(e,"export",t)))return}}a(Uo,"specifierInStaticStatement");function nd(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(nd,"skipTemplateLiteral");function rd(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=de(e,t+7);if(e[r]!=="(")return;r=de(e,r+1);let o=wt(e,r);return o?{...o,requireCall:!0}:void 0}a(rd,"specifierAfterRequire");function sd(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=
|
|
17
|
-
`).length;r.push({file:e.path,symbol:s,capability:
|
|
18
|
-
`).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=od(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(Go,"moduleFactsFor");function od(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(od,"resolveSpecifier");function Bo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Fs(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}a(Bo,"violationsFor");var id={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 ad(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(ad,"hasActiveArkRules");function ld(e,t){return ad(e,t)?ee(K(fr({config:e,arkRules:t,warnings:[]}))):ee(K(pr(e)))}a(ld,"policyHashFor");function fn(e,t,n){let r=typeof e=="string"?or(e,t):rn(e,t),o=n?.arkRules??He();return{...r,arkRules:o,policyHash:ld(r.config,o)}}a(fn,"loadContract");function zo(e){let t=fn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=fn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Cr(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&&_r(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(zo,"analyzePolicyDelta");function Nt(e){let t=e.files.map(m=>{let f=je(m.path);return{path:f,content:m.content,contentHash:ee(m.content),layer:ge(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=Go(m,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=Bo(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(Ge(m))]));for(let m of o){let f=n.get(m.file)?.layer;if(!f)continue;let g=i.get(f),d=_e(m.symbol,g?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${m.symbol}" because it is the import form of forbidden global "${d}".`,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",u=c==="complete"?[]:[{...id}],p={schemaVersion:lr,policyHash:e.contract.policyHash,compilerOptionsHash:ee(K(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:u,valid:c==="complete"&&s.length===0,ir:p}}a(Nt,"analyzeProject");function gn(e){let t=new Map(e.files.map(n=>[je(n.path),n]));for(let n of e.changes){let r=je(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Nt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(gn,"analyzeChange");function Wo(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(Wo,"explainViolation");function xr(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 u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==c);u.length>1&&i.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(xr,"detectArchitectureCycles");function st(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let i=Oe(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let f=$s(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,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=i.sliceVerdict,m=p?ze({surface:"import",verdict:p,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.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}:{},...Ne(p),message:u?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...u?{failsStrict:!1,severity:"warning"}:{}})}t.push(...ud(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=xr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}a(st,"evaluateArchitectureGraph");var cd="CROSS_PARENT_VIA_SHARED",dd="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function qo(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&r.sharedImportsSlice==="deny-cross-parent")return r}a(qo,"denyingCrossParentRule");function Or(e,t,n,r){let o=Be(n,e,Hs(e,t,r)).universeId;return o?{kind:"slice",id:o}:mt(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Or,"placeFile");function ud(e){let t=e.rules??[];if(!t.some(s=>s.sharedImportsSlice==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=pd(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=qo(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Or(i,s.fromLayer,s.from,e.config.layers),c=Or(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared")continue;let u=[{file:s.to,path:[s.from,s.to]}],p=new Set([s.to]);for(;u.length>0;){let m=u.shift();if(!m)break;for(let f of n.get(m.file)??[]){let g=qo(t,f.fromLayer,f.toLayer);if(!g)continue;let d=Or(g,f.fromLayer,f.to,e.config.layers);if(d.kind==="shared"){if(p.has(f.to))continue;p.add(f.to),u.push({file:f.to,path:[...m.path,f.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase())continue;let h=[...m.path,f.to],E=`${s.from}\0${f.to}`,_={file:s.from,target:f.to,line:s.line,fromLayer:s.fromLayer,toLayer:f.toLayer,fromSlice:l.id,toSlice:d.id,path:h},k=r.get(E);(!k||h.length<k.path.length||h.length===k.path.length&&h.join("\0")<k.path.join("\0"))&&r.set(E,_)}}}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=ht(s.fromSlice),l=ht(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:cd,file:s.file,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.target,peerIsolation:!0,...i&&l?{universeFrom:i,universeTo:l}:{},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}. ${dd}`}})}a(ud,"crossParentViaSharedViolations");function pd(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(pd,"valueHop");function Yo(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(Yo,"structureFreezeTarget");var fd=["no-anemic-model"],ti=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Nr=new RegExp(`\\b(${ti.join("|")})\\b`),ni="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Lr=new RegExp(`\\bthis\\.${ni}\\.push\\s*\\(`),gd=new RegExp(`^this\\.${ni}\\s*=\\s*\\[\\s*\\]`),md=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,hd=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,ri="truncatedUntil";function Pr(){return`${ti.join(", ")}, or events-array .push(`}a(Pr,"expectedDomainInvariantWordsPhrase");function yd(e){return Nr.test(e)||Lr.test(e)}a(yd,"referencesGuardOrPublish");function Dr(e,t,n){let r=e.slice(t);if(gd.test(r))return!0;if(!md.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(Dr,"isIdiomaticEventsReset");function Ad(e,t){let n=new RegExp(hd.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!Dr(t,r.index,e))return!0;return!1}a(Ad,"methodAssignsThis");function Rd(e,t){return t==null||Object.defineProperty(e,ri,{value:t,enumerable:!1,configurable:!0}),e}a(Rd,"attachShapeTruncation");function wr(e){let t=Object.getOwnPropertyDescriptor(e,ri)?.value;return typeof t=="number"?t:void 0}a(wr,"shapeTruncatedUntil");function kd(e){let t=wr(e);return t==null?"":` shape analysed until character ${t}`}a(kd,"shapeTruncationSuffix");function Jo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Jo,"escapeGlobLiteral");function Sd(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+=Jo(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Jo(o)}return new RegExp(`^${n}$`)}a(Sd,"globToRegExp");function ot(e,t){return!t||t.length===0?!0:t.some(n=>Sd(n).test(e))}a(ot,"matchesAppliesTo");function si(e){return fd.includes(e)}a(si,"isTier2");function oi(e){return e.mode==="enforced"&&!si(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(oi,"severityFor");function Te(e,t,n,r=1){let{severity:o,failsStrict:s}=oi(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(Te,"baseViolation");function hn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(hn,"isInRuleLayer");function yn(e,t,n){return t.filter(r=>!(!r.exported||!ot(r.file,e.appliesTo)||!hn(r.file,e,n)))}a(yn,"shapesForRule");function Id(e,t,n){let r=[];for(let o of yn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Te(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(Id,"evaluateAggregatePrivateState");function Ed(e,t,n){let r=[];for(let o of yn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Te(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(Ed,"evaluateAlwaysValidFactory");function bd(e,t,n){let r=[],o=Pr();for(let s of yn(e,t,n)){let i=kd(s);wr(s)!=null&&r.push(Te(e,s.file,`Exported class ${s.className} shape analysed until character ${wr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(Te(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(bd,"evaluateDomainEventOnMutation");function vd(e,t){let n=[];for(let r of t.files)ot(r,e.appliesTo)&&hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Te(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(vd,"evaluateOrchestrationOnly");function Cd(e,t){let n=[];for(let r of t.files)ot(r,e.appliesTo)&&hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Te(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(Cd,"evaluateThinAdapter");function _d(e,t){let n=[];for(let r of t.files)ot(r,e.appliesTo)&&hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Te(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(_d,"evaluateWritesViaAggregate");function Od(e,t,n){let r=[];for(let o of yn(e,t,n))if(o.dataOnly===!0){let s=Te(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(Od,"evaluateNoAnemicModel");function Mr(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(...Id(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Ed(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...bd(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...vd(n,e));break;case"thin-adapter":t.push(...Cd(n,e));break;case"writes-via-aggregate":t.push(..._d(n,e));break;case"no-anemic-model":t.push(...Od(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(Mr,"evaluateArkRuleSensors");function Fr(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=>ot(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=oi(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=>ot(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(Fr,"collectEmptyAppliesToFindings");var Xo=64;function xd(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(xd,"stripTrailingDots");function Td(e){let t=e.trim(),n=t.length>Xo?t.slice(0,Xo):t;return xd(n)}a(Td,"normalizeIntentPrefix");function wd(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(wd,"layerNameLooksDomain");function Nd(e){return e.some(t=>{let n=Td(t);return n==="Domain"||n.startsWith("Domain.")})}a(Nd,"ownsDomainIntent");function Ld(e,t=[]){return wd(e)||Nd(t)}a(Ld,"isDomainRoleLayerName");function ii(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Ld(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=t.find(c=>e.arkRules.byLayer?.[c])??t[0],i=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!si(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(ii,"collectEmptyInvariantCatalogFindings");var Zo=/\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)/,Qo=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Pd=/\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 Dd(e){return e==="PersistenceAdapters"}a(Dd,"isPersistenceDriverLayer");function Md(e,t){if(Zo.test(e)||Qo.test(e))return!0;if(!t)return!1;for(let n of t){if(Dd(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Zo.test(o)||Qo.test(o))return!0}return!1}a(Md,"sourceImportsPersistenceDriver");var Fd=/\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*=)/,$d=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Hd=/\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*=/,jd=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function ai(e,t,n){if(!t)return null;let r=Md(t,n),o=r&&Pd.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Hd.source,"g"))??[],i=t.match(new RegExp(jd.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,p=Fd.test(t)||$d.test(t),m=s.length>=1||i.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=r&&m||p&&m||r&&f&&(l>=4||s.length>=1)||p&&r;return!u&&!g&&!o?null:{...u?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(ai,"deriveArkRuleFileHints");function $r(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=ai(r,o,t?.[s]);i&&(n[s]=i)}return n}a($r,"buildArkRuleFileHints");var Vd=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Kd=new Set(["if","match","when"]);function mn(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}a(mn,"skipStringOrComment");function Lt(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=mn(e,n);continue}break}return n}a(Lt,"skipWsAndComments");function ei(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(ei,"readIdent");function Tr(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=mn(e,s);if(i!==s){s=i;continue}let l=e[s];l===n?o+=1:l===r&&(o-=1),s+=1}return o===0?s:null}a(Tr,"skipBalanced");function Ud(e){let t=[],n=0,r;for(;n<e.length&&(n=Lt(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=ei(e,s);if(!p||!Vd.has(p.ident))break;o.push(p.ident),s=Lt(e,p.end)}let i=ei(e,s);if(!i){n+=1;continue}if(s=Lt(e,i.end),e[s]==="<"){let p=Tr(e,s,"<",">");if(p==null){r=e.length;break}s=Lt(e,p)}if(e[s]==="("){let p=Tr(e,s,"(",")");if(p==null){r=e.length;break}if(s=Lt(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let m=mn(e,s);if(m!==s){s=m;continue}s+=1}if(e[s]==="{"){let m=Tr(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,u=0;for(;s<e.length;){let p=mn(e,s);if(p!==s){s=p;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==="[")u+=1;else if(m==="]")u-=1;else if(m===";"&&l===0&&c===0&&u===0){s+=1;break}s+=1}t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(Ud,"scanClassMembers");function Gd(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],i=o.index+o[0].length,l=1,c=i;for(;c<t.length&&l>0;){let S=t[c];S==="{"?l+=1:S==="}"&&(l-=1),c+=1}let u=t.slice(i,c-1),p=l>0,m=Ud(u),f=p?t.length:m.truncatedAt==null?void 0:i+m.truncatedAt,g=m.members.filter(S=>!(S.kind!=="field"||S.name==="constructor"||S.modifiers.includes("private")||S.modifiers.includes("protected")||S.modifiers.includes("readonly")||S.modifiers.includes("static")||S.modifiers.includes("get")||S.modifiers.includes("set"))),d=g.length>0,h=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),E=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),_=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!E,k=/(?:^|[\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),b=[];for(let S of m.members)S.kind==="method"&&S.name!=="constructor"&&(S.modifiers.includes("static")||S.modifiers.includes("get")||S.modifiers.includes("set")||Kd.has(S.name)||Ad(S.name,S.body)&&b.push({name:S.name,referencesGuardOrPublish:yd(S.body)}));let D=m.members.filter(S=>S.kind==="method").length<=1&&g.length>=2&&d;n.push(Rd({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:h,hasPublicConstructor:_,hasStaticFactory:k,mutatingMethods:[...b],dataOnly:D},f))}return n}a(Gd,"extractClassShapesFromSource");var Bd=50;function Hr(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(Hr,"normalizeExtraMergeTeethClassification");function ke(e){let t=Hr(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 jr(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(jr,"classifyResolvedLayerCoverage");function Vr(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}a(Vr,"isArkRunRuleId");function li(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}a(li,"isArkOrderRuleId");function ci(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(ci,"isExtraPlaneFinding");function zd(e,t={}){if(!Array.isArray(e)||ke(t))return e;for(let n of e)ci(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}a(zd,"demoteExtraPlaneTeethUnderClassificationFloor");var di="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 Re(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}a(Re,"countOrZero");function An(e={}){let t=Hr(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=Re(i?.structureEnforced),c=Re(i?.structureTotal),u=typeof i?.structureAdvisory=="number"?Re(i.structureAdvisory):Math.max(0,c-l),p=Re(i?.invariantEnforced),m=Re(i?.invariantTotal),f=typeof i?.invariantAdvisory=="number"?Re(i.invariantAdvisory):Math.max(0,m-p),g=l>0||p>0,d=e.arkRun?.present===!0,h=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,E=Re(e.arkRun?.residualCount),_=d&&h==="enforced",k=_&&s,b=e.arkOrder?.present===!0,O=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,D=Re(e.arkOrder?.residualCount),S=b&&O==="enforced",L=S&&s,j=g||_||S,T=j&&s,M=j&&o&&!s,P;if(T){let z=[];g&&z.push("enforced structure/invariant findings"),_&&z.push("enforced ArkRun skip findings"),S&&z.push("enforced ArkOrder skip findings"),P=`Layer graph failures plus ${z.join(" and ")} (advisory extras never fail merge alone).`}else if(M)P=`Layer graph only \u2014 enforced ${[g?"ArkRules structure/invariant":null,_?"ArkRun":null,S?"ArkOrder":null].filter(fe=>!!fe).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 z=d?h==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",fe=b?O==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";P="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+z+fe}let V={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:m,enforced:p,advisory:f,covered:Re(i?.covered),uncovered:Re(i?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:d,mode:h,residualCount:E,extraMergeTeeth:k,note:d?h==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},arkOrder:{role:"pattern-slaving",present:b,mode:O,residualCount:D,extraMergeTeeth:L,note:b?O==="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:T,dualPlaneStamp:di,failMergeWhen:P};return o&&(V.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),V}a(An,"composeMergePlanesHonesty");var pi=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],Wd=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],qd=new Set(pi),Yd=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"]),Jd=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function Mt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(Mt,"isArkRunKernelModuleSpecifier");var fi=["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"],Kr=new Set(fi);function Gr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Kr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Kr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Kr.has(e.slice(0,r))}a(Gr,"isArkRunTransportBypassSpecifier");function Ur(e){if(qd.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(Ur,"arkRunKernelCallKind");function Dt(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}a(Dt,"lineAt");function Ft(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}a(Ft,"stripCommentsPreservingLines");function Xd(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(Xd,"firstStringLiteralArg");function ui(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(ui,"keywordBefore");function Rn(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(Rn,"parseValueImportClause");function Zd(e,t){Rn(Ft(e),t)}a(Zd,"forEachArkRunValueImportClause");function Br(e,t){let n=Ft(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:Dt(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:Dt(t,s.index),resolution:"resolved-external"})}return r}a(Br,"extractArkRunValueImportDependenciesFromSource");function zr(e){let t=[];return Zd(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)}}),Pt(t)}a(zr,"extractArkRunImportedConstructorNamesFromSource");function Qd(e){let t=new Map,n=new Set;return Rn(e,(r,o)=>{if(!Mt(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 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 m=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);m?.[1]&&t.set(m[1],m[1])}}),{named:t,namespaces:n}}a(Qd,"collectKernelImportBindings");function eu(e,t){let n=new Set(t);return Rn(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),u=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],p=c?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(Mt(o)||t.has(p)||t.has(u))&&(n.add(u),n.add(p))}}),n}a(eu,"collectImportedConstructors");function tu(e,t){let n;return Rn(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}a(tu,"importedFromForName");function Wr(e,t){let n=Ft(t),r=Qd(n),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,i;for(;(i=s.exec(n))!==null;){let l=i[1],c=i.index;if(ui(n,c,"function")||ui(n,c,"class"))continue;let p=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],m=r.named.get(l)??l,f=Ur(m)??Ur(l);if(!f)continue;let g=r.named.has(l)||p!==void 0&&r.namespaces.has(p);if(f!=="factory"&&(!g&&p===void 0||p&&Jd.has(p)&&!g))continue;let d=Xd(n,c+i[0].length);o.push({file:e,line:Dt(t,c),kind:f,callee:l,viaImport:g,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}a(Wr,"extractArkRunKernelCallsFromSource");function qr(e,t,n){let r=Ft(t),o=eu(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(Yd.has(c)||!o.has(c))continue;let u=tu(r,c);s.push({file:e,line:Dt(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return s}a(qr,"extractArkRunManagedNewsFromSource");function nu(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(nu,"matchingBracketEnd");function ru(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(ru,"stringLiteralsInList");function Pt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(Pt,"uniqueSorted");function su(e,t){let n=Ft(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],i=[],l=[],c,u;for(;(u=r.exec(n))!==null;){let p=n.slice(u.index+u[0].length),m=/^\s*\[/.exec(p);if(!m)continue;let f=u.index+u[0].length+(m[0].length-1),g=nu(n,f);if(g<0)continue;let d=ru(n,f,g);if(d.length===0)continue;c===void 0&&(c=u.index);let h=u[1];h==="uses"?o.push(...d):h==="reactsTo"?s.push(...d):h==="raises"?i.push(...d):l.push(...d)}return c===void 0?[]:[{file:e,line:Dt(t,c),uses:Pt(o),reactsTo:Pt(s),raises:Pt(i),sends:Pt(l)}]}a(su,"extractArkRunDeclarationsFromSource");var ou=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],iu=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],au=new Set(iu);function lu(e){return au.has(e)}a(lu,"isArkRunEditorSensor");var Yr={"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"},hi="ARKRUN_INTERACTION_NAME_INCOMPLETE";function yi(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(yi,"isDomainRoleLayer");function cu(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(cu,"compareFindings");function ve(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Yr[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:Yr[t],fromLayer:s?.fromLayer,target:s?.target})}}a(ve,"finding");function du(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(du,"bagForFile");function gi(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(gi,"emitKinds");function mi(e){return e==="subscribe"||e==="register-handler"}a(mi,"handleKinds");function uu(e){return e==="resolve"||e==="resolve-singleton"}a(uu,"dependKinds");function pu(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ve(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(l.length===0){r.push(ve(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(ve(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(pu,"evaluateMissingRoot");function fu(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||!Mt(c))continue;let u=r(l.from);u&&yi(u,s.get(u)??[])&&i.push(ve(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return i}a(fu,"evaluateKernelInDomain");function gu(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),c=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(c.has(p.file))continue;let m=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(m.endsWith("Error")||m==="Error")||m.endsWith("DTO")||m.endsWith("VO"))continue;let f=o(p.file);!f||!i.has(f)||yi(f,l.get(f)??[])||u.push(ve(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}a(gu,"evaluateDirectNew");function mu(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(!gi(c.kind)&&!mi(c.kind)&&!uu(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:hi,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=du(n,c.file);if(gi(c.kind)){if(p.raises.has(c.nameLiteral)||p.sends.has(c.nameLiteral))continue;s.push(ve(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(mi(c.kind)){if(p.reactsTo.has(c.nameLiteral))continue;s.push(ve(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(ve(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(mu,"evaluateUndeclared");function hu(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||!Gr(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(ve(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(hu,"evaluateTransportBypass");function kn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=ke(e.classification),r=mu(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...pu(t,e.compositionRootHits,n),...fu(t,e.layers,e.dependencies,e.layerForFile,n),...gu(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...hu(t,e.dependencies,e.layerForFile,n)].sort(cu),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}a(kn,"evaluateArkRunSensors");function Ai(e){return{findings:kn(e).findings.filter(n=>lu(n.sensor)),completenessReasons:[]}}a(Ai,"evaluateArkRunEditorSensors");function yu(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(yu,"fileMatchesCompositionRoot");function Au(e,t,n){let r=Wr(t,n).some(i=>i.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let i of s)yu(i,t)&&o.push({file:t,matchedRoot:i,hasKernelFactory:r});return o}a(Au,"compositionRootHitsForSource");function Ru(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(zr(e.source));return Ai({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:qr(e.file,e.source,n),compositionRootHits:Au(t,e.file,e.source),declarations:[],dependencies:Br(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}a(Ru,"evaluateArkRunEditorSensorsFromSource");function Ri(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Ri,"isArkOrderModuleSpecifier");var ki=new Map;function Si(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Si,"escapeAppliesToLiteral");function ku(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(ku,"normalizeAppliesToGlob");function Su(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(Su,"appliesToBracesBalanced");function Iu(e){let t=ki.get(e);if(t)return t;let n=ku(e),r=Su(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Si(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+=Si(c)}let i=new RegExp(`^${o}$`);return ki.set(e,i),i}a(Iu,"globToRegExp");var Eu=["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"],Jr={"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 bu(e,t){return!t||t.length===0?!0:t.some(n=>Iu(n).test(e))}a(bu,"matchesArkOrderAppliesTo");function vu(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(vu,"isDomainRoleLayer");function we(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Jr[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:Jr[t],fromLayer:s?.fromLayer,target:s?.target})}}a(we,"finding");function Xr(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(we(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let 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(we(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(m=>m.hasPlaneFactory)||r.push(we(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||!Ri(u))continue;let p=e.layerForFile(c.from);p&&vu(p,s.get(p)??[])&&r.push(we(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(we(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(we(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(we(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||bu(c.file,t.appliesTo)&&r.push(we(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}a(Xr,"evaluateArkOrderSensors");function te(e,t,n={}){return{ruleId:e,message:t,...n}}a(te,"configWarning");function Sn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(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 h=t.safety[d];h!==void 0&&(!Number.isInteger(h)||h<0)&&s.push(te("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);i.length===0&&s.push(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 i){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(E=>typeof E!="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 h=Array.isArray(d.patterns)?d.patterns:[];if(h.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 E of h){let _;try{_=Ae(E)}catch(b){s.push(te("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${E}": ${b instanceof Error?b.message:String(b)}`,{layer:d.name,pattern:E}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(b=>_.test(b))&&!k&&s.push(te("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${E}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:E,failsStrict:!1,reserved:!1}))}}for(let d of 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 m=new Set;if(i.length>1)for(let d of r){let h=-1,E=[];for(let _ of i)for(let k of _.patterns??[]){if(!Ae(k).test(d))continue;let b=Gn(k,d);b>h?(h=b,E=[_.name]):b===h&&!E.includes(_.name)&&E.push(_.name)}E.length>1&&m.add([...E].sort().join(" + "))}m.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: ${[...m].join(", ")}.`,{pairs:[...m]}));let f=r.filter(d=>!ge(d,i));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 Ls(n))s.push(te("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));for(let d of Ms(n,r))s.push(te(d.ruleId,d.message,{failsStrict:!1,...d.path?{file:d.path}:{},...d.fromLayer?{fromLayer:d.fromLayer}:{},...d.toLayer?{toLayer:d.toLayer}:{}}));let g=lo(t);if(g.length>0){let d=g[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:g,nextAction:co(d)}))}return s}a(Sn,"collectAnalysisConfigWarnings");function Ii(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:Yo({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(Ii,"toArkRuleEngineViolation");function Cu(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Cu,"arkRulesMapIsOn");function Ei(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(Ei,"arkRuleFindingNextAction");function _u(e,t){return t.some(n=>{try{return Ae(n).test(e)}catch{return!1}})}a(_u,"matchesAny");function Ou(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(h=>h.kind==="ts-suppression").map(({file:h,line:E})=>({file:h,line:E})),l=t.safetyUses.filter(h=>h.kind==="any-cast").map(({file:h,line:E})=>({file:h,line:E})),c=t.safetyUses.filter(h=>(h.kind==="dynamic-import"||h.kind==="dynamic-require")&&!_u(h.file,s)).map(h=>({file:h.file,line:h.line,kind:h.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(h=>h.kind==="in-memory-store").map(h=>({file:h.file,line:h.line,store:h.symbol??"in-memory store"})),p=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(h=>h.peerIsolation===!1||h.allowed===!1&&!!h.from&&h.from===h.to&&h.peerIsolation!==!0).map(h=>({from:h.from,to:h.to})),m={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],g=c.filter(h=>h.kind==="import");if(g.length>0){let h=g[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${g.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(h=>h.kind==="require");if(d.length>0){let h=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let h=i[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let h=l[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let h=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:h.file,line:h.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:m,warnings:f}}a(Ou,"evaluateSafety");function xu(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(xu,"ambientForbiddenGlobal");function bi(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Zn(e,n.length>0?n:Xn.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(bi,"intentLayer");function Tu(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||!xu(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&>(s.symbol,c))){if(s.source==="import-based"){let p=_e(s.symbol,c);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...u?{edgeKind:u}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}Ge(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of At({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=bi(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=bi(s.intent,e.contract);if(!l)continue;let c=Oe(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.sliceVerdict,p=`${i} must not reference ${l} intent ${s.intent}.`,m=u?ze({surface:"intent",verdict:u,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,defaultMessage:p}):c.rule.message??p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},...Ne(u),message:m})}return r}a(Tu,"contentViolations");function wu(e){let{facts:t}=e,n=vt(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,ie)=>{let ct=`${A.code}\0${A.file??""}\0${A.message}`,dt=`${ie.code}\0${ie.file??""}\0${ie.message}`;return ct<dt?-1:ct>dt?1:0}),i=t.files.map(A=>({...A,layer:ge(A.path,e.contract.config.layers)??null})),l=new Map(i.map(A=>[A.path,A.layer])),c=t.dependencies.map(A=>{let ie=A.target?l.get(A.target)??ge(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,...ie?{toLayer:ie}:{}}:{},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=Sn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(A=>A.path)}),p=Ou(e,t),m=e.contract.arkRules??He(),f=i.map(A=>A.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?$r(e.coverageInputs.fileContents):{},...e.fileHints??{}},h=a(A=>l.get(A)??ge(A,e.contract.config.layers),"resolveLayer"),E=[...Mr({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:h,fileHints:d}),...Fr(m,f),...ii({arkRulesActive:Cu(e.contract.config),arkRules:m,layers:e.contract.config.layers??[],files:f.map(A=>({path:A,layer:h(A)}))})],_=(m.invariants?.length??0)>0,k=No({hasEnforcedInvariant:kr(m.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),b=k.length>0?[]:wo({adopted:e.adopted===!0,hasDomainInvariants:Rr(m.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),O=[...k.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})),...b.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=E.filter(A=>A.failsStrict).map(A=>Ii(A,Ei(A,!1))),S=E.filter(A=>!A.failsStrict).map(A=>({...Ii(A,Ei(A,!0)),failsStrict:!1})),L=_?yr({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},j=L.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.`})),T=L.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).`})),M=jr(i),P=kn({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(A=>l.get(A)??ge(A,e.contract.config.layers),"layerForFile"),classification:M}),V=e.contract.config.arkRun?.mode,z=P.findings.filter(()=>V==="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}:{}})),fe=P.findings.filter(()=>V!=="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})),Se=Xr({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:a(A=>l.get(A)??ge(A,e.contract.config.layers),"layerForFile"),classification:M}),lt=e.contract.config.arkOrder?.mode,Ut=Se.findings.filter(()=>lt==="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}:{}})),Rs=Se.findings.filter(()=>lt!=="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=[...L.partial&&L.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."}]:[],...P.completenessReasons,...Se.completenessReasons],x=st({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(A=>A.layer).map(A=>A.path),contentViolations:[...Tu(e,t,l),...D,...O,...j,...z,...Ut],edges:c,warnings:[...u,...p.warnings,...S,...T,...fe,...Rs],safety:p.report}),y=o==="complete"&&v.length>0?"partial":o,R=y==="complete"?s:[...s,...v].sort((A,ie)=>{let ct=`${A.code}\0${A.file??""}\0${A.message}`,dt=`${ie.code}\0${ie.file??""}\0${ie.message}`;return ct<dt?-1:ct>dt?1:0}),F=x.violations.filter(A=>A.failsStrict!==!1),Q=y==="complete"&&F.length===0,Ce=Q&&x.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:y,completenessReasons:R,valid:Q,strictValid:Ce,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(A=>A.name),edges:c,capabilityUses:t.capabilityUses,violations:x.violations,warnings:x.warnings}}}a(wu,"analyzeCanonicalResolvedProject");function $t(e){return wu({contract:e.contract,facts:xe(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}a($t,"analyzeResolvedProject");function vi(e){return ee(K(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(vi,"analysisTreeHash");function Ci(e){let t=Nt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let h=d.path.replace(/\\/g,"/"),E=je(d.path);if(!E||E===".."||E.startsWith("../")||h.startsWith("/")||/^[A-Za-z]:\//.test(h)||h.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(E)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:E,line:1,message:`The atomic change set contains more than one operation for ${E}.`});continue}o.add(E),"delete"in d&&d.delete&&!n.has(E)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:E,line:1,message:`Cannot delete ${E} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:E,delete:!0}:{path:E,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=gn({...e,changes:r}),l=new Map(i.ir.files.map(d=>[d.path,d])),c=i.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let h=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}:{},...h?{fromLayer:h}:{},edgeKind:"import",message:d.message}}),u=st({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(d=>d.path),contentViolations:c,edges:i.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(d=>{let h=je(d.path),E=n.get(h),_=l.get(h);return{path:h,operation:"delete"in d&&d.delete?"delete":E?"update":"create",...E?{beforeContentHash:E.contentHash}:{},..._?{candidateContentHash:_.contentHash}:{}}}).sort((d,h)=>d.path.localeCompare(h.path)),m=[...s,...u.violations].map(d=>({...d,nextAction:ye(d)})),f=m.filter(d=>d.failsStrict!==!1),g=e.changeMap?tt({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:i.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&f.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:vi(t.ir.files),candidateTreeHash:vi(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:p,violations:m,warnings:u.warnings}}a(Ci,"preflightChange");function Nu(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(Nu,"canonicalChangePath");function Lu(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(Lu,"identityViolations");function Pu(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(Pu,"preparedChange");function _i(e){let t=xe(e.baseFacts),n=xe(e.candidateFacts),r=$t({contract:e.contract,facts:t}),o=$t({contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),i=new Map(n.files.map(g=>[g.path,g])),l=Lu(t,n),c=new Map,u=[];for(let g of e.changes){let d=Nu(g.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,g);let h=s.get(d),E=i.get(d);if("delete"in g&&g.delete)h||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let _="content"in g?g.content:"",k=ee(_);E?E.contentHash!==k&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:E.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(Pu(g,d,s,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let g of new Set([...s.keys(),...i.keys()])){if(c.has(g))continue;let d=s.get(g),h=i.get(g);d&&h&&K(d)===K(h)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:g,line:1,message:`Candidate facts change ${g}, but the atomic change set does not declare it.`})}let p=e.changeMap?tt({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[]),candidateDependencies:o.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[])}):void 0,m=[...l,...o.ir.violations].map(g=>({...g,nextAction:ye(g)})),f=m.filter(g=>g.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((g,d)=>g.path<d.path?-1:g.path>d.path?1:0),violations:m,warnings:o.ir.warnings}}a(_i,"preflightResolvedChange");var Oi="1.0",Du=12,Mu="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",Fu="Next: /ark-runtime to wire one candidate.";function xi(e){return e==="enforced"||e==="advisory"?e:null}a(xi,"closedMode");function $u(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Vr(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}a($u,"uniqueArkRunRuleIds");function Hu(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:xi(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(Hu,"extraFromConfig");function ju(e={}){let t=Hu(e.arkRun),n=t.present?$u(e.findings):[],r=n.slice(0,Du),o=n.length,s=An({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}}),i=t.present&&t.mode==="enforced"&&ke(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.":i?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:Oi,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:r},extraMergeTeeth:i,failMergeWhen:s.failMergeWhen,note:l,mergePlanes:s}}a(ju,"summarizeArkRunSection");function Zr(e={}){let t=e.present===!0,n=xi(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(Zr,"projectStatusArkRun");function Vu(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=[Mu,`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(Fu)}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}a(Vu,"formatArkRunDoctorLines");function In(e,t){return e.slice(0,t).split(`
|
|
20
|
-
`).length}a(In,"lineOf");function Ti(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Ti,"normalizeInventoryPath");function Ni(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}a(Ni,"ownsIntent");function wi(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Ni(t,["Domain"])}a(wi,"isDomainLayer");function Ku(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Ni(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}a(Ku,"isControllerEligibleLayer");function Uu(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(Uu,"isNonPilotSurface");function Gu(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[Ti(c),u])),o=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),s=(e.layerContexts??[]).find(c=>wi(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([p],[m])=>p.localeCompare(m))){let p=Ti(c);if(Uu(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let m=r.has(p),f=r.get(p),g=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),h=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),E=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),_=/controller|handler|resolver/i.test(c)||h||E||/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),k=m?!!(f&&Ku(f,g)&&_):_,b=m?!!(f&&wi(f,g)):/domain|entity|aggregate|model/i.test(c),O=!m||b||k;if(k&&!d){let T=/\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,M;for(;(M=T.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:In(u,M.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,S,L=a(T=>/^(?: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(T)||/^(?: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(T)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(T)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(T)||/^(?: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(T)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(T)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(T)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(T)||/_(?:OID|OIDS)$/i.test(T)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(T)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(T),"isInfraMagicName"),j=a((T,M)=>{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(T)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(T))return!0;let P=M.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(M)&&(/\s/.test(P)||/[.!?…]$/.test(P))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(S=D.exec(u))!==null;){let T=S[2],M=S[3]??"";!O||L(T)||j(T,M)||d&&!b||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!b||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:In(u,S.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(b){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,M;for(;(M=T.exec(u))!==null;){let P=M[2]??"",V=(P.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(P.match(/:\s*[A-Za-z]/g)??[]).length>=2&&V<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:In(u,M.index),message:`Class ${M[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(b&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let M=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,P;for(;(P=M.exec(u))!==null;){let V=u.lastIndexOf("class ",P.index),z=V>=0?u.indexOf("{",V):-1,fe=V>=0&&z>=V&&z<P.index?u.slice(V,z):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(fe)||Dr(u,P.index))continue;let Se=u.slice(Math.max(0,P.index-200),P.index+200);if(!Nr.test(Se)&&!Lr.test(Se)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:In(u,P.index),message:`Domain field mutation without nearby ${Pr()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let i=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&&i.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&i.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}a(Gu,"buildRulesInventory");function Bu(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(Bu,"inventoryToExtractionCard");var zu="1.1";var Wu="1.0";var Qr="docs/diagnostics.md",qu="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 En=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("CONFIG_CHILD_SLICES_VERSION","config","childSlices needs a newer arkgate","The rule schema sets additionalProperties to false. arkgate 4.8.22 and older reject a config that contains childSlices instead of ignoring the key.","Pin arkgate newer than 4.8.22 before shipping a config that sets childSlices. 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("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.")]),es=new Map(En.map(e=>[e.ruleId,e])),Yu=Object.freeze(En.map(e=>e.ruleId));function Ju(e){return typeof e=="string"&&e.length>0&&es.has(e)}a(Ju,"isKnownDiagnosticCode");function Xu(e){return typeof e!="string"||e.length===0?!1:es.has(e)?!0:e.startsWith("ARKRULE_")}a(Xu,"isCataloguedOrArkRuleFamily");function bn(e){if(!(typeof e!="string"||e.length===0))return es.get(e)}a(bn,"getDiagnosticCatalogEntry");function Li(e){return`#${bn(e)?.docsAnchor??e}`}a(Li,"diagnosticDocsFragment");function Zu(e){return`${Qr}${Li(e)}`}a(Zu,"diagnosticDocsPath");function Qu(){return{schemaVersion:"1.0",docsPath:Qr,codes:En}}a(Qu,"serializeDiagnosticCatalog");function ep(e){return bn(e)?.fix}a(ep,"catalogFixForRuleId");function tp(e){return bn(e)?.why}a(tp,"catalogWhyForRuleId");var np=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. An enforce list makes those importer subtrees errors. Other sibling crossings stay warnings, and a new one past the baseline still fails."}),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."})]),qm=new Map(np.map(e=>[e.reasonId,e]));function rp(e){return e==="enforced"||e==="advisory"?e:null}a(rp,"closedMode");function Pi(e={}){let t=e.present===!0,n=rp(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(Pi,"projectStatusArkOrder");var ts="1.0",Di="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Mi=["full","subset","unavailable"],Fi=["doctor-facts","report-snapshot","none"],vn={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},$i=/^sha256:[a-f0-9]{64}$/;function Hi(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"||!$i.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(Hi,"evaluateStatusBinding");function ji(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(ji,"classifyStatusWritePath");function Vi(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(Vi,"defaultHonestLabel");function Ki(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."}}a(Ki,"resolveStatusNextAction");function sp(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&$i.test(e.projectId)?e.projectId:null,r=Hi({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=ji({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Vi(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:Ht(e.activeViolations),frozenResidual:Ht(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ht(e.rulesInventoried),underContract:Ht(e.rulesUnderContract),frozenResidual:Ht(e.rulesFrozenResidual)},p={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:ts,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:p,lastCheck:c,rules:u,nextAction:Ki(e,r,p,c,u)},g=Gi(e.improvementCompass);return g&&(f.improvementCompass=g),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Zr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=Pi(e.arkOrder)),f}a(sp,"buildStatusManifest");var Ui=new Set(Mi),op=new Set(Fi);function ns(e){let t=Ui.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&op.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:vn.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:vn.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(ns,"projectStatusImprovementCompass");function ip(e={}){return ns({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??vn.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})}a(ip,"unavailableStatusImprovementCompass");function Gi(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"&&Ui.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",ns({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(Gi,"normalizeStatusImprovementCompass");function ap(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(ap,"statusCompassResidualIsSubsetOfDoctor");function Ht(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}a(Ht,"numberOrNull");var lp={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Di,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:ts},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 Cn="1.0",_n=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],On=5,Ve=["scalability","resilience","security"],it=new Set(Ve),rs={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},ss={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"},os={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 is(e){return ss[e]??e}a(is,"improvementCompassHumanLabel");function as(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}a(as,"smellIdOf");function ls(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}a(ls,"violationRuleId");function B(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(B,"pushEvidence");function oe(e,t,n){it.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}a(oe,"markResidual");function Bi(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`${ss[e]} \u2014 no residual from current sensors.`}}a(Bi,"defaultOkSummary");function zi(){return _n.map(e=>it.has(e)?{id:e,status:"out-of-scope",summary:os[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:Bi(e),evidence:[]}:{id:e,status:"ok",summary:Bi(e),evidence:[]})}a(zi,"createInitialImprovementCompassLenses");function cp(e,t){for(let n of t){let r=as(n);if(!r)continue;let o=n.outcome||n.message||void 0,i=(Array.isArray(n.evidence)?n.evidence:[])[0],l=a((p,m,f)=>{let g=e.get(p);!g||it.has(p)||(B(g,"designSmells",r,o),i&&B(g,"designSmells",i,r),oe(g,m,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}}}a(cp,"mapDesignSmells");function dp(e){return e.failsStrict===!1||e.typeOnly===!0}a(dp,"isTypeOnlyPlacementDebt");function up(e,t){for(let n of t){let r=ls(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),i=a((c,u,p)=>{let m=e.get(c);!m||it.has(c)||(B(m,"violations",r,o),n.file&&B(m,"violations",n.file,r),oe(m,u,p))},"attach");if(dp(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(up,"mapViolations");function pp(e,t){let n=Number(t.cycleCount)||0;if(n>0){let g=e.get("coupling");B(g,"cycles",`count:${n}`),oe(g,"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 g=e.get("coupling");B(g,"peerIsolation",`count:${r}`),oe(g,"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 g=e.get("cohesion");B(g,"physicalCohesion",`findings:${o}`),oe(g,"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");B(d,"physicalCohesion",`findings:${o}`),oe(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,i=Number(t.forbiddenGlobalResidual)||0;if(s>0||i>0){let g=e.get("dip");s>0&&B(g,"capability",`residual:${s}`),i>0&&B(g,"forbiddenGlobals",`residual:${i}`),oe(g,"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&&B(d,"capability",`residual:${s}`),i>0&&B(d,"forbiddenGlobals",`residual:${i}`),oe(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 g=e.get("encapsulation");B(g,"arkRules",`structureResidual:${l}`),oe(g,"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");B(d,"arkRules",`structureResidual:${l}`),oe(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 g=e.get("maintainability");B(g,"designFitness","design-weak"),oe(g,"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 g=e.get("maintainability");t.dirtyBaselineRisk===!0&&B(g,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&B(g,"baseline",`stale:${t.baselineStale}`),oe(g,"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 g=e.get("maintainability");B(g,"baseline",`frozen:${c}`),oe(g,"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 g=e.get("modularity");u>0&&B(g,"coverage",`ungovernedDirs:${u}`),p>0&&B(g,"coverage",`emptyLayers:${p}`),oe(g,"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 g=e.get("modularity");B(g,"goldenPattern","absent"),oe(g,"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(pp,"mapCountsAndFlags");function Wi(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>as(r).localeCompare(as(o)));cp(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=ls(r).localeCompare(ls(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});up(e,n)}pp(e,t)}a(Wi,"projectImprovementCompassFacts");function qi(e){for(let t of Ve){let n=e.get(t);n.status="out-of-scope",n.summary=os[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(qi,"lockImprovementCompassOutOfScope");function Yi(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(Yi,"sortImprovementCompassEvidence");function Ji(e){return e.filter(n=>n.status==="residual"&&!it.has(n.id)).slice().sort((n,r)=>{let o=rs[n.id]??150,s=rs[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}a(Ji,"finalizeImprovementCompassTopResidual");function fp(e={}){let t=zi(),n=new Map(t.map(o=>[o.id,o]));Wi(n,e),qi(n),Yi(t);let r=Ji(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(fp,"buildImprovementCompass");function Xi(e){return e.topResidual.map(t=>is(t))}a(Xi,"formatImprovementCompassResidualLabels");function Zi(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(Zi,"primaryImprovementCompassNextAction");function gp(e){let t=Xi(e),n=Ve.map(s=>is(s)),r=Zi(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(gp,"formatImprovementCompassDoctorLines");var Ke="1.0",Qi="<!-- arkgate:agent-projection:begin",xn="<!-- arkgate:agent-projection:end -->",Tn="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",jt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ea=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 at(e){let t=String(e??"").replace(/\r\n/g,`
|
|
21
|
-
`)
|
|
22
|
-
`)}a(Vt,"normalizeNewlines");function Ue(e){let t=Vt(e);return t.endsWith(`
|
|
16
|
+
`,t);return e.slice(n,r===-1?e.length:r)}a(Lu,"lineAt");function $u(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a($u,"isImportLine");function Ni(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($u(Lu(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;o<s;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(;o<s&&e[o]!==`
|
|
17
|
+
`;)i(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(i(o,"comment"),i(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)i(o,"comment"),o+=1;o<s&&(i(o,"comment"),i(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let d=l;for(i(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===d){i(o,"string"),o+=1;break}i(o,"string"),o+=1}continue}i(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(Ni,"mentionContext");function Fi(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(Fi,"symbolNeedle");function Du(e){return Fi(e.coverage?.symbol)?.name??e.id}a(Du,"declaredLabel");function Li(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Li,"sortedContentFiles");function Mi(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(m=>ft(m))),s=(t.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),i=e.coverage?.test!==!1&&n,l=Fi(e.coverage?.symbol??void 0),c,d;if(i){for(let m of r){let u=t.fileContents[m];if(!u)continue;let h=Pu(u,e.id);if(h!==void 0){if(s.length===0||$i(m,s)){c={file:m,title:h};break}d??={file:m,title:h}}}c??=d}let p;if(l)for(let m of Li(t.fileContents)){if(o.has(ft(m)))continue;let u=t.fileContents[m];if(!u)continue;let h=l.className?Nu(u,l.className,l.name):Di(u,l.name);if(h){p={file:m,shape:h};break}}let g;if(!c&&!p){if(i)for(let m of r){let u=t.fileContents[m];if(!u)continue;let h=Ni(u,e.id,!0);if(h){g={file:m,context:h};break}}if(!g&&l)for(let m of Li(t.fileContents)){if(o.has(ft(m)))continue;let u=t.fileContents[m];if(!u)continue;let h=Ni(u,l.name,!1);if(h){g={file:m,context:h};break}}}let f=c?{kind:"test-title",file:c.file,title:c.title}:p?{kind:"declaration",file:p.file,shape:p.shape}:g?{kind:"mention-only",file:g.file,context:g.context}:{kind:"none"};return f.kind==="mention-only"&&f.context==="comment"&&l&&Fu(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...p?{declaration:p}:{}}}a(Mi,"rankCoverage");function Fu(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${es(n)}(?=$|[^A-Za-z0-9_$])`),s=ft(r);for(let i of Object.keys(e)){if(t.has(ft(i))||ft(i)===s)continue;let l=e[i];if(l&&o.test(ts(l,!0)))return!0}return!1}a(Fu,"symbolInCodeElsewhere");function Mu(e,t){return Mi(e,t).best}a(Mu,"classifyCoverage");function ji(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(ji,"countsAsCoverage");function ju(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(ju,"mentionWhere");function Hi(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${Du(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${ju(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(Hi,"describeCoverage");function ns(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=Pi(s),l=Pi(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",d=(e.coverageRoots??[]).filter(u=>typeof u=="string"&&u.length>0),p=d.length>0,g=d.join(", "),f=[],m=[];for(let u of t){let h=u.coverage?.test!==!1,k=u.coverage?.symbol,C=!r&&h,S=Mi(u,{fileContents:e.fileContents,testFiles:n,coverageRoots:d},C),I=S.best,E=[];C&&S.testTitle&&E.push("test-title"),S.declaration&&E.push("symbol");let H=ji(I),N,$;C&&S.testTitle&&(N=S.testTitle.file,p&&($=!$i(N,d)));let v=S.declaration?.file,D=S.declaration?.shape,w=u.coverage?.test===!0||!!k||u.coverage===void 0,P=u.coverage?.test===!1&&!k,M=w&&H||P&&u.mode!=="enforced"?!0:H,F=r&&h&&!H;if(f.push({invariantId:u.id,layer:u.provenance.layer,sourceFile:u.provenance.sourceFile,mode:u.mode,covered:M&&!F,evidence:E,partial:F,description:u.description,...N!==void 0?{testEvidenceFile:N}:{},...v!==void 0?{symbolEvidenceFile:v}:{},...D!==void 0?{shape:D}:{},...$!==void 0?{outsideDeclaredRoots:$}:{},coverageRootsDeclared:p}),$===!0&&N!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${u.id} is covered only by ${N}, which is outside the declared coverage roots (${g}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:N,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:"warning",failsStrict:!1}),!M||F){let re=u.mode==="enforced"&&!F,ke=r||n.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(F?o?`Invariant ${u.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${u.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:P?`Invariant ${u.id} is enforced but declares no evidence (coverage.test is false and no coverage.symbol); set coverage.symbol, drop test:false, or keep mode "advisory".`:`Invariant ${u.id}: ${Hi(u,I)} (${ke==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(F&&o?l:i),file:u.provenance.sourceFile,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:re?"error":"warning",failsStrict:re,kind:ke})}}return{coverage:f,violations:m,partial:f.some(u=>u.partial)}}a(ns,"evaluateInvariantCoverage");function rs(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?Array.isArray(e.evidence)&&e.evidence.length===0?{ok:!1,reason:`Invariant ${e.invariantId} declares no evidence (coverage.test:false and no symbol); add coverage.symbol or a test title before promoting to enforced.`}:e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:e.probe?.fresh===!0&&wi(e.probe.verdict)?{ok:!1,reason:Ti(e.invariantId,e.probe),blocker:"probe-survived"}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a(rs,"canPromoteInvariant");function Qr(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(Qr,"nonEmptyPathStrings");function Hu(e){return!e||typeof e!="object"?[]:[...Qr(e.testGlobs),...Qr(e.coverageRoots)]}a(Hu,"configuredInvariantTestsPaths");function Vu(e){return Hu(e).length>0}a(Vu,"hasConfiguredInvariantTestsPath");function ss(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(ss,"catalogDemandsInvariantTestsPath");function Vi(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&ss(e.invariants);return e.adopted!==!0||!t?[]:Vu(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:xu,message:Ou,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(Vi,"collectMissingInvariantTestsPathFindings");function Ku(e){return!e||typeof e!="object"?[]:Qr(e.coverageRoots)}a(Ku,"configuredCoverageRoots");function Uu(e){return Ku(e).length>0}a(Uu,"hasConfiguredCoverageRoots");function os(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(os,"catalogHasEnforcedInvariant");function Ki(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&os(e.invariants)?Uu(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:wu,message:Tu,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(Ki,"collectMissingCoverageRootsFindings");var cs="1.0",Gu="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function O(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Gu}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}a(O,"addFinding");function z(e){return[...new Set(e??[])].sort()}a(z,"sortedUnique");function me(e,t,n,r,o){let s=z(n),i=z(r),l=new Set(s),c=new Set(i),d=i.filter(g=>!l.has(g)),p=s.filter(g=>!c.has(g));d.length===0&&p.length===0||(d.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),p.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(me,"compareStringSets");function jt(e,t,n,r,o,s,i){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(jt,"compareBoolean");function $n(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($n,"keyed");function Bu(e,t,n){let r=$n(t,s=>s.name),o=$n(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&O(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){O(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){O(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;me(e,`${c}.patterns`,i.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),me(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let d=kn(i),p=kn(l);me(e,`${c}.forbiddenGlobals`,d.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),me(e,`${c}.capabilities`,d.atoms,p.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),z(i.intentPrefixes).join("\0")!==z(l.intentPrefixes).join("\0")&&O(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:z(i.intentPrefixes),after:z(l.intentPrefixes)}),jt(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."),jt(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 zu(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=$n(t,r),s=$n(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&O(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),d=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?O(e,{kind:"deny-added",path:d,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):O(e,{kind:"allow-added",path:d,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&O(e,{kind:"deny-removed",path:d,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&O(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${d}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let p=l.peerIsolation===!0,g=c.peerIsolation===!0;if(p!==g){let k=l.from===l.to&&c.from===c.to;O(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${d}.peerIsolation`,classification:k?g?"strengthening":"weakening":"judgment-required",message:k?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:p,after:g})}z(l.sliceFolders).join("\0")!==z(c.sliceFolders).join("\0")&&O(e,{kind:"slice-folders-changed",path:`${d}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:z(l.sliceFolders),after:z(c.sliceFolders)});let f=l.sliceIdentity??"path",m=c.sliceIdentity??"path";if(f!==m&&O(e,{kind:"slice-identity-changed",path:`${d}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:m}),!p&&!g)continue;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(ls)),z((c.allowedCrossSlice??[]).map(ls)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let u=Le(l.sharedImportsSlice)??null,h=Le(c.sharedImportsSlice)??null;if(u!==h){let k=Qi(h)>Qi(u);O(e,{kind:"shared-imports-slice",path:`${d}.sharedImportsSlice`,classification:k?"strengthening":"weakening",message:ap(u,h),before:u,after:h})}else h==="deny-cross-parent"&&Ln(e,`${d}.sharedImportsSlice.stopAt`,"shared-walk-stop",Gi(l.sharedImportsSlice),Gi(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.");qu(e,d,l,c)}}a(zu,"compareRules");function Ui(e){let t=e.childSlices;return t?JSON.stringify([z(t.sliceFolders??[]),t.sliceIdentity??"path",z(t.commonFolders??[])]):""}a(Ui,"childSliceFoldersKey");function Gi(e){return z(Cn(e).map(t=>Ht(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Gi,"stopAtKeys");function Bi(e){return e==="always"?2:e==="auto"?1:0}a(Bi,"siblingRatchetRank");function Wu(e){return z((e??[]).map(t=>Ht(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(Wu,"enforceKeys");function zi(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:Wu(t.enforce),ratchet:ri(t)}}a(zi,"childSliceSiblingPolicy");function qu(e,t,n,r){let o=zi(n),s=zi(r);if(o===null&&s===null)return;if(o===null&&s!==null){O(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:s.mode==="advisory"?"judgment-required":"strengthening",message:s.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(o!==null&&s===null){O(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(Ui(n)!==Ui(r)){O(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(o===null||s===null)return;if(o.mode!==s.mode){let c=s.mode==="advisory";O(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?s.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:o.mode,after:s.mode})}else if(o.mode==="advisory"&&(Yu(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce),o.ratchet!==s.ratchet)){let c=Bi(s.ratchet)>Bi(o.ratchet);O(e,{kind:"child-slices-siblings-ratchet",path:`${t}.childSlices.siblings.ratchet`,classification:c?"strengthening":"weakening",message:c?"New advisory sibling crossings past the baseline fail in more cases.":s.ratchet==="never"?"Advisory sibling crossings are measured only and never fail.":"New advisory sibling crossings past the baseline fail in fewer cases.",before:o.ratchet,after:s.ratchet})}let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&O(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:i,after:l}),Qu(e,t,n,r),Ju(e,t,n,r)}a(qu,"compareChildSlices");function ea(e,t){if(JSON.stringify(e)===JSON.stringify(t))return null;let n=t.filter(o=>!e.includes(o)),r=e.filter(o=>!t.includes(o));return{added:n,removed:r,bothWays:n.length>0&&r.length>0}}a(ea,"stringListDelta");function Yu(e,t,n,r){let o=ea(n,r);if(!o)return;let{added:s,bothWays:i}=o;O(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":s.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":s.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(Yu,"compareSiblingEnforceList");function ls(e){return JSON.stringify([e.from,e.to])}a(ls,"crossSliceKey");function Wi(e){return z((e.childSlices?.allowedCrossSlice??[]).map(ls))}a(Wi,"childCrossSliceKeys");function gt(e){return Ht(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(gt,"allowanceSegments");function qi(e,t){let n=gt(e),r=gt(t);if(n.length===0||n.length!==r.length)return!1;let o=!1;for(let s=0;s<n.length;s+=1)if(n[s]!==r[s]){if(n[s]==="*"&&r[s]!=="*"){o=!0;continue}return!1}return o}a(qi,"patternWidens");function Xu(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=gt(n[0]).join("/")===gt(r[0]).join("/"),s=gt(n[1]).join("/")===gt(r[1]).join("/"),i=qi(n[0],r[0]),l=qi(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(Xu,"allowanceWidens");function Zu(e){return JSON.stringify([Ht(e.from.trim().replace(/\\/g,"/")).toLowerCase(),Ht(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Zu,"aliasEntryKey");function Yi(e){return z((e.childSlices?.sliceAliases??[]).map(Zu))}a(Yi,"sliceAliasKeys");function Ju(e,t,n,r){let o=Yi(n),s=Yi(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(d=>!o.includes(d)),l=o.filter(d=>!s.includes(d)),c=i.length>0&&l.length>0;O(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:o,after:s})}a(Ju,"compareSliceAliases");function Qu(e,t,n,r){let o=Wi(n),s=Wi(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(c=>!o.includes(c)),l=o.filter(c=>!s.includes(c));if(i.length>0&&l.length>0&&l.filter(d=>!i.some(p=>Xu(p,d))).length===0){O(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:o,after:s});return}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(Qu,"compareChildCrossSliceAllowances");function Ln(e,t,n,r,o,s,i){let l=ea(r,o);if(!l)return;let{added:c,bothWays:d}=l;O(e,{kind:d?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:d?"judgment-required":c.length>0?"weakening":"strengthening",message:d?`${s} Entries were added and removed in the same change.`:c.length>0?s:i,before:r,after:o})}a(Ln,"compareDeclaredExceptions");function ep(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&O(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])jt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(ep,"compareSafety");function is(e){return e.mode==="enforced"?"enforced":"advisory"}a(is,"arkRunMode");function as(e){return e.mode==="enforced"?"enforced":"advisory"}a(as,"arkOrderMode");function tp(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${as(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=as(r),l=as(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}me(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(tp,"compareArkOrder");function np(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${is(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=is(r),l=is(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}me(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),jt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(np,"compareArkRun");function rp(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(rp,"overallClassification");function Xi(e,t){return`${e}::${t}`}a(Xi,"ruleKey");function Zi(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Xi(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Xi(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Zi,"indexEffectiveRules");function sp(e){return typeof e=="string"?e.length>0?[e]:[]:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(sp,"arkRulesRefPaths");function op(e,t){if(!e)return[];let n=new Set;for(let r of[...e.structure,...e.invariants])r.provenance?.layer===t&&r.provenance.sourceFile&&n.add(r.provenance.sourceFile);return[...n]}a(op,"arkRulesLayerSources");function Ji(e,t,n){return[...new Set([...sp(e),...op(t,n)])].sort()}a(Ji,"arkRulesCatalogPaths");function ip(e,t,n,r,o,s){let i=new Map((s??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},d=new Set([...Object.keys(l),...Object.keys(c)]);for(let f of[...r?.structure??[],...r?.invariants??[],...o?.structure??[],...o?.invariants??[]])f.provenance?.layer&&d.add(f.provenance.layer);for(let f of[...d].sort()){let m=l[f],u=c[f],h=`$.arkRules[${f}]`,k=Ji(m,r,f),C=Ji(u,o,f);if(k.join("\0")===C.join("\0"))continue;if(typeof m=="string"&&typeof u=="string"&&m!==u&&k.length===1&&C.length===1&&k[0]===m&&C[0]===u){O(e,{kind:"arkrules-ref-path-changed",path:h,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:m,after:u});continue}let S=new Set(k),I=new Set(C);for(let E of C)S.has(E)||O(e,{kind:"arkrules-ref-added",path:E,classification:"strengthening",message:`ArkRules reference for layer ${f} was added (${E}).`,after:E});for(let E of k)I.has(E)||O(e,{kind:"arkrules-ref-removed",path:E,classification:"weakening",message:`ArkRules reference for layer ${f} was removed (${E}).`,before:E})}let p=Zi(r),g=Zi(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),u=g.structure.get(f),h=`$.arkRules.structure[${f}]`;if(!m&&u){O(e,{kind:"arkrule-structure-added",path:h,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(m&&!u){O(e,{kind:"arkrule-structure-removed",path:h,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!u)){if(m.mode!==u.mode){let k=m.mode==="advisory"&&u.mode==="enforced";O(e,{kind:k?"arkrule-promoted":"arkrule-demoted",path:`${h}.mode`,classification:k?"strengthening":"weakening",message:k?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:m.mode,after:u.mode})}m.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${h}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:m.sensor,after:u.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),u=g.invariants.get(f),h=`$.arkRules.invariants[${f}]`;if(!m&&u){O(e,{kind:"arkrule-invariant-added",path:h,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(m&&!u){O(e,{kind:"arkrule-invariant-removed",path:h,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!u)&&m.mode!==u.mode)if(m.mode==="advisory"&&u.mode==="enforced"){let C=i?.get(u.id),S=rs(C);S.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${h}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${h}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${S.reason}`,before:m.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${h}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:m.mode,after:u.mode})}}a(ip,"compareArkRules");function ds(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."}),jt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&O(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Bu(r,e.layers,t.layers),zu(r,e.rules,t.rules),ep(r,e,t),ip(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),np(r,e,t),tp(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:cs,classification:rp(r),findings:r}}a(ds,"classifyArkPolicyDelta");function us(e,t){if(!e||e.schemaVersion!==cs||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(us,"policyDeltaAcknowledgementMatches");function Ht(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Ht,"trimTrailingSlashes");function Qi(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(Qi,"sharedImportsSliceRank");function ap(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(ap,"sharedImportsSliceMessage");function ze(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(ze,"normalizePath");function ta(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(ta,"isIdentifierStart");function Dn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(Dn,"isIdentifierCharacter");function ue(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ue,"skipWhitespace");function Vt(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(Vt,"readString");function pe(e,t,n){return e.startsWith(t,n)&&!Dn(e[n-1])&&!Dn(e[n+t.length])}a(pe,"isWordAt");function na(e,t){let n=ue(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ue(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!pe(e,"type",n))return!1;let o=ue(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||pe(e,"as",o)||!ta(e[o]))return!1;for(n=o;n<e.length&&Dn(e[n]);)n+=1;if(n=ue(e,n),pe(e,"as",n)){if(n=ue(e,n+2),!ta(e[n]))return!1;for(;n<e.length&&Dn(e[n]);)n+=1}r=!0}return!1}a(na,"bracedNamedBindingsAreTypeOnly");function lp(e,t){if(t=ue(e,t+6),e[t]==="(")return Vt(e,ue(e,t+1));let n=!1;if(pe(e,"type",t)){let o=ue(e,t+4);e[o]!==","&&!pe(e,"from",o)&&(n=!0)}else na(e,t)&&(n=!0);let r=ra(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(lp,"specifierAfterImport");function cp(e,t){t=t+6;let n=ue(e,t),r=!1;if(pe(e,"type",n)){let s=ue(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else na(e,n)&&(r=!0);let o=ra(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(cp,"specifierAfterExport");function ra(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(pe(e,"from",t))return Vt(e,ue(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Vt(e,t);if(t>0&&(pe(e,"import",t)||pe(e,"export",t)))return}}a(ra,"specifierInStaticStatement");function dp(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(dp,"skipTemplateLiteral");function up(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ue(e,t+7);if(e[r]!=="(")return;r=ue(e,r+1);let o=Vt(e,r);return o?{...o,requireCall:!0}:void 0}a(up,"specifierAfterRequire");function pp(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=dp(e,n);continue}if(r==="'"||r==='"'){let s=Vt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&pe(e,"import",n)?lp(e,n):r==="e"&&pe(e,"export",n)?cp(e,n):r==="r"&&pe(e,"require",n)?up(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(pp,"moduleSpecifiers");function sa(e,t){let n=[],r=[];for(let o of pp(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let d=_t(s);if(!d)continue;let p=e.content.slice(0,o.offset).split(`
|
|
19
|
+
`).length;r.push({file:e.path,symbol:s,capability:d,evidence:{kind:"import",file:e.path,line:p,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
|
|
20
|
+
`).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=fp(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(sa,"moduleFactsFor");function fp(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(fp,"resolveSpecifier");function oa(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:xn(s,o.sliceVerdict)??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(oa,"violationsFor");var gp={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 mp(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(mp,"hasActiveArkRules");function hp(e,t){return mp(e,t)?ee(Z(Jr({config:e,arkRules:t,warnings:[]}))):ee(Z(Zr(e)))}a(hp,"policyHashFor");function Fn(e,t,n){let r=typeof e=="string"?Sr(e,t):hn(e,t),o=n?.arkRules??Ge();return{...r,arkRules:o,policyHash:hp(r.config,o)}}a(Fn,"loadContract");function ia(e){let t=Fn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Fn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=ds(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&&us(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(ia,"analyzePolicyDelta");function Kt(e){let t=e.files.map(g=>{let f=ze(g.path);return{path:f,content:g.content,contentHash:ee(g.content),layer:ge(f,e.contract.config.layers)??null}}).sort((g,f)=>g.path.localeCompare(f.path)),n=new Map(t.map(g=>[g.path,g])),r=[],o=[];for(let g of t){let f=sa(g,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=oa(r,e.contract.config),i=new Map(e.contract.config.layers.map(g=>[g.name,g])),l=new Map(e.contract.config.layers.map(g=>[g.name,new Set(et(g))]));for(let g of o){let f=n.get(g.file)?.layer;if(!f)continue;let m=i.get(f),u=Ne(g.symbol,m?.forbiddenGlobals??[]);if(u){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${u}".`,symbol:g.symbol,evidence:g.evidence});continue}l.get(f)?.has(g.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let c=t.length===0?"complete":"partial",d=c==="complete"?[]:[{...gp}],p={schemaVersion:Wr,policyHash:e.contract.policyHash,compilerOptionsHash:ee(Z(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:d,valid:c==="complete"&&s.length===0,ir:p}}a(Kt,"analyzeProject");function Mn(e){let t=new Map(e.files.map(n=>[ze(n.path),n]));for(let n of e.changes){let r=ze(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})}a(Mn,"analyzeChange");function aa(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(aa,"explainViolation");function fs(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let g of[...e.get(c)??[]].sort())e.has(g)&&(n.has(g)?o.has(g)&&r.set(c,Math.min(r.get(c)??0,n.get(g)??0)):(l(g),r.set(c,Math.min(r.get(c)??0,r.get(g)??0))));if(r.get(c)!==n.get(c))return;let d=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),d.push(p)}while(p!==c);d.length>1&&i.push(d.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,d)=>c[0]<d[0]?-1:c[0]>d[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(fs,"detectArchitectureCycles");function mt(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=si(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});f&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:f.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:f.toPath,toSlice:f.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${f.fromPath} \u2192 slice ${f.toSlice} (${f.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,d=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=i.sliceVerdict,g=p?st({surface:"import",verdict:p,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.message,childMessage:l.childSlices?.message}):l.message??`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},...Ke(p),message:d?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...d?{failsStrict:!1,severity:"warning"}:{}})}t.push(...Rp(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=fs(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(mt,"evaluateArchitectureGraph");var yp="CROSS_PARENT_VIA_SHARED",Ap="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function la(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&Le(r.sharedImportsSlice)==="deny-cross-parent")return r}a(la,"denyingCrossParentRule");function ps(e,t,n,r){let o=Ot(n,e,$r(e,t,r)).universeId;return o?{kind:"slice",id:o}:nt(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(ps,"placeFile");function ca(e,t){return Xo(t,Cn(e.sharedImportsSlice))}a(ca,"isWalkStop");function Rp(e){let t=e.rules??[];if(!t.some(s=>Le(s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=Sp(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=la(t,s.fromLayer,s.toLayer);if(!i)continue;let l=ps(i,s.fromLayer,s.from,e.config.layers),c=ps(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||ca(i,s.to))continue;let d=[{file:s.to,path:[s.from,s.to]}],p=new Set([s.to]);for(;d.length>0;){let g=d.shift();if(!g)break;for(let f of n.get(g.file)??[]){let m=la(t,f.fromLayer,f.toLayer);if(!m)continue;let u=ps(m,f.fromLayer,f.to,e.config.layers);if(u.kind==="shared"){if(p.has(f.to)||ca(m,f.to))continue;p.add(f.to),d.push({file:f.to,path:[...g.path,f.to]});continue}if(u.kind!=="slice"||u.id.toLowerCase()===l.id.toLowerCase()||bn(i.allowedCrossSlice,l.id,u.id))continue;if(i.sliceIdentity==="stars"){let I=Lr(i,$r(i,s.fromLayer,e.config.layers),s.from,f.to);if(I.crossSliceAllowed||I.from.universeId&&I.from.universeId===I.to.universeId)continue}let h=[...g.path,f.to],k=`${s.from}\0${f.to}`,C={file:s.from,target:f.to,line:s.line,fromLayer:s.fromLayer,toLayer:f.toLayer,fromSlice:l.id,toSlice:u.id,path:h},S=r.get(k);(!S||h.length<S.path.length||h.length===S.path.length&&h.join("\0")<S.path.join("\0"))&&r.set(k,C)}}}return[...r.values()].sort((s,i)=>s.file<i.file?-1:s.file>i.file?1:s.target<i.target?-1:s.target>i.target?1:0).map(s=>{let i=wt(s.fromSlice),l=wt(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:yp,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}. ${Ap}`}})}a(Rp,"crossParentViaSharedViolations");function Sp(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(Sp,"valueHop");function da(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(da,"structureFreezeTarget");var kp=/\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)/,Ip=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,bp=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,vp=["db","tx","client","prisma","prismaClient","drizzle"],Ep="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",ga=/\b(?:INSERT\s+INTO|(?<!\b(?:FOR(?:\s+NO\s+KEY)?|DO)\s)UPDATE(?:\s+ONLY)?(?!\s+(?:OF|SET)\b)|DELETE\s+FROM(?:\s+ONLY)?|MERGE\s+INTO|TRUNCATE(?:\s+TABLE)?(?:\s+ONLY)?)\s+(?:(?:(?:"[^"]*"|[A-Za-z_][\w$]*)\s*\.\s*)?(?:"[^"]*"|[A-Za-z_][\w$]*)|\$\{[^}]+\})/i,Cp=/^(?:await|return|throw|yield|new|typeof|void|delete|if|else|case|of|in|instanceof|async|function|class|const|let|var|import|export|from|as|default|type)$/,ua=/(^|[^\w$])([A-Za-z_$][\w$]*)\s*`((?:[^`\\]|\\[\s\S])*)`/g,_p=/\bINSERT\s+INTO\b[\s\S]*?\bON\s+CONFLICT\b[\s\S]*?\bDO\s+UPDATE\s+SET\b[^;`]*/gi,pa="\\((?:[^()]|\\([^()]*\\))*\\)",xp=`\\bnew\\s+PrismaClient\\s*${pa}|\\bdrizzle\\s*${pa}`,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,wp=/(?<![\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 Tp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Tp,"escapeRegExp");function jn(e){return kp.test(e)||Ip.test(e)}a(jn,"sourceImportsPersistenceDriverText");function fa(e,t,n){let r=new RegExp(e.source,"g"),o;for(;(o=r.exec(t))!==null;)o[1]&&n.add(o[1])}a(fa,"collectFirstGroup");function Pp(e){let t=new Set;fa(Op,e,t),fa(wp,e,t);let n=new RegExp(bp.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(Pp,"persistenceClientBindings");function ma(e){return e.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|`(?:[^`\\]|\\[\s\S])*`|'(?:[^'\\]|\\[\s\S])*'|"(?:[^"\\]|\\[\s\S])*"/g,t=>t.charCodeAt(0)===47?t.replace(/[^\n]/g," "):t.charCodeAt(0)===96?t.replace(/--[^\n`]*/g,n=>" ".repeat(n.length)):t)}a(ma,"blankPersistenceComments");function ha(e){let t=ma(e);ua.lastIndex=0;let n;for(;(n=ua.exec(t))!==null;)if(!Cp.test(n[2]??"")&&ga.test((n[3]??"").replace(_p," ")))return!0;return!1}a(ha,"sourceHasTaggedSqlWrite");function gs(e){let t=ma(e),n=[...vp,...Pp(t)].map(Tp).join("|");return new RegExp(`(?:\\b(?:${n})(?![\\w$])|${xp})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${Ep}\\s*\\(`,"i").test(t)?!0:ga.test(t)}a(gs,"sourceHasPersistenceWrite");var Np=["no-anemic-model"],Sa=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],ms=new RegExp(`\\b(${Sa.join("|")})\\b`),ka="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",hs=new RegExp(`\\bthis\\.${ka}\\.push\\s*\\(`),Lp=new RegExp(`^this\\.${ka}\\s*=\\s*\\[\\s*\\]`),$p=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,Dp=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g;function ys(){return`${Sa.join(", ")}, or events-array .push(`}a(ys,"expectedDomainInvariantWordsPhrase");function Fp(e){return ms.test(e)||hs.test(e)}a(Fp,"referencesGuardOrPublish");function As(e,t,n){let r=e.slice(t);if(Lp.test(r))return!0;if(!$p.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(As,"isIdiomaticEventsReset");function Mp(e,t){let n=new RegExp(Dp.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!As(t,r.index,e))return!0;return!1}a(Mp,"methodAssignsThis");function ya(e,t){return t==null?e:{...e,truncatedUntil:t}}a(ya,"attachShapeTruncation");function Ia(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}a(Ia,"shapeTruncatedUntil");function jp(e){let t=Ia(e);return t==null?"":` shape analysed until character ${t}`}a(jp,"shapeTruncationSuffix");function Aa(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Aa,"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+=Aa(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Aa(o)}return new RegExp(`^${n}$`)}a(Hp,"globToRegExp");function ht(e,t){return!t||t.length===0?!0:t.some(n=>Hp(n).test(e))}a(ht,"matchesAppliesTo");function ba(e){return Np.includes(e)}a(ba,"isTier2");function va(e){return e.mode==="enforced"&&!ba(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(va,"severityFor");function Me(e,t,n,r=1){let{severity:o,failsStrict:s}=va(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(Me,"baseViolation");function Hn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(Hn,"isInRuleLayer");function Vn(e,t,n){return t.filter(r=>!(!r.exported||!ht(r.file,e.appliesTo)||!Hn(r.file,e,n)))}a(Vn,"shapesForRule");function Rs(e,t,n){let r=Ia(t);if(r!=null)return Me(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}a(Rs,"truncatedShapeViolation");function Vp(e,t,n){let r=[];for(let o of Vn(e,t,n)){let s=Rs(e,o,"members");s&&r.push(s),(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Me(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}a(Vp,"evaluateAggregatePrivateState");function Kp(e,t,n){let r=[];for(let o of Vn(e,t,n)){let s=Rs(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(Me(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}a(Kp,"evaluateAlwaysValidFactory");function Up(e,t,n){let r=[],o=ys();for(let s of Vn(e,t,n)){let i=jp(s),l=Rs(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Me(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(Up,"evaluateDomainEventOnMutation");function Gp(e,t){let n=[];for(let r of t.files)ht(r,e.appliesTo)&&Hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Me(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(Gp,"evaluateOrchestrationOnly");function Bp(e,t){let n=[];for(let r of t.files)ht(r,e.appliesTo)&&Hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Me(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(Bp,"evaluateThinAdapter");function zp(e,t){let n=[];for(let r of t.files)ht(r,e.appliesTo)&&Hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Me(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(zp,"evaluateWritesViaAggregate");function Wp(e,t,n){let r=[];for(let o of Vn(e,t,n))if(o.dataOnly===!0){let s=Me(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(Wp,"evaluateNoAnemicModel");function Ss(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(...Vp(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Kp(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Up(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Gp(n,e));break;case"thin-adapter":t.push(...Bp(n,e));break;case"writes-via-aggregate":t.push(...zp(n,e));break;case"no-anemic-model":t.push(...Wp(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(Ss,"evaluateArkRuleSensors");function ks(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>ht(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=va(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>ht(l,o.appliesTo)))continue;let i=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a(ks,"collectEmptyAppliesToFindings");var Ra=64;function qp(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(qp,"stripTrailingDots");function Yp(e){let t=e.trim(),n=t.length>Ra?t.slice(0,Ra):t;return qp(n)}a(Yp,"normalizeIntentPrefix");function Xp(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(Xp,"layerNameLooksDomain");function Zp(e){return e.some(t=>{let n=Yp(t);return n==="Domain"||n.startsWith("Domain.")})}a(Zp,"ownsDomainIntent");function Jp(e,t=[]){return Xp(e)||Zp(t)}a(Jp,"isDomainRoleLayerName");function Ea(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Jp(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)&&!ba(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(Ea,"collectEmptyInvariantCatalogFindings");function Qp(e){return e==="PersistenceAdapters"}a(Qp,"isPersistenceDriverLayer");function ef(e,t){if(jn(e))return!0;if(!t)return!1;for(let n of t){if(Qp(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(jn(o))return!0}return!1}a(ef,"sourceImportsPersistenceDriver");var tf=/\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*=)/,nf=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,rf=/\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*=/,sf=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Ca(e,t,n){if(!t)return null;let r=ef(t,n),o=r&&gs(t)||ha(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(rf.source,"g"))??[],i=t.match(new RegExp(sf.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,d=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,p=tf.test(t)||nf.test(t),g=s.length>=1||i.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=r&&g||p&&g||r&&f&&(l>=4||s.length>=1)||p&&r;return!d&&!m&&!o?null:{...d?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(Ca,"deriveArkRuleFileHints");function Is(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=Ca(r,o,t?.[s]);i&&(n[s]=i)}return n}a(Is,"buildArkRuleFileHints");var of=new Set(["if","match","when"]);function af(e,t){let n=[];for(let r of Nn(t,{exportedOnly:!0})){let o=r.name;if(r.bodyStart==null){n.push(ya({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=Pn(l),d=i?t.length:c.truncatedAt==null?void 0:s+c.truncatedAt,p=c.members.filter(I=>!(I.kind!=="field"||I.name==="constructor"||I.modifiers.includes("private")||I.modifiers.includes("protected")||I.modifiers.includes("readonly")||I.modifiers.includes("static")||I.modifiers.includes("get")||I.modifiers.includes("set"))),g=p.length>0,f=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(l),m=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(l),u=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(l)&&!m,h=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(l)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(l),k=[];for(let I of c.members)I.kind==="method"&&I.name!=="constructor"&&(I.modifiers.includes("static")||I.modifiers.includes("get")||I.modifiers.includes("set")||of.has(I.name)||Mp(I.name,I.body)&&k.push({name:I.name,referencesGuardOrPublish:Fp(I.body)}));let S=c.members.filter(I=>I.kind==="method").length<=1&&p.length>=2&&g;n.push(ya({file:e,className:o,exported:!0,hasPublicMutableFields:g,hasPublicSetters:f,hasPublicConstructor:u,hasStaticFactory:h,mutatingMethods:[...k],dataOnly:S},d))}return n}a(af,"extractClassShapesFromSource");var lf=50;function bs(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(bs,"normalizeExtraMergeTeethClassification");function Re(e){let t=bs(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(Re,"extraMergeTeethAllowed");function vs(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(vs,"classifyResolvedLayerCoverage");function Es(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}a(Es,"isArkRunRuleId");function _a(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}a(_a,"isArkOrderRuleId");function xa(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(xa,"isExtraPlaneFinding");function cf(e,t={}){if(!Array.isArray(e)||Re(t))return e;for(let n of e)xa(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}a(cf,"demoteExtraPlaneTeethUnderClassificationFloor");var Oa="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 Cs(e){return{active:e?.active===!0,structureEnforced:e?.structureEnforced,structureTotal:e?.structureTotal,structureAdvisory:e?.structureAdvisory,invariantEnforced:e?.invariantEnforced,invariantTotal:e?.invariantTotal,invariantAdvisory:e?.invariantAdvisory,covered:e?.covered,uncovered:e?.uncovered}}a(Cs,"mergePlanesArkRulesInput");function Kn(e={}){let t=e.present===!0,n=e.mode==="enforced"||e.mode==="advisory"?e.mode:null,r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}a(Kn,"projectExtraPlaneStatus");function Ae(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}a(Ae,"countOrZero");function Un(e={}){let t=bs(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=Re(t),i=e.arkRules,l=Ae(i?.structureEnforced),c=Ae(i?.structureTotal),d=typeof i?.structureAdvisory=="number"?Ae(i.structureAdvisory):Math.max(0,c-l),p=Ae(i?.invariantEnforced),g=Ae(i?.invariantTotal),f=typeof i?.invariantAdvisory=="number"?Ae(i.invariantAdvisory):Math.max(0,g-p),m=l>0||p>0,u=e.arkRun?.present===!0,h=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,k=Ae(e.arkRun?.residualCount),C=u&&h==="enforced",S=C&&s,I=e.arkOrder?.present===!0,E=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,H=Ae(e.arkOrder?.residualCount),N=I&&E==="enforced",$=N&&s,v=m||C||N,D=v&&s,w=v&&o&&!s,P;if(D){let F=[];m&&F.push("enforced structure/invariant findings"),C&&F.push("enforced ArkRun skip findings"),N&&F.push("enforced ArkOrder skip findings"),P=`Layer graph failures plus ${F.join(" and ")} (advisory extras never fail merge alone).`}else if(w)P=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,C?"ArkRun":null,N?"ArkOrder":null].filter(re=>!!re).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`;else{let F=u?h==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",re=I?E==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";P="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+F+re}let M={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:d,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:g,enforced:p,advisory:f,covered:Ae(i?.covered),uncovered:Ae(i?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:u,mode:h,residualCount:k,extraMergeTeeth:S,note:u?h==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},arkOrder:{role:"pattern-slaving",present:I,mode:E,residualCount:H,extraMergeTeeth:$,note:I?E==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:D,dualPlaneStamp:Oa,failMergeWhen:P};return o&&(M.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),M}a(Un,"composeMergePlanesHonesty");var Pa=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"],df="ArkModule",uf=["forRoot","forRootAsync"],pf=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"],Na=new Set(["eventBus"]),ff=new Set(["publisher","eventBus"]),gf=new Set(uf),mf=new Set(pf),hf=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Gn=new Set(Pa),yf=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"]),La=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function yt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}a(yt,"isArkRunKernelModuleSpecifier");var $a=["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"],_s=new Set($a);function xs(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(_s.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(_s.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:_s.has(e.slice(0,r))}a(xs,"isArkRunTransportBypassSpecifier");function Bn(e){if(Gn.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(Bn,"arkRunKernelCallKind");function Gt(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}a(Gt,"lineAt");function Bt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}a(Bt,"stripCommentsPreservingLines");function Af(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(Af,"firstStringLiteralArg");function wa(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(wa,"keywordBefore");function zt(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(zt,"parseValueImportClause");function Rf(e,t){zt(Bt(e),t)}a(Rf,"forEachArkRunValueImportClause");function Os(e,t){let n=Bt(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:Gt(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:Gt(t,s.index),resolution:"resolved-external"})}return r}a(Os,"extractArkRunValueImportDependenciesFromSource");function ws(e){let t=/\{([^}]*)\}/.exec(e);if(!t?.[1])return[];let n=[];for(let r of t[1].split(",")){let o=r.trim();if(!o||o.startsWith("type "))continue;let s=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),i=s?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],l=s?.[1]??i;i&&l&&n.push({local:i,original:l})}return n}a(ws,"bracedValueImportBindings");function Ts(e){let t=[];return Rf(e,n=>{for(let{local:r,original:o}of ws(n))/^[A-Z]/.test(o)&&t.push(r,o)}),Ut(t)}a(Ts,"extractArkRunImportedConstructorNamesFromSource");function Sf(e){let t=new Map,n=new Set;return zt(e,(r,o)=>{if(!yt(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let i=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());i?.[1]&&t.set(i[1],i[1]);for(let{local:l,original:c}of ws(r))t.set(l,c)}),{named:t,namespaces:n}}a(Sf,"collectKernelImportBindings");function kf(e,t){let n=new Set(t);return zt(e,(r,o)=>{for(let{local:s,original:i}of ws(r))/^[A-Z]/.test(i)&&(yt(o)||t.has(i)||t.has(s))&&(n.add(s),n.add(i))}),n}a(kf,"collectImportedConstructors");function If(e,t){let n;return zt(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}a(If,"importedFromForName");function bf(e){let t=new Set,n=/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;){if(!yt(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;mf.has(c)&&t.add(d)}}return t}a(bf,"collectKernelTypeNames");function vf(e,t){let n=e.split(".");if(n.length===2)return t.namespaces.has(n[0])&&Gn.has(n[1]);if(n.length!==1)return!1;let r=t.named.get(n[0]);return r!==void 0&&Gn.has(r)}a(vf,"isFactoryCalleeExpression");function Ef(e,t,n,r){zt(e,(o,s)=>{if(!t(s))return;let i=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(o);i?.[1]&&(n.add(i[1]),r?.add(i[1]));let l=/^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(o.trim());l?.[1]&&n.add(l[1]);let c=/\{([^}]*)\}/.exec(o);for(let d of c?.[1]?.split(",")??[]){let p=d.trim();if(!p||p.startsWith("type "))continue;let g=/([A-Za-z_$][\w$]*)$/.exec(p)?.[1];g&&n.add(g)}})}a(Ef,"addRootModuleImports");function Cf(e,t){let{receivers:n,calleeBindings:r}=t,o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:await\s+)?(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)\b/g,s=/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*[;\n)]/g,i=/(?:\b(?:const|let|var)\s+|\bthis\s*\.\s*|(?:^|[;{}\n])\s*)([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?(?<![=!<>])=(?![=>])\s*(?:this\s*\.\s*)?([A-Za-z_$][\w$]*)\s*(?:as\s+[A-Za-z_$][\w$.<>]*\s*)?(?=[;\n,)])/g,l=/([A-Za-z_$][\w$]*)\s*\??\s*:\s*typeof\s+([A-Za-z_$][\w$]*)\b/g,c;for(let d=!0;d;){d=!1;for(let p of[i,l])for(p.lastIndex=0;(c=p.exec(e))!==null;)!n.has(c[2])||n.has(c[1])||(n.add(c[1]),d=!0);for(o.lastIndex=0;(c=o.exec(e))!==null;)n.has(c[2])&&(!ff.has(c[3])&&!t.rootNamespaces.has(c[2])||n.has(c[1])||(n.add(c[1]),d=!0));for(s.lastIndex=0;(c=s.exec(e))!==null;)if(n.has(c[2]))for(let p of c[1].split(",")){let g=/^\s*([A-Za-z_$][\w$]*)\s*(?::\s*([A-Za-z_$][\w$]*))?\s*$/.exec(p);if(!g)continue;let f=g[1],m=g[2]??f;if(Na.has(f)){if(n.has(m))continue;n.add(m),d=!0}else Bn(f)&&!Gn.has(f)&&r.add(m)}}}a(Cf,"addDerivedReceivers");function _f(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;)vf(s[2].replace(/\s+/g,""),t)&&r.receivers.add(s[1]);let i=bf(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 Cf(e,r),r}a(_f,"traceKernelReceivers");function xf(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(xf,"matchingOpenParen");function Ta(e){let t=e.split(".").map(n=>n.trim()).filter(n=>n.length>0);return t[0]==="this"?t.slice(1):t}a(Ta,"chainParts");function Of(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:Ta(r[1].replace(/\?/g,"")),viaPublisherCall:!1}}let o=/\)\s*\??\.\s*$/.exec(n);if(!o)return;let s=t-n.length+o.index,i=xf(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:Ta(c[1].replace(/\?/g,"")),viaPublisherCall:!0}:{parts:["<expr>"],viaPublisherCall:!1}}a(Of,"receiverChainBefore");function wf(e,t,n){let[r,...o]=e.parts;return r?o.length===0&&t.namespaces.has(r)?!0:La.has(r)||!n.receivers.has(r)?!1:(n.rootNamespaces.has(r)?o.slice(1):o).every(i=>Na.has(i)):!1}a(wf,"chainReachesKernel");function Tf(e){let t=new Set,n=a((c,d,p)=>{let g=c.get(d);g!==void 0&&g!==p?t.add(d):c.set(d,p)},"bind"),r=new Map,o=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(['"])((?:\\.|[^\\])*?)\2\s*(?:as\s+const\s*)?[;\n,)]/g,s;for(;(s=o.exec(e))!==null;)s[3]&&n(r,s[1],s[3]);for(let c of t)r.delete(c);let i=new Map(r),l=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:[A-Za-z_$][\w$]*\s*\.\s*)*(?:define|defineIntent)\s*(?:<[^>]*>)?\s*\(\s*(?:(['"])((?:\\.|[^\\])*?)\2|([A-Za-z_$][\w$]*)\s*[,)])/g;for(;(s=l.exec(e))!==null;){let c=s[3]??(s[4]?r.get(s[4]):void 0);c?n(i,s[1],c):(t.has(s[4]??"")||i.has(s[1]))&&t.add(s[1])}for(let c of t)i.delete(c);return i}a(Tf,"collectDefinedIntentNames");function Pf(e,t){return/^\s*([A-Za-z_$][\w$]*)\s*[,)]/.exec(e.slice(t))?.[1]}a(Pf,"firstIdentifierArg");function Nf(e,t){return ve(e)?!0:(t??[]).some(n=>{let r=n.trim();if(!r)return!1;let o=r.endsWith(".")?r:`${r}.`;return e.startsWith(o)&&/^[A-Za-z0-9_.]+$/.test(e.slice(o.length))})}a(Nf,"carriesIntentPrefix");function Lf(e){if(!e)return;if(e.viaPublisherCall)return"publisher";let t=e.parts[e.parts.length-1];return t==="<expr>"?void 0:t}a(Lf,"receiverName");function $f(e,t,n){if(!e||t===void 0||!Nf(t,n))return!1;let r=e.parts[0];return r!==void 0&&r!=="<expr>"&&!La.has(r)}a($f,"untracedKernelNameEvidence");function Ps(e,t,n={}){let r=Bt(t),o=Sf(r),s=_f(r,o,n.isKernelRootSpecifier),i=Tf(r),l=[],c=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,d;for(;(d=c.exec(r))!==null;){let p=d[1],g=d.index;if(wa(r,g,"function")||wa(r,g,"class"))continue;let f=Of(r,g),m=Lf(f),u=o.named.get(p)??p,h=Bn(u)??Bn(p),k=o.named.has(p)||s.calleeBindings.has(p)||f?.parts.length===1&&o.namespaces.has(f.parts[0]);if(!h&&gf.has(p)&&f?.parts.length===1&&o.named.get(f.parts[0])===df&&(h="factory",k=!0),!h||h==="factory"&&f!==void 0&&!k)continue;let C=g+d[0].length,S=Af(r,C);if(h!=="factory"&&(f===void 0?!k:!wf(f,o,s))&&!$f(f,S,n.intentPrefixes))continue;let I=Pf(r,C),E=S??(I?i.get(I):void 0);l.push({file:e,line:Gt(t,g),kind:h,callee:p,viaImport:k,...m?{receiver:m}:{},...E?{nameLiteral:E}:{}})}return l}a(Ps,"extractArkRunKernelCallsFromSource");function Ns(e,t,n){let r=Bt(t),o=kf(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(yf.has(c)||!o.has(c))continue;let d=If(r,c);s.push({file:e,line:Gt(t,l.index),typeName:c,...d?{importedFrom:d}:{}})}return s}a(Ns,"extractArkRunManagedNewsFromSource");function Df(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(Df,"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 Ut(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(Ut,"uniqueSorted");function Mf(e,t){let n=Bt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],i=[],l=[],c,d;for(;(d=r.exec(n))!==null;){let p=n.slice(d.index+d[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=d.index+d[0].length+(g[0].length-1),m=Df(n,f);if(m<0)continue;let u=Ff(n,f,m);if(u.length===0)continue;c===void 0&&(c=d.index);let h=d[1];h==="uses"?o.push(...u):h==="reactsTo"?s.push(...u):h==="raises"?i.push(...u):l.push(...u)}return c===void 0?[]:[{file:e,line:Gt(t,c),uses:Ut(o),reactsTo:Ut(s),raises:Ut(i),sends:Ut(l)}]}a(Mf,"extractArkRunDeclarationsFromSource");var jf=["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"],Vf=new Set(Hf);function Kf(e){return Vf.has(e)}a(Kf,"isArkRunEditorSensor");var Ls={"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"},Ma="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ja(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(ja,"isDomainRoleLayer");function Uf(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Uf,"compareFindings");function Oe(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Ls[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:he({ruleId:Ls[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Oe,"finding");function Gf(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(Gf,"bagForFile");function Da(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(Da,"emitKinds");function Fa(e){return e==="subscribe"||e==="register-handler"}a(Fa,"handleKinds");function Bf(e){return e==="resolve"||e==="resolve-singleton"}a(Bf,"dependKinds");function zf(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,p)=>d.file.localeCompare(p.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(zf,"evaluateMissingRoot");function Wf(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||!yt(c))continue;let d=r(l.from);d&&ja(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(Wf,"evaluateKernelInDomain");function qf(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),c=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),d=[];for(let p of n){if(c.has(p.file))continue;let g=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let f=o(p.file);!f||!i.has(f)||ja(f,l.get(f)??[])||d.push(Oe(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return d}a(qf,"evaluateDirectNew");function Yf(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(!Da(c.kind)&&!Fa(c.kind)&&!Bf(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:Ma,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name or same-file define/defineIntent binding; enforced extra cannot prove the declaration.`});continue}let p=Gf(n,c.file);if(Da(c.kind)){if(p.raises.has(c.nameLiteral)||p.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(Fa(c.kind)){if(p.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}p.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(Yf,"evaluateUndeclared");function Xf(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||!xs(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(Xf,"evaluateTransportBypass");function zn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=Yf(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...zf(t,e.compositionRootHits,n),...Wf(t,e.layers,e.dependencies,e.layerForFile,n),...qf(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Xf(t,e.dependencies,e.layerForFile,n)].sort(Uf),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(zn,"evaluateArkRunSensors");function Ha(e){return{findings:zn(e).findings.filter(n=>Kf(n.sensor)),completenessReasons:[]}}a(Ha,"evaluateArkRunEditorSensors");function Zf(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(Zf,"fileMatchesCompositionRoot");function Jf(e,t,n){let r=Ps(t,n).some(i=>i.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let i of s)Zf(i,t)&&o.push({file:t,matchedRoot:i,hasKernelFactory:r});return o}a(Jf,"compositionRootHitsForSource");function Qf(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(Ts(e.source));return Ha({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Ns(e.file,e.source,n),compositionRootHits:Jf(t,e.file,e.source),declarations:[],dependencies:Os(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}a(Qf,"evaluateArkRunEditorSensorsFromSource");function Va(e){return ce(e)}a(Va,"arkOrderGlobToRegExp");function Ka(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Ka,"isArkOrderModuleSpecifier");var eg=["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"],$s={"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 tg(e,t){return!t||t.length===0?!0:t.some(n=>Va(n).test(e))}a(tg,"matchesArkOrderAppliesTo");function ng(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(ng,"isDomainRoleLayer");function Se(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:$s[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:he({ruleId:$s[t],fromLayer:s?.fromLayer,target:s?.target})}}a(Se,"finding");function Ds(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Se(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let d of e.planeRootHits){let p=c.get(d.matchedRoot)??[];p.push(d),c.set(d.matchedRoot,p)}for(let d of o){let p=c.get(d)??[];if(p.length===0){r.push(Se(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(d)} matched no governed files and has no createOrderPlane factory.`,{target:d},n));continue}p.some(g=>g.hasPlaneFactory)||r.push(Se(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(d)} has no createOrderPlane factory.`,{target:d},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let d=c.specifier;if(!d||!Ka(d))continue;let p=e.layerForFile(c.from);p&&ng(p,s.get(p)??[])&&r.push(Se(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:d},n))}for(let c of e.genericUpdates)r.push(Se(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Se(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(Se(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));for(let c of e.xiTtlKeys??[])r.push(Se(t,"arkorder-xi-ttl",c.file,c.line,`\u03BE key ${JSON.stringify(c.key)} is a freshness field; freshness belongs on \u03C3 (freshUntil), never on \u03BE.`,{target:c.key},n));for(let c of e.budgetLeaks??[])r.push(Se(t,"arkorder-information-budget",c.file,c.line,`Projection allowedKinds lists ${JSON.stringify(c.kind)}, which informationBudget.cannotObserve denies.`,{target:c.kind},n));let l=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let d=e.layerForFile(c.file);!d||!l.has(d)||tg(c.file,t.appliesTo)&&r.push(Se(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:d,target:c.key},n))}return r.sort((c,d)=>c.file.localeCompare(d.file)||c.ruleId.localeCompare(d.ruleId)||c.line-d.line),{findings:r,completenessReasons:[]}}a(Ds,"evaluateArkOrderSensors");var Wt="4.8.24";function qt(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}a(qt,"childSlicesOf");var Ua=Object.freeze([{key:"childSlices.arkRulesFile",minVersion:Wt,uses:a(e=>typeof qt(e)?.arkRulesFile=="string","uses")},{key:"childSlices.sliceAliases.pinned",minVersion:Wt,uses:a(e=>{let t=qt(e)?.sliceAliases;return Array.isArray(t)?t.some(n=>{if(n===null||typeof n!="object")return!1;let r=n;return r.pinned!==void 0||r.reason!==void 0}):!1},"uses")},{key:"sharedImportsSlice.stopAt",minVersion:Wt,uses:a(e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:Wt,uses:a(e=>qt(e)?.message!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:Wt,uses:a(e=>{let t=qt(e)?.siblings;return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:a(e=>qt(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 Wn(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}a(Wn,"versionCore");function Yt(e,t){let n=Wn(e),r=Wn(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(Yt,"compareArkgateVersion");function Ga(e,t){return t&&Wn(t)&&Yt(t,e)<0?t.replace(/^v/,""):e}a(Ga,"effectiveFloor");function rg(e,t){let n=[],r=null;for(let o of Ua){if(!(e??[]).some(i=>i&&o.uses(i)))continue;n.push(o.key);let s=Ga(o.minVersion,t);(!r||Yt(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}a(rg,"configVersionFloors");function Ba(e){let t=rg(e.rules,e.runningVersion);if(!t||!e.pins?.length)return[];let n=e.runningVersion,r=n&&Wn(n)&&Yt(n,t.required)>0?n.replace(/^v/,""):t.required,o=a(l=>Ua.filter(c=>t.keys.includes(c.key)&&Yt(l.version,Ga(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,i=[];for(let l of e.pins){if(Yt(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(Ba,"configVersionPinFindings");function J(e,t,n={}){return{ruleId:e,message:t,...n}}a(J,"configWarning");function qn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(u=>typeof u!="string"))&&s.push(J("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(J("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let u of["maxTsSuppressions","maxAnyCasts"]){let h=t.safety[u];h!==void 0&&(!Number.isInteger(h)||h<0)&&s.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${u} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(u=>u.name).filter(Boolean),...l.map(u=>u.name).filter(u=>!!u)]);i.length===0&&s.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let d=new Set,p=new Set;for(let u of i){if(!u.name){s.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}d.has(u.name)&&p.add(u.name),d.add(u.name),u.forbiddenGlobals!==void 0&&(!Array.isArray(u.forbiddenGlobals)||u.forbiddenGlobals.some(k=>typeof k!="string"))&&s.push(J("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${u.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:u.name}));let h=Array.isArray(u.patterns)?u.patterns:[];if(h.length===0){s.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${u.name}" has no file patterns and will never classify files.`,{layer:u.name}));continue}for(let k of h){let C;try{C=ce(k)}catch(I){s.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${u.name}" has an invalid pattern "${k}": ${I instanceof Error?I.message:String(I)}`,{layer:u.name,pattern:k}));continue}let S=u.optional===!0||u.reserved===!0||u.allowEmpty===!0;!r.some(I=>C.test(I))&&!S&&s.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${u.name}" pattern "${k}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:u.name,pattern:k,failsStrict:!1,reserved:!1}))}}for(let u of p)s.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${u}" is configured more than once.`,{layer:u}));if(c.size>0)for(let u of n??[])u.from&&!c.has(u.from)&&s.push(J("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${u.from}".`,{fromLayer:u.from,toLayer:u.to})),u.to&&!c.has(u.to)&&s.push(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${u.to}".`,{fromLayer:u.from,toLayer:u.to}));let g=new Set;if(i.length>1)for(let u of r){let h=-1,k=[];for(let C of i)for(let S of C.patterns??[]){if(!ce(S).test(u))continue;let I=wr(S,u);I>h?(h=I,k=[C.name]):I===h&&!k.includes(C.name)&&k.push(C.name)}k.length>1&&g.add([...k].sort().join(" + "))}g.size>0&&s.push(J("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let f=r.filter(u=>!ge(u,i));f.length>0&&s.push(J("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));for(let u of zo(n))s.push(J("CONFIG_SLICE_IDENTITY_COLLISION",u.message,{paths:[...u.paths],fromLayer:u.from,toLayer:u.to,failsStrict:!1}));for(let u of ni(n,r))s.push(J(u.ruleId,u.message,{failsStrict:!1,...u.path?{file:u.path}:{},...u.fromLayer?{fromLayer:u.fromLayer}:{},...u.toLayer?{toLayer:u.toLayer}:{}}));for(let u of Ba({rules:n,pins:e.arkgatePins,runningVersion:e.runningArkgateVersion}))s.push(J(u.ruleId,u.message,{failsStrict:!1,file:u.path,line:u.line,nextAction:u.nextAction}));let m=Oo(t);if(m.length>0){let u=m[0]??"this layer";s.push(J("CONFIG_LAYER_MISSING_OWNER",`${u} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:m,nextAction:wo(u)}))}return s}a(qn,"collectAnalysisConfigWarnings");function za(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:da({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(za,"toArkRuleEngineViolation");function sg(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(sg,"arkRulesMapIsOn");function Wa(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(Wa,"arkRuleFindingNextAction");function og(e,t){return t.some(n=>{try{return ce(n).test(e)}catch{return!1}})}a(og,"matchesAny");function ig(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(h=>h.kind==="ts-suppression").map(({file:h,line:k})=>({file:h,line:k})),l=t.safetyUses.filter(h=>h.kind==="any-cast").map(({file:h,line:k})=>({file:h,line:k})),c=t.safetyUses.filter(h=>(h.kind==="dynamic-import"||h.kind==="dynamic-require")&&!og(h.file,s)).map(h=>({file:h.file,line:h.line,kind:h.kind==="dynamic-require"?"require":"import"})),d=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(h=>h.kind==="in-memory-store").map(h=>({file:h.file,line:h.line,store:h.symbol??"in-memory store"})),p=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(h=>h.peerIsolation===!1||h.allowed===!1&&!!h.from&&h.from===h.to&&h.peerIsolation!==!0).map(h=>({from:h.from,to:h.to})),g={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:d,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],m=c.filter(h=>h.kind==="import");if(m.length>0){let h=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let u=c.filter(h=>h.kind==="require");if(u.length>0){let h=u[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:h.file,line:h.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let h=i[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let h=l[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:h.file,line:h.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(d.length>0){let h=d[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:h.file,line:h.line,message:`${d.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:f}}a(ig,"evaluateSafety");function ag(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(ag,"ambientForbiddenGlobal");function qa(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Ir(e,n.length>0?n:Et.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(qa,"intentLayer");function lg(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||!ag(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],d=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&xt(s.symbol,c))){if(s.source==="import-based"){let p=Ne(s.symbol,c);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...d?{edgeKind:d}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}et(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 Ct({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=qa(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=qa(s.intent,e.contract);if(!l)continue;let c=Ee(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let d=c.sliceVerdict,p=`${i} must not reference ${l} intent ${s.intent}.`,g=d?st({surface:"intent",verdict:d,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,childMessage:c.rule.childSlices?.message,defaultMessage:p}):c.rule.message??p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},...Ke(d),message:g})}return r}a(lg,"contentViolations");function Ya(e,t){return t==="enforced"?{violations:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:n.failsStrict,...n.severity?{severity:n.severity}:{}})),warnings:[]}:{violations:[],warnings:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:!1}))}}a(Ya,"splitExtraPlaneFindings");function Yn(e){let{facts:t}=e,n=Dt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((R,y)=>{let A=`${R.code}\0${R.file??""}\0${R.message}`,L=`${y.code}\0${y.file??""}\0${y.message}`;return A<L?-1:A>L?1:0}),i=t.files.map(R=>({...R,layer:ge(R.path,e.contract.config.layers)??null})),l=new Map(i.map(R=>[R.path,R.layer])),c=t.dependencies.map(R=>{let y=R.target?l.get(R.target)??ge(R.target,e.contract.config.layers):void 0;return{from:R.from,fromLayer:l.get(R.from)??null,...R.resolution==="resolved-project"&&R.target?{to:R.target,...y?{toLayer:y}:{}}:{},line:R.line,kind:R.kind,typeOnly:R.typeOnly,...R.targetTypeOnlyExports?{targetTypeOnlyExports:R.targetTypeOnlyExports}:{},...R.sourcePureTypeModule?{sourcePureTypeModule:R.sourcePureTypeModule}:{},...R.namedBindingsTypeOnly?{namedBindingsTypeOnly:R.namedBindingsTypeOnly}:{},...R.portProofEligible?{portProofEligible:R.portProofEligible}:{}}}),d=qn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(R=>R.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),p=ig(e,t),g=e.contract.arkRules??Ge(),f=i.map(R=>R.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Is(e.coverageInputs.fileContents):{},...e.fileHints??{}},h=a(R=>l.get(R)??ge(R,e.contract.config.layers),"resolveLayer"),k=[...Ss({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:h,fileHints:u}),...ks(g,f),...Ea({arkRulesActive:sg(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(R=>({path:R,layer:h(R)}))})],C=(g.invariants?.length??0)>0,S=Ki({hasEnforcedInvariant:os(g.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),I=S.length>0?[]:Vi({adopted:e.adopted===!0,hasDomainInvariants:ss(g.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),E=[...S.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...I.map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],H=k.filter(R=>R.failsStrict).map(R=>za(R,Wa(R,!1))),N=k.filter(R=>!R.failsStrict).map(R=>({...za(R,Wa(R,!0)),failsStrict:!1})),$=C?ns({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},v=$.violations.filter(R=>R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,nextAction:`Add a test title or declared symbol covering ${R.arkruleId} (declared in ${R.arkruleSource}), then preflight again.`})),D=$.violations.filter(R=>!R.failsStrict).map(R=>({ruleId:R.ruleId,file:R.file,line:R.line,message:R.message,fromLayer:R.fromLayer,arkruleId:R.arkruleId,arkruleSource:R.arkruleSource,failsStrict:!1,nextAction:R.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${R.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${R.arkruleId} in ${R.arkruleSource} (advisory / partial).`})),w=vs(i),P=zn({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:a(R=>l.get(R)??ge(R,e.contract.config.layers),"layerForFile"),classification:w}),{violations:M,warnings:F}=Ya(P.findings,e.contract.config.arkRun?.mode),re=Ds({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,xiTtlKeys:t.arkOrderXiTtlKeys,budgetLeaks:t.arkOrderBudgetLeaks,dependencies:t.dependencies,layerForFile:a(R=>l.get(R)??ge(R,e.contract.config.layers),"layerForFile"),classification:w}),{violations:ke,warnings:St}=Ya(re.findings,e.contract.config.arkOrder?.mode),pr=[...$.partial&&$.coverage.some(R=>R.mode==="enforced"&&R.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...P.completenessReasons,...re.completenessReasons],je=mt({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(R=>R.layer).map(R=>R.path),contentViolations:[...lg(e,t,l),...H,...E,...v,...M,...ke],edges:c,warnings:[...d,...p.warnings,...N,...D,...F,...St],safety:p.report}),Xe=o==="complete"&&pr.length>0?"partial":o,en=Xe==="complete"?s:[...s,...pr].sort((R,y)=>{let A=`${R.code}\0${R.file??""}\0${R.message}`,L=`${y.code}\0${y.file??""}\0${y.message}`;return A<L?-1:A>L?1:0}),no=je.violations.filter(R=>R.failsStrict!==!1),tn=Xe==="complete"&&no.length===0,_=tn&&je.warnings.every(R=>R.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Xe,completenessReasons:en,valid:tn,strictValid:_,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(R=>R.name),edges:c,capabilityUses:t.capabilityUses,violations:je.violations,warnings:je.warnings}}}a(Yn,"analyzeCanonicalResolvedProject");function Xa(e){return Yn({contract:e.contract,facts:$e(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent,arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion})}a(Xa,"analyzeResolvedProject");function Za(e){return ee(Z(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Za,"analysisTreeHash");function Ja(e){let t=Kt(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],o=new Set,s=[];for(let u of e.changes){let h=u.path.replace(/\\/g,"/"),k=ze(u.path);if(!k||k===".."||k.startsWith("../")||h.startsWith("/")||/^[A-Za-z]:\//.test(h)||h.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(k)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}o.add(k),"delete"in u&&u.delete&&!n.has(k)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:k,delete:!0}:{path:k,content:"content"in u?u.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=Mn({...e,changes:r}),l=new Map(i.ir.files.map(u=>[u.path,u])),c=i.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let h=l.get(u.evidence.file)?.layer;return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...h?{fromLayer:h}:{},edgeKind:"import",message:u.message}}),d=mt({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(u=>u.path),contentViolations:c,edges:i.ir.edges.filter(u=>!!u.fromLayer).map(u=>({from:u.from,fromLayer:u.fromLayer,...u.to?{to:u.to}:{},...u.toLayer?{toLayer:u.toLayer}:{},line:u.evidence.line,kind:"import",...u.typeOnly?{typeOnly:!0}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(u=>{let h=ze(u.path),k=n.get(h),C=l.get(h);return{path:h,operation:"delete"in u&&u.delete?"delete":k?"update":"create",...k?{beforeContentHash:k.contentHash}:{},...C?{candidateContentHash:C.contentHash}:{}}}).sort((u,h)=>u.path.localeCompare(h.path)),g=[...s,...d.violations].map(u=>({...u,nextAction:he(u)})),f=g.filter(u=>u.failsStrict!==!1),m=e.changeMap?ut({changeMap:e.changeMap,changes:p,baseDependencies:dt(t.ir.edges),candidateDependencies:dt(i.ir.edges)}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Za(t.ir.files),candidateTreeHash:Za(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:d.warnings}}a(Ja,"preflightChange");function cg(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(cg,"identityViolations");function dg(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(dg,"preparedChange");function Xn(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}a(Xn,"isArkRulesPlaneRule");function Qa(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,e.file??"",t,e.target??e.message].join("|")}a(Qa,"ratchetKey");function el(e,t){let n=new Map;for(let r of e){if(!Xn(r.ruleId)||r.failsStrict===!1)continue;let o=Qa(r);n.set(o,(n.get(o)??0)+1)}return t.map(r=>{if(!Xn(r.ruleId))return r;let o=Qa(r),s=n.get(o)??0;return s===0?r:(n.set(o,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}a(el,"ratchetPreExistingArkRules");function ug(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>Xn(n.ruleId)),warnings:e.ir.warnings.filter(n=>Xn(n.ruleId))}}}a(ug,"baseAnalysisSummary");function tl(e){return pg(e,$e(e.baseFacts),$e(e.candidateFacts))}a(tl,"preflightResolvedChange");function pg(e,t,n){let r=ug(Yn({...e.baseAnalysisInputs??{},contract:e.contract,facts:t}),e.changeMap!==void 0),o=Yn({...e.candidateAnalysisInputs??{},contract:e.contract,facts:n}),s=new Map(t.files.map(h=>[h.path,h])),i=new Map(n.files.map(h=>[h.path,h])),l=cg(t,n),c=new Map,d=[];for(let h of e.changes){let k=hi(h.path);if(!k){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(k)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}c.set(k,h);let C=s.get(k),S=i.get(k);if("delete"in h&&h.delete)C||l.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base facts.`}),S&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:k,line:1,message:`Candidate facts still contain deleted file ${k}.`});else{let I="content"in h?h.content:"",E=ee(I);S?S.contentHash!==E&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:k,line:1,expectedContentHash:E,candidateContentHash:S.contentHash,message:`Candidate facts for ${k} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:k,line:1,message:`Candidate facts do not contain changed file ${k}.`})}d.push(dg(h,k,s,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let h of new Set([...s.keys(),...i.keys()])){if(c.has(h))continue;let k=s.get(h),C=i.get(h);k&&C&&Z(k)===Z(C)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:h,line:1,message:`Candidate facts change ${h}, but the atomic change set does not declare it.`})}let p=e.changeMap?ut({changeMap:e.changeMap,changes:d,baseDependencies:dt(r.ir.edges),candidateDependencies:dt(o.ir.edges)}):void 0,g=el(r.ir.violations,o.ir.violations),f=el(r.ir.warnings,o.ir.warnings),m=[...l,...g].map(h=>({...h,nextAction:he(h)})),u=m.filter(h=>h.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.completeness==="complete"&&f.every(h=>h.failsStrict===!1)&&u.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:d.sort((h,k)=>h.path<k.path?-1:h.path>k.path?1:0),violations:m,warnings:f}}a(pg,"preflightCanonicalChange");var fg="1.1";var gg="1.0";var mg="1.0",nl="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Zn="^sha256:[a-f0-9]{64}$",rl={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:Zn,description:"Project id previously returned by ark_identity or ark_manifest."}}},sl={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:Zn},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},hg={$schema:"https://json-schema.org/draft/2020-12/schema",$id:nl,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:Zn},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Zn},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:rl,binding:sl}};function yg(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(yg,"createProjectId");function Ag(e){return{schemaVersion:"1.0",...e}}a(Ag,"createProjectIdentity");var ol="1.0",Rg=12,Sg="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",kg="Next: /ark-runtime to wire one candidate.";function Ig(e){return e==="enforced"||e==="advisory"?e:null}a(Ig,"closedMode");function bg(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Es(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}a(bg,"uniqueArkRunRuleIds");function vg(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Ig(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(vg,"extraFromConfig");function Eg(e={}){let t=vg(e.arkRun),n=t.present&&Array.isArray(e.layerFlow?.layers)?Po({layers:e.layerFlow.layers,rules:Array.isArray(e.layerFlow.rules)?e.layerFlow.rules:[]}):[],r=t.present?bg(e.findings):[],o=r.slice(0,Rg),s=r.length,i=Un({classification:e.classification,arkRules:Cs(e.arkRules),arkRun:{present:t.present,mode:t.mode,residualCount:s}}),l=t.present&&t.mode==="enforced"&&Re(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:ol,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(Eg,"summarizeArkRunSection");function Fs(e={}){return Kn(e)}a(Fs,"projectStatusArkRun");function Cg(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[Sg,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),i=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${i}`),r.push(kg)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");let o=Array.isArray(e.layerFlowUnresolvable)?e.layerFlowUnresolvable:[];return o.length>0&&r.push(`Runtime layer flow: ${o.join(", ")} name(s) in a deny rule but map to no intent (no intentPrefixes, not a canonical layer). A kernel from this config cannot enforce those rules \u2014 add intentPrefixes (ARKRUN_LAYER_FLOW_UNRESOLVABLE).`),e.failMergeWhen&&r.push(e.failMergeWhen),r}a(Cg,"formatArkRunDoctorLines");function _g(e){let t=e.split("|",1)[0]??"";return t.startsWith("ARKRULE_")||t.startsWith("INVARIANT_")}a(_g,"isArkRulesFrozenKey");function Jn(e,t){return e.slice(0,t).split(`
|
|
21
|
+
`).length}a(Jn,"lineOf");function il(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(il,"normalizeInventoryPath");function ll(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}a(ll,"ownsIntent");function al(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||ll(t,["Domain"])}a(al,"isDomainLayer");function xg(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||ll(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}a(xg,"isControllerEligibleLayer");function Og(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(Og,"isNonPilotSurface");function wg(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,p])=>[il(d),p])),o=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),s=(e.layerContexts??[]).find(d=>al(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,p]of Object.entries(e.fileContents).sort(([g],[f])=>g.localeCompare(f))){let g=il(d);if(Og(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(p.slice(0,320)))continue;let f=r.has(g),m=r.get(g),u=m?o.get(m)??[]:[],h=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),k=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),C=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(p),S=/controller|handler|resolver/i.test(d)||k||C||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!h||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(p)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(p)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(p),I=f?!!(m&&xg(m,u)&&S):S,E=f?!!(m&&al(m,u)):/domain|entity|aggregate|model/i.test(d),H=!f||E||I;if(I&&!h){let w=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,P;for(;(P=w.exec(p))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:d,line:Jn(p,P.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:m,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let N=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,$,v=a(w=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(w)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(w)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(w)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(w)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(w)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(w)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(w)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(w)||/_(?:OID|OIDS)$/i.test(w)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(w)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(w),"isInfraMagicName"),D=a((w,P)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(w)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(w))return!0;let M=P.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(P)&&(/\s/.test(M)||/[.!?…]$/.test(M))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(w))},"isUxMessageConstant");for(;($=N.exec(p))!==null;){let w=$[2],P=$[3]??"";!H||v(w)||D(w,P)||h&&!E||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!E||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:d,line:Jn(p,$.index),message:`Magic business constant ${w} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:s,invariantId:`INV-${w}`},neverMechanicalSafe:!0}))}if(E){let w=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,P;for(;(P=w.exec(p))!==null;){let M=P[2]??"",F=(M.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(M.match(/:\s*[A-Za-z]/g)??[]).length>=2&&F<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:d,line:Jn(p,P.index),message:`Class ${P[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(E&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let P=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,M;for(;(M=P.exec(p))!==null;){let F=p.lastIndexOf("class ",M.index),re=F>=0?p.indexOf("{",F):-1,ke=F>=0&&re>=F&&re<M.index?p.slice(F,re):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(ke)||As(p,M.index))continue;let St=p.slice(Math.max(0,M.index-200),M.index+200);if(!ms.test(St)&&!hs.test(St)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:Jn(p,M.index),message:`Domain field mutation without nearby ${ys()}.`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let i=new Set(e.contractedRuleIds??[]);t.sort((d,p)=>+(p.confidence==="direct-evidence")-+(d.confidence==="direct-evidence")||d.file.localeCompare(p.file)||d.line-p.line||d.kind.localeCompare(p.kind)||d.id.localeCompare(p.id));let l=new Set((e.contractedStructure??[]).map(d=>`${d.layer}\0${d.sensor}`)),c=t.filter(d=>{let p=d.suggestedArkRule;return p?p.invariantId&&i.has(p.invariantId)?!0:p.structureId?p.sensor&&l.has(`${p.layer}\0${p.sensor}`)?!0:i.has(p.structureId):!1:!1}).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).filter(_g).length,notAScore:!0}}a(wg,"buildRulesInventory");function Tg(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(Tg,"inventoryToExtractionCard");function cl(e={}){return Kn(e)}a(cl,"projectStatusArkOrder");function dl(e){return{type:"object",description:`${e} extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.`,additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}a(dl,"extraPlaneStatusSchema");var Ms="1.0",ul="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",pl=["full","subset","unavailable"],fl=["doctor-facts","report-snapshot","none"],Qn={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},gl=/^sha256:[a-f0-9]{64}$/;function ml(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"||!gl.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(ml,"evaluateStatusBinding");function hl(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(hl,"classifyStatusWritePath");function yl(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(yl,"defaultHonestLabel");function Al(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(Al,"normalizedConfigErrors");function Rl(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=Al(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(Rl,"resolveStatusNextAction");function Pg(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&gl.test(e.projectId)?e.projectId:null,r=ml({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=hl({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():yl(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:Xt(e.activeViolations),frozenResidual:Xt(e.frozenResidual)},d={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Xt(e.rulesInventoried),underContract:Xt(e.rulesUnderContract),frozenResidual:Xt(e.rulesFrozenResidual)},p={writePath:i,host:s,honestLabel:l},g={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},f={schemaVersion:Ms,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:c,rules:d,nextAction:Rl(e,r,p,c,d)},m=Al(e.configErrors);g.resolvedConfigPath&&m.length>0&&(f.contract={valid:!1,errors:m});let u=kl(e.improvementCompass);return u&&(f.improvementCompass=u),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Fs(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=cl(e.arkOrder)),f}a(Pg,"buildStatusManifest");var Sl=new Set(pl),Ng=new Set(fl);function js(e){let t=Sl.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Ng.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:Qn.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:Qn.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(js,"projectStatusImprovementCompass");function Lg(e={}){return js({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??Qn.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(Lg,"unavailableStatusImprovementCompass");function kl(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"&&Sl.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",js({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(kl,"normalizeStatusImprovementCompass");function $g(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($g,"statusCompassResidualIsSubsetOfDoctor");function Xt(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}a(Xt,"numberOrNull");var Dg={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ul,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:Ms},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:dl("ArkRun"),arkOrder:dl("ArkOrder")}};var er="1.0",tr=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],nr=5,We=["scalability","resilience","security"],At=new Set(We),Hs={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},Vs={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"},Ks={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 Us(e){return Vs[e]??e}a(Us,"improvementCompassHumanLabel");function Gs(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}a(Gs,"smellIdOf");function Bs(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}a(Bs,"violationRuleId");function q(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}a(q,"pushEvidence");function oe(e,t,n){At.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}a(oe,"markResidual");function Il(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`${Vs[e]} \u2014 no residual from current sensors.`}}a(Il,"defaultOkSummary");function bl(){return tr.map(e=>At.has(e)?{id:e,status:"out-of-scope",summary:Ks[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:Il(e),evidence:[]}:{id:e,status:"ok",summary:Il(e),evidence:[]})}a(bl,"createInitialImprovementCompassLenses");function Fg(e,t){for(let n of t){let r=Gs(n);if(!r)continue;let o=n.outcome||n.message||void 0,i=(Array.isArray(n.evidence)?n.evidence:[])[0],l=a((p,g,f)=>{let m=e.get(p);!m||At.has(p)||(q(m,"designSmells",r,o),i&&q(m,"designSmells",i,r),oe(m,g,f))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},d={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":l("soc","Business rules still mix with UI or presentation surfaces.",c),l("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",c);break;case"facade-sql-in-routes":l("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",c),l("dip","Transport depends on concrete persistence instead of a port.",d);break;case"io-under-application":l("soc","Application/business code reaches I/O directly \u2014 separation is weak.",c),l("dip","I/O is not inverted behind ports/adapters.",d),l("testability","Direct I/O under application code hurts pure unit testing.",d);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}a(Fg,"mapDesignSmells");function Mg(e){return e.failsStrict===!1||e.typeOnly===!0}a(Mg,"isTypeOnlyPlacementDebt");function jg(e,t){for(let n of t){let r=Bs(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),i=a((c,d,p)=>{let g=e.get(c);!g||At.has(c)||(q(g,"violations",r,o),n.file&&q(g,"violations",n.file,r),oe(g,d,p))},"attach");if(Mg(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(jg,"mapViolations");function Hg(e,t){let n=Number(t.cycleCount)||0;if(n>0){let m=e.get("coupling");q(m,"cycles",`count:${n}`),oe(m,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let m=e.get("coupling");q(m,"peerIsolation",`count:${r}`),oe(m,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let m=e.get("cohesion");q(m,"physicalCohesion",`findings:${o}`),oe(m,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let u=e.get("srp");q(u,"physicalCohesion",`findings:${o}`),oe(u,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,i=Number(t.forbiddenGlobalResidual)||0;if(s>0||i>0){let m=e.get("dip");s>0&&q(m,"capability",`residual:${s}`),i>0&&q(m,"forbiddenGlobals",`residual:${i}`),oe(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let u=e.get("testability");s>0&&q(u,"capability",`residual:${s}`),i>0&&q(u,"forbiddenGlobals",`residual:${i}`),oe(u,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let m=e.get("encapsulation");q(m,"arkRules",`structureResidual:${l}`),oe(m,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let u=e.get("domain");q(u,"arkRules",`structureResidual:${l}`),oe(u,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let m=e.get("maintainability");q(m,"designFitness","design-weak"),oe(m,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let m=e.get("maintainability");t.dirtyBaselineRisk===!0&&q(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&q(m,"baseline",`stale:${t.baselineStale}`),oe(m,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let c=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&c>=10&&e.get("maintainability").status!=="residual"){let m=e.get("maintainability");q(m,"baseline",`frozen:${c}`),oe(m,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let d=Number(t.ungovernedDirCount)||0,p=Number(t.emptyLayerCount)||0;if(d>0||p>0){let m=e.get("modularity");d>0&&q(m,"coverage",`ungovernedDirs:${d}`),p>0&&q(m,"coverage",`emptyLayers:${p}`),oe(m,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let m=e.get("modularity");q(m,"goldenPattern","absent"),oe(m,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}a(Hg,"mapCountsAndFlags");function vl(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>Gs(r).localeCompare(Gs(o)));Fg(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=Bs(r).localeCompare(Bs(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});jg(e,n)}Hg(e,t)}a(vl,"projectImprovementCompassFacts");function El(e){for(let t of We){let n=e.get(t);n.status="out-of-scope",n.summary=Ks[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(El,"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 _l(e){return e.filter(n=>n.status==="residual"&&!At.has(n.id)).slice().sort((n,r)=>{let o=Hs[n.id]??150,s=Hs[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}a(_l,"finalizeImprovementCompassTopResidual");function Vg(e={}){let t=bl(),n=new Map(t.map(o=>[o.id,o]));vl(n,e),El(n),Cl(t);let r=_l(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(Vg,"buildImprovementCompass");function xl(e){return e.topResidual.map(t=>Us(t))}a(xl,"formatImprovementCompassResidualLabels");function Ol(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(Ol,"primaryImprovementCompassNextAction");function Kg(e){let t=xl(e),n=We.map(s=>Us(s)),r=Ol(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(Kg,"formatImprovementCompassDoctorLines");var qe="1.0",wl="<!-- arkgate:agent-projection:begin",rr="<!-- arkgate:agent-projection:end -->",sr="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"]),Tl=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 Rt(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(Rt,"agentProjectionContentIdentity");function Jt(e){return String(e??"").replace(/\r\n/g,`
|
|
23
|
+
`)}a(Jt,"normalizeNewlines");function Ye(e){let t=Jt(e);return t.endsWith(`
|
|
23
24
|
`)?t:`${t}
|
|
24
|
-
`}a(
|
|
25
|
+
`}a(Ye,"ensureTrailingNewline");function Qt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}a(Qt,"safeVersion");function Pl(e){return e==="compact"?"compact":"full"}a(Pl,"resolveProfile");function zs(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(zs,"buildAgentProjectionBeginMarker");function or(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
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(`
|
|
27
|
-
`)}`}a(
|
|
28
|
+
`)}`}a(or,"formatAgentProjectionLayers");function Ws(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).`}a(
|
|
31
|
-
`),""),
|
|
31
|
+
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}a(Ws,"formatAgentProjectionCatalogShortList");function ir(e){let t=Qt(e.arkgateVersion),n=Pl(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","",sr,"","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)","",or(l),""):d.push("### Contract layers","",or(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)","",Ws(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(p=>`- \`${p}\``).join(`
|
|
32
|
+
`),""),d.join(`
|
|
32
33
|
`).replace(/\n{3,}/g,`
|
|
33
34
|
|
|
34
35
|
`).trimEnd()+`
|
|
35
|
-
`}a(
|
|
36
|
-
${t}${
|
|
37
|
-
`}a(
|
|
38
|
-
`)&&(
|
|
39
|
-
`,s=
|
|
36
|
+
`}a(ir,"buildAgentProjectionBody");function Nl(e){let t=ir(e);return`${zs({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
|
|
37
|
+
${t}${rr}
|
|
38
|
+
`}a(Nl,"buildAgentProjectionBlock");function Ll(e){let t=ir(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:Rt(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:Pl(e.profile)}}a(Ll,"buildAgentProjectionMeta");var qs=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,$l=/<!--\s*arkgate:agent-projection:end\s*-->/i,Ug=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Gg=/\bschema=([A-Za-z0-9._+-]+)/i;function ar(e){let t=Jt(e??""),n=qs.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=$l.exec(s);if(!i)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=i.index,c=l+i[0].length,d=s.slice(0,l);d.startsWith(`
|
|
39
|
+
`)&&(d=d.slice(1));let p=t.slice(r,o+c),g=s.slice(c);return{block:p,body:d,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}a(ar,"extractAgentProjectionBlock");function Ys(e){let t=String(e??""),r=qs.exec(t)?.[1]??t,o=Ug.exec(r),s=Gg.exec(r),i=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:i}}a(Ys,"parseAgentProjectionStamp");function Dl(e,t){let n=Ys(e).arkgateVersion;return n?n===Qt(t):!1}a(Dl,"projectionMatchesPackageVersion");function Fl(e){return String(e??"").includes("non-authoritative")}a(Fl,"projectionHasNonEnforcementLabel");function Ml(e,t){let n=Ye(Jt(t)),o=ar(n).body??n.replace(qs,"").replace($l,"").trim()+`
|
|
40
|
+
`,s=Rt(o);if(e==null||!String(e).trim())return{content:Ye(`# Ark Enforcement
|
|
40
41
|
|
|
41
|
-
${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let i=
|
|
42
|
+
${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let i=Jt(e),l=ar(i);if(l.block!=null){let d=l.body??"";if(Rt(d)===s)return{content:Ye(i),action:"unchanged",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0};let p=l.before.replace(/\s*$/,`
|
|
42
43
|
|
|
43
|
-
`),
|
|
44
|
-
`);return{content:
|
|
45
|
-
${
|
|
44
|
+
`),g=l.after.replace(/^\s*/,`
|
|
45
|
+
`);return{content:Ye(`${p}${n.trimEnd()}
|
|
46
|
+
${g}`),action:"block-replaced",previousBlock:l.block,contentIdentity:s,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(i);if(c&&c.index!=null){let d=c.index+c[1].length,p=i.slice(0,d).replace(/\s*$/,`
|
|
46
47
|
|
|
47
|
-
`),
|
|
48
|
-
`);return{content:
|
|
49
|
-
${
|
|
48
|
+
`),g=i.slice(d).replace(/^\s*/,`
|
|
49
|
+
`);return{content:Ye(`${p}${n.trimEnd()}
|
|
50
|
+
${g}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:Ye(`${n.trimEnd()}
|
|
50
51
|
|
|
51
|
-
${i.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}a(
|
|
52
|
+
${i.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}a(Ml,"mergeAgentProjectionDocument");var Bg="1.0",Kl="templates/agent-skills",Ul="templates/skills",Gl="SKILL.md",zg=Object.freeze(["Contener","Guiar","Ordenar"]),Qs=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),Xs=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),lr=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"]}),cr=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),Bl=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),jl="Contener \xB7 Guiar \xB7 Ordenar",Hl="Do not invent `/ark-order`",dr=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"]),zl=dr.length,Wg=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Wl(e){return typeof e!="string"||e.length<1||e.length>64?!1:Wg.test(e)}a(Wl,"isValidAgentSkillName");function eo(e){return dr.includes(e)}a(eo,"isArkSkillName");function Zs(e){return Qs.includes(e)}a(Zs,"isFirstClassArkSkillName");function qg(e){return e in Xs?Xs[e]:null}a(qg,"arkSkillStubRedirect");function ql(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
|
|
55
|
-
`)}a(
|
|
55
|
+
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let p=1;p<o;p+=1){let g=r[p]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let f=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let m=f[1],u=f[2]??"";(u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1)),s[m]=u}let i=r.slice(o+1).join(n),l=typeof s.name=="string"&&s.name.length>0?s.name:null,c=typeof s.description=="string"&&s.description.length>0?s.description:null,d=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:l,description:c,license:d},body:i}}a(ql,"parseSkillDocument");function Yl(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=ql(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&&!eo(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(Yl,"validateAgentSkillDocument");function Yg(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(...Yl({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&Js(o.content)!==Js(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 dr)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)eo(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:zl,presentCount:r.length}}a(Yg,"validateAgentSkillsPackage");function fe(e,t){e.push(t)}a(fe,"pushCapacityIssue");function Vl(e,t){return e.includes(t)}a(Vl,"skillMentionsSurface");function Xg(e){let t=[],n=e.skills??{},r=Object.keys(lr);for(let s of cr)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)cr.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 cr){let i=lr[s];if(!i||i.length===0)continue;for(let c of i)Zs(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"&&Vl(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(Bl)){if(!lr[s]?.includes(i)||!Zs(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"||!Vl(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 Qs){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(jl),c=/When \/ not when|\*\*When:\*\*/.test(i),d=/Not when|Do \*\*not\*\* use|Prefer instead/.test(i),p=/Handoff|hand off|`\/ark-/i.test(i);(!l||!c||!d||!p)&&fe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is missing when / not when / handoff or Contener \xB7 Guiar \xB7 Ordenar. First-class skills must say when to use them and which sibling to call next.`}),i.includes(Hl)&&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(jl)||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(Hl)&&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(Xg,"validateSkillProductCapacity");var to=/^arkgate@(\S+)\.\s/;function Xl(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}a(Xl,"skillDescriptionVersionPrefix");function Zl(e){return String(e??"").replace(to,"")}a(Zl,"stripSkillDescriptionVersion");function Zg(e){return String(e??"").match(to)?.[1]??null}a(Zg,"parseSkillDescriptionVersion");function Jg(e,t){let n=Zl(e),r=typeof t=="string"?t.trim():"";return r?`${Xl(r)}${n}`:n}a(Jg,"stampSkillDescription");function Js(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
56
|
+
`)}a(Js,"normalizeSkillContent");function Jl(e){return`${e}/${Gl}`}a(Jl,"agentSkillEntryRelativePath");function Qg(e){return`${Kl}/${Jl(e)}`}a(Qg,"agentSkillPackageFileRelativePath");function em(e){return`${Ul}/${e}.md`}a(em,"flatSkillTemplateFileRelativePath");export{an as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,wl as AGENT_PROJECTION_BEGIN_MARKER,rr as AGENT_PROJECTION_END_MARKER,Zt as AGENT_PROJECTION_ENFORCEMENT_SURFACES,sr as AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,Kl as AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,Gl as AGENT_SKILL_ENTRY_FILENAME,Wr as ANALYSIS_IR_SCHEMA_VERSION,$s as ARKORDER_RULE_IDS,eg as ARKORDER_TIER1_SENSOR_IDS,Ma as ARKRUN_INTERACTION_NAME_INCOMPLETE,Pa as ARKRUN_KERNEL_FACTORY_CALLEES,hf as ARKRUN_KERNEL_INTERACTION_CALLEES,Ls as ARKRUN_RULE_IDS,jf as ARKRUN_TIER1_SENSOR_IDS,$a as ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,qe as ARK_AGENT_PROJECTION_SCHEMA_VERSION,Bg as ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,oo as ARK_ANALYSIS_RESULT_SCHEMA,on as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Rr as ARK_CONFIG_SCHEMA,le as ARK_CONFIG_SCHEMA_VERSION,gg as ARK_DESIGN_DELTA_SCHEMA_VERSION,fg as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Qs as ARK_FIRST_CLASS_SKILL_NAMES,er as ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,hg as ARK_PROJECT_IDENTITY_SCHEMA,nl as ARK_PROJECT_IDENTITY_SCHEMA_URL,mg as ARK_PROJECT_IDENTITY_SCHEMA_VERSION,Yr as ARK_RULES_SCHEMA,pt as ARK_RULES_SCHEMA_VERSION,ki as ARK_RULE_SENSORS,ol as ARK_RUN_DOCTOR_SCHEMA_VERSION,lr as ARK_SKILL_CAPACITY,Bl as ARK_SKILL_CAPACITY_DEDICATED_DOORS,to as ARK_SKILL_DESCRIPTION_VERSION_PATTERN,dr as ARK_SKILL_NAMES,zl as ARK_SKILL_NAME_COUNT,zg as ARK_SKILL_NORTH_STAR,cr as ARK_SKILL_REQUIRED_SURFACES,Xs as ARK_SKILL_STUB_REDIRECTS,Dg as ARK_STATUS_MANIFEST_SCHEMA,ul as ARK_STATUS_MANIFEST_SCHEMA_URL,Ms as ARK_STATUS_MANIFEST_SCHEMA_VERSION,De as ArkRulesValidationError,Tl as DEFAULT_AGENT_PROJECTION_RULE_IDS,rn as DIAGNOSTIC_CATALOG,tc as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,gr as DIAGNOSTIC_DOCS_RELATIVE_PATH,nc as DIAGNOSTIC_RULE_IDS,lf as EXTRA_MERGE_TEETH_GOVERNED_FLOOR,wn as EffectiveContractError,Ul as FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,We as IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,nr as IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,tr as IMPROVEMENT_LENS_IDS,Oa as MERGE_PLANES_DUAL_STAMP,cs as POLICY_DELTA_SCHEMA_VERSION,sl as PROJECT_BINDING_SCHEMA,rl as PROJECT_EXPECTATION_SCHEMA,zr as RESOLVED_CANDIDATE_FACTS_SCHEMA,Ue as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,fl as STATUS_COMPASS_FACTS_SOURCES,pl as STATUS_COMPASS_MODES,Qn as STATUS_COMPASS_REASON_CODES,cn as adapterDocsCodePath,It as adapterFindingOccurrenceTargetKeys,ln as adapterFindingRefFromTargetKey,kt as adapterFindingTargetKey,Rt as agentProjectionContentIdentity,Jl as agentSkillEntryRelativePath,Qg as agentSkillPackageFileRelativePath,ut as analyzeArchitectureConvergence,Mn as analyzeChange,ia as analyzePolicyDelta,Kt as analyzeProject,Xa as analyzeResolvedProject,Bn as arkRunKernelCallKind,qg as arkSkillStubRedirect,zs as buildAgentProjectionBeginMarker,Nl as buildAgentProjectionBlock,ir as buildAgentProjectionBody,Ll as buildAgentProjectionMeta,Is as buildArkRuleFileHints,Xr as buildEffectiveArkRules,Vg as buildImprovementCompass,wg as buildRulesInventory,Pg as buildStatusManifest,rs as canPromoteInvariant,ac as catalogFixForRuleId,lc as catalogWhyForRuleId,ds as classifyArkPolicyDelta,Mu as classifyCoverage,vs as classifyResolvedLayerCoverage,hl as classifyStatusWritePath,qn as collectAnalysisConfigWarnings,ks as collectEmptyAppliesToFindings,at as collectForbiddenCapabilityUses,Un as composeMergePlanesHonesty,ji as countsAsCoverage,pi as createAICodeGate,Ic as createAdapterResult,Rn as createArchitectureProfile,No as createArchitectureProfileFromArkConfig,Lo as createElevenLayerArkConfig,yg as createProjectId,Ag as createProjectIdentity,Br as createResolvedCandidateFacts,yl as defaultHonestLabel,cf as demoteExtraPlaneTeethUnderClassificationFloor,Ca as deriveArkRuleFileHints,Hi as describeCoverage,fs as detectArchitectureCycles,ee as deterministicHash,ro as diagnosticDocsFragment,oc as diagnosticDocsPath,Jr as effectiveContractPolicyPayload,An as elevenLayerProfile,Ge as emptyEffectiveArkRules,mt as evaluateArchitectureGraph,Ds as evaluateArkOrderSensors,Ss as evaluateArkRuleSensors,Ha as evaluateArkRunEditorSensors,Qf as evaluateArkRunEditorSensorsFromSource,zn as evaluateArkRunSensors,ns as evaluateInvariantCoverage,ml as evaluateStatusBinding,aa as explainViolation,Re as extraMergeTeethAllowed,ar as extractAgentProjectionBlock,Mf as extractArkRunDeclarationsFromSource,Ts as extractArkRunImportedConstructorNamesFromSource,Ps as extractArkRunKernelCallsFromSource,Ns as extractArkRunManagedNewsFromSource,Os as extractArkRunValueImportDependenciesFromSource,af as extractClassShapesFromSource,it as extractSemanticDependencies,em as flatSkillTemplateFileRelativePath,Ws as formatAgentProjectionCatalogShortList,or as formatAgentProjectionLayers,Cg as formatArkRunDoctorLines,Kg as formatImprovementCompassDoctorLines,xl as formatImprovementCompassResidualLabels,sn as getDiagnosticCatalogEntry,Tg as inventoryToExtractionCard,_a as isArkOrderRuleId,yt as isArkRunKernelModuleSpecifier,Es as isArkRunRuleId,xs as isArkRunTransportBypassSpecifier,eo as isArkSkillName,sc as isCataloguedOrArkRuleFamily,xa as isExtraPlaneFinding,Zs as isFirstClassArkSkillName,rc as isKnownDiagnosticCode,Wl as isValidAgentSkillName,hn as loadArkConfigContract,Mt as loadArkRulesContract,Fn as loadContract,$e as loadResolvedCandidateFacts,Ml as mergeAgentProjectionDocument,bs as normalizeExtraMergeTeethClassification,Js as normalizeSkillContent,kl as normalizeStatusImprovementCompass,Ys as parseAgentProjectionStamp,Sr as parseArkConfigJson,Su as parseArkRulesJson,Zg as parseSkillDescriptionVersion,ql as parseSkillDocument,us as policyDeltaAcknowledgementMatches,Ja as preflightChange,tl as preflightResolvedChange,Ol as primaryImprovementCompassNextAction,Fs as projectStatusArkRun,js as projectStatusImprovementCompass,Fl as projectionHasNonEnforcementLabel,Dl as projectionMatchesPackageVersion,ku as resolveEffectiveContract,Rl as resolveStatusNextAction,Dt as resolvedFactsEvidenceRequirementsHash,ic as serializeDiagnosticCatalog,Xl as skillDescriptionVersionPrefix,Z as stableSerialize,Jg as stampSkillDescription,$g as statusCompassResidualIsSubsetOfDoctor,Zl as stripSkillDescriptionVersion,Eg as summarizeArkRunSection,hr as toAdapterDiagnostic,Lg as unavailableStatusImprovementCompass,Yl as validateAgentSkillDocument,Yg as validateAgentSkillsPackage,Xg as validateSkillProductCapacity,ec as version};
|