arkgate 4.8.25 → 4.8.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +2 -2
- package/bin/lib/policy-delta-io.mjs +5 -4
- package/bin/lib/project-root.mjs +12 -23
- package/dist/{chunk-AHACEKSV.js → chunk-G3JRBJGH.js} +1 -1
- package/dist/{chunk-UN5EH4QV.cjs → chunk-R3AJ5RSZ.cjs} +1 -1
- package/dist/eslint/index.cjs +1 -1
- package/dist/eslint/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +5 -5
- package/dist/runtime/index.d.cts +1 -1
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/docs/README.md +2 -1
- package/docs/agent-guide.md +6 -4
- package/docs/ai-gates.md +1 -1
- package/docs/diagnostics.md +1 -1
- package/docs/product-voice.md +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
package/dist/runtime/index.d.cts
CHANGED
|
@@ -447,7 +447,7 @@ declare function createSaga<P extends SagaContext = SagaContext>(def: SagaDefini
|
|
|
447
447
|
}): SagaInstance<P>;
|
|
448
448
|
|
|
449
449
|
/** ArkGate library version — single source of truth. */
|
|
450
|
-
declare const version = "4.8.
|
|
450
|
+
declare const version = "4.8.26";
|
|
451
451
|
|
|
452
452
|
/** Versioned public result contract types + JSON Schema (adapter envelope). */
|
|
453
453
|
/**
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -447,7 +447,7 @@ declare function createSaga<P extends SagaContext = SagaContext>(def: SagaDefini
|
|
|
447
447
|
}): SagaInstance<P>;
|
|
448
448
|
|
|
449
449
|
/** ArkGate library version — single source of truth. */
|
|
450
|
-
declare const version = "4.8.
|
|
450
|
+
declare const version = "4.8.26";
|
|
451
451
|
|
|
452
452
|
/** Versioned public result contract types + JSON Schema (adapter envelope). */
|
|
453
453
|
/**
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as ko,A as Ne,Aa as qr,B as Ee,C as zn,D as Wn,E as de,F as qn,G as Ht,H as Qa,I as eo,J as to,K as no,L as ro,M as so,N as ao,O as oo,P as io,Q as lo,R as co,S as uo,T as po,U as fo,V as go,W as mo,X as ho,Y as yo,Z as Ro,_ as Ao,a as qa,aa as vo,b as Dn,ba as bo,c as Fn,ca as Io,d as $n,da as Eo,e as Mn,ea as So,f as dt,fa as Co,g as $t,ga as _o,h as be,ha as Oo,i as Be,ia as xo,j as Ya,ja as wo,k as Xa,ka as To,l as Za,la as No,m as Ja,ma as Po,n as Te,na as Lo,o as ut,oa as Do,p as Ie,pa as Fo,q as Hn,qa as $o,r as ae,ra as Mo,s as Kn,sa as Ho,t as Vn,ta as Vr,u as Un,ua as Ur,v as Gn,va as Gr,w as jn,wa as jr,x as Bn,xa as Br,y as Mt,ya as zr,z as pt,za as Wr}from"../chunk-AHACEKSV.js";import{A as Rr,B as Ar,C as kr,D as vr,E as br,F as Ir,G as Er,H as Sr,I as Cr,J as _r,K as Or,L as xr,M as wr,N as Tr,O as Nr,P as Pr,Q as Lr,R as Dr,S as Fr,T as $r,U as Mr,V as Hr,W as Kr,a as i,c as Yn,d as Xn,f as Zn,g as Jn,h as Qn,i as er,j as tr,k as nr,l as rr,m as sr,n as ar,o as or,p as ir,q as lr,r as cr,s as dr,t as ur,u as pr,v as fr,w as gr,x as mr,y as hr,z as yr}from"../chunk-SVSQVGFJ.js";var Kt="docs/diagnostics.md",Ko="1.0";function v(e,t,n,r,a,s){return{ruleId:e,title:n,why:r,fix:a,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(v,"entry");var ft=Object.freeze([v("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."),v("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."),v("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."),v("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}),v("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."),v("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}),v("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}),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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}),v("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."),v("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}),v("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."),v("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."),v("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}),v("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."),v("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}),v("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}),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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."),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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."),v("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}),v("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}),v("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}),v("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.")]),Vt=new Map(ft.map(e=>[e.ruleId,e])),Vo=Object.freeze(ft.map(e=>e.ruleId));function Uo(e){return typeof e=="string"&&e.length>0&&Vt.has(e)}i(Uo,"isKnownDiagnosticCode");function Go(e){return typeof e!="string"||e.length===0?!1:Vt.has(e)?!0:e.startsWith("ARKRULE_")}i(Go,"isCataloguedOrArkRuleFamily");function gt(e){if(!(typeof e!="string"||e.length===0))return Vt.get(e)}i(gt,"getDiagnosticCatalogEntry");function Yr(e){return`#${gt(e)?.docsAnchor??e}`}i(Yr,"diagnosticDocsFragment");function jo(e){return`${Kt}${Yr(e)}`}i(jo,"diagnosticDocsPath");function Bo(){return{schemaVersion:"1.0",docsPath:Kt,codes:ft}}i(Bo,"serializeDiagnosticCatalog");function zo(e){return gt(e)?.fix}i(zo,"catalogFixForRuleId");function Wo(e){return gt(e)?.why}i(Wo,"catalogWhyForRuleId");var qo=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."})]),Yo=new Map(qo.map(e=>[e.reasonId,e]));function Xr(e){if(!(typeof e!="string"||e.length===0))return Yo.get(e)}i(Xr,"sliceReasonHint");var Xo=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Zo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Jo=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Qo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),a=String(t?.toLayer??"");return Xo.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Zo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${a} ${n}`))?"kernel-emit":Jo.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&a==="PersistenceAdapters"?"use-case":"unknown"}i(Qo,"classifyLayerImportKind");function ei(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}i(ei,"sliceHintAction");function ti(e){let t=Xr(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${ei(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=Qo(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."}i(ti,"layerImportNextAction");function ni(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ni,"arkRunCallSiteName");function ri(e){let t=ni(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ri,"arkRunNextAction");function ie(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ti(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 ri(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ie,"deterministicNextAction");var mt="1.5",Ut="docs/diagnostics.md",Zr={$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 ht(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,a=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",a??"",s??""].join("|")}i(ht,"adapterFindingTargetKey");function yt(e){let t=new Map;return e.map(n=>{let r=ht(n),a=(t.get(r)??0)+1;return t.set(r,a),a===1?r:`${r}#${a}`})}i(yt,"adapterFindingOccurrenceTargetKeys");function Gt(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Gt,"adapterFindingRefFromTargetKey");function jt(e){return`${Ut}#${e}`}i(jt,"adapterDocsCodePath");function _(e){return typeof e=="string"&&e.length>0?e:void 0}i(_,"text");function Jr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Jr,"positiveInteger");function si(e,t,n){return ie({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0,reasonId:_(t.reasonId)??void 0})}i(si,"nextActionForDiagnostic");var ai=new Set(["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]);function oi(e){let t=e.details,n=t!==null&&typeof t=="object"?t.reasonId:void 0,r=_(e.reasonId)??_(n);return r&&ai.has(r)?r:void 0}i(oi,"sliceReasonOf");function Bt(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",a=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s=oi(e),o={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},..._(e.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{},...s?{reasonId:s}:{},...s&&_(e.universeFrom)?{universeFrom:_(e.universeFrom)}:{},...s&&_(e.universeTo)?{universeTo:_(e.universeTo)}:{}},c=n??ht(e),l=Gt(c);return{ruleId:r,severity:a,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:Jr(e.line,1),column:Jr(e.column,1)},evidence:o,nextAction:_(e.nextAction)??si(r,o,e),findingRef:l,targetKey:c,docsCodePath:jt(r)}}i(Bt,"toAdapterDiagnostic");function ii(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(h=>({code:_(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(h.message)??`Analysis ${t}: required evidence is incomplete.`,..._(h.file)?{file:_(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],a={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!a[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],o=e.warnings??[],c=yt(s),l=yt(o),p=[...s.map((h,u)=>Bt(h,"error",c[u])),...o.map((h,u)=>Bt(h,"warning",l[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...a};let h={policyHash:a.policyHash,resolverIdentity:a.resolverIdentity,factsHash:a.factsHash,candidateTreeHash:a.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...h}:{...f,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...a}:{...f,mode:n,valid:!1,completeness:t,...a}}i(ii,"createAdapterResult");var Wt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Yt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Xt=Object.freeze(Object.keys(Yt).sort()),zt=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"}),qt=Object.freeze({process:Object.freeze(["process","node:process"])});function ze(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=zt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),a=zt[r];if(a)return a;let s=e.indexOf("/",n+1);return s<0?null:zt[e.slice(0,s)]??null}i(ze,"capabilityForModuleSpecifier");function he(e,t){for(let n of t)if(qt[n]?.includes(e))return n;return null}i(he,"forbiddenGlobalForModuleSpecifier");function Rt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),a=Yt[r];if(a)return a}return null}i(Rt,"capabilityForAmbientName");function Pe(e){if(e?.pure===!0)return[...Wt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Wt.includes(r));return[...new Set(n)].sort()}i(Pe,"effectiveCapabilityDeny");function We(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let a=r.length;a>=1;a-=1)if(n.has(r.slice(0,a).join(".")))return!0;return!1}i(We,"ambientCoveredByForbiddenGlobals");function At(e){let t=new Set,n=new Set,r=Object.keys(Yt);for(let a of e?.forbiddenGlobals??[]){let s=r.filter(o=>o===a||o.startsWith(`${a}.`));if(s.length===0)n.add(a);else for(let o of s)t.add(`ambient:${o}`);for(let o of qt[a]??[])t.add(`import-exact:${o}`)}for(let a of Pe(e)){if(t.add(`import:${a}`),a==="process")for(let s of qt.process)t.add(`import-exact:${s}`);for(let s of r)Rt(s)===a&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(At,"loweredLayerCoverage");function Le(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Le,"literalText");function ts(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(ts,"lineOf");function Qr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let a=r.namedBindings;return!!(a&&e.isNamedImports(a)&&a.elements.length>0&&a.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(Qr,"isTypeOnlyReference");function ns(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=a=>a===t.fileName?t:void 0,r.fileExists=a=>a===t.fileName,r.readFile=a=>a===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(ns,"singleFileChecker");function Zt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Zt,"symbolAt");function Jt(e,t,n,r){let a=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=a?t.getShorthandAssignmentValueSymbol(r.parent):Zt(t,r)}catch{s=void 0}return!!s?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}i(Jt,"localDeclaration");function De(e,t){let n,r=[],a=i((o,c,l,p=!1)=>r.push({specifier:l,kind:c,line:ts(t,o),typeOnly:p,unresolved:l===void 0,node:o}),"add"),s=i(o=>{if(e.isImportDeclaration(o))a(o,"import",Le(e,o.moduleSpecifier),Qr(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)a(o,"export",Le(e,o.moduleSpecifier),Qr(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))a(o,"require",Le(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let c=o.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Jt(e,n??(n=ns(e,t)),t,o.expression);(c||p)&&a(o,p?"require":"dynamic-import",Le(e,o.arguments[0]))}e.forEachChild(o,s)},"visit");return s(t),r}i(De,"extractSemanticDependencies");function li(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let a=Le(e,r.argumentExpression);if(a===void 0)return;n.unshift(a)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(li,"staticAccessPath");function ci(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(ci,"runtimeIdentifierReference");function es(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let a=n.slice(0,r).join(".");if(e.has(a))return a}}i(es,"bestForbiddenMatch");function Fe(e,t,n){if(n.length===0)return[];let r=new Set(n),a=ns(e,t),s=new Map,o=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let A of u.declarationList.declarations)e.isIdentifier(A.name)&&o.add(A.name.text);let c=i(u=>{let A=li(e,u);if(!A)return;let d=Zt(a,A.root),g=d?s.get(d):void 0;return g?[...g,...A.segments.slice(1)]:Jt(e,a,t,A.root)||o.has(A.root.text)?void 0:A.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let A of u.declarationList.declarations){if(!A.initializer||!e.isIdentifier(A.name))continue;let d=c(A.initializer),g=Zt(a,A.name);!d||!g||s.set(g,d)}let l=[],p=new Set,f=i((u,A)=>{let d=ts(t,A),g=`${u}:${A.getStart(t)}`;p.has(g)||(p.add(g),l.push({name:u,line:d,node:A}))},"flag"),h=i(u=>{let A=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!A){let d=c(u),g=d?es(r,d):void 0;g&&f(g,u)}else e.isIdentifier(u)&&r.has(u.text)&&ci(e,u)&&!Jt(e,a,t,u)&&f(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let d=c(u.initializer);if(d)for(let g of u.name.elements){if(!e.isIdentifier(g.name))continue;let b=g.propertyName?Le(e,g.propertyName)??g.propertyName.text:g.name.text,x=es(r,[...d,b]);x&&f(x,u.initializer)}}e.forEachChild(u,h)},"visit");return h(t),l}i(Fe,"collectForbiddenCapabilityUses");function Qt(e,t,n){let r=[];for(let a of n?.dependencies??De(e,t)){if(a.typeOnly||!a.specifier)continue;let s=ze(a.specifier);s&&r.push({capability:s,symbol:a.specifier,line:a.line,source:"import-based"})}for(let a of n?.ambientUses??Fe(e,t,Xt)){let s=Rt(a.name);s&&r.push({capability:s,symbol:a.name,line:a.line,source:"ambient-global"})}return r.sort((a,s)=>a.line-s.line||a.capability.localeCompare(s.capability)||a.symbol.localeCompare(s.symbol))}i(Qt,"collectCapabilityUses");function B(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(B,"violation");function di(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."}i(di,"peerSuggestion");function $e(e,t){return e.slice(0,t).split(`
|
|
1
|
+
import{$ as ko,A as Ne,Aa as qr,B as Ee,C as zn,D as Wn,E as de,F as qn,G as Ht,H as Qa,I as eo,J as to,K as no,L as ro,M as so,N as ao,O as oo,P as io,Q as lo,R as co,S as uo,T as po,U as fo,V as go,W as mo,X as ho,Y as yo,Z as Ro,_ as Ao,a as qa,aa as vo,b as Dn,ba as bo,c as Fn,ca as Io,d as $n,da as Eo,e as Mn,ea as So,f as dt,fa as Co,g as $t,ga as _o,h as be,ha as Oo,i as Be,ia as xo,j as Ya,ja as wo,k as Xa,ka as To,l as Za,la as No,m as Ja,ma as Po,n as Te,na as Lo,o as ut,oa as Do,p as Ie,pa as Fo,q as Hn,qa as $o,r as ae,ra as Mo,s as Kn,sa as Ho,t as Vn,ta as Vr,u as Un,ua as Ur,v as Gn,va as Gr,w as jn,wa as jr,x as Bn,xa as Br,y as Mt,ya as zr,z as pt,za as Wr}from"../chunk-G3JRBJGH.js";import{A as Rr,B as Ar,C as kr,D as vr,E as br,F as Ir,G as Er,H as Sr,I as Cr,J as _r,K as Or,L as xr,M as wr,N as Tr,O as Nr,P as Pr,Q as Lr,R as Dr,S as Fr,T as $r,U as Mr,V as Hr,W as Kr,a as i,c as Yn,d as Xn,f as Zn,g as Jn,h as Qn,i as er,j as tr,k as nr,l as rr,m as sr,n as ar,o as or,p as ir,q as lr,r as cr,s as dr,t as ur,u as pr,v as fr,w as gr,x as mr,y as hr,z as yr}from"../chunk-SVSQVGFJ.js";var Kt="docs/diagnostics.md",Ko="1.0";function v(e,t,n,r,a,s){return{ruleId:e,title:n,why:r,fix:a,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(v,"entry");var ft=Object.freeze([v("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."),v("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."),v("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."),v("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}),v("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."),v("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}),v("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}),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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}),v("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."),v("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}),v("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."),v("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."),v("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}),v("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."),v("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}),v("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}),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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."),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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."),v("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}),v("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}),v("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}),v("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}),v("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}),v("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}),v("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."),v("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}),v("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}),v("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}),v("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.")]),Vt=new Map(ft.map(e=>[e.ruleId,e])),Vo=Object.freeze(ft.map(e=>e.ruleId));function Uo(e){return typeof e=="string"&&e.length>0&&Vt.has(e)}i(Uo,"isKnownDiagnosticCode");function Go(e){return typeof e!="string"||e.length===0?!1:Vt.has(e)?!0:e.startsWith("ARKRULE_")}i(Go,"isCataloguedOrArkRuleFamily");function gt(e){if(!(typeof e!="string"||e.length===0))return Vt.get(e)}i(gt,"getDiagnosticCatalogEntry");function Yr(e){return`#${gt(e)?.docsAnchor??e}`}i(Yr,"diagnosticDocsFragment");function jo(e){return`${Kt}${Yr(e)}`}i(jo,"diagnosticDocsPath");function Bo(){return{schemaVersion:"1.0",docsPath:Kt,codes:ft}}i(Bo,"serializeDiagnosticCatalog");function zo(e){return gt(e)?.fix}i(zo,"catalogFixForRuleId");function Wo(e){return gt(e)?.why}i(Wo,"catalogWhyForRuleId");var qo=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."})]),Yo=new Map(qo.map(e=>[e.reasonId,e]));function Xr(e){if(!(typeof e!="string"||e.length===0))return Yo.get(e)}i(Xr,"sliceReasonHint");var Xo=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Zo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Jo=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Qo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),a=String(t?.toLayer??"");return Xo.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Zo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${a} ${n}`))?"kernel-emit":Jo.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&a==="PersistenceAdapters"?"use-case":"unknown"}i(Qo,"classifyLayerImportKind");function ei(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}i(ei,"sliceHintAction");function ti(e){let t=Xr(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${ei(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=Qo(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."}i(ti,"layerImportNextAction");function ni(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ni,"arkRunCallSiteName");function ri(e){let t=ni(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ri,"arkRunNextAction");function ie(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ti(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 ri(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ie,"deterministicNextAction");var mt="1.5",Ut="docs/diagnostics.md",Zr={$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 ht(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,a=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",a??"",s??""].join("|")}i(ht,"adapterFindingTargetKey");function yt(e){let t=new Map;return e.map(n=>{let r=ht(n),a=(t.get(r)??0)+1;return t.set(r,a),a===1?r:`${r}#${a}`})}i(yt,"adapterFindingOccurrenceTargetKeys");function Gt(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(Gt,"adapterFindingRefFromTargetKey");function jt(e){return`${Ut}#${e}`}i(jt,"adapterDocsCodePath");function _(e){return typeof e=="string"&&e.length>0?e:void 0}i(_,"text");function Jr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Jr,"positiveInteger");function si(e,t,n){return ie({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0,reasonId:_(t.reasonId)??void 0})}i(si,"nextActionForDiagnostic");var ai=new Set(["CROSS_PARENT_SLICE","CROSS_SIBLING_SLICE","CROSS_PARENT_VIA_SHARED"]);function oi(e){let t=e.details,n=t!==null&&typeof t=="object"?t.reasonId:void 0,r=_(e.reasonId)??_(n);return r&&ai.has(r)?r:void 0}i(oi,"sliceReasonOf");function Bt(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",a=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s=oi(e),o={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},..._(e.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{},...s?{reasonId:s}:{},...s&&_(e.universeFrom)?{universeFrom:_(e.universeFrom)}:{},...s&&_(e.universeTo)?{universeTo:_(e.universeTo)}:{}},c=n??ht(e),l=Gt(c);return{ruleId:r,severity:a,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:Jr(e.line,1),column:Jr(e.column,1)},evidence:o,nextAction:_(e.nextAction)??si(r,o,e),findingRef:l,targetKey:c,docsCodePath:jt(r)}}i(Bt,"toAdapterDiagnostic");function ii(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(h=>({code:_(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(h.message)??`Analysis ${t}: required evidence is incomplete.`,..._(h.file)?{file:_(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],a={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!a[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],o=e.warnings??[],c=yt(s),l=yt(o),p=[...s.map((h,u)=>Bt(h,"error",c[u])),...o.map((h,u)=>Bt(h,"warning",l[u]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...a};let h={policyHash:a.policyHash,resolverIdentity:a.resolverIdentity,factsHash:a.factsHash,candidateTreeHash:a.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...h}:{...f,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...a}:{...f,mode:n,valid:!1,completeness:t,...a}}i(ii,"createAdapterResult");var Wt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Yt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Xt=Object.freeze(Object.keys(Yt).sort()),zt=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"}),qt=Object.freeze({process:Object.freeze(["process","node:process"])});function ze(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=zt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),a=zt[r];if(a)return a;let s=e.indexOf("/",n+1);return s<0?null:zt[e.slice(0,s)]??null}i(ze,"capabilityForModuleSpecifier");function he(e,t){for(let n of t)if(qt[n]?.includes(e))return n;return null}i(he,"forbiddenGlobalForModuleSpecifier");function Rt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),a=Yt[r];if(a)return a}return null}i(Rt,"capabilityForAmbientName");function Pe(e){if(e?.pure===!0)return[...Wt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Wt.includes(r));return[...new Set(n)].sort()}i(Pe,"effectiveCapabilityDeny");function We(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let a=r.length;a>=1;a-=1)if(n.has(r.slice(0,a).join(".")))return!0;return!1}i(We,"ambientCoveredByForbiddenGlobals");function At(e){let t=new Set,n=new Set,r=Object.keys(Yt);for(let a of e?.forbiddenGlobals??[]){let s=r.filter(o=>o===a||o.startsWith(`${a}.`));if(s.length===0)n.add(a);else for(let o of s)t.add(`ambient:${o}`);for(let o of qt[a]??[])t.add(`import-exact:${o}`)}for(let a of Pe(e)){if(t.add(`import:${a}`),a==="process")for(let s of qt.process)t.add(`import-exact:${s}`);for(let s of r)Rt(s)===a&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(At,"loweredLayerCoverage");function Le(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Le,"literalText");function ts(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(ts,"lineOf");function Qr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let a=r.namedBindings;return!!(a&&e.isNamedImports(a)&&a.elements.length>0&&a.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(Qr,"isTypeOnlyReference");function ns(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=a=>a===t.fileName?t:void 0,r.fileExists=a=>a===t.fileName,r.readFile=a=>a===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(ns,"singleFileChecker");function Zt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Zt,"symbolAt");function Jt(e,t,n,r){let a=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=a?t.getShorthandAssignmentValueSymbol(r.parent):Zt(t,r)}catch{s=void 0}return!!s?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}i(Jt,"localDeclaration");function De(e,t){let n,r=[],a=i((o,c,l,p=!1)=>r.push({specifier:l,kind:c,line:ts(t,o),typeOnly:p,unresolved:l===void 0,node:o}),"add"),s=i(o=>{if(e.isImportDeclaration(o))a(o,"import",Le(e,o.moduleSpecifier),Qr(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)a(o,"export",Le(e,o.moduleSpecifier),Qr(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))a(o,"require",Le(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let c=o.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Jt(e,n??(n=ns(e,t)),t,o.expression);(c||p)&&a(o,p?"require":"dynamic-import",Le(e,o.arguments[0]))}e.forEachChild(o,s)},"visit");return s(t),r}i(De,"extractSemanticDependencies");function li(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let a=Le(e,r.argumentExpression);if(a===void 0)return;n.unshift(a)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(li,"staticAccessPath");function ci(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(ci,"runtimeIdentifierReference");function es(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let a=n.slice(0,r).join(".");if(e.has(a))return a}}i(es,"bestForbiddenMatch");function Fe(e,t,n){if(n.length===0)return[];let r=new Set(n),a=ns(e,t),s=new Map,o=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let A of u.declarationList.declarations)e.isIdentifier(A.name)&&o.add(A.name.text);let c=i(u=>{let A=li(e,u);if(!A)return;let d=Zt(a,A.root),g=d?s.get(d):void 0;return g?[...g,...A.segments.slice(1)]:Jt(e,a,t,A.root)||o.has(A.root.text)?void 0:A.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let A of u.declarationList.declarations){if(!A.initializer||!e.isIdentifier(A.name))continue;let d=c(A.initializer),g=Zt(a,A.name);!d||!g||s.set(g,d)}let l=[],p=new Set,f=i((u,A)=>{let d=ts(t,A),g=`${u}:${A.getStart(t)}`;p.has(g)||(p.add(g),l.push({name:u,line:d,node:A}))},"flag"),h=i(u=>{let A=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!A){let d=c(u),g=d?es(r,d):void 0;g&&f(g,u)}else e.isIdentifier(u)&&r.has(u.text)&&ci(e,u)&&!Jt(e,a,t,u)&&f(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let d=c(u.initializer);if(d)for(let g of u.name.elements){if(!e.isIdentifier(g.name))continue;let b=g.propertyName?Le(e,g.propertyName)??g.propertyName.text:g.name.text,x=es(r,[...d,b]);x&&f(x,u.initializer)}}e.forEachChild(u,h)},"visit");return h(t),l}i(Fe,"collectForbiddenCapabilityUses");function Qt(e,t,n){let r=[];for(let a of n?.dependencies??De(e,t)){if(a.typeOnly||!a.specifier)continue;let s=ze(a.specifier);s&&r.push({capability:s,symbol:a.specifier,line:a.line,source:"import-based"})}for(let a of n?.ambientUses??Fe(e,t,Xt)){let s=Rt(a.name);s&&r.push({capability:s,symbol:a.name,line:a.line,source:"ambient-global"})}return r.sort((a,s)=>a.line-s.line||a.capability.localeCompare(s.capability)||a.symbol.localeCompare(s.symbol))}i(Qt,"collectCapabilityUses");function B(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(B,"violation");function di(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."}i(di,"peerSuggestion");function $e(e,t){return e.slice(0,t).split(`
|
|
2
2
|
`).length}i($e,"lineOf");var ui=new Set(["publish","subscribe","defineIntent","registerHandler"]);function pi(e,t){return e.index+e[0].indexOf(t)}i(pi,"captureIndex");function fi(e){let t=[],n=new Set,r=i((c,l)=>{!c||n.has(l)||(n.add(l),t.push({value:c,index:l}))},"push"),a=i(c=>{c.lastIndex=0;let l;for(;(l=c.exec(e))!==null;){let p=l[1];p&&r(p,pi(l,p))}},"pushFrom");a(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),a(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,o;for(;(o=s.exec(e))!==null;){let c=o[1]??"",l=o.index+o[0].indexOf(c),p=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=p.exec(c))!==null;){let h=f[1];h&&r(h,l+f.index+f[0].indexOf(h))}}return a(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),a(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((c,l)=>c.index-l.index)}i(fi,"extractQuotedStrings");function gi(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let a;for(;(a=r.re.exec(e))!==null;){let s=a.index+a[0].indexOf(a[1]),o=a[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:a[1],index:s,kind:r.kind,typeOnly:c})}}return t.sort((r,a)=>r.index-a.index)}i(gi,"extractModuleSpecifiers");function mi(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}i(mi,"isSyntaxWrapper");function en(e,t){let n=t;for(;n?.parent&&mi(e,n.parent);)n=n.parent;return n}i(en,"unwrapWrappers");function tn(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}i(tn,"callCalleeName");function hi(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=en(e,n),a=r.parent;if(!a)return!1;if(e.isCallExpression(a)&&tn(e,a)==="publish"){let s=a.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(a)&&nn(e,a.name)==="metadata"){let s=a.parent;if(!s)return!1;let c=en(e,s).parent;return!!(c&&e.isCallExpression(c)&&tn(e,c)==="publish")}return!1}i(hi,"isPublishMetadataSource");function rs(e,t){let n=en(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let a=tn(e,r);if(a&&ui.has(a)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return rs(e,r);if(e.isPropertyAssignment(r)){let a=nn(e,r.name);if(a==="intent"||a==="onEvent"||a==="reactsTo"||a==="source"&&hi(e,r))return!0}return!1}i(rs,"isDeclaredIntentSite");function yi(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],a=i(s=>{e.isStringLiteralLike(s)&&rs(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,a)},"visit");return a(n),r}i(yi,"extractQuotedStringsAst");function Ri(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}i(Ri,"hasInfrastructureToken");function Ai(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(Ai,"isKnownInfrastructurePackage");function ki(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(ki,"layerHasInfrastructureRole");function Ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ye,"tsStringLiteralText");function nn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(nn,"tsPropertyName");function ss(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:nn(e,r.name)===n)}i(ss,"tsObjectProperty");function Xe(e,t,n){return ss(e,t,n)!==void 0}i(Xe,"tsObjectHasProperty");function qe(e,t,n){let r=ss(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(qe,"tsObjectPropertyValue");function vi(e,t){let n=qe(e,t,"metadata");return Xe(e,n,"source")}i(vi,"tsObjectHasMetadataSource");function as(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?as(e,t.name):!1:!1}i(as,"tsLooksLikeIntentCreatorExpression");function bi(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}i(bi,"tsIsPublishCall");function Ii(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Ye(e,n);return r!==void 0&&be(r)||Xe(e,n,"intent")||as(e,n)}i(Ii,"tsIsArkPublishCandidate");function Ei(e,t){if(!e.isCallExpression(t))return!1;let[n,r,a]=t.arguments;return vi(e,n)||Xe(e,r,"source")||Xe(e,a,"source")}i(Ei,"tsPublishHasSource");function Si(e,t){if(!e.isCallExpression(t))return;let[n,r,a]=t.arguments,s=qe(e,n,"metadata");return Ye(e,qe(e,s,"source"))??Ye(e,qe(e,r,"source"))??Ye(e,qe(e,a,"source"))}i(Si,"tsPublishSourceLiteral");function Ci(e,t,n,r){let a=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,o=s?.filePath,c=s?.layer,l=[],p=i(h=>a.getLineAndCharacterOfPosition(h.getStart(a)).line+1,"lineForNode"),f=i(h=>{if(bi(e,h)){let u=h.arguments[0],A=Ye(e,u);for(let g of Be({publishCall:!0,rawIntentName:A,objectHasIntent:Xe(e,u,"intent"),arkPublishCandidate:Ii(e,h),hasSource:Ei(e,h)}))l.push(B(g.ruleId,g.message,{line:p(h),filePath:o}));let d=Si(e,h);if(r&&c&&d&&be(d)){let g=r.resolveLayer(d);g&&g!==c&&l.push(B("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${g}, but the target file is classified as ${c}.`,{line:p(h),filePath:o,target:d,fromLayer:c,toLayer:g}))}}e.forEachChild(h,f)},"visit");return f(a),l}i(Ci,"analyzePublishAst");function os(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),a=e.enforceIntentAllowlist??t.size>0;return{validate(s,o){let c=[],l=o,p=l?.filePath,f=l?.layer,h=e.typescript,u=h?h.createSourceFile(p??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,A=u?De(e.typescript,u):void 0,d=A?A.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(u),kind:k.kind,typeOnly:k.typeOnly})):gi(s),g=e.typescript?yi(e.typescript,s):fi(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let k of A?.filter(({unresolved:E})=>E)??[]){let E=k.kind==="require";c.push(B(E?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${E?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:p}))}let b=f!==void 0&&(r.has(f)||ki(f)),x=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let E=k.exec(s);k.lastIndex=0,E&&c.push(B("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:E.index===void 0?void 0:$e(s,E.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+x}))}else s.includes(k)&&c.push(B("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:$e(s,s.indexOf(k)),filePath:p}));for(let k of d){let E=e.resolveImportTarget?.(k.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,p)}:void 0),C=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,U=E?.layer;if(U&&f){let K=de(e.architectureProfile?.rules,f,U,{fromPath:C?.relPath,toPath:E?.relPath,layers:e.architectureLayers});if(K){let G=K.rule;if(k.typeOnly&&!G.peerIsolation)continue;let I=!!G.peerIsolation,D=K.sliceVerdict,Y=Ee(D),re=pt(G,D)??(I?`Layer "${f}" must not import across slices into "${U}".`:`Layer "${f}" must not import "${U}".`),me=I&&D?.explanation&&(Y.reasonId||K.peerIsolationReason!=="cross-slice")?D.explanation:void 0;c.push(B("LAYER_IMPORT_VIOLATION",me?`${re} ${me}`:re,{line:$e(s,k.index),source:k.value,target:k.value,filePath:p,fromLayer:f,toLayer:U,...I?{peerIsolation:!0}:{},...Y.reasonId?{reasonId:Y.reasonId}:{},...Y.universeFrom?{universeFrom:Y.universeFrom}:{},...Y.universeTo?{universeTo:Y.universeTo}:{},...Y.failsStrict===!1?{failsStrict:!1}:{},suggestion:di(I,K.peerIsolationReason),details:{importKind:k.kind,peerIsolation:I,...k.typeOnly?{typeOnly:!0}:{},...Y.reasonId?{reasonId:Y.reasonId}:{}}}));continue}continue}b||k.typeOnly||!Ri(k.value)&&!Ai(k.value)||c.push(B("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:$e(s,k.index),source:k.value,target:k.value,filePath:p,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+x,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let E=k.check({source:s,context:o});if(E!==!0)if(Array.isArray(E))for(let C of E)c.push(B("POLICY_VIOLATION",C.message,{filePath:p,suggestion:`Fix violation of policy "${k.name}".`}));else E===!1?c.push(B("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):c.push(B("POLICY_VIOLATION",E.message))}if(a&&t.size>0)for(let k of g)be(k.value)&&!t.has(k.value)&&c.push(B("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:$e(s,k.index),filePath:p,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let k of g){if(!be(k.value))continue;let E=e.architectureProfile.resolveLayer(k.value);if(!E)continue;let C=de(e.architectureProfile.rules,f,E,{fromPath:typeof p=="string"?p:void 0,layers:e.architectureLayers});if(C){let U=C.sliceVerdict,K=`Layer "${f}" must not reference "${E}" through "${k.value}".`,G=U?Ne({surface:"intent",verdict:U,fromLayer:f,toLayer:E,fromPath:typeof p=="string"?p:void 0,ruleMessage:C.rule.message,childMessage:C.rule.childSlices?.message,defaultMessage:K}):C.rule.message??K,I=Ee(U);c.push(B("LAYER_REFERENCE_VIOLATION",G,{line:$e(s,k.index),filePath:p,target:k.value,fromLayer:f,toLayer:E,...I.reasonId?{reasonId:I.reasonId}:{},...I.failsStrict===!1?{failsStrict:!1}:{},suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason,...I.reasonId?{reasonId:I.reasonId}:{}}}))}}if(e.extensions)for(let k of e.extensions)try{let E=k.analyze(s,o);c.push(...E)}catch(E){c.push(B("EXTENSION_ERROR",`Extension "${k.name}" failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript&&u&&f&&e.forbiddenGlobals?.[f]?.length)try{let k=e.forbiddenGlobals[f];c.push(...Fe(e.typescript,u,k).map(E=>B("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${E.name}".`,{line:E.line,filePath:p,target:E.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let E of A??[]){if(E.typeOnly||!E.specifier)continue;let C=he(E.specifier,k);C&&c.push(B("FORBIDDEN_GLOBAL",`${f} must not use module "${E.specifier}" because it is the import form of forbidden global "${C}".`,{line:E.line,filePath:p,source:E.specifier,target:E.specifier,fromLayer:f,details:{importKind:E.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){c.push(B("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&u&&f&&e.capabilityWalls?.[f]?.length)try{let k=new Set(e.capabilityWalls[f]),E=e.forbiddenGlobals?.[f]??[];for(let C of Qt(e.typescript,u))k.has(C.capability)&&(C.source==="ambient-global"&&We(C.symbol,E)||C.source==="import-based"&&he(C.symbol,E)||c.push(B("CAPABILITY_VIOLATION",C.source==="import-based"?`${f} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${f} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:p,target:C.symbol,capability:C.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){c.push(B("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{c.push(...Ci(e.typescript,s,o,e.architectureProfile))}catch(k){c.push(B("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:!c.some(k=>k.failsStrict!==!1),violations:c}}}}i(os,"createAICodeGate");function X(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(X,"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(",")}}`}i(z,"stableSerialize");function ue(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}i(ue,"feedText");function rn(e,t){if(Array.isArray(e)){ue("[",t);for(let a=0;a<e.length;a+=1){if(a>0&&ue(",",t),!(a in e))continue;let s=e[a];if(s!==null&&typeof s=="object")rn(s,t);else{let o=JSON.stringify(s);o!==void 0&&ue(o,t)}}ue("]",t);return}let n=e,r=Object.keys(n).sort();ue("{",t);for(let a=0;a<r.length;a+=1){a>0&&ue(",",t);let s=r[a];ue(`${JSON.stringify(s)}:`,t);let o=n[s];o!==null&&typeof o=="object"?rn(o,t):ue(`${JSON.stringify(o)}`,t)}ue("}",t)}i(rn,"feedStable");function sn(e){if(e===null||typeof e!="object")return X(z(e));let t={hash:2166136261};return rn(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}i(sn,"stableHash");var Se="1.2",is=["network","filesystem","clock","randomness","environment","process","persistence"];function V(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])}i(V,"sortCanonical");function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Z,"sortedUnique");function Ze(e){let t={schemaVersion:"1.2",include:Z(e.include??[]),exclude:Z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Z(e.dynamicImportAllowlist??[]),layers:V(e.layers.map(n=>({name:n.name,patterns:Z(n.patterns??[]),exclude:Z(n.exclude??[]),forbiddenGlobals:Z(n.forbiddenGlobals??[]),intentPrefixes:Z(n.intentPrefixes??[]),capabilityDeny:Z(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:Z(e.arkRun.compositionRoots),managedLayers:Z(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return X(z(t))}i(Ze,"resolvedFactsEvidenceRequirementsHash");function _i(e){let t=V(e.completenessReasons.map(I=>({code:I.code,message:I.message,...I.file?{file:I.file}:{}}))),n=e.files.map(I=>({...I,typeOnlyExportNames:Z(I.typeOnlyExportNames)})).sort((I,D)=>I.path<D.path?-1:I.path>D.path?1:0),r=V(e.dependencies.map(I=>({...I,...I.namedBindings?{namedBindings:Z(I.namedBindings)}:{}}))),a=V(e.capabilityUses.map(I=>({...I}))),s=V(e.ambientUses.map(I=>({...I}))),o=V(e.publishCalls.map(I=>({...I}))),c=V(e.intentReferences.map(I=>({...I}))),l=V(e.safetyUses.map(I=>({...I}))),p=V((e.classShapes??[]).map(I=>({...I,mutatingMethods:[...I.mutatingMethods??[]].map(D=>({...D}))}))),f=V((e.arkRunKernelCalls??[]).map(I=>({...I}))),h=V((e.arkRunManagedNews??[]).map(I=>({...I}))),u=V((e.arkRunCompositionRootHits??[]).map(I=>({...I}))),A=V((e.arkRunDeclarations??[]).map(I=>({...I,uses:Z(I.uses),reactsTo:Z(I.reactsTo),raises:Z(I.raises),sends:Z(I.sends)}))),d=V((e.arkOrderPlaneCalls??[]).map(I=>({...I}))),g=V((e.arkOrderGenericUpdates??[]).map(I=>({...I}))),b=V((e.arkOrderRootHits??[]).map(I=>({...I}))),x=V((e.arkOrderXiFieldWrites??[]).map(I=>({...I}))),k=V((e.arkOrderIngestWritesXi??[]).map(I=>({...I}))),E=V((e.arkOrderReleaseKeyCounts??[]).map(I=>({...I}))),C=V((e.arkOrderXiTtlKeys??[]).map(I=>({...I}))),U=V((e.arkOrderBudgetLeaks??[]).map(I=>({...I}))),K=e.files.map(({path:I,contentHash:D})=>({path:I,contentHash:D})).sort((I,D)=>I.path<D.path?-1:I.path>D.path?1:0),G=sn(K);return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:G,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:a,ambientUses:s,publishCalls:o,intentReferences:c,safetyUses:l,classShapes:p,arkRunKernelCalls:f,arkRunManagedNews:h,arkRunCompositionRootHits:u,arkRunDeclarations:A,arkOrderPlaneCalls:d,arkOrderGenericUpdates:g,arkOrderRootHits:b,arkOrderXiFieldWrites:x,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:E,arkOrderXiTtlKeys:C,arkOrderBudgetLeaks:U}}i(_i,"canonicalResolvedFactsInput");function ls(e){let t=_i(e);return{...t,factsHash:sn(t)}}i(ls,"createCanonicalResolvedCandidateFacts");function on(e){return ls(cs(P(e,"$"),!1))}i(on,"createResolvedCandidateFacts");function P(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(P,"asRecord");function L(e,t,n){let r=Object.keys(e).find(a=>!t.includes(a));if(r)throw new Error(`${n}.${r} is not part of schema ${"1.2"}.`)}i(L,"assertOnlyKeys");function N(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(N,"requiredText");function pe(e,t,n){if(e[t]!==void 0)return N(e,t,n)}i(pe,"optionalText");function F(e,t,n){let r=N(e,t,n),a=r.replace(/\\/g,"/");if(!a||a.startsWith("/")||/^[A-Za-z]:\//.test(a)||/[\u0000-\u001f\u007f]/.test(a))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let c of a.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let o=s.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}i(F,"requiredProjectPath");function j(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(j,"requiredBoolean");function an(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(an,"requiredInteger");function q(e,t,n){let r=an(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(q,"requiredPositiveInteger");function $(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i($,"requiredArray");function fe(e,t,n,r){let a=e[t];if(typeof a!="string"||!n.includes(a))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return a}i(fe,"enumValue");function Me(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(Me,"parseStringArray");function Oi(e,t,n){let r=new Set;for(let a of e){let s=t(a);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(Oi,"assertUnique");function cs(e,t){L(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts","arkOrderXiTtlKeys","arkOrderBudgetLeaks",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=fe(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=fe(e,"completeness",["complete","partial","unavailable"],"$"),a=$(e,"completenessReasons","$").map((S,R)=>{let m=`$.completenessReasons[${R}]`,y=P(S,m);L(y,["code","message","file"],m);let T=y.file===void 0?void 0:F(y,"file",m);return{code:N(y,"code",m),message:N(y,"message",m),...T?{file:T}:{}}});if(r==="complete"&&a.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&a.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=$(e,"files","$").map((S,R)=>{let m=`$.files[${R}]`,y=P(S,m);return L(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],m),{path:F(y,"path",m),contentHash:N(y,"contentHash",m),parseStatus:fe(y,"parseStatus",["parsed","invalid"],m),parseDiagnosticCount:an(y,"parseDiagnosticCount",m),exportsOnlyTypes:j(y,"exportsOnlyTypes",m),typeOnlyExportNames:Me(y.typeOnlyExportNames,`${m}.typeOnlyExportNames`),hasTopLevelSideEffects:j(y,"hasTopLevelSideEffects",m)}}),o=$(e,"dependencies","$").map((S,R)=>{let m=`$.dependencies[${R}]`,y=P(S,m);L(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],m);let T=pe(y,"specifier",m),Q=pe(y,"target",m),we=fe(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],m);if(we==="resolved-project"&&!Q)throw new Error(`${m}.target is required for resolved-project dependencies.`);if(we!=="resolved-project"&&Q)throw new Error(`${m}.target is only allowed for resolved-project dependencies.`);if(we!=="dynamic"&&!T)throw new Error(`${m}.specifier is required unless resolution is dynamic.`);return{from:F(y,"from",m),...T?{specifier:T}:{},kind:fe(y,"kind",["import","export","dynamic-import","require"],m),typeOnly:j(y,"typeOnly",m),line:q(y,"line",m),resolution:we,...Q?{target:F(y,"target",m)}:{},...y.namedBindings!==void 0?{namedBindings:Me(y.namedBindings,`${m}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:j(y,"targetTypeOnlyExports",m)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:j(y,"sourcePureTypeModule",m)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:j(y,"namedBindingsTypeOnly",m)}:{},...y.portProofEligible!==void 0?{portProofEligible:j(y,"portProofEligible",m)}:{}}}),c=$(e,"capabilityUses","$").map((S,R)=>{let m=`$.capabilityUses[${R}]`,y=P(S,m);return L(y,["file","line","symbol","capability","source"],m),{file:F(y,"file",m),line:q(y,"line",m),symbol:N(y,"symbol",m),capability:fe(y,"capability",is,m),source:fe(y,"source",["ambient-global","import-based"],m)}}),l=$(e,"ambientUses","$").map((S,R)=>{let m=`$.ambientUses[${R}]`,y=P(S,m);return L(y,["file","line","symbol"],m),{file:F(y,"file",m),line:q(y,"line",m),symbol:N(y,"symbol",m)}}),p=$(e,"publishCalls","$").map((S,R)=>{let m=`$.publishCalls[${R}]`,y=P(S,m);L(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],m);let T=pe(y,"rawIntentName",m),Q=pe(y,"sourceIntent",m);return{file:F(y,"file",m),line:q(y,"line",m),...T?{rawIntentName:T}:{},objectHasIntent:j(y,"objectHasIntent",m),arkPublishCandidate:j(y,"arkPublishCandidate",m),hasSource:j(y,"hasSource",m),...Q?{sourceIntent:Q}:{}}}),f=$(e,"intentReferences","$").map((S,R)=>{let m=`$.intentReferences[${R}]`,y=P(S,m);return L(y,["file","line","intent"],m),{file:F(y,"file",m),line:q(y,"line",m),intent:N(y,"intent",m)}}),h=$(e,"safetyUses","$").map((S,R)=>{let m=`$.safetyUses[${R}]`,y=P(S,m);L(y,["file","line","kind","symbol"],m);let T=pe(y,"symbol",m),Q=fe(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],m);if(Q==="in-memory-store"&&!T)throw new Error(`${m}.symbol is required for in-memory-store facts.`);if(Q!=="in-memory-store"&&T)throw new Error(`${m}.symbol is only allowed for in-memory-store facts.`);return{file:F(y,"file",m),line:q(y,"line",m),kind:Q,...T?{symbol:T}:{}}});Oi(s,S=>S.path,"$.files");let u=new Set(s.map(S=>S.path));for(let S of s){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of o)if(!u.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:$(e,"arkRunKernelCalls","$")).map((S,R)=>{let m=`$.arkRunKernelCalls[${R}]`,y=P(S,m);L(y,["file","line","kind","callee","viaImport","receiver","nameLiteral"],m);let T=pe(y,"receiver",m),Q=pe(y,"nameLiteral",m);return{file:F(y,"file",m),line:q(y,"line",m),kind:fe(y,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],m),callee:N(y,"callee",m),viaImport:j(y,"viaImport",m),...T?{receiver:T}:{},...Q?{nameLiteral:Q}:{}}}),b=(e.arkRunManagedNews===void 0?[]:$(e,"arkRunManagedNews","$")).map((S,R)=>{let m=`$.arkRunManagedNews[${R}]`,y=P(S,m);L(y,["file","line","typeName","importedFrom"],m);let T=pe(y,"importedFrom",m);return{file:F(y,"file",m),line:q(y,"line",m),typeName:N(y,"typeName",m),...T?{importedFrom:T}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:$(e,"arkRunCompositionRootHits","$")).map((S,R)=>{let m=`$.arkRunCompositionRootHits[${R}]`,y=P(S,m);return L(y,["file","matchedRoot","hasKernelFactory"],m),{file:F(y,"file",m),matchedRoot:N(y,"matchedRoot",m),hasKernelFactory:j(y,"hasKernelFactory",m)}}),E=e.arkRunDeclarations===void 0?[]:$(e,"arkRunDeclarations","$"),U=(e.arkOrderPlaneCalls===void 0?[]:$(e,"arkOrderPlaneCalls","$")).map((S,R)=>{let m=`$.arkOrderPlaneCalls[${R}]`,y=P(S,m);return L(y,["file","line","callee"],m),{file:F(y,"file",m),line:q(y,"line",m),callee:N(y,"callee",m)}}),G=(e.arkOrderGenericUpdates===void 0?[]:$(e,"arkOrderGenericUpdates","$")).map((S,R)=>{let m=`$.arkOrderGenericUpdates[${R}]`,y=P(S,m);return L(y,["file","line","method"],m),{file:F(y,"file",m),line:q(y,"line",m),method:N(y,"method",m)}}),D=(e.arkOrderRootHits===void 0?[]:$(e,"arkOrderRootHits","$")).map((S,R)=>{let m=`$.arkOrderRootHits[${R}]`,y=P(S,m);return L(y,["file","matchedRoot","hasPlaneFactory"],m),{file:F(y,"file",m),matchedRoot:N(y,"matchedRoot",m),hasPlaneFactory:j(y,"hasPlaneFactory",m)}}),re=(e.arkOrderXiFieldWrites===void 0?[]:$(e,"arkOrderXiFieldWrites","$")).map((S,R)=>{let m=`$.arkOrderXiFieldWrites[${R}]`,y=P(S,m);return L(y,["file","line","key"],m),{file:F(y,"file",m),line:q(y,"line",m),key:N(y,"key",m)}}),se=(e.arkOrderIngestWritesXi===void 0?[]:$(e,"arkOrderIngestWritesXi","$")).map((S,R)=>{let m=`$.arkOrderIngestWritesXi[${R}]`,y=P(S,m);return L(y,["file","line"],m),{file:F(y,"file",m),line:q(y,"line",m)}}),ke=(e.arkOrderReleaseKeyCounts===void 0?[]:$(e,"arkOrderReleaseKeyCounts","$")).map((S,R)=>{let m=`$.arkOrderReleaseKeyCounts[${R}]`,y=P(S,m);return L(y,["file","line","keyCount"],m),{file:F(y,"file",m),line:q(y,"line",m),keyCount:q(y,"keyCount",m)}}),Lt=(e.arkOrderXiTtlKeys===void 0?[]:$(e,"arkOrderXiTtlKeys","$")).map((S,R)=>{let m=`$.arkOrderXiTtlKeys[${R}]`,y=P(S,m);return L(y,["file","line","key"],m),{file:F(y,"file",m),line:q(y,"line",m),key:N(y,"key",m)}}),ve=(e.arkOrderBudgetLeaks===void 0?[]:$(e,"arkOrderBudgetLeaks","$")).map((S,R)=>{let m=`$.arkOrderBudgetLeaks[${R}]`,y=P(S,m);return L(y,["file","line","kind"],m),{file:F(y,"file",m),line:q(y,"line",m),kind:N(y,"kind",m)}}),xe=E.map((S,R)=>{let m=`$.arkRunDeclarations[${R}]`,y=P(S,m);return L(y,["file","line","uses","reactsTo","raises","sends"],m),{file:F(y,"file",m),line:q(y,"line",m),uses:Me(y.uses,`${m}.uses`),reactsTo:Me(y.reactsTo,`${m}.reactsTo`),raises:Me(y.raises,`${m}.raises`),sends:Me(y.sends,`${m}.sends`)}});for(let[S,R]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",p],["$.intentReferences",f],["$.safetyUses",h],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",xe],["$.arkOrderPlaneCalls",U],["$.arkOrderGenericUpdates",G],["$.arkOrderRootHits",D],["$.arkOrderXiFieldWrites",re],["$.arkOrderIngestWritesXi",se],["$.arkOrderReleaseKeyCounts",ke],["$.arkOrderXiTtlKeys",Lt],["$.arkOrderBudgetLeaks",ve]])for(let m of R)if(!u.has(m.file))throw new Error(`${S} references missing file ${m.file}.`);let it=pe(e,"projectPackageName","$"),lt=(e.classShapes===void 0?[]:$(e,"classShapes","$")).map((S,R)=>{let m=`$.classShapes[${R}]`,y=P(S,m);L(y,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],m);let T=$(y,"mutatingMethods",m).map((Q,we)=>{let ct=`${m}.mutatingMethods[${we}]`,Ft=P(Q,ct);return L(Ft,["name","referencesGuardOrPublish"],ct),{name:N(Ft,"name",ct),referencesGuardOrPublish:j(Ft,"referencesGuardOrPublish",ct)}});return{file:F(y,"file",m),className:N(y,"className",m),exported:j(y,"exported",m),hasPublicMutableFields:j(y,"hasPublicMutableFields",m),hasPublicSetters:j(y,"hasPublicSetters",m),hasPublicConstructor:j(y,"hasPublicConstructor",m),hasStaticFactory:j(y,"hasStaticFactory",m),mutatingMethods:T,...y.dataOnly===void 0?{}:{dataOnly:j(y,"dataOnly",m)},...y.truncatedUntil===void 0?{}:{truncatedUntil:an(y,"truncatedUntil",m)}}});return{schemaVersion:n,completeness:r,completenessReasons:a,resolverIdentity:N(e,"resolverIdentity","$"),compilerIdentity:N(e,"compilerIdentity","$"),compilerOptionsHash:N(e,"compilerOptionsHash","$"),tsconfigHash:N(e,"tsconfigHash","$"),evidenceRequirementsHash:N(e,"evidenceRequirementsHash","$"),...it?{projectPackageName:it}:{},files:s,dependencies:o,capabilityUses:c,ambientUses:l,publishCalls:p,intentReferences:f,safetyUses:h,classShapes:lt,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:k,arkRunDeclarations:xe,arkOrderPlaneCalls:U,arkOrderGenericUpdates:G,arkOrderRootHits:D,arkOrderXiFieldWrites:re,arkOrderIngestWritesXi:se,arkOrderReleaseKeyCounts:ke,arkOrderXiTtlKeys:Lt,arkOrderBudgetLeaks:ve}}i(cs,"parseResolvedFactsInput");function ye(e){let t=P(e,"$"),n=N(t,"factsHash","$"),r=N(t,"candidateTreeHash","$"),a=ls(cs(t,!0));if(a.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${a.factsHash}).`);if(r!==a.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${a.candidateTreeHash}).`);return a}i(ye,"loadResolvedCandidateFacts");var xi=["network","filesystem","clock","randomness","environment","process","persistence"],w={type:"string",minLength:1},J={type:"integer",minimum:1},M={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},ln={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:w,message:w,file:M}}},resolverIdentity:w,compilerIdentity:w,compilerOptionsHash:w,tsconfigHash:w,candidateTreeHash:w,evidenceRequirementsHash:w,projectPackageName:w,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:M,contentHash:w,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:w},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:M,specifier:w,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:J,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:M,namedBindings:{type:"array",items:w},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:M,line:J,symbol:w,capability:{enum:xi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:M,line:J,symbol:w}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:M,line:J,rawIntentName:w,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:w}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:M,line:J,intent:w}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:M,line:J,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:w},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:M,className:w,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:w,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:M,line:J,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:w,viaImport:{type:"boolean"},receiver:w,nameLiteral:w}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:M,line:J,typeName:w,importedFrom:w}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:M,matchedRoot:w,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:M,line:J,uses:{type:"array",items:w},reactsTo:{type:"array",items:w},raises:{type:"array",items:w},sends:{type:"array",items:w}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:M,line:J,callee:w}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:M,line:J,method:w}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:M,matchedRoot:w,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:M,line:J,key:w}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:M,line:J}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:M,line:J,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:M,line:J,key:w}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:M,line:J,kind:w}}},factsHash:w},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var cn="1.0";function ds(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let a of t.split("/"))if(!(!a||a==="."))if(a===".."){if(n.length===0)return;n.pop()}else n.push(a);let r=n.join("/");return r&&r===t?r:void 0}i(ds,"canonicalProjectPath");function He(e){return e.flatMap(t=>t.to?[{from:t.from,to:t.to}]:[])}i(He,"resolvedEdgeDependencies");function ee(e){return`${e.from}->${e.to}`}i(ee,"dependencyKey");function Je(e,t,n,r="dependency"){return{id:`${e}:${r}:${ee(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ee(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ee(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ee(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ee(t)} from the candidate, then preflight again.`}:{}}}i(Je,"dependencyFinding");function Ke(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),a=new Map(e.changeMap.map.dependencies.map(u=>[ee(u),u])),s=new Map(e.baseDependencies.map(u=>[ee(u),u])),o=new Map(e.candidateDependencies.map(u=>[ee(u),u]));for(let u of[...n.values()].sort((A,d)=>A.path.localeCompare(d.path))){let A=r.get(u.path);A?A.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:A.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${A.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:A.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((A,d)=>A.path.localeCompare(d.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let c=new Set;for(let u of[...a.values()].sort((A,d)=>ee(A).localeCompare(ee(d)))){if(o.has(ee(u))){t.push(Je("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let A={from:u.to,to:u.from};o.has(ee(A))?(c.add(ee(A)),t.push(Je("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Je("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[u,A]of[...o].sort(([d],[g])=>d.localeCompare(g)))s.has(u)||a.has(u)||c.has(u)||!l.has(A.from)&&!l.has(A.to)||t.push({...Je("unplanned",A,`${A.from} -> ${A.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,A]of[...s].sort(([d],[g])=>d.localeCompare(g)))o.has(u)||p.has(A.from)||p.has(A.to)||!l.has(A.from)&&!l.has(A.to)||t.push({...Je("unplanned",A,`${A.from} -> ${A.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,A)=>f[u.classification]-f[A.classification]||(u.subject===A.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(A.id));let h={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}i(Ke,"analyzeArchitectureConvergence");var dn="1.0",us="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",wi=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var ps={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Bd={$schema:"https://json-schema.org/draft/2020-12/schema",$id:us,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:us},schemaVersion:{type:"string",const:dn,default:dn},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:[...wi]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ps,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:ps}}}};function Qe(){return{schemaVersion:dn,byLayer:{},structure:[],invariants:[]}}i(Qe,"emptyEffectiveArkRules");function un(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:a,...s}=t;return s})}}i(un,"omitLayerDescriptions");function fs(e){let{stewards:t,...n}=un(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(fs,"effectiveContractPolicyPayload");var Ti=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Ni=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),Pi=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function Li(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(n<0)return!0;let r=e[n];if(/[A-Za-z0-9_$]/.test(r)){let a=n;for(;a>=0&&/[A-Za-z0-9_$]/.test(e[a]);)a-=1;return Pi.has(e.slice(a+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:Ni.has(r)}i(Li,"slashStartsRegex");function Di(e,t){if(!Li(e,t))return t;let n=t+1,r=!1;for(;n<e.length;){let a=e[n];if(a===`
|
|
3
3
|
`||a==="\r")return t;if(a==="\\"){n+=2;continue}if(r)a==="]"&&(r=!1);else if(a==="[")r=!0;else if(a==="/"){for(n+=1;n<e.length&&/[A-Za-z]/.test(e[n]);)n+=1;return n}n+=1}return t}i(Di,"skipRegexLiteral");function Ce(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
|
|
4
4
|
`,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 Di(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}i(Ce,"skipStringOrComment");function le(e,t){let n=t;for(;n<e.length;){if(/\s/.test(e[n])){n+=1;continue}if(e[n]==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=Ce(e,n);continue}break}return n}i(le,"skipWsAndComments");function kt(e,t){let n=e[t];if(!n||!/[A-Za-z_$]/.test(n))return null;let r=t+1;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{ident:e.slice(t,r),end:r}}i(kt,"readIdent");function Re(e,t,n,r){if(e[t]!==n)return null;let a=1,s=t+1;for(;s<e.length&&a>0;){let o=Ce(e,s);if(o!==s){s=o;continue}let c=e[s];c===n?a+=1:c===r&&!(r===">"&&e[s-1]==="=")&&(a-=1),s+=1}return a===0?s:null}i(Re,"skipBalanced");function pn(e){let t=[],n=0,r;for(;n<e.length&&(n=le(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let a=[],s=n;for(;;){let f=kt(e,s);if(!f||!Ti.has(f.ident))break;a.push(f.ident),s=le(e,f.end)}if(a.length===1&&a[0]==="static"&&e[s]==="{"){let f=Re(e,s,"{","}");if(f==null){r=e.length;break}n=f;continue}let o=kt(e,s);if(!o){n+=1;continue}if(s=le(e,o.end),e[s]==="<"){let f=Re(e,s,"<",">");if(f==null){r=e.length;break}s=le(e,f)}if(e[s]==="("){let f=Re(e,s,"(",")");if(f==null){r=e.length;break}if(s=le(e,f),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let h=Ce(e,s);if(h!==s){s=h;continue}s+=1}if(e[s]==="{"){let h=Re(e,s,"{","}");if(h==null){r=e.length;break}t.push({name:o.ident,modifiers:a,kind:"method",body:e.slice(s+1,h-1)}),n=h;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let c=0,l=0,p=0;for(;s<e.length;){let f=Ce(e,s);if(f!==s){s=f;continue}let h=e[s];if(h==="{")c+=1;else if(h==="}"){if(c===0)break;c-=1}else if(h==="(")l+=1;else if(h===")")l-=1;else if(h==="[")p+=1;else if(h==="]")p-=1;else if(h===";"&&c===0&&l===0&&p===0){s+=1;break}s+=1}s>=e.length&&(c>0||l>0||p>0)&&(r=e.length),t.push({name:o.ident,modifiers:a,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}i(pn,"scanClassMembers");function gs(e,t){let n=t;for(;n<e.length;){let r=le(e,n);if(r!==n){n=r;continue}let a=e[n];if(a==="{")return n;if(a===";")return null;if(a==="<"||a==="("||a==="["){let o=Re(e,n,a,a==="<"?">":a==="("?")":"]");if(o==null)return null;n=o;continue}if(a==='"'||a==="'"||a==="`"){n=Ce(e,n);continue}n+=1}return null}i(gs,"findClassBodyBrace");function fn(e,t={}){let n=[],r=t.exportedOnly?/\bexport\s+(?:abstract\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*)/g:/(?:\b(export)\s+(?:default\s+)?)?(?:\babstract\s+)?\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,a=ms(e),s;for(;(s=r.exec(a))!==null;){let o=t.exportedOnly?s[1]:s[2],c=t.exportedOnly===!0||s[1]==="export",l=gs(e,s.index+s[0].length);if(l==null){n.push({name:o,start:s.index,exported:c,bodyStart:null,bodyEnd:null});continue}let p=Re(e,l,"{","}");n.push({name:o,start:s.index,exported:c,bodyStart:l+1,bodyEnd:p==null?null:p-1})}return n}i(fn,"findClassDeclarations");function ms(e){let t="",n=0;for(;n<e.length;){let r=Ce(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}i(ms,"maskStringsAndComments");function hs(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=ms(e),a=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),s=new RegExp(`\\b(?:(namespace|module)\\s+${a}\\s*\\{|(?:const|let|var)\\s+${a}\\s*(?::[^=;]+?)?=(?!=|>)\\s*(class\\b)?)`,"g"),o;for(;(o=s.exec(r))!==null;){let c,l;if(o[1])l="namespace",c=o.index+o[0].length-1;else if(o[2])l="class-expression",c=gs(e,o.index+o[0].length);else{l="object";let f=le(e,o.index+o[0].length);c=e[f]==="{"?f:null}if(c==null)continue;let p=Re(e,c,"{","}");n.push({kind:l,bodyStart:c+1,bodyEnd:p==null?e.length:p-1})}return n}i(hs,"findMemberContainers");function ys(e){let t=[],n=0,r=!0;for(;n<e.length;){let a=Ce(e,n);if(a!==n){n=a,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=Re(e,n,s,s==="{"?"}":s==="("?")":"]")??e.length,r=!1;continue}if(s===","){r=!0,n+=1;continue}if(r&&/[A-Za-z_$]/.test(s)){let o=kt(e,n);for(;o&&(o.ident==="async"||o.ident==="get"||o.ident==="set");){let c=le(e,o.end);e[c]==="*"&&(c=le(e,c+1));let l=kt(e,c);if(!l)break;o=l}if(o){let c=le(e,o.end);("(:,<".includes(e[c]??"")||c>=e.length)&&t.push(o.ident),n=o.end,r=!1;continue}}if(r&&s==="*"){n+=1;continue}/\s/.test(s)||(r=!1),n+=1}return t}i(ys,"objectLiteralMemberNames");function Rs(e){return e==="survived"||e==="not-reached"}i(Rs,"verdictRefusesPromotion");function Fi(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}\``}}i(Fi,"changeText");function As(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?` (${Fi(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.`}i(As,"probeRefusalReason");var $i="INVARIANT_TESTS_PATH_MISSING",Mi="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.",Hi="INVARIANT_COVERAGE_ROOTS_MISSING",Ki="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function ks(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let a=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${a}.`}i(ks,"formatCoverageDiscards");function Is(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let a=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return a===""||a==="."?!0:n===a||n.startsWith(`${a}/`)})}i(Is,"isUnderCoverageRoot");function mn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(mn,"escapeRegExp");function Ve(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Ve,"normalizePath");function hn(e,t){let n=[],r=0,a=e.length;for(;r<a;){let s=e[r],o=e[r+1];if(s==="/"&&o==="/"){for(;r<a&&e[r]!==`
|
package/docs/README.md
CHANGED
|
@@ -73,7 +73,8 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
|
|
|
73
73
|
| Field adoption kit (scaffolding, not closed) | [field/](field/) |
|
|
74
74
|
| Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
|
|
75
75
|
|
|
76
|
-
Current release: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.
|
|
76
|
+
Current release: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.26`; confirm npm with `npm view arkgate@4.8.26 version`; does not close `K01`).
|
|
77
|
+
Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.25`).
|
|
77
78
|
Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.24`).
|
|
78
79
|
Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.23`).
|
|
79
80
|
Prior published: [CHANGELOG](../CHANGELOG.md) (`arkgate@4.8.22`).
|
package/docs/agent-guide.md
CHANGED
|
@@ -559,10 +559,12 @@ When `include` matches **zero** TS/JS files, plan/doctor treat that as **not don
|
|
|
559
559
|
The **verdict path refuses** in that state rather than passing: a plain or `--strict`
|
|
560
560
|
`ark-check` over zero governed files exits 1 with `ANALYSIS_COVERS_NO_FILES`, because
|
|
561
561
|
every rule is vacuously satisfied on an empty set. It fires when source exists under the
|
|
562
|
-
analyzed root and the contract governs none of it
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
562
|
+
analyzed root and the contract governs none of it. An explicit `--config` path is a file
|
|
563
|
+
and patterns resolve against `--root`. `--strict` exits 2 when that file is outside Git.
|
|
564
|
+
Basename walk-up can still adopt a parent
|
|
565
|
+
`ark.config.json` when `--root` has none. A genuinely greenfield repo — no governable
|
|
566
|
+
source anywhere under the root you asked for — still passes, so `ark init` can land a
|
|
567
|
+
contract before the code.
|
|
566
568
|
|
|
567
569
|
"Source exists" is answered by a probe the contract cannot steer: it ignores `exclude`
|
|
568
570
|
(otherwise `exclude: ["**"]` would buy a green), skips dot-directories, never follows a
|
package/docs/ai-gates.md
CHANGED
|
@@ -961,7 +961,7 @@ checker from the ref you pin, so an older ref runs an older checker, and that ch
|
|
|
961
961
|
config keys (for example `schemaVersion` 1.3, `childSlices`, `sliceIdentity`) with exit 2:
|
|
962
962
|
|
|
963
963
|
```yaml
|
|
964
|
-
- uses: pedroknigge/arkgate@v4.8.
|
|
964
|
+
- uses: pedroknigge/arkgate@v4.8.26 # same version as the arkgate devDependency
|
|
965
965
|
with:
|
|
966
966
|
root: .
|
|
967
967
|
config: ark.config.json
|
package/docs/diagnostics.md
CHANGED
|
@@ -734,7 +734,7 @@ Haken slaving: few slow keys (ξ) determine derived fast state. Field ingest nev
|
|
|
734
734
|
|
|
735
735
|
**Analysis covered no files**
|
|
736
736
|
|
|
737
|
-
- **Why:** 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`
|
|
737
|
+
- **Why:** 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` the contract misses, basename walk-up adopting a parent that governs nothing, or `include` / `exclude` / layer patterns that match nothing. An explicit `--config` path stays a file: the check runs on `--root`.
|
|
738
738
|
- **Fix:** 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 — then re-run `npx arkgate-check --root . --config ark.config.json`. `--plan` and `--coverage` report the empty scope without refusing, and `--adopt-contract --write` proposes an `include` that matches the tree. This is a refusal about ArkGate's own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it, and `exclude` cannot silence it — the "is there source here" probe deliberately ignores the contract's own `exclude`, skips dot-directories, never follows a symlink, and skips `*.config.*` tooling files so a polyglot repo is not mistaken for a mismatch.
|
|
739
739
|
|
|
740
740
|
<a id="ANALYSIS_HOST_UNAVAILABLE"></a>
|