arkgate 4.8.15 → 4.8.16
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 +39 -0
- package/README.md +7 -5
- package/bin/ark-shared.mjs +2 -0
- package/bin/ark.mjs +17 -8
- package/bin/lib/analysis-engine.mjs +5 -5
- package/bin/lib/architecture-scan.mjs +17 -0
- package/bin/lib/baseline-key.mjs +2 -0
- package/bin/lib/config-contract.mjs +1 -1
- package/bin/lib/diagnostic-catalog.mjs +2 -0
- package/bin/lib/doctor-advisories.mjs +26 -0
- package/bin/lib/doctor-green-cite.mjs +139 -0
- package/bin/lib/doctor-human.mjs +98 -63
- package/bin/lib/doctor-next-actions.mjs +9 -0
- package/bin/lib/doctor-plan.mjs +6 -3
- package/bin/lib/field-install.mjs +47 -7
- package/bin/lib/first-run-help.mjs +1 -0
- package/bin/lib/improvement-compass-doctor.mjs +3 -1
- package/bin/lib/improvement-compass-map.mjs +3 -1
- package/bin/lib/invariant-coverage.mjs +121 -0
- package/bin/lib/invariant-tests-path.mjs +212 -0
- package/bin/lib/package-manager.mjs +8 -0
- package/bin/lib/prototype-shortcuts.mjs +224 -0
- package/bin/lib/remediation.mjs +11 -0
- package/bin/lib/start-preview.mjs +20 -1
- package/dist/{configTypes-Dt3DpVbd.d.ts → configTypes-VD0qcubY.d.ts} +2 -1
- package/dist/{diagnosticCatalog-BEg85XlE.d.ts → diagnosticCatalog-KWvGLI1U.d.ts} +24 -3
- package/dist/eslint/index.cjs +4 -4
- package/dist/eslint/index.d.ts +1 -1
- package/dist/eslint/index.js +4 -4
- package/dist/index.cjs +31 -31
- package/dist/index.d.ts +5 -5
- package/dist/index.js +31 -31
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.d.ts +3 -3
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +10 -10
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.js +10 -10
- package/dist/{types-TBiv0WHL.d.ts → types-BSzRy2X1.d.ts} +1 -1
- package/dist/{types-CN9tVMPz.d.ts → types-D5GT5ZT8.d.ts} +1 -1
- package/docs/README.md +1 -1
- package/docs/agent-guide.md +2 -0
- package/docs/configuration.md +11 -3
- package/docs/develop.md +3 -1
- package/docs/diagnostics.md +25 -1
- package/docs/package-surface.md +1 -1
- package/docs/use.md +5 -3
- package/package.json +1 -1
- package/schemas/ark.config.schema.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +15 -0
- package/templates/agent-skills/ark-autopilot/SKILL.md +6 -1
- package/templates/agent-skills/ark-coverage/SKILL.md +1 -1
- package/templates/agent-skills/ark-explain/SKILL.md +2 -1
- package/templates/agent-skills/ark-explore/SKILL.md +19 -0
- package/templates/agent-skills/ark-place/SKILL.md +4 -0
- package/templates/skills/ark-adopt.md +15 -0
- package/templates/skills/ark-autopilot.md +6 -1
- package/templates/skills/ark-coverage.md +1 -1
- package/templates/skills/ark-explain.md +2 -1
- package/templates/skills/ark-explore.md +19 -0
- package/templates/skills/ark-place.md +4 -0
package/dist/index.cjs
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
"use strict";var nr=Object.defineProperty;var hi=Object.getOwnPropertyDescriptor;var Ai=Object.getOwnPropertyNames;var Ri=Object.prototype.hasOwnProperty;var i=(e,t)=>nr(e,"name",{value:t,configurable:!0});var ki=(e,t)=>{for(var r in t)nr(e,r,{get:t[r],enumerable:!0})},Ei=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ai(t))!Ri.call(e,o)&&o!==r&&nr(e,o,{get:()=>t[o],enumerable:!(n=hi(t,o))||n.enumerable});return e};var Si=e=>Ei(nr({},"__esModule",{value:!0}),e);var bd={};ki(bd,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>ct,AGENT_PROJECTION_BEGIN_MARKER:()=>Cs,AGENT_PROJECTION_END_MARKER:()=>Wt,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>st,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>qt,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>Ls,AGENT_SKILL_ENTRY_FILENAME:()=>Ms,ANALYSIS_IR_SCHEMA_VERSION:()=>Ar,ARKORDER_RULE_IDS:()=>qr,ARKORDER_TIER1_SENSOR_IDS:()=>Ra,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>ns,ARKRUN_KERNEL_FACTORY_CALLEES:()=>ts,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>ca,ARKRUN_RULE_IDS:()=>Wr,ARKRUN_TIER1_SENSOR_IDS:()=>fa,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>rs,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Ne,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>li,ARK_ANALYSIS_RESULT_SCHEMA:()=>fn,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>lt,ARK_CONFIG_SCHEMA:()=>fr,ARK_CONFIG_SCHEMA_VERSION:()=>se,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Pa,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>wa,ARK_FIRST_CLASS_SKILL_NAMES:()=>ln,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Gt,ARK_PROJECT_IDENTITY_SCHEMA:()=>Ys,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>mn,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>qs,ARK_RULES_SCHEMA:()=>kr,ARK_RULES_SCHEMA_VERSION:()=>Po,ARK_RULE_SENSORS:()=>$n,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>is,ARK_SKILL_CAPACITY:()=>er,ARK_SKILL_CAPACITY_DEDICATED_DOORS:()=>Fs,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>dn,ARK_SKILL_NAMES:()=>rr,ARK_SKILL_NAME_COUNT:()=>$s,ARK_SKILL_NORTH_STAR:()=>ci,ARK_SKILL_REQUIRED_SURFACES:()=>tr,ARK_SKILL_STUB_REDIRECTS:()=>sn,ARK_STATUS_MANIFEST_SCHEMA:()=>qa,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>ds,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>Qr,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>_s,DIAGNOSTIC_CATALOG:()=>jt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>La,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Zr,DIAGNOSTIC_RULE_IDS:()=>Da,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>aa,EffectiveContractError:()=>Ot,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>Ds,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>Te,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>zt,IMPROVEMENT_LENS_IDS:()=>Bt,MERGE_PLANES_DUAL_STAMP:()=>Qn,POLICY_DELTA_SCHEMA_VERSION:()=>Cr,PROJECT_BINDING_SCHEMA:()=>yn,PROJECT_EXPECTATION_SCHEMA:()=>gn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>hr,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Ce,STATUS_COMPASS_FACTS_SOURCES:()=>ps,STATUS_COMPASS_MODES:()=>us,STATUS_COMPASS_REASON_CODES:()=>Vt,adapterDocsCodePath:()=>ut,adapterFindingOccurrenceTargetKeys:()=>Be,adapterFindingRefFromTargetKey:()=>dt,adapterFindingTargetKey:()=>Ge,agentProjectionContentIdentity:()=>Ue,agentSkillEntryRelativePath:()=>Gs,agentSkillPackageFileRelativePath:()=>gi,analyzeArchitectureConvergence:()=>$e,analyzeChange:()=>wt,analyzePolicyDelta:()=>Un,analyzeProject:()=>Qe,analyzeResolvedProject:()=>rt,arkRunKernelCallKind:()=>jr,arkSkillStubRedirect:()=>di,buildAgentProjectionBeginMarker:()=>tn,buildAgentProjectionBlock:()=>Os,buildAgentProjectionBody:()=>Zt,buildAgentProjectionMeta:()=>xs,buildArkRuleFileHints:()=>Mr,buildEffectiveArkRules:()=>Er,buildImprovementCompass:()=>ti,buildRulesInventory:()=>Ta,buildStatusManifest:()=>Ga,canPromoteInvariant:()=>br,catalogFixForRuleId:()=>ja,catalogWhyForRuleId:()=>Ka,classifyArkPolicyDelta:()=>_r,classifyResolvedLayerCoverage:()=>$r,classifyStatusWritePath:()=>ms,collectAnalysisConfigWarnings:()=>Ht,collectEmptyAppliesToFindings:()=>Dr,collectForbiddenCapabilityUses:()=>De,composeMergePlanesHonesty:()=>Lt,createAICodeGate:()=>wn,createAdapterResult:()=>Ws,createArchitectureProfile:()=>St,createArchitectureProfileFromArkConfig:()=>Dn,createElevenLayerArkConfig:()=>Mn,createProjectId:()=>Js,createProjectIdentity:()=>Xs,createResolvedCandidateFacts:()=>yr,defaultHonestLabel:()=>gs,demoteExtraPlaneTeethUnderClassificationFloor:()=>ia,deriveArkRuleFileHints:()=>Jn,detectArchitectureCycles:()=>Tr,deterministicHash:()=>J,diagnosticDocsFragment:()=>cs,diagnosticDocsPath:()=>$a,effectiveContractPolicyPayload:()=>Sr,elevenLayerProfile:()=>Et,emptyEffectiveArkRules:()=>_e,evaluateArchitectureGraph:()=>Ke,evaluateArkOrderSensors:()=>Yr,evaluateArkRuleSensors:()=>Lr,evaluateArkRunEditorSensors:()=>ss,evaluateArkRunEditorSensorsFromSource:()=>ga,evaluateArkRunSensors:()=>$t,evaluateInvariantCoverage:()=>Ir,evaluateStatusBinding:()=>fs,explainViolation:()=>Vn,extraMergeTeethAllowed:()=>me,extractAgentProjectionBlock:()=>Qt,extractArkRunDeclarationsFromSource:()=>da,extractArkRunImportedConstructorNamesFromSource:()=>Gr,extractArkRunKernelCallsFromSource:()=>Br,extractArkRunManagedNewsFromSource:()=>zr,extractArkRunValueImportDependenciesFromSource:()=>Vr,extractClassShapesFromSource:()=>oa,extractSemanticDependencies:()=>Le,flatSkillTemplateFileRelativePath:()=>yi,formatAgentProjectionCatalogShortList:()=>rn,formatAgentProjectionLayers:()=>Yt,formatArkRunDoctorLines:()=>Ca,formatImprovementCompassDoctorLines:()=>ri,formatImprovementCompassResidualLabels:()=>bs,getDiagnosticCatalogEntry:()=>Kt,inventoryToExtractionCard:()=>Na,isArkOrderRuleId:()=>Xn,isArkRunKernelModuleSpecifier:()=>tt,isArkRunRuleId:()=>Hr,isArkRunTransportBypassSpecifier:()=>Kr,isArkSkillName:()=>cn,isCataloguedOrArkRuleFamily:()=>Fa,isExtraPlaneFinding:()=>Zn,isFirstClassArkSkillName:()=>on,isKnownDiagnosticCode:()=>Ma,isValidAgentSkillName:()=>Hs,loadArkConfigContract:()=>kt,loadArkRulesContract:()=>_t,loadContract:()=>Nt,loadResolvedCandidateFacts:()=>Se,mergeAgentProjectionDocument:()=>Ps,normalizeExtraMergeTeethClassification:()=>Fr,normalizeSkillContent:()=>an,normalizeStatusImprovementCompass:()=>hs,parseAgentProjectionStamp:()=>nn,parseArkConfigJson:()=>gr,parseArkRulesJson:()=>Lo,parseSkillDescriptionVersion:()=>fi,parseSkillDocument:()=>js,policyDeltaAcknowledgementMatches:()=>Or,preflightChange:()=>os,preflightResolvedChange:()=>as,primaryImprovementCompassNextAction:()=>vs,projectStatusArkRun:()=>Jr,projectStatusImprovementCompass:()=>en,projectionHasNonEnforcementLabel:()=>ws,projectionMatchesPackageVersion:()=>Ns,resolveEffectiveContract:()=>Mo,resolveStatusNextAction:()=>ys,resolvedFactsEvidenceRequirementsHash:()=>Ze,serializeDiagnosticCatalog:()=>Ha,skillDescriptionVersionPrefix:()=>Us,stableSerialize:()=>$,stampSkillDescription:()=>mi,statusCompassResidualIsSubsetOfDoctor:()=>Wa,stripSkillDescriptionVersion:()=>Vs,summarizeArkRunSection:()=>va,toAdapterDiagnostic:()=>sr,unavailableStatusImprovementCompass:()=>za,validateAgentSkillDocument:()=>Ks,validateAgentSkillsPackage:()=>ui,validateSkillProductCapacity:()=>pi,version:()=>Bs});module.exports=Si(bd);var Bs="4.8.15";var Ii=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,bi=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,vi=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ci(e,t){let r=String(e??"").replace(/\\/g,"/").trim(),n=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ii.test(r)?"pure-shared":n==="PersistenceAdapters"&&(bi.test(r)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${r}`))?"kernel-emit":vi.test(r)||(n==="DomainModel"||n==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Ci,"classifyLayerImportKind");function _i(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Ci(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(_i,"layerImportNextAction");function Oi(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Oi,"arkRunCallSiteName");function xi(e){let t=Oi(e),r=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 ${r??"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(xi,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return _i(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"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 xi(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ye,"deterministicNextAction");var lt="1.5",ct="docs/diagnostics.md",fn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function Ge(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,r=typeof e.file=="string"?e.file:void 0,n=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,r,n??"",o??"",s??""].join("|")}i(Ge,"adapterFindingTargetKey");function Be(e){let t=new Map;return e.map(r=>{let n=Ge(r),o=(t.get(n)??0)+1;return t.set(n,o),o===1?n:`${n}#${o}`})}i(Be,"adapterFindingOccurrenceTargetKeys");function dt(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(dt,"adapterFindingRefFromTargetKey");function ut(e){return`${ct}#${e}`}i(ut,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}i(x,"text");function zs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(zs,"positiveInteger");function Ti(e,t,r){return ye({ruleId:e,target:x(t.target)??x(r.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:x(t.edgeKind)??void 0,capability:x(t.capability)??x(r.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}i(Ti,"nextActionForDiagnostic");function sr(e,t="error",r){let n=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=r??Ge(e),c=dt(a);return{ruleId:n,severity:o,message:x(e.message)??n,location:{file:x(e.file)??"<unknown>",line:zs(e.line,1),column:zs(e.column,1)},evidence:s,nextAction:x(e.nextAction)??Ti(n,s,e),findingRef:c,targetKey:a,docsCodePath:ut(n)}}i(sr,"toAdapterDiagnostic");function Ws(e){let t=e.completeness??"complete",r=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let n=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(g=>({code:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(r==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=Be(s),l=Be(a),u=[...s.map((g,f)=>sr(g,"error",c[f])),...a.map((g,f)=>sr(g,"warning",l[f]))],p={schemaVersion:"1.5",completenessReasons:n,diagnostics:u};if(r==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:r,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:r,valid:e.valid,completeness:t,...g}:{...p,mode:r,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:r,valid:e.valid,completeness:t,...o}:{...p,mode:r,valid:!1,completeness:t,...o}}i(Ws,"createAdapterResult");var qs="1.0",mn="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",or="^sha256:[a-f0-9]{64}$",gn={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:or,description:"Project id previously returned by ark_identity or ark_manifest."}}},yn={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:or},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Ys={$schema:"https://json-schema.org/draft/2020-12/schema",$id:mn,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:or},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:or},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:gn,binding:yn}};function Js(e,t,r){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let n=r(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(n))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${n}`}i(Js,"createProjectId");function Xs(e){return{schemaVersion:"1.0",...e}}i(Xs,"createProjectIdentity");var An=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),kn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),En=Object.freeze(Object.keys(kn).sort()),hn=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"}),Rn=Object.freeze({process:Object.freeze(["process","node:process"])});function pt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=hn[e];if(t)return t;let r=e.indexOf("/");if(r<0)return null;let n=e.slice(0,r),o=hn[n];if(o)return o;let s=e.indexOf("/",r+1);return s<0?null:hn[e.slice(0,s)]??null}i(pt,"capabilityForModuleSpecifier");function ve(e,t){for(let r of t)if(Rn[r]?.includes(e))return r;return null}i(ve,"forbiddenGlobalForModuleSpecifier");function ar(e){let t=e.split(".");for(let r=t.length;r>=1;r-=1){let n=t.slice(0,r).join("."),o=kn[n];if(o)return o}return null}i(ar,"capabilityForAmbientName");function ze(e){if(e?.pure===!0)return[...An].sort();let r=(e?.capabilities?.deny??[]).filter(n=>An.includes(n));return[...new Set(r)].sort()}i(ze,"effectiveCapabilityDeny");function ft(e,t){if(t.length===0)return!1;let r=new Set(t),n=e.split(".");for(let o=n.length;o>=1;o-=1)if(r.has(n.slice(0,o).join(".")))return!0;return!1}i(ft,"ambientCoveredByForbiddenGlobals");function ir(e){let t=new Set,r=new Set,n=Object.keys(kn);for(let o of e?.forbiddenGlobals??[]){let s=n.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)r.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Rn[o]??[])t.add(`import-exact:${a}`)}for(let o of ze(e)){if(t.add(`import:${o}`),o==="process")for(let s of Rn.process)t.add(`import-exact:${s}`);for(let s of n)ar(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...r].sort()}}i(ir,"loweredLayerCoverage");var Zs=new Map;function Qs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Qs,"escapeLiteral");function lr(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=n}return t}i(lr,"normalizeGlobSeparators");function Ni(e){let t=0;for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"){r+=1;continue}if(n==="{")t+=1;else if(n==="}"&&(t-=1,t<0))return!1}return t===0}i(Ni,"bracesBalanced");function Ae(e){let t=Zs.get(e);if(t)return t;let r=lr(e),n=Ni(r),o="",s=0;for(let c=0;c<r.length;c+=1){let l=r[c];l==="\\"&&c+1<r.length?(o+=Qs(r[c+1]),c+=1):l==="*"?r[c+1]==="*"?r[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&n?(o+="(?:",s+=1):l==="}"&&n&&s>0?(o+=")",s-=1):l===","&&n&&s>0?o+="|":o+=Qs(l)}let a=new RegExp(`^${o}$`);return Zs.set(e,a),a}i(Ae,"globToRegExp");function wi(e){return lr(String(e)).split("/").filter(Boolean).filter(r=>r!=="**"&&r!=="*"&&!r.includes("*")&&!r.includes("?")&&!r.includes("{")&&!r.includes("["))}i(wi,"concreteGlobSegments");function Sn(e,t){let r=lr(String(e)),n=wi(r),o=r.replace(/\*/g,"").length,s=n.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(n.length===0)return o;let c=0,l=-1;for(let u of n){let p=-1;for(let g=c;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;l=p,c=p+1}return(l+1)*1e6+n.length*1e4+o}i(Sn,"patternSpecificity");function pe(e,t){let r=String(e).split(/[/\\]/).join("/"),n,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Ae(a).test(r))){for(let a of s.patterns??[])if(Ae(a).test(r)){let c=Sn(a,r);c>o&&(o=c,n=s.name)}}return n}i(pe,"layerForRelativePath");function eo(e,t){if(!t?.length)return;let r=String(e).split(/[/\\]/).filter(Boolean),n=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<r.length-1;o+=1)if(n.has(r[o].toLowerCase()))return`${r[o].toLowerCase()}/${r[o+1].toLowerCase()}`}i(eo,"sliceIdForPath");function Pi(e){let t=new Set;for(let r of e??[]){let o=lr(String(r)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(Pi,"inferSliceFoldersFromPatterns");function Li(e,t,r){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let n=(r??[]).find(o=>o.name===t);return Pi(n?.patterns)}i(Li,"resolveSliceFolders");function to(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(to,"normalizeSegments");function so(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(so,"trimTrailingSlashes");var Di=["src","app"];function Mi(e){let t=so(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Mi,"isBlanketRoot");function ro(e,t){if(!e||!t?.length)return!1;let r=String(e).split(/[/\\]/).join("/"),n=r.toLowerCase(),o=to(r);for(let s of t){if(typeof s!="string"||s.length===0||Mi(s))continue;if(s.includes("*")){let l=so(s.toLowerCase());if(Ae(l).test(n)||Ae(`${l}/**`).test(n))return!0;continue}let a=to(s);if(a.length===0)continue;let c=Di.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let l of c){if(l+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[l+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(ro,"pathUnderSharedRoot");function no(e,t){let r=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!r)return!1;let n=t.toLowerCase();return r===n?!0:!r.includes("/")&&n.endsWith(`/${r}`)}i(no,"sliceMatchesDeclaration");function Fi(e,t,r){return!e?.length||!t||!r?!1:e.some(n=>n&&typeof n.from=="string"&&typeof n.to=="string"&&no(n.from,t)&&no(n.to,r))}i(Fi,"crossSliceEdgeAllowed");function $i(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let r=!!e.toSlice||e.toShared===!0;return!t||!r?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i($i,"peerIsolationDecision");function We(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let r=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${r.length>0?` (${r.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(We,"peerIsolationDenyExplanation");function cr(e,t,r,n){return Pe(e,t,r,n)?.rule}i(cr,"findDeniedEdgeRule");function Pe(e,t,r,n){for(let o of e??[])if(!(o.from!==t||o.to!==r)&&o.allowed===!1){if(o.peerIsolation){let s=n?.fromPath,a=n?.toPath,c=Li(o,t,n?.layers),l=s?eo(s,c):void 0,u=a?eo(a,c):void 0,p=$i({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:u,fromShared:!l&&ro(s,o.sharedRoots),toShared:!u&&ro(a,o.sharedRoots),crossSliceAllowed:Fi(o.allowedCrossSlice,l,u)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:l,toSlice:u};continue}if(t!==r)return{rule:o}}}i(Pe,"findDeniedEdgeDecision");function qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(qe,"literalText");function io(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(io,"lineOf");function oo(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let o=n.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let r=t.exportClause;return!!(r&&e.isNamedExports(r)&&r.elements.length>0&&r.elements.every(n=>n.isTypeOnly))}i(oo,"isTypeOnlyReference");function lo(e,t){let r={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},n=e.createCompilerHost(r,!0);return n.getSourceFile=o=>o===t.fileName?t:void 0,n.fileExists=o=>o===t.fileName,n.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],r,n).getTypeChecker()}i(lo,"singleFileChecker");function In(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(In,"symbolAt");function bn(e,t,r,n){let o=n.parent&&e.isShorthandPropertyAssignment(n.parent)&&n.parent.name===n,s;try{s=o?t.getShorthandAssignmentValueSymbol(n.parent):In(t,n)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===r.fileName)}i(bn,"localDeclaration");function Le(e,t){let r,n=[],o=i((a,c,l,u=!1)=>n.push({specifier:l,kind:c,line:io(t,a),typeOnly:u,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",qe(e,a.moduleSpecifier),oo(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",qe(e,a.moduleSpecifier),oo(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",qe(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!bn(e,r??(r=lo(e,t)),t,a.expression);(c||u)&&o(a,u?"require":"dynamic-import",qe(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),n}i(Le,"extractSemanticDependencies");function Hi(e,t){let r=[],n=t;for(;e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n);){if(e.isPropertyAccessExpression(n))r.unshift(n.name.text);else{let o=qe(e,n.argumentExpression);if(o===void 0)return;r.unshift(o)}n=n.expression}if(e.isIdentifier(n))return r.unshift(n.text),{root:n,segments:r}}i(Hi,"staticAccessPath");function ji(e,t){let r=t.parent;return e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(r)&&r.name===t}i(ji,"runtimeIdentifierReference");function ao(e,t){let r=t[0]==="globalThis"?t.slice(1):t;for(let n=r.length;n>=1;n-=1){let o=r.slice(0,n).join(".");if(e.has(o))return o}}i(ao,"bestForbiddenMatch");function De(e,t,r){if(r.length===0)return[];let n=new Set(r),o=lo(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let c=i(f=>{let m=Hi(e,f);if(!m)return;let d=In(o,m.root),A=d?s.get(d):void 0;return A?[...A,...m.segments.slice(1)]:bn(e,o,t,m.root)||a.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let d=c(m.initializer),A=In(o,m.name);!d||!A||s.set(A,d)}let l=[],u=new Set,p=i((f,m)=>{let d=io(t,m),A=`${f}:${m.getStart(t)}`;u.has(A)||(u.add(A),l.push({name:f,line:d,node:m}))},"flag"),g=i(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let d=c(f),A=d?ao(n,d):void 0;A&&p(A,f)}else e.isIdentifier(f)&&n.has(f.text)&&ji(e,f)&&!bn(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=c(f.initializer);if(d)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?qe(e,A.propertyName)??A.propertyName.text:A.name.text,O=ao(n,[...d,b]);O&&p(O,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),l}i(De,"collectForbiddenCapabilityUses");function vn(e,t,r){let n=[];for(let o of r?.dependencies??Le(e,t)){if(o.typeOnly||!o.specifier)continue;let s=pt(o.specifier);s&&n.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of r?.ambientUses??De(e,t,En)){let s=ar(o.name);s&&n.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return n.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(vn,"collectCapabilityUses");var Cn={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},_n=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function On(e,t){return t.flatMap((n,o)=>(n.prefixes??n.intentPrefixes??[]).map(s=>({layer:n.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:n})=>e.startsWith(n)).sort((n,o)=>o.prefix.length-n.prefix.length||n.layerIndex-o.layerIndex)[0]?.layer}i(On,"resolveIntentLayer");function Me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Me,"looksLikeArkIntent");function mt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Me(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Cn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Cn.PUBLISH_MISSING_SOURCE}),t}i(mt,"classifyPublishFacts");function W(e,t,r){return{ruleId:e,code:e,message:t,...r}}i(W,"violation");function Ye(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}i(Ye,"lineOf");var Ki=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ui(e,t){return e.index+e[0].indexOf(t)}i(Ui,"captureIndex");function Vi(e){let t=[],r=new Set,n=i((c,l)=>{!c||r.has(l)||(r.add(l),t.push({value:c,index:l}))},"push"),o=i(c=>{c.lastIndex=0;let l;for(;(l=c.exec(e))!==null;){let u=l[1];u&&n(u,Ui(l,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let c=a[1]??"",l=a.index+a[0].indexOf(c),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.exec(c))!==null;){let g=p[1];g&&n(g,l+p.index+p[0].indexOf(g))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((c,l)=>c.index-l.index)}i(Vi,"extractQuotedStrings");function Gi(e){let t=[],r=[{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 n of r){let o;for(;(o=n.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],c=n.kind==="import"&&/\bimport\s+type\b/.test(a)||n.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:n.kind,typeOnly:c})}}return t.sort((n,o)=>n.index-o.index)}i(Gi,"extractModuleSpecifiers");function Bi(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(Bi,"isSyntaxWrapper");function xn(e,t){let r=t;for(;r?.parent&&Bi(e,r.parent);)r=r.parent;return r}i(xn,"unwrapWrappers");function Tn(e,t){if(!t||!e.isCallExpression(t))return;let r=t.expression;if(e.isIdentifier(r))return r.text;if(e.isPropertyAccessExpression(r))return r.name.text}i(Tn,"callCalleeName");function zi(e,t){let r=t.parent;if(!r||!e.isObjectLiteralExpression(r))return!1;let n=xn(e,r),o=n.parent;if(!o)return!1;if(e.isCallExpression(o)&&Tn(e,o)==="publish"){let s=o.arguments;return s[1]===n||s[2]===n}if(e.isPropertyAssignment(o)&&Nn(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let c=xn(e,s).parent;return!!(c&&e.isCallExpression(c)&&Tn(e,c)==="publish")}return!1}i(zi,"isPublishMetadataSource");function co(e,t){let r=xn(e,t),n=r.parent;if(!n)return!1;if(e.isCallExpression(n)){let o=Tn(e,n);if(o&&Ki.has(o)&&n.arguments.some(s=>s===r))return!0}if(e.isArrayLiteralExpression(n))return co(e,n);if(e.isPropertyAssignment(n)){let o=Nn(e,n.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&zi(e,n))return!0}return!1}i(co,"isDeclaredIntentSite");function Wi(e,t){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),n=[],o=i(s=>{e.isStringLiteralLike(s)&&co(e,s)&&n.push({value:s.text,index:s.getStart(r)}),e.forEachChild(s,o)},"visit");return o(r),n}i(Wi,"extractQuotedStringsAst");function qi(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(r=>t.includes(r))}i(qi,"hasInfrastructureToken");function Yi(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(r=>t===r||t.startsWith(`${r}/`))}i(Yi,"isKnownInfrastructurePackage");function Ji(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(r=>t.includes(r))}i(Ji,"layerHasInfrastructureRole");function yt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(yt,"tsStringLiteralText");function Nn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Nn,"tsPropertyName");function uo(e,t,r){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(n=>!e.isPropertyAssignment(n)&&!e.isShorthandPropertyAssignment(n)?!1:Nn(e,n.name)===r)}i(uo,"tsObjectProperty");function ht(e,t,r){return uo(e,t,r)!==void 0}i(ht,"tsObjectHasProperty");function gt(e,t,r){let n=uo(e,t,r);return n&&e.isPropertyAssignment(n)?n.initializer:void 0}i(gt,"tsObjectPropertyValue");function Xi(e,t){let r=gt(e,t,"metadata");return ht(e,r,"source")}i(Xi,"tsObjectHasMetadataSource");function po(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?po(e,t.name):!1:!1}i(po,"tsLooksLikeIntentCreatorExpression");function Zi(e,t){if(!e.isCallExpression(t))return!1;let r=t.expression;return e.isPropertyAccessExpression(r)?r.name.text==="publish":e.isIdentifier(r)&&r.text==="publish"}i(Zi,"tsIsPublishCall");function Qi(e,t){if(!e.isCallExpression(t))return!1;let r=t.arguments[0],n=yt(e,r);return n!==void 0&&Me(n)||ht(e,r,"intent")||po(e,r)}i(Qi,"tsIsArkPublishCandidate");function el(e,t){if(!e.isCallExpression(t))return!1;let[r,n,o]=t.arguments;return Xi(e,r)||ht(e,n,"source")||ht(e,o,"source")}i(el,"tsPublishHasSource");function tl(e,t){if(!e.isCallExpression(t))return;let[r,n,o]=t.arguments,s=gt(e,r,"metadata");return yt(e,gt(e,s,"source"))??yt(e,gt(e,n,"source"))??yt(e,gt(e,o,"source"))}i(tl,"tsPublishSourceLiteral");function rl(e,t,r,n){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=r,a=s?.filePath,c=s?.layer,l=[],u=i(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=i(g=>{if(Zi(e,g)){let f=g.arguments[0],m=yt(e,f);for(let A of mt({publishCall:!0,rawIntentName:m,objectHasIntent:ht(e,f,"intent"),arkPublishCandidate:Qi(e,g),hasSource:el(e,g)}))l.push(W(A.ruleId,A.message,{line:u(g),filePath:a}));let d=tl(e,g);if(n&&c&&d&&Me(d)){let A=n.resolveLayer(d);A&&A!==c&&l.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${A}, but the target file is classified as ${c}.`,{line:u(g),filePath:a,target:d,fromLayer:c,toLayer:A}))}}e.forEachChild(g,p)},"visit");return p(o),l}i(rl,"analyzePublishAst");function wn(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),r=e.forbiddenPatterns||[],n=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],l=a,u=l?.filePath,p=l?.layer,g=e.typescript,f=g?g.createSourceFile(u??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?Le(e.typescript,f):void 0,d=m?m.filter(E=>E.specifier!==void 0).map(E=>({value:E.specifier,index:E.node.getStart(f),kind:E.kind,typeOnly:E.typeOnly})):Gi(s),A=e.typescript?Wi(e.typescript,s):Vi(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let E of m?.filter(({unresolved:I})=>I)??[]){let I=E.kind==="require";c.push(W(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:E.line,filePath:u}))}let b=p!==void 0&&(n.has(p)||Ji(p)),O=p!==void 0?` If "${p}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let E of r)if(E instanceof RegExp){E.lastIndex=0;let I=E.exec(s);E.lastIndex=0,I&&c.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${E}`,{line:I.index===void 0?void 0:Ye(s,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+O}))}else s.includes(E)&&c.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${E}`,{line:Ye(s,s.indexOf(E)),filePath:u}));for(let E of d){let I=e.resolveImportTarget?.(E.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(E.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,L=I?.layer;if(L&&p){let k=cr(e.architectureProfile?.rules,p,L,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(k){if(E.typeOnly&&!k.peerIsolation)continue;let P=!!k.peerIsolation;c.push(W("LAYER_IMPORT_VIOLATION",k.message??(P?`Layer "${p}" must not import across slices into "${L}".`:`Layer "${p}" must not import "${L}".`),{line:Ye(s,E.index),source:E.value,target:E.value,filePath:u,fromLayer:p,toLayer:L,suggestion:P?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:E.kind,peerIsolation:P,...E.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||E.typeOnly||!qi(E.value)&&!Yi(E.value)||c.push(W("FORBIDDEN_IMPORT",`Forbidden ${E.kind} target: "${E.value}".`,{line:Ye(s,E.index),source:E.value,target:E.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+O,details:{importKind:E.kind}}))}if(e.policies)for(let E of e.policies){let I=E.check({source:s,context:a});if(I!==!0)if(Array.isArray(I))for(let C of I)c.push(W("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${E.name}".`}));else I===!1?c.push(W("POLICY_VIOLATION",`Policy ${E.name} failed on generated code`)):c.push(W("POLICY_VIOLATION",I.message))}if(o&&t.size>0)for(let E of A)Me(E.value)&&!t.has(E.value)&&c.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${E.value}"`,{line:Ye(s,E.index),filePath:u,target:E.value,suggestion:`Register intent "${E.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let E of A){if(!Me(E.value))continue;let I=e.architectureProfile.resolveLayer(E.value);if(!I)continue;let C=Pe(e.architectureProfile.rules,p,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let L=C.rule.peerIsolation?We(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,k=`Layer "${p}" must not reference "${I}" through "${E.value}".`,P=L&&C.peerIsolationReason!=="cross-slice"?`${k} ${L}`:C.rule.message?L?`${C.rule.message} (${L})`:C.rule.message:k;c.push(W("LAYER_REFERENCE_VIOLATION",P,{line:Ye(s,E.index),filePath:u,target:E.value,fromLayer:p,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let E of e.extensions)try{let I=E.analyze(s,a);c.push(...I)}catch(I){c.push(W("EXTENSION_ERROR",`Extension "${E.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let E=e.forbiddenGlobals[p];c.push(...De(e.typescript,f,E).map(I=>W("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of m??[]){if(I.typeOnly||!I.specifier)continue;let C=ve(I.specifier,E);C&&c.push(W("FORBIDDEN_GLOBAL",`${p} must not use module "${I.specifier}" because it is the import form of forbidden global "${C}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:p,details:{importKind:I.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(E){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let E=new Set(e.capabilityWalls[p]),I=e.forbiddenGlobals?.[p]??[];for(let C of vn(e.typescript,f))E.has(C.capability)&&(C.source==="ambient-global"&&ft(C.symbol,I)||C.source==="import-based"&&ve(C.symbol,I)||c.push(W("CAPABILITY_VIOLATION",C.source==="import-based"?`${p} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${p} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(E){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript)try{c.push(...rl(e.typescript,s,a,e.architectureProfile))}catch(E){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}i(wn,"createAICodeGate");var Fe={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},fo={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Fe,default:[]},kernelRoots:{...Fe},managedLayers:{...Fe,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},mo={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Fe,default:[]},managedLayers:{...Fe,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Fe,default:[]},appliesTo:{...Fe,default:[]}}};function At(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(At,"isObject");function go(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let r of e.layers)At(r)&&typeof r.name=="string"&&r.name.length>0&&t.add(r.name);return t}i(go,"declaredLayerNames");function yo(e){if(!At(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(yo,"defaultedArkRun");function ho(e){if(!At(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(ho,"defaultedArkOrder");function Ao(e,t){let r=e.arkRun;if(r===void 0||!At(r))return;let n=go(e),o=r.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!n.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),r.mode==="enforced"){let s=r.kernelRoots??r.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:r.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Ao,"validateArkRunExtra");function Ro(e,t){let r=e.arkOrder;if(r===void 0||!At(r))return;let n=go(e),o=r.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!n.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),r.mode==="enforced"){let s=r.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Ro,"validateArkOrderExtra");function dr(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(dr,"normalizeStewardId");function ko(e){let t=dr(e);return!t||Pn(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(ko,"isGitHubHandle");function nl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Pn(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(nl,"isGitHubEmail");function sl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&ko(t[1])?dr(t[1]):null}i(sl,"githubHandleFromEmail");function Eo(e){let t=sl(e);if(t)return t;let r=dr(e);return!r||Pn(r)?null:ko(r)||nl(r)?r:null}i(Eo,"canonicalStewardId");var ol=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Pn(e){let t=dr(e);return!t||ol.test(t)}i(Pn,"isAutomationAuthor");var se="1.3",al=["public","auth","admin","internal"];function il(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(il,"isFutureHouseLayer");function ll(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let r=t.filter(n=>typeof n=="string"&&n.length>0);return r.length>0?r:void 0}i(ll,"layerOwnersList");function Io(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!il(t)&&!ll(t)).map(t=>t.name)}i(Io,"layersMissingRequiredOwners");function bo(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(bo,"missingLayerOwnersNextAction");var pr="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",So=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],cl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function dl(){let e=[];for(let t of So)for(let r of So)t===r||cl.has(`${t}->${r}`)||e.push({from:t,to:r,allowed:!1});return e}i(dl,"createDefaultRules");var mr=dl(),Ln=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ae={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},fr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:pr,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:pr,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:se,default:se},name:{type:"string",minLength:1},include:{...ae,minItems:1,default:["src"]},exclude:{...ae,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:mr,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ae,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ae,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ae,minItems:1},exclude:ae,intentPrefixes:ae,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...al]},owners:{...ae,minItems:1},forbiddenGlobals:ae,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ae,minItems:1},sharedRoots:{...ae,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...ae,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...ae,minItems:1}}},arkRun:fo,arkOrder:mo}},Re=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,r){super(`Invalid ArkGate config (${t}):
|
|
3
|
-
${
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=r}};function vo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(vo,"isObject");function ur(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(ur,"propertyPath");function Je(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Je,"valueType");function ul(e,t){let r="#/$defs/";if(e.startsWith(r))return t.$defs[e.slice(r.length)]}i(ul,"resolveSchemaRef");function Rt(e,t,r,n,o){if(t.$ref){let s=ul(t.$ref,n);if(!s){o.push({path:r,message:`schema reference ${t.$ref} cannot be resolved`});return}Rt(e,s,r,n,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:r,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:r,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!vo(e)){o.push({path:r,message:`must be an object; received ${Je(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:ur(r,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:ur(r,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||Rt(e[c],a,ur(r,c),n,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&Rt(e[a],c,ur(r,a),n,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:r,message:`must be an array; received ${Je(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:r,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:r,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>Rt(s,t.items,`${r}[${a}]`,n,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:r,message:`must be a string; received ${Je(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:r,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:r,message:`must be a boolean; received ${Je(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:r,message:`must be an integer; received ${Je(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:r,message:`must be at least ${t.minimum}`})}}i(Rt,"validateNode");function pl(e,t){let r=e.layers;Array.isArray(r)&&r.forEach((n,o)=>{if(!n||typeof n!="object"||Array.isArray(n)||!("owners"in n))return;let s=n.owners;Array.isArray(s)&&s.forEach((a,c)=>{typeof a=="string"&&(Eo(a)||t.push({path:`$.layers[${o}].owners[${c}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(pl,"validateLayerOwners");function fl(e){let t={...e,$schema:e.$schema===void 0?pr:e.$schema,schemaVersion:e.schemaVersion===void 0?se:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?mr.map(r=>({...r})):e.rules};return e.arkRun!==void 0&&(t.arkRun=yo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=ho(e.arkOrder)),t}i(fl,"defaultedConfig");function ml(e){return e===se?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(ml,"migratedFromOf");function gl(){let e=new Set([se]);for(let t of Ln)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(gl,"knownInputVersions");function yl(e,t="ark.config.json"){if(!vo(e))throw new Re(t,[{path:"$",message:`must be an object; received ${Je(e)}`}]);let r=gl(),n=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(n===null)throw new Re(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${se}`}]);if(n!=="unversioned"&&!r.has(n))throw new Re(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${se}`}]);let o=n,s={...e},a=0;for(;o!==se&&a<Ln.length+1;){a+=1;let c=Ln.find(l=>l.from===o);if(!c)throw new Re(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${se}`}]);o=c.to,s.schemaVersion=o}if(o!==se)throw new Re(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${se}`}]);return{candidate:fl(s),migratedFrom:ml(n)}}i(yl,"migrateArkConfig");function kt(e,t="ark.config.json"){let{candidate:r,migratedFrom:n}=yl(e,t),o=[];if(Rt(r,fr,"$",fr,o),Ao(r,o),Ro(r,o),pl(r,o),o.length>0)throw new Re(t,o);return{config:r,migratedFrom:n}}i(kt,"loadArkConfigContract");function gr(e,t="ark.config.json"){let r;try{r=JSON.parse(e)}catch(n){throw new Re(t,[{path:"$",message:`invalid JSON: ${n instanceof Error?n.message:String(n)}`}])}return kt(r,t)}i(gr,"parseArkConfigJson");function Co(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:pr,schemaVersion:se};for(let[r,n]of Object.entries(e))r!=="$schema"&&r!=="schemaVersion"&&(t[r]=n);return t}i(Co,"withArkConfigMetadata");function hl(e){return e.endsWith(".")?e:`${e}.`}i(hl,"normalizePrefix");function Al(e,t){let r=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-r}i(Al,"byLongestPrefix");function St(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(hl)})),r=[...t].sort(Al),n=[...e.rules??[]];return{name:e.name,layers:t,rules:n,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??r.find(s=>s.prefixes.some(a=>o.startsWith(a)))?.name}}}i(St,"createArchitectureProfile");function Dn(e,t={}){return St({name:t.name??e.name??"ark.config.json",layers:e.layers.map((r,n)=>({name:r.name,prefixes:r.intentPrefixes??[],description:r.description,trustBoundary:r.trustBoundary,owners:r.owners,order:n+1})),rules:e.rules??[]})}i(Dn,"createArchitectureProfileFromArkConfig");var Rl=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Et=St({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Rl,rules:mr.map(e=>({...e}))}),kl={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Mn(e={}){let t=e.rootDir??"src",r=e.optionalLayers??!0,n=t==="."?"":`${t}/`;return Co({include:e.include??[t],layers:Et.layers.map(o=>({name:o.name,patterns:(kl[o.name]??[o.name]).map(s=>`${n}${s}/**`),intentPrefixes:o.prefixes,optional:r})),rules:[...Et.rules]})}i(Mn,"createElevenLayerArkConfig");function J(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(J,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${$(t[r])}`).join(",")}}`}i($,"stableSerialize");var Ce="1.2";var _o=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let r=$(e),n=$(t);return r<n?-1:r>n?1:0}i(q,"compareCanonical");function Z(e){return[...new Set(e)].sort((t,r)=>t<r?-1:t>r?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:e.layers.map(r=>({name:r.name,patterns:Z(r.patterns??[]),exclude:Z(r.exclude??[]),forbiddenGlobals:Z(r.forbiddenGlobals??[]),intentPrefixes:Z(r.intentPrefixes??[]),capabilityDeny:Z(r.capabilities?.deny??[]),pure:r.pure===!0})).sort(q),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 J($(t))}i(Ze,"resolvedFactsEvidenceRequirementsHash");function El(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(q),r=e.files.map(k=>({...k,typeOnlyExportNames:Z(k.typeOnlyExportNames)})).sort((k,P)=>k.path<P.path?-1:k.path>P.path?1:0),n=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:Z(k.namedBindings)}:{}})).sort(q),o=e.capabilityUses.map(k=>({...k})).sort(q),s=e.ambientUses.map(k=>({...k})).sort(q),a=e.publishCalls.map(k=>({...k})).sort(q),c=e.intentReferences.map(k=>({...k})).sort(q),l=e.safetyUses.map(k=>({...k})).sort(q),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(P=>({...P}))})).sort(q),p=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(q),g=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(q),f=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(q),m=(e.arkRunDeclarations??[]).map(k=>({...k,uses:Z(k.uses),reactsTo:Z(k.reactsTo),raises:Z(k.raises),sends:Z(k.sends)})).sort(q),d=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(q),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(q),b=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(q),O=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(q),E=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(q),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(q),C=e.files.map(({path:k,contentHash:P})=>({path:k,contentHash:P})).sort((k,P)=>k.path<P.path?-1:k.path>P.path?1:0),L=J($(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:L,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:r,dependencies:n,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:l,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:d,arkOrderGenericUpdates:A,arkOrderRootHits:b,arkOrderXiFieldWrites:O,arkOrderIngestWritesXi:E,arkOrderReleaseKeyCounts:I}}i(El,"canonicalResolvedFactsInput");function Oo(e){let t=El(e);return{...t,factsHash:J($(t))}}i(Oo,"createCanonicalResolvedCandidateFacts");function yr(e){return Oo(To(H(e,"$"),!1))}i(yr,"createResolvedCandidateFacts");function H(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(H,"asRecord");function j(e,t,r){let n=new Set(t),o=Object.keys(e).find(s=>!n.has(s));if(o)throw new Error(`${r}.${o} is not part of schema ${"1.2"}.`)}i(j,"assertOnlyKeys");function F(e,t,r){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`${r}.${t} must be a non-empty string.`);return n}i(F,"requiredText");function ke(e,t,r){if(e[t]!==void 0)return F(e,t,r)}i(ke,"optionalText");function U(e,t,r){let n=F(e,t,r),o=n.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${r}.${t} must be a canonical project-relative path.`);let s=[];for(let c of o.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${r}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==n)throw new Error(`${r}.${t} must be a canonical project-relative path.`);return a}i(U,"requiredProjectPath");function V(e,t,r){if(typeof e[t]!="boolean")throw new Error(`${r}.${t} must be a boolean.`);return e[t]}i(V,"requiredBoolean");function xo(e,t,r){let n=e[t];if(!Number.isInteger(n)||Number(n)<0)throw new Error(`${r}.${t} must be a non-negative integer.`);return Number(n)}i(xo,"requiredInteger");function te(e,t,r){let n=xo(e,t,r);if(n===0)throw new Error(`${r}.${t} must be a positive integer.`);return n}i(te,"requiredPositiveInteger");function G(e,t,r){let n=e[t];if(!Array.isArray(n))throw new Error(`${r}.${t} must be an array.`);return n}i(G,"requiredArray");function Ee(e,t,r,n){let o=e[t];if(typeof o!="string"||!r.includes(o))throw new Error(`${n}.${t} must be one of ${r.join(", ")}.`);return o}i(Ee,"enumValue");function Xe(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!r))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(Xe,"parseStringArray");function Sl(e,t,r){let n=new Set;for(let o of e){let s=t(o);if(n.has(s))throw new Error(`${r} must not contain duplicate facts (${s}).`);n.add(s)}}i(Sl,"assertUnique");function To(e,t){j(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let r=Ee(e,"schemaVersion",["1.0","1.1","1.2"],"$"),n=Ee(e,"completeness",["complete","partial","unavailable"],"$"),o=G(e,"completenessReasons","$").map((v,_)=>{let h=`$.completenessReasons[${_}]`,R=H(v,h);j(R,["code","message","file"],h);let y=R.file===void 0?void 0:U(R,"file",h);return{code:F(R,"code",h),message:F(R,"message",h),...y?{file:y}:{}}});if(n==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(n!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=G(e,"files","$").map((v,_)=>{let h=`$.files[${_}]`,R=H(v,h);return j(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:U(R,"path",h),contentHash:F(R,"contentHash",h),parseStatus:Ee(R,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:xo(R,"parseDiagnosticCount",h),exportsOnlyTypes:V(R,"exportsOnlyTypes",h),typeOnlyExportNames:Xe(R.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:V(R,"hasTopLevelSideEffects",h)}}),a=G(e,"dependencies","$").map((v,_)=>{let h=`$.dependencies[${_}]`,R=H(v,h);j(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let y=ke(R,"specifier",h),D=ke(R,"target",h),ce=Ee(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ce==="resolved-project"&&!D)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ce!=="resolved-project"&&D)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ce!=="dynamic"&&!y)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:U(R,"from",h),...y?{specifier:y}:{},kind:Ee(R,"kind",["import","export","dynamic-import","require"],h),typeOnly:V(R,"typeOnly",h),line:te(R,"line",h),resolution:ce,...D?{target:U(R,"target",h)}:{},...R.namedBindings!==void 0?{namedBindings:Xe(R.namedBindings,`${h}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:V(R,"targetTypeOnlyExports",h)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:V(R,"sourcePureTypeModule",h)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:V(R,"namedBindingsTypeOnly",h)}:{},...R.portProofEligible!==void 0?{portProofEligible:V(R,"portProofEligible",h)}:{}}}),c=G(e,"capabilityUses","$").map((v,_)=>{let h=`$.capabilityUses[${_}]`,R=H(v,h);return j(R,["file","line","symbol","capability","source"],h),{file:U(R,"file",h),line:te(R,"line",h),symbol:F(R,"symbol",h),capability:Ee(R,"capability",_o,h),source:Ee(R,"source",["ambient-global","import-based"],h)}}),l=G(e,"ambientUses","$").map((v,_)=>{let h=`$.ambientUses[${_}]`,R=H(v,h);return j(R,["file","line","symbol"],h),{file:U(R,"file",h),line:te(R,"line",h),symbol:F(R,"symbol",h)}}),u=G(e,"publishCalls","$").map((v,_)=>{let h=`$.publishCalls[${_}]`,R=H(v,h);j(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let y=ke(R,"rawIntentName",h),D=ke(R,"sourceIntent",h);return{file:U(R,"file",h),line:te(R,"line",h),...y?{rawIntentName:y}:{},objectHasIntent:V(R,"objectHasIntent",h),arkPublishCandidate:V(R,"arkPublishCandidate",h),hasSource:V(R,"hasSource",h),...D?{sourceIntent:D}:{}}}),p=G(e,"intentReferences","$").map((v,_)=>{let h=`$.intentReferences[${_}]`,R=H(v,h);return j(R,["file","line","intent"],h),{file:U(R,"file",h),line:te(R,"line",h),intent:F(R,"intent",h)}}),g=G(e,"safetyUses","$").map((v,_)=>{let h=`$.safetyUses[${_}]`,R=H(v,h);j(R,["file","line","kind","symbol"],h);let y=ke(R,"symbol",h),D=Ee(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(D==="in-memory-store"&&!y)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(D!=="in-memory-store"&&y)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:U(R,"file",h),line:te(R,"line",h),kind:D,...y?{symbol:y}:{}}});Sl(s,v=>v.path,"$.files");let f=new Set(s.map(v=>v.path));for(let v of s){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(n==="complete"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((v,_)=>{let h=`$.arkRunKernelCalls[${_}]`,R=H(v,h);j(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let y=ke(R,"receiver",h),D=ke(R,"nameLiteral",h);return{file:U(R,"file",h),line:te(R,"line",h),kind:Ee(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:F(R,"callee",h),viaImport:V(R,"viaImport",h),...y?{receiver:y}:{},...D?{nameLiteral:D}:{}}}),b=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((v,_)=>{let h=`$.arkRunManagedNews[${_}]`,R=H(v,h);j(R,["file","line","typeName","importedFrom"],h);let y=ke(R,"importedFrom",h);return{file:U(R,"file",h),line:te(R,"line",h),typeName:F(R,"typeName",h),...y?{importedFrom:y}:{}}}),E=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let h=`$.arkRunCompositionRootHits[${_}]`,R=H(v,h);return j(R,["file","matchedRoot","hasKernelFactory"],h),{file:U(R,"file",h),matchedRoot:F(R,"matchedRoot",h),hasKernelFactory:V(R,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),L=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let h=`$.arkOrderPlaneCalls[${_}]`,R=H(v,h);return j(R,["file","line","callee"],h),{file:U(R,"file",h),line:te(R,"line",h),callee:F(R,"callee",h)}}),P=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let h=`$.arkOrderGenericUpdates[${_}]`,R=H(v,h);return j(R,["file","line","method"],h),{file:U(R,"file",h),line:te(R,"line",h),method:F(R,"method",h)}}),T=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((v,_)=>{let h=`$.arkOrderRootHits[${_}]`,R=H(v,h);return j(R,["file","matchedRoot","hasPlaneFactory"],h),{file:U(R,"file",h),matchedRoot:F(R,"matchedRoot",h),hasPlaneFactory:V(R,"hasPlaneFactory",h)}}),M=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((v,_)=>{let h=`$.arkOrderXiFieldWrites[${_}]`,R=H(v,h);return j(R,["file","line","key"],h),{file:U(R,"file",h),line:te(R,"line",h),key:F(R,"key",h)}}),Y=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((v,_)=>{let h=`$.arkOrderIngestWritesXi[${_}]`,R=H(v,h);return j(R,["file","line"],h),{file:U(R,"file",h),line:te(R,"line",h)}}),we=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((v,_)=>{let h=`$.arkOrderReleaseKeyCounts[${_}]`,R=H(v,h);return j(R,["file","line","keyCount"],h),{file:U(R,"file",h),line:te(R,"line",h),keyCount:te(R,"keyCount",h)}}),un=I.map((v,_)=>{let h=`$.arkRunDeclarations[${_}]`,R=H(v,h);return j(R,["file","line","uses","reactsTo","raises","sends"],h),{file:U(R,"file",h),line:te(R,"line",h),uses:Xe(R.uses,`${h}.uses`),reactsTo:Xe(R.reactsTo,`${h}.reactsTo`),raises:Xe(R.raises,`${h}.raises`),sends:Xe(R.sends,`${h}.sends`)}});for(let[v,_]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",E],["$.arkRunDeclarations",un],["$.arkOrderPlaneCalls",L],["$.arkOrderGenericUpdates",P],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",M],["$.arkOrderIngestWritesXi",Y],["$.arkOrderReleaseKeyCounts",we]])for(let h of _)if(!f.has(h.file))throw new Error(`${v} references missing file ${h.file}.`);let ot=ke(e,"projectPackageName","$"),it=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((v,_)=>{let h=`$.classShapes[${_}]`,R=H(v,h);j(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let y=G(R,"mutatingMethods",h).map((D,ce)=>{let ge=`${h}.mutatingMethods[${ce}]`,pn=H(D,ge);return j(pn,["name","referencesGuardOrPublish"],ge),{name:F(pn,"name",ge),referencesGuardOrPublish:V(pn,"referencesGuardOrPublish",ge)}});return{file:U(R,"file",h),className:F(R,"className",h),exported:V(R,"exported",h),hasPublicMutableFields:V(R,"hasPublicMutableFields",h),hasPublicSetters:V(R,"hasPublicSetters",h),hasPublicConstructor:V(R,"hasPublicConstructor",h),hasStaticFactory:V(R,"hasStaticFactory",h),mutatingMethods:y,...R.dataOnly===void 0?{}:{dataOnly:V(R,"dataOnly",h)}}});return{schemaVersion:r,completeness:n,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...ot?{projectPackageName:ot}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:l,publishCalls:u,intentReferences:p,safetyUses:g,classShapes:it,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:E,arkRunDeclarations:un,arkOrderPlaneCalls:L,arkOrderGenericUpdates:P,arkOrderRootHits:T,arkOrderXiFieldWrites:M,arkOrderIngestWritesXi:Y,arkOrderReleaseKeyCounts:we}}i(To,"parseResolvedFactsInput");function Se(e){let t=H(e,"$"),r=F(t,"factsHash","$"),n=F(t,"candidateTreeHash","$"),o=Oo(To(t,!0));if(o.factsHash!==r)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(n!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(Se,"loadResolvedCandidateFacts");var Il=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},oe={type:"integer",minimum:1},B={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},hr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:N,message:N,file:B}}},resolverIdentity:N,compilerIdentity:N,compilerOptionsHash:N,tsconfigHash:N,candidateTreeHash:N,evidenceRequirementsHash:N,projectPackageName:N,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:B,contentHash:N,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:N},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:B,specifier:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:B,namedBindings:{type:"array",items:N},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:B,line:oe,symbol:N,capability:{enum:Il},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:B,line:oe,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:B,line:oe,rawIntentName:N,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:N}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:B,line:oe,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:N},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:B,className:N,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:N,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:B,line:oe,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:N,viaImport:{type:"boolean"},receiver:N,nameLiteral:N}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:B,line:oe,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:B,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:B,line:oe,uses:{type:"array",items:N},reactsTo:{type:"array",items:N},raises:{type:"array",items:N},sends:{type:"array",items:N}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:B,line:oe,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:B,line:oe,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:B,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:oe,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:B,line:oe}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:B,line:oe,keyCount:{type:"integer",minimum:1}}}},factsHash:N},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Ar="1.0";function ie(e){return`${e.from}->${e.to}`}i(ie,"dependencyKey");function It(e,t,r,n="dependency"){return{id:`${e}:${n}:${ie(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:r,...e==="missing"?{nextAction:`Add the planned dependency ${ie(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ie(t)}, then preflight again.`}:e==="unplanned"?{nextAction:n==="dependency-removed"?`Restore the removed dependency ${ie(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ie(t)} from the candidate, then preflight again.`}:{}}}i(It,"dependencyFinding");function $e(e){let t=[],r=new Map(e.changeMap.map.files.map(f=>[f.path,f])),n=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[ie(f),f])),s=new Map(e.baseDependencies.map(f=>[ie(f),f])),a=new Map(e.candidateDependencies.map(f=>[ie(f),f]));for(let f of[...r.values()].sort((m,d)=>m.path.localeCompare(d.path))){let m=n.get(f.path);m?m.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${m.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...n.values()].sort((m,d)=>m.path.localeCompare(d.path)))r.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let c=new Set;for(let f of[...o.values()].sort((m,d)=>ie(m).localeCompare(ie(d)))){if(a.has(ie(f))){t.push(It("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};a.has(ie(m))?(c.add(ie(m)),t.push(It("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(It("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let l=new Set([...r.keys(),...n.keys()]);for(let[f,m]of[...a].sort(([d],[A])=>d.localeCompare(A)))s.has(f)||o.has(f)||c.has(f)||!l.has(m.from)&&!l.has(m.to)||t.push({...It("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([d],[A])=>d.localeCompare(A)))a.has(f)||u.has(m.from)||u.has(m.to)||!l.has(m.from)&&!l.has(m.to)||t.push({...It("unplanned",m,`${m.from} -> ${m.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,m)=>p[f.classification]-p[m.classification]||(f.subject===m.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(m.id));let g={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}i($e,"analyzeArchitectureConvergence");var Po="1.0",Fn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",$n=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],bl=["no-anemic-model"],No={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},kr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Fn,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:Fn},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...$n]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:No,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:No}}}},He=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,r){super(`Invalid ArkRules (${t}):
|
|
5
|
-
${
|
|
6
|
-
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=
|
|
7
|
-
${
|
|
8
|
-
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=r}};function Do(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Do,"normalizeRel");function Mo(e,t="ark.config.json"){let r=e.config.arkRules,n=[];if(!r||Object.keys(r).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let l of[...e.discoveredArkRulesFiles].sort())n.push({path:l,message:`ArkRules file ${JSON.stringify(l)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:_e(),warnings:n}}let o=new Set(e.config.layers.map(l=>l.name)),s=[],a=[],c=new Set;for(let l of Object.keys(r).sort()){let u=r[l],p=`$.arkRules[${JSON.stringify(l)}]`;if(typeof u!="string"||u.length===0){s.push({path:p,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){s.push({path:p,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(l)){s.push({path:p,message:`layer ${JSON.stringify(l)} is not declared in layers[]`});continue}let g=Do(u);c.add(g);let f=e.fileContents[g]??e.fileContents[u];if(f===void 0){s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let m=_t(JSON.parse(f),g,l);a.push({layer:l,sourceFile:g,file:m.config})}catch(m){if(m instanceof He)for(let d of m.issues)s.push({path:`${p}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${g}: ${d.message}`});else m instanceof SyntaxError?s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${m.message}`}):s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${m instanceof Error?m.message:String(m)}`})}}if(e.discoveredArkRulesFiles)for(let l of[...e.discoveredArkRulesFiles].sort()){let u=Do(l);c.has(u)||n.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(s.length>0)throw new Ot(t,s);return{config:e.config,arkRules:Er(a),warnings:n}}i(Mo,"resolveEffectiveContract");function Hn(e){return{...e,layers:e.layers.map(t=>{let{description:r,trustBoundary:n,owners:o,...s}=t;return s})}}i(Hn,"omitLayerDescriptions");function Sr(e){let{stewards:t,...r}=Hn(e.config);return{config:r,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(n=>({id:n.id,sensor:n.sensor,mode:n.mode,appliesTo:n.appliesTo??null,description:n.description??null,provenance:n.provenance})),invariants:e.arkRules.invariants.map(n=>({id:n.id,description:n.description,aggregate:n.aggregate??null,coverage:n.coverage??null,mode:n.mode,appliesTo:n.appliesTo??null,provenance:n.provenance}))}}}i(Sr,"effectiveContractPolicyPayload");function Fo(e,t=!1){if(!e)return"";let r=e.discarded,n=[];if(r.budget>0&&!t&&n.push(`${r.budget} past the ${e.maxFiles}-file budget`),r.noInvariantMention>0&&n.push(`${r.noInvariantMention} naming no catalogued invariant`),r.oversize>0&&n.push(`${r.oversize} over the per-file byte cap`),r.unreadable>0&&n.push(`${r.unreadable} unreadable (files or directories)`),r.depthLimited>0&&n.push(`${r.depthLimited} directories past the walk depth limit`),r.outOfRoot>0&&n.push(`${r.outOfRoot} symlinked outside the project root`),n.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${n.join(", ")}${o}.`}i(Fo,"formatCoverageDiscards");function xl(e,t){let r=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(n=>{let o=n.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:r===o||r.startsWith(`${o}/`)})}i(xl,"isUnderCoverageRoot");function Tl(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${r}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Tl,"titleMatchesInvariant");function Nl(e,t){if(!t)return!1;let r=t.split("."),n=r[r.length-1],o=r.length>1?r[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(Nl,"symbolPresent");function Ir(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let r=e.testFiles??[],n=e.testGlobsMissing===!0||r.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=Fo(s),c=Fo(s,!0),l=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,g=u.join(", "),f=[],m=[];for(let d of t){let A=[],b=d.coverage?.test!==!1,O=d.coverage?.symbol,E,I;if(!n&&b){let P;for(let X of r){let T=e.fileContents[X];if(!(!T||!Tl(T,d.id))){if(!p||xl(X,u)){E=X,I=p?!1:void 0;break}P??=X}}E===void 0&&P!==void 0&&(E=P,I=!0),E!==void 0&&A.push("test-title")}O&&Nl(e.fileContents,O)&&A.push("symbol");let L=(d.coverage?.test===!0||!!O||d.coverage===void 0)&&A.length>0||d.coverage?.test===!1&&!O?!0:A.length>0,k=n&&b&&A.length===0;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:L&&!k,evidence:A,partial:k,description:d.description,...E!==void 0?{testEvidenceFile:E}:{},...I!==void 0?{outsideDeclaredRoots:I}:{}}),I===!0&&E!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${E}, which is outside the declared coverage roots (${g}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:E,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!L||k){let P=d.mode==="enforced"&&!k,X=n||r.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(k?o?`Invariant ${d.id} coverage cannot be proven (${l}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:X==="tests-disappeared"?`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(k&&o?c:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:P?"error":"warning",failsStrict:P,kind:X})}}return{coverage:f,violations:m,partial:f.some(d=>d.partial)}}i(Ir,"evaluateInvariantCoverage");function br(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(br,"canPromoteInvariant");var Cr="1.0";function w(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(w,"addFinding");function Q(e){return[...new Set(e??[])].sort()}i(Q,"sortedUnique");function fe(e,t,r,n,o){let s=Q(r),a=Q(n),c=new Set(s),l=new Set(a),u=a.filter(g=>!c.has(g)),p=s.filter(g=>!l.has(g));u.length===0&&p.length===0||(u.length>0&&w(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),p.length>0&&w(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(fe,"compareStringSets");function xt(e,t,r,n,o,s,a){if(r===n)return;w(e,{kind:n?"enabled":"disabled",path:t,classification:n?o:o==="strengthening"?"weakening":"strengthening",message:n?s:a,before:r,after:n})}i(xt,"compareBoolean");function vr(e,t){let r=new Map,n=new Set;for(let o of e){let s=t(o);r.has(s)?n.add(s):r.set(s,o)}return{values:r,duplicates:[...n].sort()}}i(vr,"keyed");function wl(e,t,r){let n=vr(t,s=>s.name),o=vr(r,s=>s.name);(n.duplicates.length>0||o.duplicates.length>0)&&w(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:n.duplicates,after:o.duplicates});for(let s of[...new Set([...n.values.keys(),...o.values.keys()])].sort()){let a=n.values.get(s),c=o.values.get(s),l=`$.layers[${s}]`;if(!a&&c){w(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){w(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;fe(e,`${l}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),fe(e,`${l}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=ir(a),p=ir(c);fe(e,`${l}.forbiddenGlobals`,u.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),fe(e,`${l}.capabilities`,u.atoms,p.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Q(a.intentPrefixes).join("\0")!==Q(c.intentPrefixes).join("\0")&&w(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Q(a.intentPrefixes),after:Q(c.intentPrefixes)}),xt(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),xt(e,`${l}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(wl,"compareLayers");function Pl(e,t,r){let n=i(a=>`${a.from}->${a.to}`,"keyOf"),o=vr(t,n),s=vr(r,n);(o.duplicates.length>0||s.duplicates.length>0)&&w(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let c=o.values.get(a),l=s.values.get(a),u=`$.rules[${a}]`;if(!c&&l){l.allowed===!1&&w(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:l});continue}if(c&&!l){c.allowed===!1&&w(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!l)continue;c.allowed!==l.allowed&&w(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:l.allowed});let p=c.peerIsolation===!0,g=l.peerIsolation===!0;if(p!==g){let f=c.from===c.to&&l.from===l.to;w(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:f?g?"strengthening":"weakening":"judgment-required",message:f?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:p,after:g})}Q(c.sliceFolders).join("\0")!==Q(l.sliceFolders).join("\0")&&w(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Q(c.sliceFolders),after:Q(l.sliceFolders)}),!(!p&&!g)&&(Ho(e,`${u}.sharedRoots`,"shared-roots",Q(c.sharedRoots),Q(l.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Ho(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Q((c.allowedCrossSlice??[]).map($o)),Q((l.allowedCrossSlice??[]).map($o)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Pl,"compareRules");function $o(e){return JSON.stringify([e.from,e.to])}i($o,"crossSliceKey");function Ho(e,t,r,n,o,s,a){if(JSON.stringify(n)===JSON.stringify(o))return;let c=o.filter(p=>!n.includes(p)),l=n.filter(p=>!o.includes(p)),u=c.length>0&&l.length>0;w(e,{kind:u?`${r}-changed`:c.length>0?`${r}-added`:`${r}-removed`,path:t,classification:u?"judgment-required":c.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:c.length>0?s:a,before:n,after:o})}i(Ho,"compareDeclaredExceptions");function Ll(e,t,r){let n=t.safety??{},o=r.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=n[s]??0,c=o[s]??0;a!==c&&w(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])xt(e,`$.safety.${s}`,n[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Ll,"compareSafety");function jn(e){return e.mode==="enforced"?"enforced":"advisory"}i(jn,"arkRunMode");function Kn(e){return e.mode==="enforced"?"enforced":"advisory"}i(Kn,"arkOrderMode");function Dl(e,t,r){let n=t.arkOrder,o=r.arkOrder,s="$.arkOrder";if(!n&&!o)return;if(!n&&o){w(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Kn(o)}).`,after:o});return}if(n&&!o){w(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:n});return}if(!n||!o)return;let a=Kn(n),c=Kn(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:c})}fe(e,`${s}.planeRoots`,n.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),fe(e,`${s}.managedLayers`,n.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Dl,"compareArkOrder");function Ml(e,t,r){let n=t.arkRun,o=r.arkRun,s="$.arkRun";if(!n&&!o)return;if(!n&&o){w(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${jn(o)}).`,after:o});return}if(n&&!o){w(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:n});return}if(!n||!o)return;let a=jn(n),c=jn(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:c})}fe(e,`${s}.compositionRoots`,n.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),fe(e,`${s}.managedLayers`,n.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),xt(e,`${s}.requireDeclarations`,n.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Ml,"compareArkRun");function Fl(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(Fl,"overallClassification");function jo(e,t){return`${e}::${t}`}i(jo,"ruleKey");function Ko(e){let t=new Map,r=new Map;if(!e)return{structure:t,invariants:r};for(let n of e.structure)t.set(jo(n.provenance.layer,n.id),n);for(let n of e.invariants)r.set(jo(n.provenance.layer,n.id),n);return{structure:t,invariants:r}}i(Ko,"indexEffectiveRules");function $l(e,t,r,n,o,s){let a=new Map((s??[]).map(f=>[f.invariantId,f])),c=t.arkRules??{},l=r.arkRules??{},u=[...new Set([...Object.keys(c),...Object.keys(l)])].sort();for(let f of u){let m=c[f],d=l[f],A=`$.arkRules[${f}]`;if(m===void 0&&d!==void 0){w(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(m!==void 0&&d===void 0){w(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:m});continue}m!==d&&w(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:m,after:d})}let p=Ko(n),g=Ko(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),d=g.structure.get(f),A=`$.arkRules.structure[${f}]`;if(!m&&d){w(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!d)){if(m.mode!==d.mode){let b=m.mode==="advisory"&&d.mode==="enforced";w(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}m.sensor!==d.sensor&&w(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:m.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),d=g.invariants.get(f),A=`$.arkRules.invariants[${f}]`;if(!m&&d){w(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!d)&&m.mode!==d.mode)if(m.mode==="advisory"&&d.mode==="enforced"){let O=a?.get(d.id),E=br(O);E.ok?w(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:d.mode}):w(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${E.reason}`,before:m.mode,after:d.mode})}else w(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}}i($l,"compareArkRules");function _r(e,t,r){let n=[];fe(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),fe(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),fe(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),xt(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let c=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";w(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&w(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),wl(n,e.layers,t.layers),Pl(n,e.rules,t.rules),Ll(n,e,t),$l(n,e,t,r?.baseArkRules,r?.candidateArkRules,r?.candidateInvariantCoverage),Ml(n,e,t),Dl(n,e,t),n.sort((c,l)=>c.path.localeCompare(l.path)||c.id.localeCompare(l.id)),{schemaVersion:Cr,classification:Fl(n),findings:n}}i(_r,"classifyArkPolicyDelta");function Or(e,t){if(!e||e.schemaVersion!==Cr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let r=Q(e.findingIds),n=Q(t.findingIds);return r.length===n.length&&r.every((o,s)=>o===n[s])}i(Or,"policyDeltaAcknowledgementMatches");function je(e){let t=[];for(let r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(r));return t.join("/")}i(je,"normalizePath");function Uo(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Uo,"isIdentifierStart");function xr(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(xr,"isIdentifierCharacter");function le(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(le,"skipWhitespace");function Tt(e,t){let r=e[t];if(r!=="'"&&r!=='"')return;let n=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===r)return{value:o,offset:n,excerpt:e.slice(n,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Tt,"readString");function de(e,t,r){return e.startsWith(t,r)&&!xr(e[r-1])&&!xr(e[r+t.length])}i(de,"isWordAt");function Vo(e,t){let r=le(e,t);if(e[r]!=="{")return!1;r+=1;let n=!1;for(;r<e.length;){if(r=le(e,r),e[r]==="}")return n;if(e[r]===","){r+=1;continue}if(!de(e,"type",r))return!1;let o=le(e,r+4);if(o>=e.length||e[o]===","||e[o]==="}"||de(e,"as",o)||!Uo(e[o]))return!1;for(r=o;r<e.length&&xr(e[r]);)r+=1;if(r=le(e,r),de(e,"as",r)){if(r=le(e,r+2),!Uo(e[r]))return!1;for(;r<e.length&&xr(e[r]);)r+=1}n=!0}return!1}i(Vo,"bracedNamedBindingsAreTypeOnly");function Hl(e,t){if(t=le(e,t+6),e[t]==="(")return Tt(e,le(e,t+1));let r=!1;if(de(e,"type",t)){let o=le(e,t+4);e[o]!==","&&!de(e,"from",o)&&(r=!0)}else Vo(e,t)&&(r=!0);let n=Go(e,t,!0);return n&&r?{...n,typeOnly:!0}:n}i(Hl,"specifierAfterImport");function jl(e,t){t=t+6;let r=le(e,t),n=!1;if(de(e,"type",r)){let s=le(e,r+4);(e[s]==="{"||e[s]==="*")&&(n=!0)}else Vo(e,r)&&(n=!0);let o=Go(e,t,!1);return o&&n?{...o,typeOnly:!0}:o}i(jl,"specifierAfterExport");function Go(e,t,r){for(;t<e.length;t+=1){if(e[t]===";")return;if(de(e,"from",t))return Tt(e,le(e,t+4));if(r&&(e[t]==="'"||e[t]==='"'))return Tt(e,t);if(t>0&&(de(e,"import",t)||de(e,"export",t)))return}}i(Go,"specifierInStaticStatement");function Kl(e,t){for(t+=1;t<e.length;t+=1){let r=e[t];if(r==="\\")t+=1;else if(r==="`")return t}return e.length}i(Kl,"skipTemplateLiteral");function Ul(e,t){let r=t-1;for(;r>=0&&/\s/.test(e[r]);)r-=1;if(e[r]===".")return;let n=le(e,t+7);if(e[n]!=="(")return;n=le(e,n+1);let o=Tt(e,n);return o?{...o,requireCall:!0}:void 0}i(Ul,"specifierAfterRequire");function Vl(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){if(r=e.indexOf(`
|
|
9
|
-
`,
|
|
10
|
-
`).length;
|
|
11
|
-
`).length,c={kind:"import",file:e.path,line:a,excerpt:o.excerpt},l=Gl(e.path,s,t);r.push({from:e.path,specifier:s,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:c})}return{edges:r,capabilityUses:n}}i(Bo,"moduleFactsFor");function Gl(e,t,r){let n=e.split("/");n.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?n.pop():n.push(s));let o=n.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=r.get(s);if(a)return a}}i(Gl,"resolveSpecifier");function zo(e,t){let r=[];for(let n of e){if(!n.to||!n.fromLayer||!n.toLayer)continue;let o=cr(t.rules,n.fromLayer,n.toLayer,{fromPath:n.from,toPath:n.to,layers:t.layers});o&&r.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:n,evidence:n.evidence})}return r}i(zo,"violationsFor");var Bl={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function zl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(zl,"hasActiveArkRules");function Wl(e,t){return zl(e,t)?J($(Sr({config:e,arkRules:t,warnings:[]}))):J($(Hn(e)))}i(Wl,"policyHashFor");function Nt(e,t,r){let n=typeof e=="string"?gr(e,t):kt(e,t),o=r?.arkRules??_e();return{...n,arkRules:o,policyHash:Wl(n.config,o)}}i(Nt,"loadContract");function Un(e){let t=Nt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),r=Nt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),n=_r(t.config,r.config,{baseArkRules:t.arkRules,candidateArkRules:r.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=n.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=o.length>0,a=s&&Or(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:r.policyHash,findingIds:o});return{schemaVersion:n.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:r.policyHash,classification:n.classification,findings:n.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(Un,"analyzePolicyDelta");function Qe(e){let t=e.files.map(g=>{let f=je(g.path);return{path:f,content:g.content,contentHash:J(g.content),layer:pe(f,e.contract.config.layers)??null}}).sort((g,f)=>g.path.localeCompare(f.path)),r=new Map(t.map(g=>[g.path,g])),n=[],o=[];for(let g of t){let f=Bo(g,r);n.push(...f.edges),o.push(...f.capabilityUses)}let s=zo(n,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),c=new Map(e.contract.config.layers.map(g=>[g.name,new Set(ze(g))]));for(let g of o){let f=r.get(g.file)?.layer;if(!f)continue;let m=a.get(f),d=ve(g.symbol,m?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${d}".`,symbol:g.symbol,evidence:g.evidence});continue}c.get(f)?.has(g.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let l=t.length===0?"complete":"partial",u=l==="complete"?[]:[{...Bl}],p={schemaVersion:Ar,policyHash:e.contract.policyHash,compilerOptionsHash:J($(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:n,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:l,completenessReasons:u,valid:l==="complete"&&s.length===0,ir:p}}i(Qe,"analyzeProject");function wt(e){let t=new Map(e.files.map(r=>[je(r.path),r]));for(let r of e.changes){let n=je(r.path);"delete"in r&&r.delete?t.delete(n):"content"in r&&t.set(n,{path:n,content:r.content})}return Qe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(wt,"analyzeChange");function Vn(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let r=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${r}. ${e.message}`}i(Vn,"explainViolation");function Tr(e){let t=0,r=new Map,n=new Map,o=new Set,s=[],a=[],c=i(l=>{r.set(l,t),n.set(l,t),t+=1,s.push(l),o.add(l);for(let g of[...e.get(l)??[]].sort())e.has(g)&&(r.has(g)?o.has(g)&&n.set(l,Math.min(n.get(l)??0,r.get(g)??0)):(c(g),n.set(l,Math.min(n.get(l)??0,n.get(g)??0))));if(n.get(l)!==r.get(l))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==l);u.length>1&&a.push(u.sort())},"connect");for(let l of[...e.keys()].sort())r.has(l)||c(l);return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(Tr,"detectArchitectureCycles");function Ke(e){let t=e.contentViolations.map(s=>({...s})),r=(e.warnings??[]).map(s=>({...s})),n=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&n.has(s.from)&&n.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Pe(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let c=a.rule,l=!!c.peerIsolation,u=!l&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=l?We(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,g=c.message?p?`${c.message} (${p})`:c.message:p?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${p}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...l?{peerIsolation:!0}:{},message:u?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Tr(n);o==="soft"||o==="framework-soft"?r.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:r,safety:e.safety}}i(Ke,"evaluateArchitectureGraph");function Wo(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let n=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);n?.[1]&&(t=n[1])}let r=String(e.symbol||"").trim();return t?r?`${t}:${r}`:t:r}i(Wo,"structureFreezeTarget");var ql=["no-anemic-model"],Qo=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],zn=new RegExp(`\\b(${Qo.join("|")})\\b`),ea="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Wn=new RegExp(`\\bthis\\.${ea}\\.push\\s*\\(`),Yl=new RegExp(`^this\\.${ea}\\s*=\\s*\\[\\s*\\]`),Jl=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,Xl=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,ta="truncatedUntil";function qn(){return`${Qo.join(", ")}, or events-array .push(`}i(qn,"expectedDomainInvariantWordsPhrase");function Zl(e){return zn.test(e)||Wn.test(e)}i(Zl,"referencesGuardOrPublish");function Yn(e,t,r){let n=e.slice(t);if(Yl.test(n))return!0;if(!Jl.test(n))return!1;if(r&&/^pullEvents$/i.test(r))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}i(Yn,"isIdiomaticEventsReset");function Ql(e,t){let r=new RegExp(Xl.source,"g"),n;for(;(n=r.exec(t))!==null;)if(!Yn(t,n.index,e))return!0;return!1}i(Ql,"methodAssignsThis");function ec(e,t){return t==null||Object.defineProperty(e,ta,{value:t,enumerable:!1,configurable:!0}),e}i(ec,"attachShapeTruncation");function Bn(e){let t=Object.getOwnPropertyDescriptor(e,ta)?.value;return typeof t=="number"?t:void 0}i(Bn,"shapeTruncatedUntil");function tc(e){let t=Bn(e);return t==null?"":` shape analysed until character ${t}`}i(tc,"shapeTruncationSuffix");function qo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(qo,"escapeGlobLiteral");function rc(e){let t="";for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=o}let r="";for(let n=0;n<t.length;n+=1){let o=t[n];o==="\\"&&n+1<t.length?(r+=qo(t[n+1]),n+=1):o==="*"?t[n+1]==="*"?t[n+2]==="/"?(r+="(?:.*/)?",n+=2):(r+=".*",n+=1):r+="[^/]*":o==="?"?r+="[^/]":r+=qo(o)}return new RegExp(`^${r}$`)}i(rc,"globToRegExp");function et(e,t){return!t||t.length===0?!0:t.some(r=>rc(r).test(e))}i(et,"matchesAppliesTo");function ra(e){return ql.includes(e)}i(ra,"isTier2");function na(e){return e.mode==="enforced"&&!ra(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(na,"severityFor");function Oe(e,t,r,n=1){let{severity:o,failsStrict:s}=na(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:r,file:t,line:n,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(Oe,"baseViolation");function wr(e,t,r){if(!r)return!0;let n=r(e);return n?n===t.provenance.layer:!1}i(wr,"isInRuleLayer");function Pr(e,t,r){return t.filter(n=>!(!n.exported||!et(n.file,e.appliesTo)||!wr(n.file,e,r)))}i(Pr,"shapesForRule");function nc(e,t,r){let n=[];for(let o of Pr(e,t,r))(o.hasPublicSetters||o.hasPublicMutableFields)&&n.push(Oe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return n}i(nc,"evaluateAggregatePrivateState");function sc(e,t,r){let n=[];for(let o of Pr(e,t,r))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;n.push(Oe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return n}i(sc,"evaluateAlwaysValidFactory");function oc(e,t,r){let n=[],o=qn();for(let s of Pr(e,t,r)){let a=tc(s);Bn(s)!=null&&n.push(Oe(e,s.file,`Exported class ${s.className} shape analysed until character ${Bn(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let c of s.mutatingMethods)c.referencesGuardOrPublish||n.push(Oe(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return n}i(oc,"evaluateDomainEventOnMutation");function ac(e,t){let r=[];for(let n of t.files)et(n,e.appliesTo)&&wr(n,e,t.layerForFile)&&t.fileHints?.[n]?.orchestrationHeavy&&r.push(Oe(e,n,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return r}i(ac,"evaluateOrchestrationOnly");function ic(e,t){let r=[];for(let n of t.files)et(n,e.appliesTo)&&wr(n,e,t.layerForFile)&&t.fileHints?.[n]?.adapterThick&&r.push(Oe(e,n,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return r}i(ic,"evaluateThinAdapter");function lc(e,t){let r=[];for(let n of t.files)et(n,e.appliesTo)&&wr(n,e,t.layerForFile)&&t.fileHints?.[n]?.persistenceWrite&&r.push(Oe(e,n,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return r}i(lc,"evaluateWritesViaAggregate");function cc(e,t,r){let n=[];for(let o of Pr(e,t,r))if(o.dataOnly===!0){let s=Oe(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);n.push({...s,severity:"warning",failsStrict:!1})}return n}i(cc,"evaluateNoAnemicModel");function Lr(e){if(!e.arkRules.structure.length)return[];let t=[];for(let r of e.arkRules.structure)switch(r.sensor){case"aggregate-private-state":t.push(...nc(r,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...sc(r,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...oc(r,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...ac(r,e));break;case"thin-adapter":t.push(...ic(r,e));break;case"writes-via-aggregate":t.push(...lc(r,e));break;case"no-anemic-model":t.push(...cc(r,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((r,n)=>r.file.localeCompare(n.file)||r.arkruleId.localeCompare(n.arkruleId)||r.message.localeCompare(n.message))}i(Lr,"evaluateArkRuleSensors");function Dr(e,t){let r=[],n=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||n.some(l=>et(l,o.appliesTo)))continue;let{severity:a,failsStrict:c}=na(o);r.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:c})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||n.some(c=>et(c,o.appliesTo)))continue;let a=o.mode==="enforced";r.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return r.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(Dr,"collectEmptyAppliesToFindings");var Yo=64;function dc(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(dc,"stripTrailingDots");function uc(e){let t=e.trim(),r=t.length>Yo?t.slice(0,Yo):t;return dc(r)}i(uc,"normalizeIntentPrefix");function pc(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(pc,"layerNameLooksDomain");function fc(e){return e.some(t=>{let r=uc(t);return r==="Domain"||r.startsWith("Domain.")})}i(fc,"ownsDomainIntent");function mc(e,t=[]){return pc(e)||fc(t)}i(mc,"isDomainRoleLayerName");function sa(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(l=>mc(l.name,l.intentPrefixes??[])).map(l=>l.name);if(t.length===0)return[];let r=new Set(t);if(!(e.files??[]).some(l=>{let u=typeof l.layer=="string"?l.layer:"";return u.length>0&&r.has(u)}))return[];if((e.arkRules.invariants??[]).filter(l=>r.has(l.provenance.layer)).length>0)return[];let s=t.find(l=>e.arkRules.byLayer?.[l])??t[0],a=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,c=(e.arkRules.structure??[]).some(l=>l.mode==="enforced"&&r.has(l.provenance.layer)&&!ra(l.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${a}.`,file:a,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:a,severity:c?"error":"warning",sensor:"invariant-coverage",failsStrict:c}]}i(sa,"collectEmptyInvariantCatalogFindings");var Jo=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,Xo=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,gc=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function yc(e){return e==="PersistenceAdapters"}i(yc,"isPersistenceDriverLayer");function hc(e,t){if(Jo.test(e)||Xo.test(e))return!0;if(!t)return!1;for(let r of t){if(yc(r.layer))return!0;let n=r.specifier;if(!n)continue;let o=`from '${n}'`;if(Jo.test(o)||Xo.test(o))return!0}return!1}i(hc,"sourceImportsPersistenceDriver");var Ac=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,Rc=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,kc=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Ec=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Jn(e,t,r){if(!t)return null;let n=hc(t,r),o=n&&gc.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(kc.source,"g"))??[],a=t.match(new RegExp(Ec.source,"g"))??[],c=(t.match(/\bif\s*\(/g)??[]).length,l=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&c+l>=6,p=Ac.test(t)||Rc.test(t),g=s.length>=1||a.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=n&&g||p&&g||n&&f&&(c>=4||s.length>=1)||p&&n;return!u&&!m&&!o?null:{...u?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(Jn,"deriveArkRuleFileHints");function Mr(e,t){let r={};for(let[n,o]of Object.entries(e)){let s=n.replace(/\\/g,"/"),a=Jn(n,o,t?.[s]);a&&(r[s]=a)}return r}i(Mr,"buildArkRuleFileHints");var Sc=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Ic=new Set(["if","match","when"]);function Nr(e,t){let r=e[t];if(r==="/"&&e[t+1]==="/"){let n=e.indexOf(`
|
|
12
|
-
`,t);return n===-1?e.length:n}if(r==="/"&&e[t+1]==="*"){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}if(r==="'"||r==='"'||r==="`"){let n=t+1;for(;n<e.length;){if(e[n]==="\\"){n+=2;continue}if(e[n]===r)return n+1;n+=1}return e.length}return t}i(Nr,"skipStringOrComment");function Pt(e,t){let r=t;for(;r<e.length;){if(/\s/.test(e[r])){r+=1;continue}if(e[r]==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=Nr(e,r);continue}break}return r}i(Pt,"skipWsAndComments");function Zo(e,t){let r=e[t];if(!r||!/[A-Za-z_]/.test(r))return null;let n=t+1;for(;n<e.length&&/[A-Za-z0-9_]/.test(e[n]);)n+=1;return{ident:e.slice(t,n),end:n}}i(Zo,"readIdent");function Gn(e,t,r,n){if(e[t]!==r)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let a=Nr(e,s);if(a!==s){s=a;continue}let c=e[s];c===r?o+=1:c===n&&(o-=1),s+=1}return o===0?s:null}i(Gn,"skipBalanced");function bc(e){let t=[],r=0,n;for(;r<e.length&&(r=Pt(e,r),!(r>=e.length));){if(e[r]===";"){r+=1;continue}let o=[],s=r;for(;;){let p=Zo(e,s);if(!p||!Sc.has(p.ident))break;o.push(p.ident),s=Pt(e,p.end)}let a=Zo(e,s);if(!a){r+=1;continue}if(s=Pt(e,a.end),e[s]==="<"){let p=Gn(e,s,"<",">");if(p==null){n=e.length;break}s=Pt(e,p)}if(e[s]==="("){let p=Gn(e,s,"(",")");if(p==null){n=e.length;break}if(s=Pt(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=Nr(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=Gn(e,s,"{","}");if(g==null){n=e.length;break}t.push({name:a.ident,modifiers:o,kind:"method",body:e.slice(s+1,g-1)}),r=g;continue}if(e[s]===";"){r=s+1;continue}r=s+1;continue}let c=0,l=0,u=0;for(;s<e.length;){let p=Nr(e,s);if(p!==s){s=p;continue}let g=e[s];if(g==="{")c+=1;else if(g==="}"){if(c===0)break;c-=1}else if(g==="(")l+=1;else if(g===")")l-=1;else if(g==="[")u+=1;else if(g==="]")u-=1;else if(g===";"&&c===0&&l===0&&u===0){s+=1;break}s+=1}t.push({name:a.ident,modifiers:o,kind:"field",body:""}),r=s}return{members:t,truncatedAt:n}}i(bc,"scanClassMembers");function oa(e,t){let r=[],n=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,o;for(;(o=n.exec(t))!==null;){let s=o[1],a=o.index+o[0].length,c=1,l=a;for(;l<t.length&&c>0;){let k=t[l];k==="{"?c+=1:k==="}"&&(c-=1),l+=1}let u=t.slice(a,l-1),p=c>0,g=bc(u),f=p?t.length:g.truncatedAt==null?void 0:a+g.truncatedAt,m=g.members.filter(k=>!(k.kind!=="field"||k.name==="constructor"||k.modifiers.includes("private")||k.modifiers.includes("protected")||k.modifiers.includes("readonly")||k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set"))),d=m.length>0,A=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),b=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),O=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!b,E=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),I=[];for(let k of g.members)k.kind==="method"&&k.name!=="constructor"&&(k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set")||Ic.has(k.name)||Ql(k.name,k.body)&&I.push({name:k.name,referencesGuardOrPublish:Zl(k.body)}));let L=g.members.filter(k=>k.kind==="method").length<=1&&m.length>=2&&d;r.push(ec({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:A,hasPublicConstructor:O,hasStaticFactory:E,mutatingMethods:[...I],dataOnly:L},f))}return r}i(oa,"extractClassShapesFromSource");var aa=50;function Fr(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,r=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return r==null&&typeof e.classifiedFiles=="number"&&(r=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:r}}i(Fr,"normalizeExtraMergeTeethClassification");function me(e){let t=Fr(e),r=typeof t.governedPercent=="number"?t.governedPercent:null,n=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return r==null&&n==null?!0:(r??0)>=50&&(n??0)>=1}i(me,"extraMergeTeethAllowed");function $r(e){let t=e.length,r=0,n=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(r+=1,n.add(s))}return{governedPercent:t>0?Math.round(r/t*100):0,populatedLayerCount:n.size}}i($r,"classifyResolvedLayerCoverage");function Hr(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Hr,"isArkRunRuleId");function Xn(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(Xn,"isArkOrderRuleId");function Zn(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")||t.startsWith("ARKORDER_")}i(Zn,"isExtraPlaneFinding");function ia(e,t={}){if(!Array.isArray(e)||me(t))return e;for(let r of e)Zn(r)&&r.failsStrict!==!1&&(r.failsStrict=!1,r.severity==="error"&&(r.severity="warning"));return e}i(ia,"demoteExtraPlaneTeethUnderClassificationFloor");var Qn="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function he(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(he,"countOrZero");function Lt(e={}){let t=Fr(e.classification),r=typeof t.governedPercent=="number"?t.governedPercent:null,n=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=r!=null||n!=null,s=me(t),a=e.arkRules,c=he(a?.structureEnforced),l=he(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?he(a.structureAdvisory):Math.max(0,l-c),p=he(a?.invariantEnforced),g=he(a?.invariantTotal),f=typeof a?.invariantAdvisory=="number"?he(a.invariantAdvisory):Math.max(0,g-p),m=c>0||p>0,d=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=he(e.arkRun?.residualCount),O=d&&A==="enforced",E=O&&s,I=e.arkOrder?.present===!0,C=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,L=he(e.arkOrder?.residualCount),k=I&&C==="enforced",P=k&&s,X=m||O||k,T=X&&s,z=X&&o&&!s,M;if(T){let Y=[];m&&Y.push("enforced structure/invariant findings"),O&&Y.push("enforced ArkRun skip findings"),k&&Y.push("enforced ArkOrder skip findings"),M=`Layer graph failures plus ${Y.join(" and ")} (advisory extras never fail merge alone).`}else if(z)M=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,O?"ArkRun":null,k?"ArkOrder":null].filter(be=>!!be).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`;else{let Y=d?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",be=I?C==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";M="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+Y+be}let ee={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:l,enforced:c,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:g,enforced:p,advisory:f,covered:he(a?.covered),uncovered:he(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:d,mode:A,residualCount:b,extraMergeTeeth:E,note:d?A==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},arkOrder:{role:"pattern-slaving",present:I,mode:C,residualCount:L,extraMergeTeeth:P,note:I?C==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:T,dualPlaneStamp:Qn,failMergeWhen:M};return o&&(ee.classificationGate={governedPercent:r,populatedLayerCount:n,floorPercent:50,allowsTeeth:s}),ee}i(Lt,"composeMergePlanesHonesty");var ts=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],ca=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],vc=new Set(ts),Cc=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),_c=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function tt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(tt,"isArkRunKernelModuleSpecifier");var rs=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],es=new Set(rs);function Kr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(es.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let r=e.slice(0,t);if(es.has(r))return!0;let n=e.indexOf("/",t+1);return n<0?!1:es.has(e.slice(0,n))}i(Kr,"isArkRunTransportBypassSpecifier");function jr(e){if(vc.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}i(jr,"arkRunKernelCallKind");function Mt(e,t){let r=1;for(let n=0;n<t;n+=1)e.charCodeAt(n)===10&&(r+=1);return r}i(Mt,"lineAt");function Ft(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,r=>" ".repeat(r.length)))}i(Ft,"stripCommentsPreservingLines");function Oc(e,t){let r=e.slice(t),n=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(r);if(!n)return;let o=n[2]??"";return o.length>0?o:void 0}i(Oc,"firstStringLiteralArg");function la(e,t,r){let n=Math.max(0,t-r.length-8),o=e.slice(n,t);return new RegExp(`\\b${r}\\s+$`).test(o)}i(la,"keywordBefore");function Ur(e,t){let r=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,n;for(;(n=r.exec(e))!==null;)n[1]||t(n[2]??"",n[3]??"")}i(Ur,"parseValueImportClause");function xc(e,t){Ur(Ft(e),t)}i(xc,"forEachArkRunValueImportClause");function Vr(e,t){let r=Ft(t),n=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(r))!==null;){let c=s[3]??"";if(!c)continue;let l=s[0]??"";n.push({from:e,specifier:c,kind:/^\s*export/.test(l)?"export":"import",typeOnly:!!s[1],line:Mt(t,s.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=a.exec(r))!==null;){let c=s[1]??"";if(!c)continue;let l=s[0]?.startsWith("import")?"dynamic-import":"require";n.push({from:e,specifier:c,kind:l,typeOnly:!1,line:Mt(t,s.index),resolution:"resolved-external"})}return n}i(Vr,"extractArkRunValueImportDependenciesFromSource");function Gr(e){let t=[];return xc(e,r=>{let n=/\{([^}]*)\}/.exec(r);if(n?.[1])for(let o of n[1].split(",")){let s=o.trim();if(!s||s.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),c=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],l=a?.[1]??c;c&&l&&/^[A-Z]/.test(l)&&t.push(c,l)}}),Dt(t)}i(Gr,"extractArkRunImportedConstructorNamesFromSource");function Tc(e){let t=new Map,r=new Set;return Ur(e,(n,o)=>{if(!tt(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(n);s?.[1]&&r.add(s[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(n.trim());a?.[1]&&t.set(a[1],a[1]);let c=/\{([^}]*)\}/.exec(n);if(c?.[1])for(let l of c[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let p=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(p){t.set(p[2],p[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:r}}i(Tc,"collectKernelImportBindings");function Nc(e,t){let r=new Set(t);return Ur(e,(n,o)=>{let s=/\{([^}]*)\}/.exec(n);if(s?.[1])for(let a of s[1].split(",")){let c=a.trim();if(!c||c.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(c),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(c)?.[1],p=l?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(tt(o)||t.has(p)||t.has(u))&&(r.add(u),r.add(p))}}),r}i(Nc,"collectImportedConstructors");function wc(e,t){let r;return Ur(e,(n,o)=>{!r&&new RegExp(`\\b${t}\\b`).test(n)&&(r=o)}),r}i(wc,"importedFromForName");function Br(e,t){let r=Ft(t),n=Tc(r),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=s.exec(r))!==null;){let c=a[1],l=a.index;if(la(r,l,"function")||la(r,l,"class"))continue;let p=r.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=n.named.get(c)??c,f=jr(g)??jr(c);if(!f)continue;let m=n.named.has(c)||p!==void 0&&n.namespaces.has(p);if(f!=="factory"&&(!m&&p===void 0||p&&_c.has(p)&&!m))continue;let d=Oc(r,l+a[0].length);o.push({file:e,line:Mt(t,l),kind:f,callee:c,viaImport:m,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}i(Br,"extractArkRunKernelCallsFromSource");function zr(e,t,r){let n=Ft(t),o=Nc(n,r),s=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,c;for(;(c=a.exec(n))!==null;){let l=c[1];if(Cc.has(l)||!o.has(l))continue;let u=wc(n,l);s.push({file:e,line:Mt(t,c.index),typeName:l,...u?{importedFrom:u}:{}})}return s}i(zr,"extractArkRunManagedNewsFromSource");function Pc(e,t){let r=0,n;for(let o=t;o<e.length;o+=1){let s=e[o];if(n){if(s==="\\"){o+=1;continue}s===n&&(n=void 0);continue}if(s==="'"||s==='"'||s==="`"){n=s;continue}if(s==="[")r+=1;else if(s==="]"&&(r-=1,r===0))return o}return-1}i(Pc,"matchingBracketEnd");function Lc(e,t,r){let n=e.slice(t+1,r),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=s.exec(n))!==null;){let c=a[2]??"";c.length>0&&o.push(c)}return o}i(Lc,"stringLiteralsInList");function Dt(e){return[...new Set(e)].sort((t,r)=>t<r?-1:t>r?1:0)}i(Dt,"uniqueSorted");function da(e,t){let r=Ft(t),n=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],a=[],c=[],l,u;for(;(u=n.exec(r))!==null;){let p=r.slice(u.index+u[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=u.index+u[0].length+(g[0].length-1),m=Pc(r,f);if(m<0)continue;let d=Lc(r,f,m);if(d.length===0)continue;l===void 0&&(l=u.index);let A=u[1];A==="uses"?o.push(...d):A==="reactsTo"?s.push(...d):A==="raises"?a.push(...d):c.push(...d)}return l===void 0?[]:[{file:e,line:Mt(t,l),uses:Dt(o),reactsTo:Dt(s),raises:Dt(a),sends:Dt(c)}]}i(da,"extractArkRunDeclarationsFromSource");var fa=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Dc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Mc=new Set(Dc);function Fc(e){return Mc.has(e)}i(Fc,"isArkRunEditorSensor");var Wr={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},ns="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ma(e,t=[]){let r=e.trim();return/^domain(?:model)?$/i.test(r)||/^domain(?=[A-Z_\-\s])/i.test(r)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(r)?!0:t.some(n=>{let o=n.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(ma,"isDomainRoleLayer");function $c(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i($c,"compareFindings");function Ie(e,t,r,n,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Wr[t],sensor:t,message:o,file:r,line:n,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ye({ruleId:Wr[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Ie,"finding");function Hc(e,t){let r=[],n=[],o=[],s=[];for(let a of e)a.file===t&&(r.push(...a.uses),n.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(r),reactsTo:new Set(n),raises:new Set(o),sends:new Set(s)}}i(Hc,"bagForFile");function ua(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(ua,"emitKinds");function pa(e){return e==="subscribe"||e==="register-handler"}i(pa,"handleKinds");function jc(e){return e==="resolve"||e==="resolve-singleton"}i(jc,"dependKinds");function Kc(e,t,r){let n=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return n.push(Ie(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,r)),n;let s=new Map;for(let a of t){let c=s.get(a.matchedRoot)??[];c.push(a),s.set(a.matchedRoot,c)}for(let a of o){let c=[...s.get(a)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(c.length===0){n.push(Ie(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},r));continue}if(c.some(u=>u.hasKernelFactory))continue;let l=c[0];n.push(Ie(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},r))}return n}i(Kc,"evaluateMissingRoot");function Uc(e,t,r,n,o){let s=new Map(t.map(c=>[c.name,c.intentPrefixes??[]])),a=[];for(let c of r){let l=c.specifier;if(!l||!tt(l))continue;let u=n(c.from);u&&ma(u,s.get(u)??[])&&a.push(Ie(e,"arkrun-kernel-in-domain",c.from,c.line,`${u} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:u,target:l},o))}return a}i(Uc,"evaluateKernelInDomain");function Vc(e,t,r,n,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let c=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),l=new Set(n.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of r){if(l.has(p.file))continue;let g=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let f=o(p.file);!f||!a.has(f)||ma(f,c.get(f)??[])||u.push(Ie(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}i(Vc,"evaluateDirectNew");function Gc(e,t,r,n,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let c=new Set(e.managedLayers);if(c.size===0)return{findings:s,completenessReasons:a};for(let l of t){if(!ua(l.kind)&&!pa(l.kind)&&!jc(l.kind))continue;let u=n(l.file);if(!u||!c.has(u))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:ns,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let p=Hc(r,l.file);if(ua(l.kind)){if(p.raises.has(l.nameLiteral)||p.sends.has(l.nameLiteral))continue;s.push(Ie(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:l.nameLiteral},o));continue}if(pa(l.kind)){if(p.reactsTo.has(l.nameLiteral))continue;s.push(Ie(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:l.nameLiteral},o));continue}p.uses.has(l.nameLiteral)||s.push(Ie(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:l.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(Gc,"evaluateUndeclared");function Bc(e,t,r,n){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let c=a.specifier;if(!c||!Kr(c))continue;let l=r(a.from);!l||!o.has(l)||s.push(Ie(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(c)}; use the ArkRun kernel transport.`,{fromLayer:l,target:c},n))}return s}i(Bc,"evaluateTransportBypass");function $t(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let r=me(e.classification),n=Gc(t,e.kernelCalls,e.declarations,e.layerForFile,r),o=[...Kc(t,e.compositionRootHits,r),...Uc(t,e.layers,e.dependencies,e.layerForFile,r),...Vc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,r),...n.findings,...Bc(t,e.dependencies,e.layerForFile,r)].sort($c),s=[...n.completenessReasons].sort((a,c)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,u=`${c.code}\0${c.file??""}\0${c.message}`;return l<u?-1:l>u?1:0});return{findings:o,completenessReasons:s}}i($t,"evaluateArkRunSensors");function ss(e){return{findings:$t(e).findings.filter(r=>Fc(r.sensor)),completenessReasons:[]}}i(ss,"evaluateArkRunEditorSensors");function zc(e,t){if(e===t)return!0;let r=e.indexOf("*");if(r<0)return!1;let n=e.slice(0,r).replace(/\/$/,"");return n.length>0&&(t===n||t.startsWith(`${n}/`))}i(zc,"fileMatchesCompositionRoot");function Wc(e,t,r){let n=Br(t,r).some(a=>a.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let a of s)zc(a,t)&&o.push({file:t,matchedRoot:a,hasKernelFactory:n});return o}i(Wc,"compositionRootHitsForSource");function ga(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let r=new Set(Gr(e.source));return ss({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:zr(e.file,e.source,r),compositionRootHits:Wc(t,e.file,e.source),declarations:[],dependencies:Vr(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(ga,"evaluateArkRunEditorSensorsFromSource");function ya(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(ya,"isArkOrderModuleSpecifier");var ha=new Map;function Aa(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Aa,"escapeAppliesToLiteral");function qc(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=n}return t}i(qc,"normalizeAppliesToGlob");function Yc(e){let t=0;for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"){r+=1;continue}if(n==="{")t+=1;else if(n==="}"&&(t-=1,t<0))return!1}return t===0}i(Yc,"appliesToBracesBalanced");function Jc(e){let t=ha.get(e);if(t)return t;let r=qc(e),n=Yc(r),o="",s=0;for(let c=0;c<r.length;c+=1){let l=r[c];l==="\\"&&c+1<r.length?(o+=Aa(r[c+1]),c+=1):l==="*"?r[c+1]==="*"?r[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&n?(o+="(?:",s+=1):l==="}"&&n&&s>0?(o+=")",s-=1):l===","&&n&&s>0?o+="|":o+=Aa(l)}let a=new RegExp(`^${o}$`);return ha.set(e,a),a}i(Jc,"globToRegExp");var Ra=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],qr={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Xc(e,t){return!t||t.length===0?!0:t.some(r=>Jc(r).test(e))}i(Xc,"matchesArkOrderAppliesTo");function Zc(e,t=[]){let r=e.trim();return/^domain(?:model)?$/i.test(r)||/^domain(?=[A-Z_\-\s])/i.test(r)?!0:t.some(n=>{let o=n.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Zc,"isDomainRoleLayer");function xe(e,t,r,n,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:qr[t],sensor:t,message:o,file:r,line:n,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ye({ruleId:qr[t],fromLayer:s?.fromLayer,target:s?.target})}}i(xe,"finding");function Yr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let r=me(e.classification),n=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)n.push(xe(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,r));else{let l=new Map;for(let u of e.planeRootHits){let p=l.get(u.matchedRoot)??[];p.push(u),l.set(u.matchedRoot,p)}for(let u of o){let p=l.get(u)??[];if(p.length===0){n.push(xe(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},r));continue}p.some(g=>g.hasPlaneFactory)||n.push(xe(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},r))}}let s=new Map(e.layers.map(l=>[l.name,l.intentPrefixes??[]]));for(let l of e.dependencies){let u=l.specifier;if(!u||!ya(u))continue;let p=e.layerForFile(l.from);p&&Zc(p,s.get(p)??[])&&n.push(xe(t,"arkorder-kernel-in-domain",l.from,l.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},r))}for(let l of e.genericUpdates)n.push(xe(t,"arkorder-generic-update",l.file,l.line,`Generic ${l.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:l.method},r));let a=t.xiKeys??[];for(let l of e.releaseKeyCounts??[])l.keyCount<=t.maxXiKeys||n.push(xe(t,"arkorder-too-many-params",l.file,l.line,`release() freezes ${l.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(l.keyCount)},r));for(let l of e.ingestWritesXi??[])n.push(xe(t,"arkorder-ingest-writes-xi",l.file,l.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,r));let c=new Set(t.managedLayers);for(let l of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(l.file);!u||!c.has(u)||Xc(l.file,t.appliesTo)&&n.push(xe(t,"arkorder-xi-field-write",l.file,l.line,`This file writes ${JSON.stringify(l.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:l.key},r))}return n.sort((l,u)=>l.file.localeCompare(u.file)||l.ruleId.localeCompare(u.ruleId)||l.line-u.line),{findings:n,completenessReasons:[]}}i(Yr,"evaluateArkOrderSensors");function re(e,t,r={}){return{ruleId:e,message:t,...r}}i(re,"configWarning");function Ht(e){let{config:t,rules:r,files:n,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(re("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(re("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let A=t.safety[d];A!==void 0&&(!Number.isInteger(A)||A<0)&&s.push(re("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],l=new Set([...a.map(d=>d.name).filter(Boolean),...c.map(d=>d.name).filter(d=>!!d)]);a.length===0&&s.push(re("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of a){if(!d.name){s.push(re("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="string"))&&s.push(re("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let A=Array.isArray(d.patterns)?d.patterns:[];if(A.length===0){s.push(re("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let b of A){let O;try{O=Ae(b)}catch(I){s.push(re("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${I instanceof Error?I.message:String(I)}`,{layer:d.name,pattern:b}));continue}let E=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!n.some(I=>O.test(I))&&!E&&s.push(re("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of p)s.push(re("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(l.size>0)for(let d of r??[])d.from&&!l.has(d.from)&&s.push(re("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!l.has(d.to)&&s.push(re("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let g=new Set;if(a.length>1)for(let d of n){let A=-1,b=[];for(let O of a)for(let E of O.patterns??[]){if(!Ae(E).test(d))continue;let I=Sn(E,d);I>A?(A=I,b=[O.name]):I===A&&!b.includes(O.name)&&b.push(O.name)}b.length>1&&g.add([...b].sort().join(" + "))}g.size>0&&s.push(re("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let f=n.filter(d=>!pe(d,a));f.length>0&&s.push(re("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));let m=Io(t);if(m.length>0){let d=m[0]??"this layer";s.push(re("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:m,nextAction:bo(d)}))}return s}i(Ht,"collectAnalysisConfigWarnings");function ka(e,t){let r=e.ruleId==="ARKRULE_STRUCTURE",n=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...r?{sensor:e.sensor,code:e.code,target:Wo({sensor:e.sensor,code:e.code})}:{},...n||o?{freezable:!1}:{},nextAction:t}}i(ka,"toArkRuleEngineViolation");function Qc(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(Qc,"arkRulesMapIsOn");function Ea(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}i(Ea,"arkRuleFindingNextAction");function ed(e,t){return t.some(r=>{try{return Ae(r).test(e)}catch{return!1}})}i(ed,"matchesAny");function td(e,t){let r=e.contract.config.safety??{},n=Number.isInteger(r.maxTsSuppressions)?Number(r.maxTsSuppressions):0,o=Number.isInteger(r.maxAnyCasts)?Number(r.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:b})=>({file:A,line:b})),c=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:b})=>({file:A,line:b})),l=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!ed(A.file,s)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),u=r.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(A=>A.kind==="in-memory-store").map(A=>({file:A.file,line:A.line,store:A.symbol??"in-memory store"})),p=r.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(A=>A.peerIsolation===!1||A.allowed===!1&&!!A.from&&A.from===A.to&&A.peerIsolation!==!0).map(A=>({from:A.from,to:A.to})),g={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:l,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:n,maxAnyCasts:o}},f=[],m=l.filter(A=>A.kind==="import");if(m.length>0){let A=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=l.filter(A=>A.kind==="require");if(d.length>0){let A=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>n){let A=a[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${n}).`})}if(c.length>o){let A=c[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let A=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:f}}i(td,"evaluateSafety");function rd(e,t){return[...t].filter(r=>e===r||e.startsWith(`${r}.`)).sort((r,n)=>n.length-r.length)[0]}i(rd,"ambientForbiddenGlobal");function Sa(e,t){let r=t.config.layers.filter(n=>(n.intentPrefixes??[]).length>0);return On(e,r.length>0?r:_n.map(n=>({name:n.layer,prefixes:n.prefixes})))}i(Sa,"intentLayer");function nd(e,t,r){let n=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=r.get(s.file);!a||!rd(s.symbol,o.get(a)?.forbiddenGlobals??[])||n.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=r.get(s.file);if(!a)continue;let c=o.get(a),l=c?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&ft(s.symbol,l))){if(s.source==="import-based"){let p=ve(s.symbol,l);if(p){n.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}ze(c).includes(s.capability)&&n.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=r.get(s.file);if(!a)continue;for(let l of mt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))n.push({ruleId:l.ruleId,file:s.file,line:s.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!s.sourceIntent)continue;let c=Sa(s.sourceIntent,e.contract);!c||c===a||n.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=r.get(s.file);if(!a)continue;let c=Sa(s.intent,e.contract);if(!c)continue;let l=Pe(e.contract.config.rules,a,c,{fromPath:s.file,layers:e.contract.config.layers});if(!l)continue;let u=l.rule.peerIsolation?We(l.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:l.fromSlice,toSlice:l.toSlice}):void 0,p=`${a} must not reference ${c} intent ${s.intent}.`,g=u&&l.peerIsolationReason!=="cross-slice"?`${p} ${u}`:l.rule.message?u?`${l.rule.message} (${u})`:l.rule.message:p;n.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,...l.rule.peerIsolation?{peerIsolation:!0}:{},message:g})}return n}i(nd,"contentViolations");function sd(e){let{facts:t}=e,r=Ze(e.contract.config),n=t.evidenceRequirementsHash===r,o=n?t.completeness:"unavailable",s=n?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((y,D)=>{let ce=`${y.code}\0${y.file??""}\0${y.message}`,ge=`${D.code}\0${D.file??""}\0${D.message}`;return ce<ge?-1:ce>ge?1:0}),a=t.files.map(y=>({...y,layer:pe(y.path,e.contract.config.layers)??null})),c=new Map(a.map(y=>[y.path,y.layer])),l=t.dependencies.map(y=>{let D=y.target?c.get(y.target)??pe(y.target,e.contract.config.layers):void 0;return{from:y.from,fromLayer:c.get(y.from)??null,...y.resolution==="resolved-project"&&y.target?{to:y.target,...D?{toLayer:D}:{}}:{},line:y.line,kind:y.kind,typeOnly:y.typeOnly,...y.targetTypeOnlyExports?{targetTypeOnlyExports:y.targetTypeOnlyExports}:{},...y.sourcePureTypeModule?{sourcePureTypeModule:y.sourcePureTypeModule}:{},...y.namedBindingsTypeOnly?{namedBindingsTypeOnly:y.namedBindingsTypeOnly}:{},...y.portProofEligible?{portProofEligible:y.portProofEligible}:{}}}),u=Ht({config:e.contract.config,rules:e.contract.config.rules,files:a.map(y=>y.path)}),p=td(e,t),g=e.contract.arkRules??_e(),f=a.map(y=>y.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Mr(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=i(y=>c.get(y)??pe(y,e.contract.config.layers),"resolveLayer"),b=[...Lr({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:A,fileHints:d}),...Dr(g,f),...sa({arkRulesActive:Qc(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(y=>({path:y,layer:A(y)}))})],O=b.filter(y=>y.failsStrict).map(y=>ka(y,Ea(y,!1))),E=b.filter(y=>!y.failsStrict).map(y=>({...ka(y,Ea(y,!0)),failsStrict:!1})),C=(g.invariants?.length??0)>0?Ir({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},L=C.violations.filter(y=>y.failsStrict).map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,arkruleId:y.arkruleId,arkruleSource:y.arkruleSource,nextAction:`Add a test title or declared symbol covering ${y.arkruleId} (declared in ${y.arkruleSource}), then preflight again.`})),k=C.violations.filter(y=>!y.failsStrict).map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,arkruleId:y.arkruleId,arkruleSource:y.arkruleSource,failsStrict:!1,nextAction:y.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${y.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${y.arkruleId} in ${y.arkruleSource} (advisory / partial).`})),P=$r(a),X=$t({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(y=>c.get(y)??pe(y,e.contract.config.layers),"layerForFile"),classification:P}),T=e.contract.config.arkRun?.mode,z=X.findings.filter(()=>T==="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:y.failsStrict,...y.severity?{severity:y.severity}:{}})),M=X.findings.filter(()=>T!=="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:!1})),ee=Yr({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(y=>c.get(y)??pe(y,e.contract.config.layers),"layerForFile"),classification:P}),Y=e.contract.config.arkOrder?.mode,be=ee.findings.filter(()=>Y==="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:y.failsStrict,...y.severity?{severity:y.severity}:{}})),we=ee.findings.filter(()=>Y!=="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:!1})),ot=[...C.partial&&C.coverage.some(y=>y.mode==="enforced"&&y.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...X.completenessReasons,...ee.completenessReasons],at=Ke({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(y=>y.layer).map(y=>y.path),contentViolations:[...nd(e,t,c),...O,...L,...z,...be],edges:l,warnings:[...u,...p.warnings,...E,...k,...M,...we],safety:p.report}),it=o==="complete"&&ot.length>0?"partial":o,v=it==="complete"?s:[...s,...ot].sort((y,D)=>{let ce=`${y.code}\0${y.file??""}\0${y.message}`,ge=`${D.code}\0${D.file??""}\0${D.message}`;return ce<ge?-1:ce>ge?1:0}),_=at.violations.filter(y=>y.failsStrict!==!1),h=it==="complete"&&_.length===0,R=h&&at.warnings.every(y=>y.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:it,completenessReasons:v,valid:h,strictValid:R,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(y=>y.name),edges:l,capabilityUses:t.capabilityUses,violations:at.violations,warnings:at.warnings}}}i(sd,"analyzeCanonicalResolvedProject");function rt(e){return sd({contract:e.contract,facts:Se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(rt,"analyzeResolvedProject");function Ia(e){return J($(e.map(({path:t,contentHash:r})=>({path:t,contentHash:r}))))}i(Ia,"analysisTreeHash");function os(e){let t=Qe(e),r=new Map(t.ir.files.map(d=>[d.path,d])),n=[],o=new Set,s=[];for(let d of e.changes){let A=d.path.replace(/\\/g,"/"),b=je(d.path);if(!b||b===".."||b.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!r.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),n.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=wt({...e,changes:n}),c=new Map(a.ir.files.map(d=>[d.path,d])),l=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let A=c.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:d.message}}),u=Ke({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:l,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=n.map(d=>{let A=je(d.path),b=r.get(A),O=c.get(A);return{path:A,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...O?{candidateContentHash:O.contentHash}:{}}}).sort((d,A)=>d.path.localeCompare(A.path)),g=[...s,...u.violations].map(d=>({...d,nextAction:ye(d)})),f=g.filter(d=>d.failsStrict!==!1),m=e.changeMap?$e({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Ia(t.ir.files),candidateTreeHash:Ia(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:u.warnings}}i(os,"preflightChange");function od(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let r=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(r.length===0)return;r.pop()}else r.push(o);let n=r.join("/");return n&&n===t?n:void 0}i(od,"canonicalChangePath");function ad(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,n,o])=>n!==o).map(([n,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:n,before:o,candidate:s,message:`Base and candidate facts must use the same ${n}.`}))}i(ad,"identityViolations");function id(e,t,r,n){let o=r.get(t),s=n.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(id,"preparedChange");function as(e){let t=Se(e.baseFacts),r=Se(e.candidateFacts),n=rt({contract:e.contract,facts:t}),o=rt({contract:e.contract,facts:r}),s=new Map(t.files.map(m=>[m.path,m])),a=new Map(r.files.map(m=>[m.path,m])),c=ad(t,r),l=new Map,u=[];for(let m of e.changes){let d=od(m.path);if(!d){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(d)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}l.set(d,m);let A=s.get(d),b=a.get(d);if("delete"in m&&m.delete)A||c.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let O="content"in m?m.content:"",E=J(O);b?b.contentHash!==E&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:E,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(id(m,d,s,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let m of new Set([...s.keys(),...a.keys()])){if(l.has(m))continue;let d=s.get(m),A=a.get(m);d&&A&&$(d)===$(A)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:m,line:1,message:`Candidate facts change ${m}, but the atomic change set does not declare it.`})}let p=e.changeMap?$e({changeMap:e.changeMap,changes:u,baseDependencies:n.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:o.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0,g=[...c,...o.ir.violations].map(m=>({...m,nextAction:ye(m)})),f=g.filter(m=>m.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:n.completeness==="complete"&&o.strictValid&&f.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:r.resolverIdentity,compilerIdentity:r.compilerIdentity,compilerOptionsHash:r.compilerOptionsHash,tsconfigHash:r.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:r.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:r.tsconfigHash,evidenceRequirementsHash:r.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:r.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:r.candidateTreeHash,baseCompleteness:n.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:n.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:u.sort((m,d)=>m.path<d.path?-1:m.path>d.path?1:0),violations:g,warnings:o.ir.warnings}}i(as,"preflightResolvedChange");var is="1.0",ld=12,cd="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",dd="Next: /ark-runtime to wire one candidate.";function ba(e){return e==="enforced"||e==="advisory"?e:null}i(ba,"closedMode");function ud(e){let t=new Set;if(!Array.isArray(e))return[];for(let r of e){let n=r?.ruleId;typeof n!="string"||!Hr(n)||t.has(n)||t.add(n)}return[...t].sort((r,n)=>r<n?-1:r>n?1:0)}i(ud,"uniqueArkRunRuleIds");function pd(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:ba(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}i(pd,"extraFromConfig");function va(e={}){let t=pd(e.arkRun),r=t.present?ud(e.findings):[],n=r.slice(0,ld),o=r.length,s=Lt({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:o}}),a=t.present&&t.mode==="enforced"&&me(e.classification),c;return t.present?t.mode==="advisory"?c="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?c="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":c="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":c="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:is,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:n},extraMergeTeeth:a,failMergeWhen:s.failMergeWhen,note:c,mergePlanes:s}}i(va,"summarizeArkRunSection");function Jr(e={}){let t=e.present===!0,r=ba(e.mode),n=e.residual,o=null;return typeof n=="number"&&Number.isFinite(n)&&n>=0&&(o=Math.floor(n)),t||(o=o??0),{notAScore:!0,present:t,mode:t?r:null,extraMergeTeeth:t&&r==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Jr,"projectStatusArkRun");function Ca(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",r=e.extraMergeTeeth===!0?"armed":"not armed",n=[cd,`mode: ${t} \xB7 extra merge teeth ${r} \xB7 not a score`];if(e.residual.count>0){let o=e.residual.ruleIds.join(", "),s=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";n.push(`Residual: ${o}${s}`),n.push(dd)}else n.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");return e.failMergeWhen&&n.push(e.failMergeWhen),n}i(Ca,"formatArkRunDoctorLines");function Xr(e,t){return e.slice(0,t).split(`
|
|
13
|
-
`).length}i(Xr,"lineOf");function _a(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(_a,"normalizeInventoryPath");function xa(e,t){return e.some(r=>{let n=r.trim().replace(/\.+$/,"");return t.some(o=>n===o||n.startsWith(`${o}.`))})}i(xa,"ownsIntent");function Oa(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||xa(t,["Domain"])}i(Oa,"isDomainLayer");function fd(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||xa(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(fd,"isControllerEligibleLayer");function md(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}i(md,"isNonPilotSurface");function Ta(e){let t=[],r=0,n=new Map(Object.entries(e.fileLayers??{}).map(([l,u])=>[_a(l),u])),o=new Map((e.layerContexts??[]).map(l=>[l.name,l.intentPrefixes??[]])),s=(e.layerContexts??[]).find(l=>Oa(l.name,l.intentPrefixes))?.name??"DomainModel";for(let[l,u]of Object.entries(e.fileContents).sort(([p],[g])=>p.localeCompare(g))){let p=_a(l);if(md(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let g=n.has(p),f=n.get(p),m=f?o.get(f)??[]:[],d=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(p)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(p)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(p),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),O=/controller|handler|resolver/i.test(l)||A||b||/route\.(?:ts|js|tsx|jsx)$/i.test(p)&&!d||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),E=g?!!(f&&fd(f,m)&&O):O,I=g?!!(f&&Oa(f,m)):/domain|entity|aggregate|model/i.test(l),C=!g||I||E;if(E&&!d){let T=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,z;for(;(z=T.exec(u))!==null;)r+=1,t.push({id:`inv-val-${r}`,kind:"validation-in-controller",file:l,line:Xr(u,z.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${r}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let L=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,k,P=i(T=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(T)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(T)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(T)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(T)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(T)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(T)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(T)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(T)||/_(?:OID|OIDS)$/i.test(T)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(T)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(T),"isInfraMagicName"),X=i((T,z)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(T)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(T))return!0;let M=z.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(z)&&(/\s/.test(M)||/[.!?…]$/.test(M))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(k=L.exec(u))!==null;){let T=k[2],z=k[3]??"";!C||P(T)||X(T,z)||d&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!I||(r+=1,t.push({id:`inv-magic-${r}`,kind:"magic-business-constant",file:l,line:Xr(u,k.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(I){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,z;for(;(z=T.exec(u))!==null;){let M=z[2]??"",ee=(M.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(M.match(/:\s*[A-Za-z]/g)??[]).length>=2&&ee<=1&&(r+=1,t.push({id:`inv-anemic-${r}`,kind:"anemic-entity",file:l,line:Xr(u,z.index),message:`Class ${z[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let z=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,M;for(;(M=z.exec(u))!==null;){let ee=u.lastIndexOf("class ",M.index),Y=ee>=0?u.indexOf("{",ee):-1,be=ee>=0&&Y>=ee&&Y<M.index?u.slice(ee,Y):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(be)||Yn(u,M.index))continue;let we=u.slice(Math.max(0,M.index-200),M.index+200);if(!zn.test(we)&&!Wn.test(we)){r+=1,t.push({id:`inv-mut-${r}`,kind:"mutation-without-guard",file:l,line:Xr(u,M.index),message:`Domain field mutation without nearby ${qn()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((l,u)=>+(u.confidence==="direct-evidence")-+(l.confidence==="direct-evidence")||l.file.localeCompare(u.file)||l.line-u.line||l.kind.localeCompare(u.kind)||l.id.localeCompare(u.id));let c=t.filter(l=>l.suggestedArkRule?.invariantId&&a.has(l.suggestedArkRule.invariantId)||l.suggestedArkRule?.structureId&&a.has(l.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Ta,"buildRulesInventory");function Na(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}i(Na,"inventoryToExtractionCard");var wa="1.1";var Pa="1.0";var Zr="docs/diagnostics.md",La="1.0";function S(e,t,r,n,o,s){return{ruleId:e,title:r,why:n,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(S,"entry");var jt=Object.freeze([S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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}),S("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."),S("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}),S("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."),S("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}),S("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),S("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),S("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."),S("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),S("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),S("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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."),S("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."),S("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}),S("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.")]),ls=new Map(jt.map(e=>[e.ruleId,e])),Da=Object.freeze(jt.map(e=>e.ruleId));function Ma(e){return typeof e=="string"&&e.length>0&&ls.has(e)}i(Ma,"isKnownDiagnosticCode");function Fa(e){return typeof e!="string"||e.length===0?!1:ls.has(e)?!0:e.startsWith("ARKRULE_")}i(Fa,"isCataloguedOrArkRuleFamily");function Kt(e){if(!(typeof e!="string"||e.length===0))return ls.get(e)}i(Kt,"getDiagnosticCatalogEntry");function cs(e){return`#${Kt(e)?.docsAnchor??e}`}i(cs,"diagnosticDocsFragment");function $a(e){return`${Zr}${cs(e)}`}i($a,"diagnosticDocsPath");function Ha(){return{schemaVersion:"1.0",docsPath:Zr,codes:jt}}i(Ha,"serializeDiagnosticCatalog");function ja(e){return Kt(e)?.fix}i(ja,"catalogFixForRuleId");function Ka(e){return Kt(e)?.why}i(Ka,"catalogWhyForRuleId");function gd(e){return e==="enforced"||e==="advisory"?e:null}i(gd,"closedMode");function Ua(e={}){let t=e.present===!0,r=gd(e.mode),n=e.residual,o=null;return typeof n=="number"&&Number.isFinite(n)&&n>=0&&(o=Math.floor(n)),t||(o=o??0),{notAScore:!0,present:t,mode:t?r:null,extraMergeTeeth:t&&r==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Ua,"projectStatusArkOrder");var Qr="1.0",ds="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",us=["full","subset","unavailable"],ps=["doctor-facts","report-snapshot","none"],Vt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Va=/^sha256:[a-f0-9]{64}$/;function fs(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let r=t.expectedRoot,n=t.expectedProjectId;if(r!==void 0&&(typeof r!="string"||r.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(n!==void 0&&(typeof n!="string"||!Va.test(n)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(r===void 0&&n!==void 0)return e.projectId&&n!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:n,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${n}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:n,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let o=e.expectedRootRelation??"unknown";return o==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:r,expectedProjectId:n,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${r}, but this process is bound to ${e.resolvedRoot}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:r,expectedProjectId:n,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="descendant"&&n===void 0?{status:"unverified",authoritative:!1,expectedRoot:r,message:`Expected workspace ${r} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:n!==void 0&&e.projectId&&n!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:r,expectedProjectId:n,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${n}, but this process is bound to ${e.projectId}.`}:o==="exact"||o==="descendant"&&n&&n===e.projectId?{status:"matched",authoritative:!0,...r?{expectedRoot:r}:{},...n?{expectedProjectId:n}:{}}:{status:"unverified",authoritative:!1,expectedRoot:r,expectedProjectId:n,message:"Project expectation could not be fully verified."}}i(fs,"evaluateStatusBinding");function ms(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}i(ms,"classifyStatusWritePath");function gs(e,t){let r=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${r} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${r}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}i(gs,"defaultHonestLabel");function ys(e,t,r,n,o){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?n.verdict==="fail"||(n.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${n.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:n.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:n.verdict==null&&n.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:r.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:r.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:o.arkRulesLoaded&&(o.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(ys,"resolveStatusNextAction");function Ga(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",r=typeof e.projectId=="string"&&Va.test(e.projectId)?e.projectId:null,n=fs({resolvedRoot:t,projectId:r,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,a=ms({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),c=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():gs(a,s),l={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Ut(e.activeViolations),frozenResidual:Ut(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ut(e.rulesInventoried),underContract:Ut(e.rulesUnderContract),frozenResidual:Ut(e.rulesFrozenResidual)},p={writePath:a,host:s,honestLabel:c},g={projectId:r,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:n.status,authoritative:n.authoritative,...n.code?{code:n.code}:{},...n.message?{message:n.message}:{}},f={schemaVersion:Qr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:l,rules:u,nextAction:ys(e,n,p,l,u)},m=hs(e.improvementCompass);return m&&(f.improvementCompass=m),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Jr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=Ua(e.arkOrder)),f}i(Ga,"buildStatusManifest");var Ba=new Set(us),yd=new Set(ps);function en(e){let t=Ba.has(e.mode)?e.mode:"unavailable",r=e.factsSource!=null&&yd.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,n=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let a={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:Vt.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:r??"none"};return n&&(a.contractHash=n),a}let o=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:Vt.FACTS_PARTIAL,s.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),r&&(s.factsSource=r),n&&(s.contractHash=n),s}i(en,"projectStatusImprovementCompass");function za(e={}){return en({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??Vt.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --doctor or --report for residual lenses. Status never invents green.",factsSource:"none",contractHash:e.contractHash})}i(za,"unavailableStatusImprovementCompass");function hs(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let r;return typeof t.mode=="string"&&Ba.has(t.mode)?r=t.mode:Array.isArray(t.topResidual)?r="subset":r="unavailable",en({mode:r,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}i(hs,"normalizeStatusImprovementCompass");function Wa(e,t){let r=Array.isArray(e)?e:[],n=new Set(Array.isArray(t)?t:[]);for(let o of r)if(!(typeof o!="string"||o.length===0)&&!n.has(o))return!1;return!0}i(Wa,"statusCompassResidualIsSubsetOfDoctor");function Ut(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ut,"numberOrNull");var qa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ds,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:Qr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},arkOrder:{type:"object",description:"ArkOrder extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var Gt="1.0",Bt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],zt=5,Te=["scalability","resilience","security"],nt=new Set(Te),As={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},Rs={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},ks={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function Es(e){return Rs[e]??e}i(Es,"improvementCompassHumanLabel");function Ss(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Ss,"smellIdOf");function Is(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Is,"violationRuleId");function K(e,t,r,n){if(!r||e.evidence.some(s=>s.source===t&&s.ref===r))return;let o={source:t,ref:r};n&&n.trim()&&(o.detail=n.trim().slice(0,240)),e.evidence.push(o)}i(K,"pushEvidence");function ne(e,t,r){nt.has(e.id)||(e.status="residual",e.summary=t,r&&(e.nextAction=r))}i(ne,"markResidual");function Ya(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${Rs[e]} \u2014 no residual from current sensors.`}}i(Ya,"defaultOkSummary");function Ja(){return Bt.map(e=>nt.has(e)?{id:e,status:"out-of-scope",summary:ks[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:Ya(e),evidence:[]}:{id:e,status:"ok",summary:Ya(e),evidence:[]})}i(Ja,"createInitialImprovementCompassLenses");function hd(e,t){for(let r of t){let n=Ss(r);if(!n)continue;let o=r.outcome||r.message||void 0,a=(Array.isArray(r.evidence)?r.evidence:[])[0],c=i((p,g,f)=>{let m=e.get(p);!m||nt.has(p)||(K(m,"designSmells",n,o),a&&K(m,"designSmells",a,n),ne(m,g,f))},"attach"),l={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(n){case"domain-logic-in-ui":c("soc","Business rules still mix with UI or presentation surfaces.",l),c("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",l);break;case"facade-sql-in-routes":c("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",l),c("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":c("soc","Application/business code reaches I/O directly \u2014 separation is weak.",l),c("dip","I/O is not inverted behind ports/adapters.",u),c("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":c("soc","HTTP/transport handlers live under persistence folders.",l);break;case"god-module":c("cohesion","Large multi-responsibility modules reduce cohesion.",l),c("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":c("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),c("cohesion","Mixed layout styles scatter the same concern across patterns.",l);break;case"soft-contract":c("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),c("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:c("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",l);break}}}i(hd,"mapDesignSmells");function Ad(e){return e.failsStrict===!1||e.typeOnly===!0}i(Ad,"isTypeOnlyPlacementDebt");function Rd(e,t){for(let r of t){let n=Is(r);if(!n)continue;let o=r.message,s=n.toUpperCase(),a=i((l,u,p)=>{let g=e.get(l);!g||nt.has(l)||(K(g,"violations",n,o),r.file&&K(g,"violations",r.file,n),ne(g,u,p))},"attach");if(Ad(r)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let c={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",c);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",c);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(s==="FORBIDDEN_GLOBAL"||s.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(s==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}i(Rd,"mapViolations");function kd(e,t){let r=Number(t.cycleCount)||0;if(r>0){let m=e.get("coupling");K(m,"cycles",`count:${r}`),ne(m,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let n=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(n>0){let m=e.get("coupling");K(m,"peerIsolation",`count:${n}`),ne(m,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let m=e.get("cohesion");K(m,"physicalCohesion",`findings:${o}`),ne(m,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let d=e.get("srp");K(d,"physicalCohesion",`findings:${o}`),ne(d,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(s>0||a>0){let m=e.get("dip");s>0&&K(m,"capability",`residual:${s}`),a>0&&K(m,"forbiddenGlobals",`residual:${a}`),ne(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let d=e.get("testability");s>0&&K(d,"capability",`residual:${s}`),a>0&&K(d,"forbiddenGlobals",`residual:${a}`),ne(d,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let c=Number(t.arkRulesStructureResidual)||0;if(c>0){let m=e.get("encapsulation");K(m,"arkRules",`structureResidual:${c}`),ne(m,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let d=e.get("domain");K(d,"arkRules",`structureResidual:${c}`),ne(d,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let m=e.get("maintainability");K(m,"designFitness","design-weak"),ne(m,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let m=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(m,"baseline",`stale:${t.baselineStale}`),ne(m,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let l=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&l>=10&&e.get("maintainability").status!=="residual"){let m=e.get("maintainability");K(m,"baseline",`frozen:${l}`),ne(m,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let u=Number(t.ungovernedDirCount)||0,p=Number(t.emptyLayerCount)||0;if(u>0||p>0){let m=e.get("modularity");u>0&&K(m,"coverage",`ungovernedDirs:${u}`),p>0&&K(m,"coverage",`emptyLayers:${p}`),ne(m,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let m=e.get("modularity");K(m,"goldenPattern","absent"),ne(m,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(kd,"mapCountsAndFlags");function Xa(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let r=[...t.designSmells].sort((n,o)=>Ss(n).localeCompare(Ss(o)));hd(e,r)}if(Array.isArray(t.violations)&&t.violations.length>0){let r=[...t.violations].sort((n,o)=>{let s=Is(n).localeCompare(Is(o));return s!==0?s:String(n.file??"").localeCompare(String(o.file??""))});Rd(e,r)}kd(e,t)}i(Xa,"projectImprovementCompassFacts");function Za(e){for(let t of Te){let r=e.get(t);r.status="out-of-scope",r.summary=ks[t],r.evidence=[],r.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}i(Za,"lockImprovementCompassOutOfScope");function Qa(e){for(let t of e)t.evidence.sort((r,n)=>{let o=r.source.localeCompare(n.source);return o!==0?o:r.ref.localeCompare(n.ref)})}i(Qa,"sortImprovementCompassEvidence");function ei(e){return e.filter(r=>r.status==="residual"&&!nt.has(r.id)).slice().sort((r,n)=>{let o=As[r.id]??150,s=As[n.id]??150;return o!==s?o-s:r.id.localeCompare(n.id)}).slice(0,5).map(r=>r.id)}i(ei,"finalizeImprovementCompassTopResidual");function ti(e={}){let t=Ja(),r=new Map(t.map(o=>[o.id,o]));Xa(r,e),Za(r),Qa(t);let n=ei(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(a=>({...a}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:n}}i(ti,"buildImprovementCompass");function bs(e){return e.topResidual.map(t=>Es(t))}i(bs,"formatImprovementCompassResidualLabels");function vs(e){for(let t of e.topResidual){let r=e.lenses.find(n=>n.id===t);if(r?.nextAction)return{...r.nextAction}}return null}i(vs,"primaryImprovementCompassNextAction");function ri(e){let t=bs(e),r=Te.map(s=>Es(s)),n=vs(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${r.join(" \xB7 ")}`),n&&o.push(`Next: ${n.ref} \u2014 ${n.summary}`),o}i(ri,"formatImprovementCompassDoctorLines");var Ne="1.0",Cs="<!-- arkgate:agent-projection:begin",Wt="<!-- arkgate:agent-projection:end -->",qt="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",st=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),_s=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]);function Ue(e){let t=String(e??"").replace(/\r\n/g,`
|
|
14
|
-
`),
|
|
15
|
-
`)}i(
|
|
1
|
+
"use strict";var on=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var vi=Object.getOwnPropertyNames;var Ci=Object.prototype.hasOwnProperty;var i=(e,t)=>on(e,"name",{value:t,configurable:!0});var _i=(e,t)=>{for(var n in t)on(e,n,{get:t[n],enumerable:!0})},Oi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vi(t))!Ci.call(e,o)&&o!==n&&on(e,o,{get:()=>t[o],enumerable:!(r=bi(t,o))||r.enumerable});return e};var xi=e=>Oi(on({},"__esModule",{value:!0}),e);var Hd={};_i(Hd,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>dt,AGENT_PROJECTION_BEGIN_MARKER:()=>xs,AGENT_PROJECTION_END_MARKER:()=>qt,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>ot,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Yt,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>Fs,AGENT_SKILL_ENTRY_FILENAME:()=>Hs,ANALYSIS_IR_SCHEMA_VERSION:()=>En,ARKORDER_RULE_IDS:()=>Xn,ARKORDER_TIER1_SENSOR_IDS:()=>Ca,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>as,ARKRUN_KERNEL_FACTORY_CALLEES:()=>ss,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>ya,ARKRUN_RULE_IDS:()=>Jn,ARKRUN_TIER1_SENSOR_IDS:()=>ka,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>os,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Pe,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>gi,ARK_ANALYSIS_RESULT_SCHEMA:()=>fr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>ct,ARK_CONFIG_SCHEMA:()=>yn,ARK_CONFIG_SCHEMA_VERSION:()=>ae,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ja,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Ha,ARK_FIRST_CLASS_SKILL_NAMES:()=>dr,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Bt,ARK_PROJECT_IDENTITY_SCHEMA:()=>eo,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>mr,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>Qs,ARK_RULES_SCHEMA:()=>In,ARK_RULES_SCHEMA_VERSION:()=>$o,ARK_RULE_SENSORS:()=>$r,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>ds,ARK_SKILL_CAPACITY:()=>tn,ARK_SKILL_CAPACITY_DEDICATED_DOORS:()=>js,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>pr,ARK_SKILL_NAMES:()=>rn,ARK_SKILL_NAME_COUNT:()=>Ks,ARK_SKILL_NORTH_STAR:()=>yi,ARK_SKILL_REQUIRED_SURFACES:()=>nn,ARK_SKILL_STUB_REDIRECTS:()=>ir,ARK_STATUS_MANIFEST_SCHEMA:()=>ti,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>fs,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>nr,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>Ts,DIAGNOSTIC_CATALOG:()=>Kt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ka,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>Va,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>fa,EffectiveContractError:()=>xt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>$s,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>we,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Wt,IMPROVEMENT_LENS_IDS:()=>zt,MERGE_PLANES_DUAL_STAMP:()=>ns,POLICY_DELTA_SCHEMA_VERSION:()=>xn,PROJECT_BINDING_SCHEMA:()=>yr,PROJECT_EXPECTATION_SCHEMA:()=>gr,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>kn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Oe,STATUS_COMPASS_FACTS_SOURCES:()=>gs,STATUS_COMPASS_MODES:()=>ms,STATUS_COMPASS_REASON_CODES:()=>Gt,adapterDocsCodePath:()=>pt,adapterFindingOccurrenceTargetKeys:()=>ze,adapterFindingRefFromTargetKey:()=>ut,adapterFindingTargetKey:()=>Be,agentProjectionContentIdentity:()=>Ue,agentSkillEntryRelativePath:()=>Ws,agentSkillPackageFileRelativePath:()=>Si,analyzeArchitectureConvergence:()=>He,analyzeChange:()=>Pt,analyzePolicyDelta:()=>Br,analyzeProject:()=>et,analyzeResolvedProject:()=>rt,arkRunKernelCallKind:()=>Un,arkSkillStubRedirect:()=>hi,buildAgentProjectionBeginMarker:()=>sr,buildAgentProjectionBlock:()=>Ns,buildAgentProjectionBody:()=>Qt,buildAgentProjectionMeta:()=>ws,buildArkRuleFileHints:()=>Hn,buildEffectiveArkRules:()=>bn,buildImprovementCompass:()=>li,buildRulesInventory:()=>Fa,buildStatusManifest:()=>Xa,canPromoteInvariant:()=>_n,catalogFixForRuleId:()=>Wa,catalogWhyForRuleId:()=>qa,classifyArkPolicyDelta:()=>Tn,classifyResolvedLayerCoverage:()=>Kn,classifyStatusWritePath:()=>hs,collectAnalysisConfigWarnings:()=>jt,collectEmptyAppliesToFindings:()=>$n,collectForbiddenCapabilityUses:()=>Me,composeMergePlanesHonesty:()=>Dt,createAICodeGate:()=>wr,createAdapterResult:()=>Zs,createArchitectureProfile:()=>It,createArchitectureProfileFromArkConfig:()=>Dr,createElevenLayerArkConfig:()=>Mr,createProjectId:()=>to,createProjectIdentity:()=>no,createResolvedCandidateFacts:()=>Rn,defaultHonestLabel:()=>As,demoteExtraPlaneTeethUnderClassificationFloor:()=>ma,deriveArkRuleFileHints:()=>Qr,detectArchitectureCycles:()=>Pn,deterministicHash:()=>J,diagnosticDocsFragment:()=>ps,diagnosticDocsPath:()=>Ba,effectiveContractPolicyPayload:()=>vn,elevenLayerProfile:()=>St,emptyEffectiveArkRules:()=>xe,evaluateArchitectureGraph:()=>Ve,evaluateArkOrderSensors:()=>Zn,evaluateArkRuleSensors:()=>Fn,evaluateArkRunEditorSensors:()=>is,evaluateArkRunEditorSensorsFromSource:()=>Sa,evaluateArkRunSensors:()=>Ht,evaluateInvariantCoverage:()=>Cn,evaluateStatusBinding:()=>ys,explainViolation:()=>zr,extraMergeTeethAllowed:()=>ge,extractAgentProjectionBlock:()=>en,extractArkRunDeclarationsFromSource:()=>ha,extractArkRunImportedConstructorNamesFromSource:()=>Wn,extractArkRunKernelCallsFromSource:()=>qn,extractArkRunManagedNewsFromSource:()=>Yn,extractArkRunValueImportDependenciesFromSource:()=>zn,extractClassShapesFromSource:()=>pa,extractSemanticDependencies:()=>De,flatSkillTemplateFileRelativePath:()=>Ii,formatAgentProjectionCatalogShortList:()=>or,formatAgentProjectionLayers:()=>Jt,formatArkRunDoctorLines:()=>Pa,formatImprovementCompassDoctorLines:()=>ci,formatImprovementCompassResidualLabels:()=>_s,getDiagnosticCatalogEntry:()=>Vt,inventoryToExtractionCard:()=>$a,isArkOrderRuleId:()=>es,isArkRunKernelModuleSpecifier:()=>nt,isArkRunRuleId:()=>Vn,isArkRunTransportBypassSpecifier:()=>Gn,isArkSkillName:()=>ur,isCataloguedOrArkRuleFamily:()=>Ga,isExtraPlaneFinding:()=>ts,isFirstClassArkSkillName:()=>lr,isKnownDiagnosticCode:()=>Ua,isValidAgentSkillName:()=>Vs,loadArkConfigContract:()=>Et,loadArkRulesContract:()=>Ot,loadContract:()=>wt,loadResolvedCandidateFacts:()=>Ie,mergeAgentProjectionDocument:()=>Ms,normalizeExtraMergeTeethClassification:()=>jn,normalizeSkillContent:()=>cr,normalizeStatusImprovementCompass:()=>ks,parseAgentProjectionStamp:()=>ar,parseArkConfigJson:()=>An,parseArkRulesJson:()=>Ho,parseSkillDescriptionVersion:()=>ki,parseSkillDocument:()=>Us,policyDeltaAcknowledgementMatches:()=>Nn,preflightChange:()=>ls,preflightResolvedChange:()=>cs,primaryImprovementCompassNextAction:()=>Os,projectStatusArkRun:()=>Qn,projectStatusImprovementCompass:()=>rr,projectionHasNonEnforcementLabel:()=>Ds,projectionMatchesPackageVersion:()=>Ls,resolveEffectiveContract:()=>Ko,resolveStatusNextAction:()=>Rs,resolvedFactsEvidenceRequirementsHash:()=>Qe,serializeDiagnosticCatalog:()=>za,skillDescriptionVersionPrefix:()=>Bs,stableSerialize:()=>$,stampSkillDescription:()=>Ei,statusCompassResidualIsSubsetOfDoctor:()=>ei,stripSkillDescriptionVersion:()=>zs,summarizeArkRunSection:()=>wa,toAdapterDiagnostic:()=>an,unavailableStatusImprovementCompass:()=>Qa,validateAgentSkillDocument:()=>Gs,validateAgentSkillsPackage:()=>Ai,validateSkillProductCapacity:()=>Ri,version:()=>Js});module.exports=xi(Hd);var Js="4.8.16";var Ti=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ni=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,wi=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Pi(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ti.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ni.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":wi.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Pi,"classifyLayerImportKind");function Li(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Pi(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Li,"layerImportNextAction");function Di(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Di,"arkRunCallSiteName");function Mi(e){let t=Di(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(Mi,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Li(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Mi(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ye,"deterministicNextAction");var ct="1.5",dt="docs/diagnostics.md",fr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function Be(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(Be,"adapterFindingTargetKey");function ze(e){let t=new Map;return e.map(n=>{let r=Be(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(ze,"adapterFindingOccurrenceTargetKeys");function ut(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(ut,"adapterFindingRefFromTargetKey");function pt(e){return`${dt}#${e}`}i(pt,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}i(x,"text");function Xs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Xs,"positiveInteger");function Fi(e,t,n){return ye({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}i(Fi,"nextActionForDiagnostic");function an(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=n??Be(e),c=ut(a);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:Xs(e.line,1),column:Xs(e.column,1)},evidence:s,nextAction:x(e.nextAction)??Fi(r,s,e),findingRef:c,targetKey:a,docsCodePath:pt(r)}}i(an,"toAdapterDiagnostic");function Zs(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(g=>({code:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=ze(s),l=ze(a),u=[...s.map((g,f)=>an(g,"error",c[f])),...a.map((g,f)=>an(g,"warning",l[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}i(Zs,"createAdapterResult");var Qs="1.0",mr="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",ln="^sha256:[a-f0-9]{64}$",gr={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:ln,description:"Project id previously returned by ark_identity or ark_manifest."}}},yr={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:ln},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},eo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:mr,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:ln},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:ln},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:gr,binding:yr}};function to(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}i(to,"createProjectId");function no(e){return{schemaVersion:"1.0",...e}}i(no,"createProjectIdentity");var Ar=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),kr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Er=Object.freeze(Object.keys(kr).sort()),hr=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"}),Rr=Object.freeze({process:Object.freeze(["process","node:process"])});function ft(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=hr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=hr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:hr[e.slice(0,s)]??null}i(ft,"capabilityForModuleSpecifier");function _e(e,t){for(let n of t)if(Rr[n]?.includes(e))return n;return null}i(_e,"forbiddenGlobalForModuleSpecifier");function cn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=kr[r];if(o)return o}return null}i(cn,"capabilityForAmbientName");function We(e){if(e?.pure===!0)return[...Ar].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Ar.includes(r));return[...new Set(n)].sort()}i(We,"effectiveCapabilityDeny");function mt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(mt,"ambientCoveredByForbiddenGlobals");function dn(e){let t=new Set,n=new Set,r=Object.keys(kr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Rr[o]??[])t.add(`import-exact:${a}`)}for(let o of We(e)){if(t.add(`import:${o}`),o==="process")for(let s of Rr.process)t.add(`import-exact:${s}`);for(let s of r)cn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(dn,"loweredLayerCoverage");var ro=new Map;function so(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(so,"escapeLiteral");function un(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(un,"normalizeGlobSeparators");function $i(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i($i,"bracesBalanced");function Re(e){let t=ro.get(e);if(t)return t;let n=un(e),r=$i(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=so(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=so(l)}let a=new RegExp(`^${o}$`);return ro.set(e,a),a}i(Re,"globToRegExp");function Hi(e){return un(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Hi,"concreteGlobSegments");function Sr(e,t){let n=un(String(e)),r=Hi(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let u of r){let p=-1;for(let g=c;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;l=p,c=p+1}return(l+1)*1e6+r.length*1e4+o}i(Sr,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Re(a).test(n))){for(let a of s.patterns??[])if(Re(a).test(n)){let c=Sr(a,n);c>o&&(o=c,r=s.name)}}return r}i(fe,"layerForRelativePath");function oo(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(oo,"sliceIdForPath");function ji(e){let t=new Set;for(let n of e??[]){let o=un(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(ji,"inferSliceFoldersFromPatterns");function Ki(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return ji(r?.patterns)}i(Ki,"resolveSliceFolders");function ao(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(ao,"normalizeSegments");function co(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(co,"trimTrailingSlashes");var Vi=["src","app"];function Ui(e){let t=co(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Ui,"isBlanketRoot");function io(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=ao(n);for(let s of t){if(typeof s!="string"||s.length===0||Ui(s))continue;if(s.includes("*")){let l=co(s.toLowerCase());if(Re(l).test(r)||Re(`${l}/**`).test(r))return!0;continue}let a=ao(s);if(a.length===0)continue;let c=Vi.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let l of c){if(l+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[l+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(io,"pathUnderSharedRoot");function lo(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(lo,"sliceMatchesDeclaration");function Gi(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&lo(r.from,t)&&lo(r.to,n))}i(Gi,"crossSliceEdgeAllowed");function Bi(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Bi,"peerIsolationDecision");function qe(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(qe,"peerIsolationDenyExplanation");function pn(e,t,n,r){return Le(e,t,n,r)?.rule}i(pn,"findDeniedEdgeRule");function Le(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=Ki(o,t,r?.layers),l=s?oo(s,c):void 0,u=a?oo(a,c):void 0,p=Bi({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:u,fromShared:!l&&io(s,o.sharedRoots),toShared:!u&&io(a,o.sharedRoots),crossSliceAllowed:Gi(o.allowedCrossSlice,l,u)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:l,toSlice:u};continue}if(t!==n)return{rule:o}}}i(Le,"findDeniedEdgeDecision");function Ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ye,"literalText");function fo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(fo,"lineOf");function uo(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(uo,"isTypeOnlyReference");function mo(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(mo,"singleFileChecker");function Ir(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Ir,"symbolAt");function br(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Ir(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(br,"localDeclaration");function De(e,t){let n,r=[],o=i((a,c,l,u=!1)=>r.push({specifier:l,kind:c,line:fo(t,a),typeOnly:u,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",Ye(e,a.moduleSpecifier),uo(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",Ye(e,a.moduleSpecifier),uo(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",Ye(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!br(e,n??(n=mo(e,t)),t,a.expression);(c||u)&&o(a,u?"require":"dynamic-import",Ye(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(De,"extractSemanticDependencies");function zi(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Ye(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(zi,"staticAccessPath");function Wi(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(Wi,"runtimeIdentifierReference");function po(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(po,"bestForbiddenMatch");function Me(e,t,n){if(n.length===0)return[];let r=new Set(n),o=mo(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let c=i(f=>{let m=zi(e,f);if(!m)return;let d=Ir(o,m.root),A=d?s.get(d):void 0;return A?[...A,...m.segments.slice(1)]:br(e,o,t,m.root)||a.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let d=c(m.initializer),A=Ir(o,m.name);!d||!A||s.set(A,d)}let l=[],u=new Set,p=i((f,m)=>{let d=fo(t,m),A=`${f}:${m.getStart(t)}`;u.has(A)||(u.add(A),l.push({name:f,line:d,node:m}))},"flag"),g=i(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let d=c(f),A=d?po(r,d):void 0;A&&p(A,f)}else e.isIdentifier(f)&&r.has(f.text)&&Wi(e,f)&&!br(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=c(f.initializer);if(d)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?Ye(e,A.propertyName)??A.propertyName.text:A.name.text,O=po(r,[...d,b]);O&&p(O,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),l}i(Me,"collectForbiddenCapabilityUses");function vr(e,t,n){let r=[];for(let o of n?.dependencies??De(e,t)){if(o.typeOnly||!o.specifier)continue;let s=ft(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Me(e,t,Er)){let s=cn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(vr,"collectCapabilityUses");var Cr={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},_r=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Or(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Or,"resolveIntentLayer");function Fe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Fe,"looksLikeArkIntent");function gt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Fe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Cr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Cr.PUBLISH_MISSING_SOURCE}),t}i(gt,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function Je(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}i(Je,"lineOf");var qi=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Yi(e,t){return e.index+e[0].indexOf(t)}i(Yi,"captureIndex");function Ji(e){let t=[],n=new Set,r=i((c,l)=>{!c||n.has(l)||(n.add(l),t.push({value:c,index:l}))},"push"),o=i(c=>{c.lastIndex=0;let l;for(;(l=c.exec(e))!==null;){let u=l[1];u&&r(u,Yi(l,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let c=a[1]??"",l=a.index+a[0].indexOf(c),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.exec(c))!==null;){let g=p[1];g&&r(g,l+p.index+p[0].indexOf(g))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((c,l)=>c.index-l.index)}i(Ji,"extractQuotedStrings");function Xi(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:c})}}return t.sort((r,o)=>r.index-o.index)}i(Xi,"extractModuleSpecifiers");function Zi(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(Zi,"isSyntaxWrapper");function xr(e,t){let n=t;for(;n?.parent&&Zi(e,n.parent);)n=n.parent;return n}i(xr,"unwrapWrappers");function Tr(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(Tr,"callCalleeName");function Qi(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=xr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Tr(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Nr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let c=xr(e,s).parent;return!!(c&&e.isCallExpression(c)&&Tr(e,c)==="publish")}return!1}i(Qi,"isPublishMetadataSource");function go(e,t){let n=xr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Tr(e,r);if(o&&qi.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return go(e,r);if(e.isPropertyAssignment(r)){let o=Nr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Qi(e,r))return!0}return!1}i(go,"isDeclaredIntentSite");function el(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&go(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(el,"extractQuotedStringsAst");function tl(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(tl,"hasInfrastructureToken");function nl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(nl,"isKnownInfrastructurePackage");function rl(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(rl,"layerHasInfrastructureRole");function ht(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ht,"tsStringLiteralText");function Nr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Nr,"tsPropertyName");function yo(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Nr(e,r.name)===n)}i(yo,"tsObjectProperty");function At(e,t,n){return yo(e,t,n)!==void 0}i(At,"tsObjectHasProperty");function yt(e,t,n){let r=yo(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(yt,"tsObjectPropertyValue");function sl(e,t){let n=yt(e,t,"metadata");return At(e,n,"source")}i(sl,"tsObjectHasMetadataSource");function ho(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?ho(e,t.name):!1:!1}i(ho,"tsLooksLikeIntentCreatorExpression");function ol(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(ol,"tsIsPublishCall");function al(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=ht(e,n);return r!==void 0&&Fe(r)||At(e,n,"intent")||ho(e,n)}i(al,"tsIsArkPublishCandidate");function il(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return sl(e,n)||At(e,r,"source")||At(e,o,"source")}i(il,"tsPublishHasSource");function ll(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=yt(e,n,"metadata");return ht(e,yt(e,s,"source"))??ht(e,yt(e,r,"source"))??ht(e,yt(e,o,"source"))}i(ll,"tsPublishSourceLiteral");function cl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,l=[],u=i(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=i(g=>{if(ol(e,g)){let f=g.arguments[0],m=ht(e,f);for(let A of gt({publishCall:!0,rawIntentName:m,objectHasIntent:At(e,f,"intent"),arkPublishCandidate:al(e,g),hasSource:il(e,g)}))l.push(W(A.ruleId,A.message,{line:u(g),filePath:a}));let d=ll(e,g);if(r&&c&&d&&Fe(d)){let A=r.resolveLayer(d);A&&A!==c&&l.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${A}, but the target file is classified as ${c}.`,{line:u(g),filePath:a,target:d,fromLayer:c,toLayer:A}))}}e.forEachChild(g,p)},"visit");return p(o),l}i(cl,"analyzePublishAst");function wr(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],l=a,u=l?.filePath,p=l?.layer,g=e.typescript,f=g?g.createSourceFile(u??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?De(e.typescript,f):void 0,d=m?m.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(f),kind:k.kind,typeOnly:k.typeOnly})):Xi(s),A=e.typescript?el(e.typescript,s):Ji(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of m?.filter(({unresolved:I})=>I)??[]){let I=k.kind==="require";c.push(W(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:u}))}let b=p!==void 0&&(r.has(p)||rl(p)),O=p!==void 0?` If "${p}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let I=k.exec(s);k.lastIndex=0,I&&c.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:I.index===void 0?void 0:Je(s,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+O}))}else s.includes(k)&&c.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:Je(s,s.indexOf(k)),filePath:u}));for(let k of d){let I=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,L=I?.layer;if(L&&p){let E=pn(e.architectureProfile?.rules,p,L,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(E){if(k.typeOnly&&!E.peerIsolation)continue;let P=!!E.peerIsolation;c.push(W("LAYER_IMPORT_VIOLATION",E.message??(P?`Layer "${p}" must not import across slices into "${L}".`:`Layer "${p}" must not import "${L}".`),{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:p,toLayer:L,suggestion:P?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:k.kind,peerIsolation:P,...k.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||k.typeOnly||!tl(k.value)&&!nl(k.value)||c.push(W("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+O,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let I=k.check({source:s,context:a});if(I!==!0)if(Array.isArray(I))for(let C of I)c.push(W("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else I===!1?c.push(W("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):c.push(W("POLICY_VIOLATION",I.message))}if(o&&t.size>0)for(let k of A)Fe(k.value)&&!t.has(k.value)&&c.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:Je(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let k of A){if(!Fe(k.value))continue;let I=e.architectureProfile.resolveLayer(k.value);if(!I)continue;let C=Le(e.architectureProfile.rules,p,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let L=C.rule.peerIsolation?qe(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,E=`Layer "${p}" must not reference "${I}" through "${k.value}".`,P=L&&C.peerIsolationReason!=="cross-slice"?`${E} ${L}`:C.rule.message?L?`${C.rule.message} (${L})`:C.rule.message:E;c.push(W("LAYER_REFERENCE_VIOLATION",P,{line:Je(s,k.index),filePath:u,target:k.value,fromLayer:p,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let k of e.extensions)try{let I=k.analyze(s,a);c.push(...I)}catch(I){c.push(W("EXTENSION_ERROR",`Extension "${k.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let k=e.forbiddenGlobals[p];c.push(...Me(e.typescript,f,k).map(I=>W("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of m??[]){if(I.typeOnly||!I.specifier)continue;let C=_e(I.specifier,k);C&&c.push(W("FORBIDDEN_GLOBAL",`${p} must not use module "${I.specifier}" because it is the import form of forbidden global "${C}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:p,details:{importKind:I.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let k=new Set(e.capabilityWalls[p]),I=e.forbiddenGlobals?.[p]??[];for(let C of vr(e.typescript,f))k.has(C.capability)&&(C.source==="ambient-global"&&mt(C.symbol,I)||C.source==="import-based"&&_e(C.symbol,I)||c.push(W("CAPABILITY_VIOLATION",C.source==="import-based"?`${p} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${p} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{c.push(...cl(e.typescript,s,a,e.architectureProfile))}catch(k){c.push(W("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.length===0,violations:c}}}}i(wr,"createAICodeGate");var $e={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ao={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...$e,default:[]},kernelRoots:{...$e},managedLayers:{...$e,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ro={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...$e,default:[]},managedLayers:{...$e,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...$e,default:[]},appliesTo:{...$e,default:[]}}};function Rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Rt,"isObject");function ko(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Rt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(ko,"declaredLayerNames");function Eo(e){if(!Rt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Eo,"defaultedArkRun");function So(e){if(!Rt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(So,"defaultedArkOrder");function Io(e,t){let n=e.arkRun;if(n===void 0||!Rt(n))return;let r=ko(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Io,"validateArkRunExtra");function bo(e,t){let n=e.arkOrder;if(n===void 0||!Rt(n))return;let r=ko(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(bo,"validateArkOrderExtra");function fn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(fn,"normalizeStewardId");function vo(e){let t=fn(e);return!t||Pr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(vo,"isGitHubHandle");function dl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Pr(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(dl,"isGitHubEmail");function ul(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&vo(t[1])?fn(t[1]):null}i(ul,"githubHandleFromEmail");function Co(e){let t=ul(e);if(t)return t;let n=fn(e);return!n||Pr(n)?null:vo(n)||dl(n)?n:null}i(Co,"canonicalStewardId");var pl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Pr(e){let t=fn(e);return!t||pl.test(t)}i(Pr,"isAutomationAuthor");var ae="1.3",fl=["public","auth","admin","internal"];function ml(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(ml,"isFutureHouseLayer");function gl(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}i(gl,"layerOwnersList");function Oo(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!ml(t)&&!gl(t)).map(t=>t.name)}i(Oo,"layersMissingRequiredOwners");function xo(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(xo,"missingLayerOwnersNextAction");var gn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",_o=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],yl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function hl(){let e=[];for(let t of _o)for(let n of _o)t===n||yl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(hl,"createDefaultRules");var hn=hl(),Lr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},yn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:gn,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:gn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ae,default:ae},name:{type:"string",minLength:1},include:{...le,minItems:1,default:["src"]},exclude:{...le,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:hn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...le,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...le,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...le,minItems:1},exclude:le,intentPrefixes:le,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...fl]},owners:{...le,minItems:1},forbiddenGlobals:le,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...le,minItems:1},sharedRoots:{...le,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...le,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...le,minItems:1}}},arkRun:Ao,arkOrder:Ro}},ke=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function To(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(To,"isObject");function mn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(mn,"propertyPath");function Xe(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Xe,"valueType");function Al(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Al,"resolveSchemaRef");function kt(e,t,n,r,o){if(t.$ref){let s=Al(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}kt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!To(e)){o.push({path:n,message:`must be an object; received ${Xe(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:mn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:mn(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||kt(e[c],a,mn(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&kt(e[a],c,mn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Xe(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>kt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${Xe(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${Xe(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${Xe(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(kt,"validateNode");function Rl(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((a,c)=>{typeof a=="string"&&(Co(a)||t.push({path:`$.layers[${o}].owners[${c}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(Rl,"validateLayerOwners");function kl(e){let t={...e,$schema:e.$schema===void 0?gn:e.$schema,schemaVersion:e.schemaVersion===void 0?ae:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?hn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Eo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=So(e.arkOrder)),t}i(kl,"defaultedConfig");function El(e){return e===ae?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(El,"migratedFromOf");function Sl(){let e=new Set([ae]);for(let t of Lr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Sl,"knownInputVersions");function Il(e,t="ark.config.json"){if(!To(e))throw new ke(t,[{path:"$",message:`must be an object; received ${Xe(e)}`}]);let n=Sl(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ae}`}]);if(r!=="unversioned"&&!n.has(r))throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);let o=r,s={...e},a=0;for(;o!==ae&&a<Lr.length+1;){a+=1;let c=Lr.find(l=>l.from===o);if(!c)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ae}`}]);o=c.to,s.schemaVersion=o}if(o!==ae)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);return{candidate:kl(s),migratedFrom:El(r)}}i(Il,"migrateArkConfig");function Et(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Il(e,t),o=[];if(kt(n,yn,"$",yn,o),Io(n,o),bo(n,o),Rl(n,o),o.length>0)throw new ke(t,o);return{config:n,migratedFrom:r}}i(Et,"loadArkConfigContract");function An(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ke(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Et(n,t)}i(An,"parseArkConfigJson");function No(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:gn,schemaVersion:ae};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(No,"withArkConfigMetadata");function bl(e){return e.endsWith(".")?e:`${e}.`}i(bl,"normalizePrefix");function vl(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}i(vl,"byLongestPrefix");function It(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(bl)})),n=[...t].sort(vl),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(a=>o.startsWith(a)))?.name}}}i(It,"createArchitectureProfile");function Dr(e,t={}){return It({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}i(Dr,"createArchitectureProfileFromArkConfig");var Cl=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],St=It({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Cl,rules:hn.map(e=>({...e}))}),_l={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Mr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return No({include:e.include??[t],layers:St.layers.map(o=>({name:o.name,patterns:(_l[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...St.rules]})}i(Mr,"createElevenLayerArkConfig");function J(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(J,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$(t[n])}`).join(",")}}`}i($,"stableSerialize");var Oe="1.2";var wo=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=$(e),r=$(t);return n<r?-1:n>r?1:0}i(q,"compareCanonical");function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Z,"sortedUnique");function Qe(e){let t={schemaVersion:"1.2",include:Z(e.include??[]),exclude:Z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Z(e.dynamicImportAllowlist??[]),layers: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})).sort(q),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 J($(t))}i(Qe,"resolvedFactsEvidenceRequirementsHash");function Ol(e){let t=e.completenessReasons.map(E=>({code:E.code,message:E.message,...E.file?{file:E.file}:{}})).sort(q),n=e.files.map(E=>({...E,typeOnlyExportNames:Z(E.typeOnlyExportNames)})).sort((E,P)=>E.path<P.path?-1:E.path>P.path?1:0),r=e.dependencies.map(E=>({...E,...E.namedBindings?{namedBindings:Z(E.namedBindings)}:{}})).sort(q),o=e.capabilityUses.map(E=>({...E})).sort(q),s=e.ambientUses.map(E=>({...E})).sort(q),a=e.publishCalls.map(E=>({...E})).sort(q),c=e.intentReferences.map(E=>({...E})).sort(q),l=e.safetyUses.map(E=>({...E})).sort(q),u=(e.classShapes??[]).map(E=>({...E,mutatingMethods:[...E.mutatingMethods??[]].map(P=>({...P}))})).sort(q),p=(e.arkRunKernelCalls??[]).map(E=>({...E})).sort(q),g=(e.arkRunManagedNews??[]).map(E=>({...E})).sort(q),f=(e.arkRunCompositionRootHits??[]).map(E=>({...E})).sort(q),m=(e.arkRunDeclarations??[]).map(E=>({...E,uses:Z(E.uses),reactsTo:Z(E.reactsTo),raises:Z(E.raises),sends:Z(E.sends)})).sort(q),d=(e.arkOrderPlaneCalls??[]).map(E=>({...E})).sort(q),A=(e.arkOrderGenericUpdates??[]).map(E=>({...E})).sort(q),b=(e.arkOrderRootHits??[]).map(E=>({...E})).sort(q),O=(e.arkOrderXiFieldWrites??[]).map(E=>({...E})).sort(q),k=(e.arkOrderIngestWritesXi??[]).map(E=>({...E})).sort(q),I=(e.arkOrderReleaseKeyCounts??[]).map(E=>({...E})).sort(q),C=e.files.map(({path:E,contentHash:P})=>({path:E,contentHash:P})).sort((E,P)=>E.path<P.path?-1:E.path>P.path?1:0),L=J($(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:L,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:l,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:d,arkOrderGenericUpdates:A,arkOrderRootHits:b,arkOrderXiFieldWrites:O,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:I}}i(Ol,"canonicalResolvedFactsInput");function Po(e){let t=Ol(e);return{...t,factsHash:J($(t))}}i(Po,"createCanonicalResolvedCandidateFacts");function Rn(e){return Po(Do(H(e,"$"),!1))}i(Rn,"createResolvedCandidateFacts");function H(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(H,"asRecord");function j(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(j,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function Ee(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Ee,"optionalText");function U(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let c of o.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 a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(U,"requiredProjectPath");function G(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(G,"requiredBoolean");function Lo(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(Lo,"requiredInteger");function te(e,t,n){let r=Lo(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(te,"requiredPositiveInteger");function B(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(B,"requiredArray");function Se(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Se,"enumValue");function Ze(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(Ze,"parseStringArray");function xl(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(xl,"assertUnique");function Do(e,t){j(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Se(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Se(e,"completeness",["complete","partial","unavailable"],"$"),o=B(e,"completenessReasons","$").map((v,_)=>{let y=`$.completenessReasons[${_}]`,R=H(v,y);j(R,["code","message","file"],y);let M=R.file===void 0?void 0:U(R,"file",y);return{code:F(R,"code",y),message:F(R,"message",y),...M?{file:M}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=B(e,"files","$").map((v,_)=>{let y=`$.files[${_}]`,R=H(v,y);return j(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:U(R,"path",y),contentHash:F(R,"contentHash",y),parseStatus:Se(R,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Lo(R,"parseDiagnosticCount",y),exportsOnlyTypes:G(R,"exportsOnlyTypes",y),typeOnlyExportNames:Ze(R.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:G(R,"hasTopLevelSideEffects",y)}}),a=B(e,"dependencies","$").map((v,_)=>{let y=`$.dependencies[${_}]`,R=H(v,y);j(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let M=Ee(R,"specifier",y),Y=Ee(R,"target",y),Ce=Se(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(Ce==="resolved-project"&&!Y)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(Ce!=="resolved-project"&&Y)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(Ce!=="dynamic"&&!M)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:U(R,"from",y),...M?{specifier:M}:{},kind:Se(R,"kind",["import","export","dynamic-import","require"],y),typeOnly:G(R,"typeOnly",y),line:te(R,"line",y),resolution:Ce,...Y?{target:U(R,"target",y)}:{},...R.namedBindings!==void 0?{namedBindings:Ze(R.namedBindings,`${y}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(R,"targetTypeOnlyExports",y)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(R,"sourcePureTypeModule",y)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(R,"namedBindingsTypeOnly",y)}:{},...R.portProofEligible!==void 0?{portProofEligible:G(R,"portProofEligible",y)}:{}}}),c=B(e,"capabilityUses","$").map((v,_)=>{let y=`$.capabilityUses[${_}]`,R=H(v,y);return j(R,["file","line","symbol","capability","source"],y),{file:U(R,"file",y),line:te(R,"line",y),symbol:F(R,"symbol",y),capability:Se(R,"capability",wo,y),source:Se(R,"source",["ambient-global","import-based"],y)}}),l=B(e,"ambientUses","$").map((v,_)=>{let y=`$.ambientUses[${_}]`,R=H(v,y);return j(R,["file","line","symbol"],y),{file:U(R,"file",y),line:te(R,"line",y),symbol:F(R,"symbol",y)}}),u=B(e,"publishCalls","$").map((v,_)=>{let y=`$.publishCalls[${_}]`,R=H(v,y);j(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let M=Ee(R,"rawIntentName",y),Y=Ee(R,"sourceIntent",y);return{file:U(R,"file",y),line:te(R,"line",y),...M?{rawIntentName:M}:{},objectHasIntent:G(R,"objectHasIntent",y),arkPublishCandidate:G(R,"arkPublishCandidate",y),hasSource:G(R,"hasSource",y),...Y?{sourceIntent:Y}:{}}}),p=B(e,"intentReferences","$").map((v,_)=>{let y=`$.intentReferences[${_}]`,R=H(v,y);return j(R,["file","line","intent"],y),{file:U(R,"file",y),line:te(R,"line",y),intent:F(R,"intent",y)}}),g=B(e,"safetyUses","$").map((v,_)=>{let y=`$.safetyUses[${_}]`,R=H(v,y);j(R,["file","line","kind","symbol"],y);let M=Ee(R,"symbol",y),Y=Se(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(Y==="in-memory-store"&&!M)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(Y!=="in-memory-store"&&M)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:U(R,"file",y),line:te(R,"line",y),kind:Y,...M?{symbol:M}:{}}});xl(s,v=>v.path,"$.files");let f=new Set(s.map(v=>v.path));for(let v of s){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:B(e,"arkRunKernelCalls","$")).map((v,_)=>{let y=`$.arkRunKernelCalls[${_}]`,R=H(v,y);j(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let M=Ee(R,"receiver",y),Y=Ee(R,"nameLiteral",y);return{file:U(R,"file",y),line:te(R,"line",y),kind:Se(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:F(R,"callee",y),viaImport:G(R,"viaImport",y),...M?{receiver:M}:{},...Y?{nameLiteral:Y}:{}}}),b=(e.arkRunManagedNews===void 0?[]:B(e,"arkRunManagedNews","$")).map((v,_)=>{let y=`$.arkRunManagedNews[${_}]`,R=H(v,y);j(R,["file","line","typeName","importedFrom"],y);let M=Ee(R,"importedFrom",y);return{file:U(R,"file",y),line:te(R,"line",y),typeName:F(R,"typeName",y),...M?{importedFrom:M}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:B(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let y=`$.arkRunCompositionRootHits[${_}]`,R=H(v,y);return j(R,["file","matchedRoot","hasKernelFactory"],y),{file:U(R,"file",y),matchedRoot:F(R,"matchedRoot",y),hasKernelFactory:G(R,"hasKernelFactory",y)}}),I=e.arkRunDeclarations===void 0?[]:B(e,"arkRunDeclarations","$"),L=(e.arkOrderPlaneCalls===void 0?[]:B(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let y=`$.arkOrderPlaneCalls[${_}]`,R=H(v,y);return j(R,["file","line","callee"],y),{file:U(R,"file",y),line:te(R,"line",y),callee:F(R,"callee",y)}}),P=(e.arkOrderGenericUpdates===void 0?[]:B(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let y=`$.arkOrderGenericUpdates[${_}]`,R=H(v,y);return j(R,["file","line","method"],y),{file:U(R,"file",y),line:te(R,"line",y),method:F(R,"method",y)}}),T=(e.arkOrderRootHits===void 0?[]:B(e,"arkOrderRootHits","$")).map((v,_)=>{let y=`$.arkOrderRootHits[${_}]`,R=H(v,y);return j(R,["file","matchedRoot","hasPlaneFactory"],y),{file:U(R,"file",y),matchedRoot:F(R,"matchedRoot",y),hasPlaneFactory:G(R,"hasPlaneFactory",y)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:B(e,"arkOrderXiFieldWrites","$")).map((v,_)=>{let y=`$.arkOrderXiFieldWrites[${_}]`,R=H(v,y);return j(R,["file","line","key"],y),{file:U(R,"file",y),line:te(R,"line",y),key:F(R,"key",y)}}),X=(e.arkOrderIngestWritesXi===void 0?[]:B(e,"arkOrderIngestWritesXi","$")).map((v,_)=>{let y=`$.arkOrderIngestWritesXi[${_}]`,R=H(v,y);return j(R,["file","line"],y),{file:U(R,"file",y),line:te(R,"line",y)}}),Ae=(e.arkOrderReleaseKeyCounts===void 0?[]:B(e,"arkOrderReleaseKeyCounts","$")).map((v,_)=>{let y=`$.arkOrderReleaseKeyCounts[${_}]`,R=H(v,y);return j(R,["file","line","keyCount"],y),{file:U(R,"file",y),line:te(R,"line",y),keyCount:te(R,"keyCount",y)}}),at=I.map((v,_)=>{let y=`$.arkRunDeclarations[${_}]`,R=H(v,y);return j(R,["file","line","uses","reactsTo","raises","sends"],y),{file:U(R,"file",y),line:te(R,"line",y),uses:Ze(R.uses,`${y}.uses`),reactsTo:Ze(R.reactsTo,`${y}.reactsTo`),raises:Ze(R.raises,`${y}.raises`),sends:Ze(R.sends,`${y}.sends`)}});for(let[v,_]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",at],["$.arkOrderPlaneCalls",L],["$.arkOrderGenericUpdates",P],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",X],["$.arkOrderReleaseKeyCounts",Ae]])for(let y of _)if(!f.has(y.file))throw new Error(`${v} references missing file ${y.file}.`);let sn=Ee(e,"projectPackageName","$"),Ys=(e.classShapes===void 0?[]:B(e,"classShapes","$")).map((v,_)=>{let y=`$.classShapes[${_}]`,R=H(v,y);j(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],y);let M=B(R,"mutatingMethods",y).map((Y,Ce)=>{let h=`${y}.mutatingMethods[${Ce}]`,oe=H(Y,h);return j(oe,["name","referencesGuardOrPublish"],h),{name:F(oe,"name",h),referencesGuardOrPublish:G(oe,"referencesGuardOrPublish",h)}});return{file:U(R,"file",y),className:F(R,"className",y),exported:G(R,"exported",y),hasPublicMutableFields:G(R,"hasPublicMutableFields",y),hasPublicSetters:G(R,"hasPublicSetters",y),hasPublicConstructor:G(R,"hasPublicConstructor",y),hasStaticFactory:G(R,"hasStaticFactory",y),mutatingMethods:M,...R.dataOnly===void 0?{}:{dataOnly:G(R,"dataOnly",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...sn?{projectPackageName:sn}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:l,publishCalls:u,intentReferences:p,safetyUses:g,classShapes:Ys,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:k,arkRunDeclarations:at,arkOrderPlaneCalls:L,arkOrderGenericUpdates:P,arkOrderRootHits:T,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:X,arkOrderReleaseKeyCounts:Ae}}i(Do,"parseResolvedFactsInput");function Ie(e){let t=H(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Po(Do(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(Ie,"loadResolvedCandidateFacts");var Tl=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},ie={type:"integer",minimum:1},z={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},kn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:N,message:N,file:z}}},resolverIdentity:N,compilerIdentity:N,compilerOptionsHash:N,tsconfigHash:N,candidateTreeHash:N,evidenceRequirementsHash:N,projectPackageName:N,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:z,contentHash:N,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:N},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:z,specifier:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ie,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:z,namedBindings:{type:"array",items:N},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:z,line:ie,symbol:N,capability:{enum:Tl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:z,line:ie,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:z,line:ie,rawIntentName:N,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:N}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:z,line:ie,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:z,line:ie,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:N},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:z,className:N,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:N,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:z,line:ie,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:N,viaImport:{type:"boolean"},receiver:N,nameLiteral:N}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:z,line:ie,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:z,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:z,line:ie,uses:{type:"array",items:N},reactsTo:{type:"array",items:N},raises:{type:"array",items:N},sends:{type:"array",items:N}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:z,line:ie,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:z,line:ie,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:z,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:z,line:ie,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:z,line:ie}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:z,line:ie,keyCount:{type:"integer",minimum:1}}}},factsHash:N},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var En="1.0";function ce(e){return`${e.from}->${e.to}`}i(ce,"dependencyKey");function bt(e,t,n,r="dependency"){return{id:`${e}:${r}:${ce(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ce(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ce(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ce(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ce(t)} from the candidate, then preflight again.`}:{}}}i(bt,"dependencyFinding");function He(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[ce(f),f])),s=new Map(e.baseDependencies.map(f=>[ce(f),f])),a=new Map(e.candidateDependencies.map(f=>[ce(f),f]));for(let f of[...n.values()].sort((m,d)=>m.path.localeCompare(d.path))){let m=r.get(f.path);m?m.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${m.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((m,d)=>m.path.localeCompare(d.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let c=new Set;for(let f of[...o.values()].sort((m,d)=>ce(m).localeCompare(ce(d)))){if(a.has(ce(f))){t.push(bt("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};a.has(ce(m))?(c.add(ce(m)),t.push(bt("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(bt("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[f,m]of[...a].sort(([d],[A])=>d.localeCompare(A)))s.has(f)||o.has(f)||c.has(f)||!l.has(m.from)&&!l.has(m.to)||t.push({...bt("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([d],[A])=>d.localeCompare(A)))a.has(f)||u.has(m.from)||u.has(m.to)||!l.has(m.from)&&!l.has(m.to)||t.push({...bt("unplanned",m,`${m.from} -> ${m.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,m)=>p[f.classification]-p[m.classification]||(f.subject===m.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(m.id));let g={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}i(He,"analyzeArchitectureConvergence");var $o="1.0",Fr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",$r=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Nl=["no-anemic-model"],Mo={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},In={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Fr,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:Fr},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...$r]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Mo,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:Mo}}}},je=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
5
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
6
|
+
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function _t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(_t,"isObject");function Sn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Sn,"propertyPath");function vt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(vt,"valueType");function wl(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(wl,"resolveSchemaRef");function Ct(e,t,n,r,o){if(t.$ref){let s=wl(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ct(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!_t(e)){o.push({path:n,message:`must be an object; received ${vt(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Sn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:Sn(n,a),message:"unknown field"});else if(_t(t.additionalProperties)){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||Ct(e[c],a,Sn(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&Ct(e[a],c,Sn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${vt(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>Ct(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${vt(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${vt(e)}`})}i(Ct,"validateNode");function Pl(e){return{...e,$schema:e.$schema===void 0?Fr:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}i(Pl,"defaultedArkRules");function Fo(e){return e==="enforced"?"enforced":"advisory"}i(Fo,"normalizeMode");function Ll(e){return Nl.includes(e)}i(Ll,"isTier2Sensor");function Dl(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],o=new Set;n.forEach((s,a)=>{if(!_t(s))return;let c=typeof s.id=="string"?s.id:"";c&&(o.has(c)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),o.add(c)),typeof s.sensor=="string"&&Ll(s.sensor)&&s.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`${c?`rule ${JSON.stringify(c)} uses sensor `:"sensor "}${JSON.stringify(s.sensor)}, which is Tier-2 advisory-only and cannot be enforced${c?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.structure[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((s,a)=>{if(!_t(s))return;let c=typeof s.id=="string"?s.id:"";c&&(o.has(c)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(c)}`}),o.add(c)),Array.isArray(s.appliesTo)&&s.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}i(Dl,"validateSemantics");function Ot(e,t="arkrules.json",n){if(!_t(e))throw new je(t,[{path:"$",message:`must be an object; received ${vt(e)}`}]);let r=Pl(e),o=[];if(Ct(r,In,"$",In,o),Dl(r,o),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&o.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),o.length>0)throw new je(t,o);return{config:r}}i(Ot,"loadArkRulesContract");function Ho(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(o){throw new je(t,[{path:"$",message:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}])}return Ot(r,t,n)}i(Ho,"parseArkRulesJson");function bn(e){let t={},n=[],r=[],o=[...e].sort((s,a)=>s.layer.localeCompare(a.layer));for(let s of o){let a=(s.file.structure??[]).map(l=>({...l,mode:Fo(l.mode),provenance:{sourceFile:s.sourceFile,ruleId:l.id,layer:s.layer}})),c=(s.file.invariants??[]).map(l=>({...l,mode:Fo(l.mode),provenance:{sourceFile:s.sourceFile,ruleId:l.id,layer:s.layer}}));t[s.layer]={sourceFile:s.sourceFile,structure:a,invariants:c},n.push(...a),r.push(...c)}return n.sort((s,a)=>{let c=s.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:s.id.localeCompare(a.id)}),r.sort((s,a)=>{let c=s.provenance.layer.localeCompare(a.provenance.layer);return c!==0?c:s.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(bn,"buildEffectiveArkRules");function xe(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(xe,"emptyEffectiveArkRules");var xt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
|
|
7
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
8
|
+
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function jo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(jo,"normalizeRel");function Ko(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let l of[...e.discoveredArkRulesFiles].sort())r.push({path:l,message:`ArkRules file ${JSON.stringify(l)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:xe(),warnings:r}}let o=new Set(e.config.layers.map(l=>l.name)),s=[],a=[],c=new Set;for(let l of Object.keys(n).sort()){let u=n[l],p=`$.arkRules[${JSON.stringify(l)}]`;if(typeof u!="string"||u.length===0){s.push({path:p,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){s.push({path:p,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!o.has(l)){s.push({path:p,message:`layer ${JSON.stringify(l)} is not declared in layers[]`});continue}let g=jo(u);c.add(g);let f=e.fileContents[g]??e.fileContents[u];if(f===void 0){s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let m=Ot(JSON.parse(f),g,l);a.push({layer:l,sourceFile:g,file:m.config})}catch(m){if(m instanceof je)for(let d of m.issues)s.push({path:`${p}${d.path==="$"?"":d.path.replace(/^\$/,"")}`,message:`${g}: ${d.message}`});else m instanceof SyntaxError?s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${m.message}`}):s.push({path:p,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${m instanceof Error?m.message:String(m)}`})}}if(e.discoveredArkRulesFiles)for(let l of[...e.discoveredArkRulesFiles].sort()){let u=jo(l);c.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(s.length>0)throw new xt(t,s);return{config:e.config,arkRules:bn(a),warnings:r}}i(Ko,"resolveEffectiveContract");function Hr(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}i(Hr,"omitLayerDescriptions");function vn(e){let{stewards:t,...n}=Hr(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(vn,"effectiveContractPolicyPayload");var Ml="INVARIANT_TESTS_PATH_MISSING",Fl="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",$l="INVARIANT_COVERAGE_ROOTS_MISSING",Hl="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 Vo(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i(Vo,"formatCoverageDiscards");function jl(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(jl,"isUnderCoverageRoot");function Kl(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Kl,"titleMatchesInvariant");function Vl(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(Vl,"symbolPresent");function Cn(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=Vo(s),c=Vo(s,!0),l=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,g=u.join(", "),f=[],m=[];for(let d of t){let A=[],b=d.coverage?.test!==!1,O=d.coverage?.symbol,k,I;if(!r&&b){let P;for(let ee of n){let T=e.fileContents[ee];if(!(!T||!Kl(T,d.id))){if(!p||jl(ee,u)){k=ee,I=p?!1:void 0;break}P??=ee}}k===void 0&&P!==void 0&&(k=P,I=!0),k!==void 0&&A.push("test-title")}O&&Vl(e.fileContents,O)&&A.push("symbol");let L=(d.coverage?.test===!0||!!O||d.coverage===void 0)&&A.length>0||d.coverage?.test===!1&&!O?!0:A.length>0,E=r&&b&&A.length===0;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:L&&!E,evidence:A,partial:E,description:d.description,...k!==void 0?{testEvidenceFile:k}:{},...I!==void 0?{outsideDeclaredRoots:I}:{},coverageRootsDeclared:p}),I===!0&&k!==void 0&&m.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${k}, which is outside the declared coverage roots (${g}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:k,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!L||E){let P=d.mode==="enforced"&&!E,ee=r||n.length===0?"never-had-tests":"tests-disappeared";m.push({ruleId:"INVARIANT_UNCOVERED",message:(E?o?`Invariant ${d.id} coverage cannot be proven (${l}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:ee==="tests-disappeared"?`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${d.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(E&&o?c:a),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:P?"error":"warning",failsStrict:P,kind:ee})}}return{coverage:f,violations:m,partial:f.some(d=>d.partial)}}i(Cn,"evaluateInvariantCoverage");function _n(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(_n,"canPromoteInvariant");function jr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(jr,"nonEmptyPathStrings");function Ul(e){return!e||typeof e!="object"?[]:[...jr(e.testGlobs),...jr(e.coverageRoots)]}i(Ul,"configuredInvariantTestsPaths");function Gl(e){return Ul(e).length>0}i(Gl,"hasConfiguredInvariantTestsPath");function Kr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(Kr,"catalogDemandsInvariantTestsPath");function Uo(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Kr(e.invariants);return e.adopted!==!0||!t?[]:Gl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Ml,message:Fl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(Uo,"collectMissingInvariantTestsPathFindings");function Bl(e){return!e||typeof e!="object"?[]:jr(e.coverageRoots)}i(Bl,"configuredCoverageRoots");function zl(e){return Bl(e).length>0}i(zl,"hasConfiguredCoverageRoots");function Vr(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(Vr,"catalogHasEnforcedInvariant");function Go(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Vr(e.invariants)?zl(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:$l,message:Hl,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(Go,"collectMissingCoverageRootsFindings");var xn="1.0";function w(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(w,"addFinding");function Q(e){return[...new Set(e??[])].sort()}i(Q,"sortedUnique");function me(e,t,n,r,o){let s=Q(n),a=Q(r),c=new Set(s),l=new Set(a),u=a.filter(g=>!c.has(g)),p=s.filter(g=>!l.has(g));u.length===0&&p.length===0||(u.length>0&&w(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),p.length>0&&w(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(me,"compareStringSets");function Tt(e,t,n,r,o,s,a){if(n===r)return;w(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(Tt,"compareBoolean");function On(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(On,"keyed");function Wl(e,t,n){let r=On(t,s=>s.name),o=On(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&w(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),c=o.values.get(s),l=`$.layers[${s}]`;if(!a&&c){w(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){w(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;me(e,`${l}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),me(e,`${l}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=dn(a),p=dn(c);me(e,`${l}.forbiddenGlobals`,u.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),me(e,`${l}.capabilities`,u.atoms,p.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Q(a.intentPrefixes).join("\0")!==Q(c.intentPrefixes).join("\0")&&w(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Q(a.intentPrefixes),after:Q(c.intentPrefixes)}),Tt(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Tt(e,`${l}.optional`,a.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Wl,"compareLayers");function ql(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=On(t,r),s=On(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&w(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let c=o.values.get(a),l=s.values.get(a),u=`$.rules[${a}]`;if(!c&&l){l.allowed===!1&&w(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:l});continue}if(c&&!l){c.allowed===!1&&w(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!l)continue;c.allowed!==l.allowed&&w(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:l.allowed});let p=c.peerIsolation===!0,g=l.peerIsolation===!0;if(p!==g){let f=c.from===c.to&&l.from===l.to;w(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:f?g?"strengthening":"weakening":"judgment-required",message:f?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:p,after:g})}Q(c.sliceFolders).join("\0")!==Q(l.sliceFolders).join("\0")&&w(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Q(c.sliceFolders),after:Q(l.sliceFolders)}),!(!p&&!g)&&(zo(e,`${u}.sharedRoots`,"shared-roots",Q(c.sharedRoots),Q(l.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),zo(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Q((c.allowedCrossSlice??[]).map(Bo)),Q((l.allowedCrossSlice??[]).map(Bo)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(ql,"compareRules");function Bo(e){return JSON.stringify([e.from,e.to])}i(Bo,"crossSliceKey");function zo(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let c=o.filter(p=>!r.includes(p)),l=r.filter(p=>!o.includes(p)),u=c.length>0&&l.length>0;w(e,{kind:u?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":c.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:c.length>0?s:a,before:r,after:o})}i(zo,"compareDeclaredExceptions");function Yl(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,c=o[s]??0;a!==c&&w(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Tt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Yl,"compareSafety");function Ur(e){return e.mode==="enforced"?"enforced":"advisory"}i(Ur,"arkRunMode");function Gr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Gr,"arkOrderMode");function Jl(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Gr(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=Gr(r),c=Gr(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Jl,"compareArkOrder");function Xl(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Ur(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=Ur(r),c=Ur(o);if(a!==c){let l=a==="advisory"&&c==="enforced";w(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:c})}me(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),me(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Tt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Xl,"compareArkRun");function Zl(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(Zl,"overallClassification");function Wo(e,t){return`${e}::${t}`}i(Wo,"ruleKey");function qo(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Wo(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Wo(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(qo,"indexEffectiveRules");function Ql(e,t,n,r,o,s){let a=new Map((s??[]).map(f=>[f.invariantId,f])),c=t.arkRules??{},l=n.arkRules??{},u=[...new Set([...Object.keys(c),...Object.keys(l)])].sort();for(let f of u){let m=c[f],d=l[f],A=`$.arkRules[${f}]`;if(m===void 0&&d!==void 0){w(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:d});continue}if(m!==void 0&&d===void 0){w(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:m});continue}m!==d&&w(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:m,after:d})}let p=qo(r),g=qo(o);for(let f of[...new Set([...p.structure.keys(),...g.structure.keys()])].sort()){let m=p.structure.get(f),d=g.structure.get(f),A=`$.arkRules.structure[${f}]`;if(!m&&d){w(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${m.id} was removed.`,before:m});continue}if(!(!m||!d)){if(m.mode!==d.mode){let b=m.mode==="advisory"&&d.mode==="enforced";w(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}m.sensor!==d.sensor&&w(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:m.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...g.invariants.keys()])].sort()){let m=p.invariants.get(f),d=g.invariants.get(f),A=`$.arkRules.invariants[${f}]`;if(!m&&d){w(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(m&&!d){w(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${m.id} was removed.`,before:m});continue}if(!(!m||!d)&&m.mode!==d.mode)if(m.mode==="advisory"&&d.mode==="enforced"){let O=a?.get(d.id),k=_n(O);k.ok?w(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:m.mode,after:d.mode}):w(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${k.reason}`,before:m.mode,after:d.mode})}else w(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:m.mode,after:d.mode})}}i(Ql,"compareArkRules");function Tn(e,t,n){let r=[];me(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),me(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),me(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Tt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let c=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";w(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:c,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&w(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Wl(r,e.layers,t.layers),ql(r,e.rules,t.rules),Yl(r,e,t),Ql(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Xl(r,e,t),Jl(r,e,t),r.sort((c,l)=>c.path.localeCompare(l.path)||c.id.localeCompare(l.id)),{schemaVersion:xn,classification:Zl(r),findings:r}}i(Tn,"classifyArkPolicyDelta");function Nn(e,t){if(!e||e.schemaVersion!==xn||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=Q(e.findingIds),r=Q(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(Nn,"policyDeltaAcknowledgementMatches");function Ke(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Ke,"normalizePath");function Yo(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Yo,"isIdentifierStart");function wn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(wn,"isIdentifierCharacter");function de(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(de,"skipWhitespace");function Nt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Nt,"readString");function ue(e,t,n){return e.startsWith(t,n)&&!wn(e[n-1])&&!wn(e[n+t.length])}i(ue,"isWordAt");function Jo(e,t){let n=de(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=de(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ue(e,"type",n))return!1;let o=de(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ue(e,"as",o)||!Yo(e[o]))return!1;for(n=o;n<e.length&&wn(e[n]);)n+=1;if(n=de(e,n),ue(e,"as",n)){if(n=de(e,n+2),!Yo(e[n]))return!1;for(;n<e.length&&wn(e[n]);)n+=1}r=!0}return!1}i(Jo,"bracedNamedBindingsAreTypeOnly");function ec(e,t){if(t=de(e,t+6),e[t]==="(")return Nt(e,de(e,t+1));let n=!1;if(ue(e,"type",t)){let o=de(e,t+4);e[o]!==","&&!ue(e,"from",o)&&(n=!0)}else Jo(e,t)&&(n=!0);let r=Xo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(ec,"specifierAfterImport");function tc(e,t){t=t+6;let n=de(e,t),r=!1;if(ue(e,"type",n)){let s=de(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Jo(e,n)&&(r=!0);let o=Xo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(tc,"specifierAfterExport");function Xo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ue(e,"from",t))return Nt(e,de(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Nt(e,t);if(t>0&&(ue(e,"import",t)||ue(e,"export",t)))return}}i(Xo,"specifierInStaticStatement");function nc(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i(nc,"skipTemplateLiteral");function rc(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=de(e,t+7);if(e[r]!=="(")return;r=de(e,r+1);let o=Nt(e,r);return o?{...o,requireCall:!0}:void 0}i(rc,"specifierAfterRequire");function sc(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
9
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=nc(e,n);continue}if(r==="'"||r==='"'){let s=Nt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&ue(e,"import",n)?ec(e,n):r==="e"&&ue(e,"export",n)?tc(e,n):r==="r"&&ue(e,"require",n)?rc(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}i(sc,"moduleSpecifiers");function Zo(e,t){let n=[],r=[];for(let o of sc(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=ft(s);if(!u)continue;let p=e.content.slice(0,o.offset).split(`
|
|
10
|
+
`).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:p,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
|
|
11
|
+
`).length,c={kind:"import",file:e.path,line:a,excerpt:o.excerpt},l=oc(e.path,s,t);n.push({from:e.path,specifier:s,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:c})}return{edges:n,capabilityUses:r}}i(Zo,"moduleFactsFor");function oc(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(oc,"resolveSpecifier");function Qo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=pn(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(Qo,"violationsFor");var ac={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function ic(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(ic,"hasActiveArkRules");function lc(e,t){return ic(e,t)?J($(vn({config:e,arkRules:t,warnings:[]}))):J($(Hr(e)))}i(lc,"policyHashFor");function wt(e,t,n){let r=typeof e=="string"?An(e,t):Et(e,t),o=n?.arkRules??xe();return{...r,arkRules:o,policyHash:lc(r.config,o)}}i(wt,"loadContract");function Br(e){let t=wt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=wt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Tn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),s=o.length>0,a=s&&Nn(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(Br,"analyzePolicyDelta");function et(e){let t=e.files.map(g=>{let f=Ke(g.path);return{path:f,content:g.content,contentHash:J(g.content),layer:fe(f,e.contract.config.layers)??null}}).sort((g,f)=>g.path.localeCompare(f.path)),n=new Map(t.map(g=>[g.path,g])),r=[],o=[];for(let g of t){let f=Zo(g,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=Qo(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),c=new Map(e.contract.config.layers.map(g=>[g.name,new Set(We(g))]));for(let g of o){let f=n.get(g.file)?.layer;if(!f)continue;let m=a.get(f),d=_e(g.symbol,m?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${g.symbol}" because it is the import form of forbidden global "${d}".`,symbol:g.symbol,evidence:g.evidence});continue}c.get(f)?.has(g.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let l=t.length===0?"complete":"partial",u=l==="complete"?[]:[{...ac}],p={schemaVersion:En,policyHash:e.contract.policyHash,compilerOptionsHash:J($(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:l,completenessReasons:u,valid:l==="complete"&&s.length===0,ir:p}}i(et,"analyzeProject");function Pt(e){let t=new Map(e.files.map(n=>[Ke(n.path),n]));for(let n of e.changes){let r=Ke(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return et({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Pt,"analyzeChange");function zr(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(zr,"explainViolation");function Pn(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],c=i(l=>{n.set(l,t),r.set(l,t),t+=1,s.push(l),o.add(l);for(let g of[...e.get(l)??[]].sort())e.has(g)&&(n.has(g)?o.has(g)&&r.set(l,Math.min(r.get(l)??0,n.get(g)??0)):(c(g),r.set(l,Math.min(r.get(l)??0,r.get(g)??0))));if(r.get(l)!==n.get(l))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==l);u.length>1&&a.push(u.sort())},"connect");for(let l of[...e.keys()].sort())n.has(l)||c(l);return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(Pn,"detectArchitectureCycles");function Ve(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Le(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let c=a.rule,l=!!c.peerIsolation,u=!l&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=l?qe(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,g=c.message?p?`${c.message} (${p})`:c.message:p?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${p}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...l?{peerIsolation:!0}:{},message:u?`${g} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:g,...u?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Pn(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(Ve,"evaluateArchitectureGraph");function ea(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}i(ea,"structureFreezeTarget");var cc=["no-anemic-model"],aa=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Yr=new RegExp(`\\b(${aa.join("|")})\\b`),ia="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Jr=new RegExp(`\\bthis\\.${ia}\\.push\\s*\\(`),dc=new RegExp(`^this\\.${ia}\\s*=\\s*\\[\\s*\\]`),uc=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,pc=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,la="truncatedUntil";function Xr(){return`${aa.join(", ")}, or events-array .push(`}i(Xr,"expectedDomainInvariantWordsPhrase");function fc(e){return Yr.test(e)||Jr.test(e)}i(fc,"referencesGuardOrPublish");function Zr(e,t,n){let r=e.slice(t);if(dc.test(r))return!0;if(!uc.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let o=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(o,t+200))}i(Zr,"isIdiomaticEventsReset");function mc(e,t){let n=new RegExp(pc.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!Zr(t,r.index,e))return!0;return!1}i(mc,"methodAssignsThis");function gc(e,t){return t==null||Object.defineProperty(e,la,{value:t,enumerable:!1,configurable:!0}),e}i(gc,"attachShapeTruncation");function qr(e){let t=Object.getOwnPropertyDescriptor(e,la)?.value;return typeof t=="number"?t:void 0}i(qr,"shapeTruncatedUntil");function yc(e){let t=qr(e);return t==null?"":` shape analysed until character ${t}`}i(yc,"shapeTruncationSuffix");function ta(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(ta,"escapeGlobLiteral");function hc(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=ta(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ta(o)}return new RegExp(`^${n}$`)}i(hc,"globToRegExp");function tt(e,t){return!t||t.length===0?!0:t.some(n=>hc(n).test(e))}i(tt,"matchesAppliesTo");function ca(e){return cc.includes(e)}i(ca,"isTier2");function da(e){return e.mode==="enforced"&&!ca(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(da,"severityFor");function Te(e,t,n,r=1){let{severity:o,failsStrict:s}=da(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(Te,"baseViolation");function Dn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Dn,"isInRuleLayer");function Mn(e,t,n){return t.filter(r=>!(!r.exported||!tt(r.file,e.appliesTo)||!Dn(r.file,e,n)))}i(Mn,"shapesForRule");function Ac(e,t,n){let r=[];for(let o of Mn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Te(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Ac,"evaluateAggregatePrivateState");function Rc(e,t,n){let r=[];for(let o of Mn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Te(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Rc,"evaluateAlwaysValidFactory");function kc(e,t,n){let r=[],o=Xr();for(let s of Mn(e,t,n)){let a=yc(s);qr(s)!=null&&r.push(Te(e,s.file,`Exported class ${s.className} shape analysed until character ${qr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Te(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(kc,"evaluateDomainEventOnMutation");function Ec(e,t){let n=[];for(let r of t.files)tt(r,e.appliesTo)&&Dn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Te(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Ec,"evaluateOrchestrationOnly");function Sc(e,t){let n=[];for(let r of t.files)tt(r,e.appliesTo)&&Dn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Te(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Sc,"evaluateThinAdapter");function Ic(e,t){let n=[];for(let r of t.files)tt(r,e.appliesTo)&&Dn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Te(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(Ic,"evaluateWritesViaAggregate");function bc(e,t,n){let r=[];for(let o of Mn(e,t,n))if(o.dataOnly===!0){let s=Te(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(bc,"evaluateNoAnemicModel");function Fn(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Ac(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Rc(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...kc(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Ec(n,e));break;case"thin-adapter":t.push(...Sc(n,e));break;case"writes-via-aggregate":t.push(...Ic(n,e));break;case"no-anemic-model":t.push(...bc(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(Fn,"evaluateArkRuleSensors");function $n(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>tt(l,o.appliesTo)))continue;let{severity:a,failsStrict:c}=da(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:c})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>tt(c,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i($n,"collectEmptyAppliesToFindings");var na=64;function vc(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(vc,"stripTrailingDots");function Cc(e){let t=e.trim(),n=t.length>na?t.slice(0,na):t;return vc(n)}i(Cc,"normalizeIntentPrefix");function _c(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(_c,"layerNameLooksDomain");function Oc(e){return e.some(t=>{let n=Cc(t);return n==="Domain"||n.startsWith("Domain.")})}i(Oc,"ownsDomainIntent");function xc(e,t=[]){return _c(e)||Oc(t)}i(xc,"isDomainRoleLayerName");function ua(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(l=>xc(l.name,l.intentPrefixes??[])).map(l=>l.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(l=>{let u=typeof l.layer=="string"?l.layer:"";return u.length>0&&n.has(u)}))return[];if((e.arkRules.invariants??[]).filter(l=>n.has(l.provenance.layer)).length>0)return[];let s=t.find(l=>e.arkRules.byLayer?.[l])??t[0],a=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,c=(e.arkRules.structure??[]).some(l=>l.mode==="enforced"&&n.has(l.provenance.layer)&&!ca(l.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${a}.`,file:a,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:a,severity:c?"error":"warning",sensor:"invariant-coverage",failsStrict:c}]}i(ua,"collectEmptyInvariantCatalogFindings");var ra=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,sa=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Tc=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function Nc(e){return e==="PersistenceAdapters"}i(Nc,"isPersistenceDriverLayer");function wc(e,t){if(ra.test(e)||sa.test(e))return!0;if(!t)return!1;for(let n of t){if(Nc(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(ra.test(o)||sa.test(o))return!0}return!1}i(wc,"sourceImportsPersistenceDriver");var Pc=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,Lc=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Dc=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Mc=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Qr(e,t,n){if(!t)return null;let r=wc(t,n),o=r&&Tc.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Dc.source,"g"))??[],a=t.match(new RegExp(Mc.source,"g"))??[],c=(t.match(/\bif\s*\(/g)??[]).length,l=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&c+l>=6,p=Pc.test(t)||Lc.test(t),g=s.length>=1||a.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=r&&g||p&&g||r&&f&&(c>=4||s.length>=1)||p&&r;return!u&&!m&&!o?null:{...u?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(Qr,"deriveArkRuleFileHints");function Hn(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=Qr(r,o,t?.[s]);a&&(n[s]=a)}return n}i(Hn,"buildArkRuleFileHints");var Fc=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),$c=new Set(["if","match","when"]);function Ln(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
|
|
12
|
+
`,t);return r===-1?e.length:r}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}if(n==="'"||n==='"'||n==="`"){let r=t+1;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]===n)return r+1;r+=1}return e.length}return t}i(Ln,"skipStringOrComment");function Lt(e,t){let n=t;for(;n<e.length;){if(/\s/.test(e[n])){n+=1;continue}if(e[n]==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=Ln(e,n);continue}break}return n}i(Lt,"skipWsAndComments");function oa(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(oa,"readIdent");function Wr(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let a=Ln(e,s);if(a!==s){s=a;continue}let c=e[s];c===n?o+=1:c===r&&(o-=1),s+=1}return o===0?s:null}i(Wr,"skipBalanced");function Hc(e){let t=[],n=0,r;for(;n<e.length&&(n=Lt(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=oa(e,s);if(!p||!Fc.has(p.ident))break;o.push(p.ident),s=Lt(e,p.end)}let a=oa(e,s);if(!a){n+=1;continue}if(s=Lt(e,a.end),e[s]==="<"){let p=Wr(e,s,"<",">");if(p==null){r=e.length;break}s=Lt(e,p)}if(e[s]==="("){let p=Wr(e,s,"(",")");if(p==null){r=e.length;break}if(s=Lt(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let g=Ln(e,s);if(g!==s){s=g;continue}s+=1}if(e[s]==="{"){let g=Wr(e,s,"{","}");if(g==null){r=e.length;break}t.push({name:a.ident,modifiers:o,kind:"method",body:e.slice(s+1,g-1)}),n=g;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let c=0,l=0,u=0;for(;s<e.length;){let p=Ln(e,s);if(p!==s){s=p;continue}let g=e[s];if(g==="{")c+=1;else if(g==="}"){if(c===0)break;c-=1}else if(g==="(")l+=1;else if(g===")")l-=1;else if(g==="[")u+=1;else if(g==="]")u-=1;else if(g===";"&&c===0&&l===0&&u===0){s+=1;break}s+=1}t.push({name:a.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}i(Hc,"scanClassMembers");function pa(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,o;for(;(o=r.exec(t))!==null;){let s=o[1],a=o.index+o[0].length,c=1,l=a;for(;l<t.length&&c>0;){let E=t[l];E==="{"?c+=1:E==="}"&&(c-=1),l+=1}let u=t.slice(a,l-1),p=c>0,g=Hc(u),f=p?t.length:g.truncatedAt==null?void 0:a+g.truncatedAt,m=g.members.filter(E=>!(E.kind!=="field"||E.name==="constructor"||E.modifiers.includes("private")||E.modifiers.includes("protected")||E.modifiers.includes("readonly")||E.modifiers.includes("static")||E.modifiers.includes("get")||E.modifiers.includes("set"))),d=m.length>0,A=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),b=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),O=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!b,k=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),I=[];for(let E of g.members)E.kind==="method"&&E.name!=="constructor"&&(E.modifiers.includes("static")||E.modifiers.includes("get")||E.modifiers.includes("set")||$c.has(E.name)||mc(E.name,E.body)&&I.push({name:E.name,referencesGuardOrPublish:fc(E.body)}));let L=g.members.filter(E=>E.kind==="method").length<=1&&m.length>=2&&d;n.push(gc({file:e,className:s,exported:!0,hasPublicMutableFields:d,hasPublicSetters:A,hasPublicConstructor:O,hasStaticFactory:k,mutatingMethods:[...I],dataOnly:L},f))}return n}i(pa,"extractClassShapesFromSource");var fa=50;function jn(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(jn,"normalizeExtraMergeTeethClassification");function ge(e){let t=jn(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(ge,"extraMergeTeethAllowed");function Kn(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Kn,"classifyResolvedLayerCoverage");function Vn(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Vn,"isArkRunRuleId");function es(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(es,"isArkOrderRuleId");function ts(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")||t.startsWith("ARKORDER_")}i(ts,"isExtraPlaneFinding");function ma(e,t={}){if(!Array.isArray(e)||ge(t))return e;for(let n of e)ts(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(ma,"demoteExtraPlaneTeethUnderClassificationFloor");var ns="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = the few big product choices (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function he(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(he,"countOrZero");function Dt(e={}){let t=jn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,o=n!=null||r!=null,s=ge(t),a=e.arkRules,c=he(a?.structureEnforced),l=he(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?he(a.structureAdvisory):Math.max(0,l-c),p=he(a?.invariantEnforced),g=he(a?.invariantTotal),f=typeof a?.invariantAdvisory=="number"?he(a.invariantAdvisory):Math.max(0,g-p),m=c>0||p>0,d=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=he(e.arkRun?.residualCount),O=d&&A==="enforced",k=O&&s,I=e.arkOrder?.present===!0,C=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,L=he(e.arkOrder?.residualCount),E=I&&C==="enforced",P=E&&s,ee=m||O||E,T=ee&&s,V=ee&&o&&!s,D;if(T){let X=[];m&&X.push("enforced structure/invariant findings"),O&&X.push("enforced ArkRun skip findings"),E&&X.push("enforced ArkOrder skip findings"),D=`Layer graph failures plus ${X.join(" and ")} (advisory extras never fail merge alone).`}else if(V)D=`Layer graph only \u2014 enforced ${[m?"ArkRules structure/invariant":null,O?"ArkRun":null,E?"ArkOrder":null].filter(ve=>!!ve).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`;else{let X=d?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",ve=I?C==="advisory"?" Advisory ArkOrder never merge-blocks.":" ArkOrder extra is present but does not arm merge teeth.":" Absence of arkOrder is silent.";D="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+X+ve}let se={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:l,enforced:c,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:g,enforced:p,advisory:f,covered:he(a?.covered),uncovered:he(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:d,mode:A,residualCount:b,extraMergeTeeth:k,note:d?A==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},arkOrder:{role:"pattern-slaving",present:I,mode:C,residualCount:L,extraMergeTeeth:P,note:I?C==="enforced"?"Enforced ArkOrder arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkOrder never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkOrder is silent \u2014 Layers verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:T,dualPlaneStamp:ns,failMergeWhen:D};return o&&(se.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:s}),se}i(Dt,"composeMergePlanesHonesty");var ss=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],ya=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],jc=new Set(ss),Kc=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Vc=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function nt(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(nt,"isArkRunKernelModuleSpecifier");var os=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],rs=new Set(os);function Gn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(rs.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(rs.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:rs.has(e.slice(0,r))}i(Gn,"isArkRunTransportBypassSpecifier");function Un(e){if(jc.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}i(Un,"arkRunKernelCallKind");function Ft(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(Ft,"lineAt");function $t(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i($t,"stripCommentsPreservingLines");function Uc(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let o=r[2]??"";return o.length>0?o:void 0}i(Uc,"firstStringLiteralArg");function ga(e,t,n){let r=Math.max(0,t-n.length-8),o=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(o)}i(ga,"keywordBefore");function Bn(e,t){let n=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;)r[1]||t(r[2]??"",r[3]??"")}i(Bn,"parseValueImportClause");function Gc(e,t){Bn($t(e),t)}i(Gc,"forEachArkRunValueImportClause");function zn(e,t){let n=$t(t),r=[],o=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;(s=o.exec(n))!==null;){let c=s[3]??"";if(!c)continue;let l=s[0]??"";r.push({from:e,specifier:c,kind:/^\s*export/.test(l)?"export":"import",typeOnly:!!s[1],line:Ft(t,s.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(s=a.exec(n))!==null;){let c=s[1]??"";if(!c)continue;let l=s[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:c,kind:l,typeOnly:!1,line:Ft(t,s.index),resolution:"resolved-external"})}return r}i(zn,"extractArkRunValueImportDependenciesFromSource");function Wn(e){let t=[];return Gc(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let o of r[1].split(",")){let s=o.trim();if(!s||s.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(s),c=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)?.[1],l=a?.[1]??c;c&&l&&/^[A-Z]/.test(l)&&t.push(c,l)}}),Mt(t)}i(Wn,"extractArkRunImportedConstructorNamesFromSource");function Bc(e){let t=new Map,n=new Set;return Bn(e,(r,o)=>{if(!nt(o))return;let s=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);s?.[1]&&n.add(s[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let c=/\{([^}]*)\}/.exec(r);if(c?.[1])for(let l of c[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let p=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(p){t.set(p[2],p[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:n}}i(Bc,"collectKernelImportBindings");function zc(e,t){let n=new Set(t);return Bn(e,(r,o)=>{let s=/\{([^}]*)\}/.exec(r);if(s?.[1])for(let a of s[1].split(",")){let c=a.trim();if(!c||c.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(c),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(c)?.[1],p=l?.[1]??u;!u||!p||!/^[A-Z]/.test(p)||(nt(o)||t.has(p)||t.has(u))&&(n.add(u),n.add(p))}}),n}i(zc,"collectImportedConstructors");function Wc(e,t){let n;return Bn(e,(r,o)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=o)}),n}i(Wc,"importedFromForName");function qn(e,t){let n=$t(t),r=Bc(n),o=[],s=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=s.exec(n))!==null;){let c=a[1],l=a.index;if(ga(n,l,"function")||ga(n,l,"class"))continue;let p=n.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=r.named.get(c)??c,f=Un(g)??Un(c);if(!f)continue;let m=r.named.has(c)||p!==void 0&&r.namespaces.has(p);if(f!=="factory"&&(!m&&p===void 0||p&&Vc.has(p)&&!m))continue;let d=Uc(n,l+a[0].length);o.push({file:e,line:Ft(t,l),kind:f,callee:c,viaImport:m,...p?{receiver:p}:{},...d?{nameLiteral:d}:{}})}return o}i(qn,"extractArkRunKernelCallsFromSource");function Yn(e,t,n){let r=$t(t),o=zc(r,n),s=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,c;for(;(c=a.exec(r))!==null;){let l=c[1];if(Kc.has(l)||!o.has(l))continue;let u=Wc(r,l);s.push({file:e,line:Ft(t,c.index),typeName:l,...u?{importedFrom:u}:{}})}return s}i(Yn,"extractArkRunManagedNewsFromSource");function qc(e,t){let n=0,r;for(let o=t;o<e.length;o+=1){let s=e[o];if(r){if(s==="\\"){o+=1;continue}s===r&&(r=void 0);continue}if(s==="'"||s==='"'||s==="`"){r=s;continue}if(s==="[")n+=1;else if(s==="]"&&(n-=1,n===0))return o}return-1}i(qc,"matchingBracketEnd");function Yc(e,t,n){let r=e.slice(t+1,n),o=[],s=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=s.exec(r))!==null;){let c=a[2]??"";c.length>0&&o.push(c)}return o}i(Yc,"stringLiteralsInList");function Mt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Mt,"uniqueSorted");function ha(e,t){let n=$t(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,o=[],s=[],a=[],c=[],l,u;for(;(u=r.exec(n))!==null;){let p=n.slice(u.index+u[0].length),g=/^\s*\[/.exec(p);if(!g)continue;let f=u.index+u[0].length+(g[0].length-1),m=qc(n,f);if(m<0)continue;let d=Yc(n,f,m);if(d.length===0)continue;l===void 0&&(l=u.index);let A=u[1];A==="uses"?o.push(...d):A==="reactsTo"?s.push(...d):A==="raises"?a.push(...d):c.push(...d)}return l===void 0?[]:[{file:e,line:Ft(t,l),uses:Mt(o),reactsTo:Mt(s),raises:Mt(a),sends:Mt(c)}]}i(ha,"extractArkRunDeclarationsFromSource");var ka=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Jc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Xc=new Set(Jc);function Zc(e){return Xc.has(e)}i(Zc,"isArkRunEditorSensor");var Jn={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},as="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ea(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(Ea,"isDomainRoleLayer");function Qc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(Qc,"compareFindings");function be(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Jn[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ye({ruleId:Jn[t],fromLayer:s?.fromLayer,target:s?.target})}}i(be,"finding");function ed(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(ed,"bagForFile");function Aa(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Aa,"emitKinds");function Ra(e){return e==="subscribe"||e==="register-handler"}i(Ra,"handleKinds");function td(e){return e==="resolve"||e==="resolve-singleton"}i(td,"dependKinds");function nd(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(be(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let c=s.get(a.matchedRoot)??[];c.push(a),s.set(a.matchedRoot,c)}for(let a of o){let c=[...s.get(a)??[]].sort((u,p)=>u.file.localeCompare(p.file));if(c.length===0){r.push(be(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(c.some(u=>u.hasKernelFactory))continue;let l=c[0];r.push(be(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(nd,"evaluateMissingRoot");function rd(e,t,n,r,o){let s=new Map(t.map(c=>[c.name,c.intentPrefixes??[]])),a=[];for(let c of n){let l=c.specifier;if(!l||!nt(l))continue;let u=r(c.from);u&&Ea(u,s.get(u)??[])&&a.push(be(e,"arkrun-kernel-in-domain",c.from,c.line,`${u} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:u,target:l},o))}return a}i(rd,"evaluateKernelInDomain");function sd(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let c=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),l=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(l.has(p.file))continue;let g=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let f=o(p.file);!f||!a.has(f)||Ea(f,c.get(f)??[])||u.push(be(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}i(sd,"evaluateDirectNew");function od(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let c=new Set(e.managedLayers);if(c.size===0)return{findings:s,completenessReasons:a};for(let l of t){if(!Aa(l.kind)&&!Ra(l.kind)&&!td(l.kind))continue;let u=r(l.file);if(!u||!c.has(u))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:as,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let p=ed(n,l.file);if(Aa(l.kind)){if(p.raises.has(l.nameLiteral)||p.sends.has(l.nameLiteral))continue;s.push(be(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:l.nameLiteral},o));continue}if(Ra(l.kind)){if(p.reactsTo.has(l.nameLiteral))continue;s.push(be(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:l.nameLiteral},o));continue}p.uses.has(l.nameLiteral)||s.push(be(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:l.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(od,"evaluateUndeclared");function ad(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let c=a.specifier;if(!c||!Gn(c))continue;let l=n(a.from);!l||!o.has(l)||s.push(be(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(c)}; use the ArkRun kernel transport.`,{fromLayer:l,target:c},r))}return s}i(ad,"evaluateTransportBypass");function Ht(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=ge(e.classification),r=od(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...nd(t,e.compositionRootHits,n),...rd(t,e.layers,e.dependencies,e.layerForFile,n),...sd(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...ad(t,e.dependencies,e.layerForFile,n)].sort(Qc),s=[...r.completenessReasons].sort((a,c)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,u=`${c.code}\0${c.file??""}\0${c.message}`;return l<u?-1:l>u?1:0});return{findings:o,completenessReasons:s}}i(Ht,"evaluateArkRunSensors");function is(e){return{findings:Ht(e).findings.filter(n=>Zc(n.sensor)),completenessReasons:[]}}i(is,"evaluateArkRunEditorSensors");function id(e,t){if(e===t)return!0;let n=e.indexOf("*");if(n<0)return!1;let r=e.slice(0,n).replace(/\/$/,"");return r.length>0&&(t===r||t.startsWith(`${r}/`))}i(id,"fileMatchesCompositionRoot");function ld(e,t,n){let r=qn(t,n).some(a=>a.kind==="factory"),o=[],s=e.kernelRoots??e.compositionRoots;for(let a of s)id(a,t)&&o.push({file:t,matchedRoot:a,hasKernelFactory:r});return o}i(ld,"compositionRootHitsForSource");function Sa(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(Wn(e.source));return is({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Yn(e.file,e.source,n),compositionRootHits:ld(t,e.file,e.source),declarations:[],dependencies:zn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Sa,"evaluateArkRunEditorSensorsFromSource");function Ia(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Ia,"isArkOrderModuleSpecifier");var ba=new Map;function va(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(va,"escapeAppliesToLiteral");function cd(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(cd,"normalizeAppliesToGlob");function dd(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(dd,"appliesToBracesBalanced");function ud(e){let t=ba.get(e);if(t)return t;let n=cd(e),r=dd(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=va(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=va(l)}let a=new RegExp(`^${o}$`);return ba.set(e,a),a}i(ud,"globToRegExp");var Ca=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],Xn={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function pd(e,t){return!t||t.length===0?!0:t.some(n=>ud(n).test(e))}i(pd,"matchesArkOrderAppliesTo");function fd(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(fd,"isDomainRoleLayer");function Ne(e,t,n,r,o,s,a){let c=e.mode==="enforced"&&a;return{ruleId:Xn[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:c?"error":"warning",failsStrict:c,nextAction:ye({ruleId:Xn[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Ne,"finding");function Zn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=ge(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Ne(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let l=new Map;for(let u of e.planeRootHits){let p=l.get(u.matchedRoot)??[];p.push(u),l.set(u.matchedRoot,p)}for(let u of o){let p=l.get(u)??[];if(p.length===0){r.push(Ne(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}p.some(g=>g.hasPlaneFactory)||r.push(Ne(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(l=>[l.name,l.intentPrefixes??[]]));for(let l of e.dependencies){let u=l.specifier;if(!u||!Ia(u))continue;let p=e.layerForFile(l.from);p&&fd(p,s.get(p)??[])&&r.push(Ne(t,"arkorder-kernel-in-domain",l.from,l.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let l of e.genericUpdates)r.push(Ne(t,"arkorder-generic-update",l.file,l.line,`Generic ${l.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:l.method},n));let a=t.xiKeys??[];for(let l of e.releaseKeyCounts??[])l.keyCount<=t.maxXiKeys||r.push(Ne(t,"arkorder-too-many-params",l.file,l.line,`release() freezes ${l.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(l.keyCount)},n));for(let l of e.ingestWritesXi??[])r.push(Ne(t,"arkorder-ingest-writes-xi",l.file,l.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let c=new Set(t.managedLayers);for(let l of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(l.file);!u||!c.has(u)||pd(l.file,t.appliesTo)&&r.push(Ne(t,"arkorder-xi-field-write",l.file,l.line,`This file writes ${JSON.stringify(l.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:l.key},n))}return r.sort((l,u)=>l.file.localeCompare(u.file)||l.ruleId.localeCompare(u.ruleId)||l.line-u.line),{findings:r,completenessReasons:[]}}i(Zn,"evaluateArkOrderSensors");function ne(e,t,n={}){return{ruleId:e,message:t,...n}}i(ne,"configWarning");function jt(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(ne("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(ne("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let A=t.safety[d];A!==void 0&&(!Number.isInteger(A)||A<0)&&s.push(ne("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],l=new Set([...a.map(d=>d.name).filter(Boolean),...c.map(d=>d.name).filter(d=>!!d)]);a.length===0&&s.push(ne("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of a){if(!d.name){s.push(ne("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="string"))&&s.push(ne("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let A=Array.isArray(d.patterns)?d.patterns:[];if(A.length===0){s.push(ne("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let b of A){let O;try{O=Re(b)}catch(I){s.push(ne("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${I instanceof Error?I.message:String(I)}`,{layer:d.name,pattern:b}));continue}let k=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(I=>O.test(I))&&!k&&s.push(ne("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of p)s.push(ne("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(l.size>0)for(let d of n??[])d.from&&!l.has(d.from)&&s.push(ne("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!l.has(d.to)&&s.push(ne("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let g=new Set;if(a.length>1)for(let d of r){let A=-1,b=[];for(let O of a)for(let k of O.patterns??[]){if(!Re(k).test(d))continue;let I=Sr(k,d);I>A?(A=I,b=[O.name]):I===A&&!b.includes(O.name)&&b.push(O.name)}b.length>1&&g.add([...b].sort().join(" + "))}g.size>0&&s.push(ne("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let f=r.filter(d=>!fe(d,a));f.length>0&&s.push(ne("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));let m=Oo(t);if(m.length>0){let d=m[0]??"this layer";s.push(ne("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:m,nextAction:xo(d)}))}return s}i(jt,"collectAnalysisConfigWarnings");function _a(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:ea({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}i(_a,"toArkRuleEngineViolation");function md(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(md,"arkRulesMapIsOn");function Oa(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}i(Oa,"arkRuleFindingNextAction");function gd(e,t){return t.some(n=>{try{return Re(n).test(e)}catch{return!1}})}i(gd,"matchesAny");function yd(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:b})=>({file:A,line:b})),c=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:b})=>({file:A,line:b})),l=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!gd(A.file,s)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(A=>A.kind==="in-memory-store").map(A=>({file:A.file,line:A.line,store:A.symbol??"in-memory store"})),p=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(A=>A.peerIsolation===!1||A.allowed===!1&&!!A.from&&A.from===A.to&&A.peerIsolation!==!0).map(A=>({from:A.from,to:A.to})),g={tsSuppressions:a,anyCasts:c,nonLiteralDynamicImports:l,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],m=l.filter(A=>A.kind==="import");if(m.length>0){let A=m[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=l.filter(A=>A.kind==="require");if(d.length>0){let A=d[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let A=a[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(c.length>o){let A=c[0];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${c.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let A=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:g,warnings:f}}i(yd,"evaluateSafety");function hd(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(hd,"ambientForbiddenGlobal");function xa(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Or(e,n.length>0?n:_r.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(xa,"intentLayer");function Ad(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!hd(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let c=o.get(a),l=c?.forbiddenGlobals??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&mt(s.symbol,l))){if(s.source==="import-based"){let p=_e(s.symbol,l);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}We(c).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let l of gt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:l.ruleId,file:s.file,line:s.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!s.sourceIntent)continue;let c=xa(s.sourceIntent,e.contract);!c||c===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${c}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let c=xa(s.intent,e.contract);if(!c)continue;let l=Le(e.contract.config.rules,a,c,{fromPath:s.file,layers:e.contract.config.layers});if(!l)continue;let u=l.rule.peerIsolation?qe(l.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:l.fromSlice,toSlice:l.toSlice}):void 0,p=`${a} must not reference ${c} intent ${s.intent}.`,g=u&&l.peerIsolationReason!=="cross-slice"?`${p} ${u}`:l.rule.message?u?`${l.rule.message} (${u})`:l.rule.message:p;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:c,target:s.intent,...l.rule.peerIsolation?{peerIsolation:!0}:{},message:g})}return r}i(Ad,"contentViolations");function Rd(e){let{facts:t}=e,n=Qe(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((h,oe)=>{let it=`${h.code}\0${h.file??""}\0${h.message}`,lt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return it<lt?-1:it>lt?1:0}),a=t.files.map(h=>({...h,layer:fe(h.path,e.contract.config.layers)??null})),c=new Map(a.map(h=>[h.path,h.layer])),l=t.dependencies.map(h=>{let oe=h.target?c.get(h.target)??fe(h.target,e.contract.config.layers):void 0;return{from:h.from,fromLayer:c.get(h.from)??null,...h.resolution==="resolved-project"&&h.target?{to:h.target,...oe?{toLayer:oe}:{}}:{},line:h.line,kind:h.kind,typeOnly:h.typeOnly,...h.targetTypeOnlyExports?{targetTypeOnlyExports:h.targetTypeOnlyExports}:{},...h.sourcePureTypeModule?{sourcePureTypeModule:h.sourcePureTypeModule}:{},...h.namedBindingsTypeOnly?{namedBindingsTypeOnly:h.namedBindingsTypeOnly}:{},...h.portProofEligible?{portProofEligible:h.portProofEligible}:{}}}),u=jt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(h=>h.path)}),p=yd(e,t),g=e.contract.arkRules??xe(),f=a.map(h=>h.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Hn(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=i(h=>c.get(h)??fe(h,e.contract.config.layers),"resolveLayer"),b=[...Fn({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:A,fileHints:d}),...$n(g,f),...ua({arkRulesActive:md(e.contract.config),arkRules:g,layers:e.contract.config.layers??[],files:f.map(h=>({path:h,layer:A(h)}))})],O=(g.invariants?.length??0)>0,k=Go({hasEnforcedInvariant:Vr(g.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),I=k.length>0?[]:Uo({adopted:e.adopted===!0,hasDomainInvariants:Kr(g.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),C=[...k.map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...I.map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],L=b.filter(h=>h.failsStrict).map(h=>_a(h,Oa(h,!1))),E=b.filter(h=>!h.failsStrict).map(h=>({..._a(h,Oa(h,!0)),failsStrict:!1})),P=O?Cn({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},ee=P.violations.filter(h=>h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,nextAction:`Add a test title or declared symbol covering ${h.arkruleId} (declared in ${h.arkruleSource}), then preflight again.`})),T=P.violations.filter(h=>!h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,failsStrict:!1,nextAction:h.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${h.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${h.arkruleId} in ${h.arkruleSource} (advisory / partial).`})),V=Kn(a),D=Ht({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(h=>c.get(h)??fe(h,e.contract.config.layers),"layerForFile"),classification:V}),se=e.contract.config.arkRun?.mode,X=D.findings.filter(()=>se==="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:h.failsStrict,...h.severity?{severity:h.severity}:{}})),ve=D.findings.filter(()=>se!=="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:!1})),Ae=Zn({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(h=>c.get(h)??fe(h,e.contract.config.layers),"layerForFile"),classification:V}),at=e.contract.config.arkOrder?.mode,sn=Ae.findings.filter(()=>at==="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:h.failsStrict,...h.severity?{severity:h.severity}:{}})),qs=Ae.findings.filter(()=>at!=="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:!1})),v=[...P.partial&&P.coverage.some(h=>h.mode==="enforced"&&h.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...D.completenessReasons,...Ae.completenessReasons],_=Ve({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(h=>h.layer).map(h=>h.path),contentViolations:[...Ad(e,t,c),...L,...C,...ee,...X,...sn],edges:l,warnings:[...u,...p.warnings,...E,...T,...ve,...qs],safety:p.report}),y=o==="complete"&&v.length>0?"partial":o,R=y==="complete"?s:[...s,...v].sort((h,oe)=>{let it=`${h.code}\0${h.file??""}\0${h.message}`,lt=`${oe.code}\0${oe.file??""}\0${oe.message}`;return it<lt?-1:it>lt?1:0}),M=_.violations.filter(h=>h.failsStrict!==!1),Y=y==="complete"&&M.length===0,Ce=Y&&_.warnings.every(h=>h.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:y,completenessReasons:R,valid:Y,strictValid:Ce,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(h=>h.name),edges:l,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}i(Rd,"analyzeCanonicalResolvedProject");function rt(e){return Rd({contract:e.contract,facts:Ie(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(rt,"analyzeResolvedProject");function Ta(e){return J($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Ta,"analysisTreeHash");function ls(e){let t=et(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let A=d.path.replace(/\\/g,"/"),b=Ke(d.path);if(!b||b===".."||b.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Pt({...e,changes:r}),c=new Map(a.ir.files.map(d=>[d.path,d])),l=a.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let A=c.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:d.message}}),u=Ve({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(d=>d.path),contentViolations:l,edges:a.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),p=r.map(d=>{let A=Ke(d.path),b=n.get(A),O=c.get(A);return{path:A,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...O?{candidateContentHash:O.contentHash}:{}}}).sort((d,A)=>d.path.localeCompare(A.path)),g=[...s,...u.violations].map(d=>({...d,nextAction:ye(d)})),f=g.filter(d=>d.failsStrict!==!1),m=e.changeMap?He({changeMap:e.changeMap,changes:p,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:a.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&f.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Ta(t.ir.files),candidateTreeHash:Ta(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p,violations:g,warnings:u.warnings}}i(ls,"preflightChange");function kd(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(kd,"canonicalChangePath");function Ed(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(Ed,"identityViolations");function Sd(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(Sd,"preparedChange");function cs(e){let t=Ie(e.baseFacts),n=Ie(e.candidateFacts),r=rt({contract:e.contract,facts:t}),o=rt({contract:e.contract,facts:n}),s=new Map(t.files.map(m=>[m.path,m])),a=new Map(n.files.map(m=>[m.path,m])),c=Ed(t,n),l=new Map,u=[];for(let m of e.changes){let d=kd(m.path);if(!d){c.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(d)){c.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}l.set(d,m);let A=s.get(d),b=a.get(d);if("delete"in m&&m.delete)A||c.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),b&&c.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let O="content"in m?m.content:"",k=J(O);b?b.contentHash!==k&&c.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:k,candidateContentHash:b.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):c.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}u.push(Sd(m,d,s,a))}e.changes.length===0&&c.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let m of new Set([...s.keys(),...a.keys()])){if(l.has(m))continue;let d=s.get(m),A=a.get(m);d&&A&&$(d)===$(A)||c.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:m,line:1,message:`Candidate facts change ${m}, but the atomic change set does not declare it.`})}let p=e.changeMap?He({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:o.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0,g=[...c,...o.ir.violations].map(m=>({...m,nextAction:ye(m)})),f=g.filter(m=>m.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&f.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:u.sort((m,d)=>m.path<d.path?-1:m.path>d.path?1:0),violations:g,warnings:o.ir.warnings}}i(cs,"preflightResolvedChange");var ds="1.0",Id=12,bd="Layers stop a bad import. ArkRun is an optional experimental runtime \u2014 in-memory, not Postgres. Data is gone on restart.",vd="Next: /ark-runtime to wire one candidate.";function Na(e){return e==="enforced"||e==="advisory"?e:null}i(Na,"closedMode");function Cd(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Vn(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(Cd,"uniqueArkRunRuleIds");function _d(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Na(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}i(_d,"extraFromConfig");function wa(e={}){let t=_d(e.arkRun),n=t.present?Cd(e.findings):[],r=n.slice(0,Id),o=n.length,s=Dt({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:o}}),a=t.present&&t.mode==="enforced"&&ge(e.classification),c;return t.present?t.mode==="advisory"?c="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?c="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":c="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":c="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:ds,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:o,ruleIds:r},extraMergeTeeth:a,failMergeWhen:s.failMergeWhen,note:c,mergePlanes:s}}i(wa,"summarizeArkRunSection");function Qn(e={}){let t=e.present===!0,n=Na(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Qn,"projectStatusArkRun");function Pa(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[bd,`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let o=e.residual.ruleIds.join(", "),s=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${o}${s}`),r.push(vd)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");return e.failMergeWhen&&r.push(e.failMergeWhen),r}i(Pa,"formatArkRunDoctorLines");function er(e,t){return e.slice(0,t).split(`
|
|
13
|
+
`).length}i(er,"lineOf");function La(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(La,"normalizeInventoryPath");function Ma(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(o=>r===o||r.startsWith(`${o}.`))})}i(Ma,"ownsIntent");function Da(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Ma(t,["Domain"])}i(Da,"isDomainLayer");function Od(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Ma(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Od,"isControllerEligibleLayer");function xd(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}i(xd,"isNonPilotSurface");function Fa(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([l,u])=>[La(l),u])),o=new Map((e.layerContexts??[]).map(l=>[l.name,l.intentPrefixes??[]])),s=(e.layerContexts??[]).find(l=>Da(l.name,l.intentPrefixes))?.name??"DomainModel";for(let[l,u]of Object.entries(e.fileContents).sort(([p],[g])=>p.localeCompare(g))){let p=La(l);if(xd(p)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let g=r.has(p),f=r.get(p),m=f?o.get(f)??[]:[],d=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(p)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(p)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(p),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(p),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(p)||/['"]use server['"]/.test(u),O=/controller|handler|resolver/i.test(l)||A||b||/route\.(?:ts|js|tsx|jsx)$/i.test(p)&&!d||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),k=g?!!(f&&Od(f,m)&&O):O,I=g?!!(f&&Da(f,m)):/domain|entity|aggregate|model/i.test(l),C=!g||I||k;if(k&&!d){let T=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,V;for(;(V=T.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:l,line:er(u,V.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let L=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,E,P=i(T=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(T)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(T)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(T)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(T)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(T)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(T)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(T)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(T)||/_(?:OID|OIDS)$/i.test(T)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(T)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(T),"isInfraMagicName"),ee=i((T,V)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(T)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(T))return!0;let D=V.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(V)&&(/\s/.test(D)||/[.!?…]$/.test(D))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(E=L.exec(u))!==null;){let T=E[2],V=E[3]??"";!C||P(T)||ee(T,V)||d&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(p)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:l,line:er(u,E.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(I){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,V;for(;(V=T.exec(u))!==null;){let D=V[2]??"",se=(D.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(D.match(/:\s*[A-Za-z]/g)??[]).length>=2&&se<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:l,line:er(u,V.index),message:`Class ${V[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(p)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(p)||/(?:^|\/)errors?(?:\/|$)/i.test(p))){let V=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,D;for(;(D=V.exec(u))!==null;){let se=u.lastIndexOf("class ",D.index),X=se>=0?u.indexOf("{",se):-1,ve=se>=0&&X>=se&&X<D.index?u.slice(se,X):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(ve)||Zr(u,D.index))continue;let Ae=u.slice(Math.max(0,D.index-200),D.index+200);if(!Yr.test(Ae)&&!Jr.test(Ae)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:l,line:er(u,D.index),message:`Domain field mutation without nearby ${Xr()}.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:s,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((l,u)=>+(u.confidence==="direct-evidence")-+(l.confidence==="direct-evidence")||l.file.localeCompare(u.file)||l.line-u.line||l.kind.localeCompare(u.kind)||l.id.localeCompare(u.id));let c=t.filter(l=>l.suggestedArkRule?.invariantId&&a.has(l.suggestedArkRule.invariantId)||l.suggestedArkRule?.structureId&&a.has(l.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:c,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Fa,"buildRulesInventory");function $a(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}i($a,"inventoryToExtractionCard");var Ha="1.1";var ja="1.0";var tr="docs/diagnostics.md",Ka="1.0";function S(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(S,"entry");var Kt=Object.freeze([S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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}),S("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."),S("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}),S("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."),S("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}),S("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."),S("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."),S("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),S("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),S("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."),S("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),S("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),S("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","Run `npx arkgate-check --root . --config ark.config.json` to confirm. Do not call ark_prepare_change from a hook deny."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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."),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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}),S("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."),S("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."),S("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}),S("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.")]),us=new Map(Kt.map(e=>[e.ruleId,e])),Va=Object.freeze(Kt.map(e=>e.ruleId));function Ua(e){return typeof e=="string"&&e.length>0&&us.has(e)}i(Ua,"isKnownDiagnosticCode");function Ga(e){return typeof e!="string"||e.length===0?!1:us.has(e)?!0:e.startsWith("ARKRULE_")}i(Ga,"isCataloguedOrArkRuleFamily");function Vt(e){if(!(typeof e!="string"||e.length===0))return us.get(e)}i(Vt,"getDiagnosticCatalogEntry");function ps(e){return`#${Vt(e)?.docsAnchor??e}`}i(ps,"diagnosticDocsFragment");function Ba(e){return`${tr}${ps(e)}`}i(Ba,"diagnosticDocsPath");function za(){return{schemaVersion:"1.0",docsPath:tr,codes:Kt}}i(za,"serializeDiagnosticCatalog");function Wa(e){return Vt(e)?.fix}i(Wa,"catalogFixForRuleId");function qa(e){return Vt(e)?.why}i(qa,"catalogWhyForRuleId");function Td(e){return e==="enforced"||e==="advisory"?e:null}i(Td,"closedMode");function Ya(e={}){let t=e.present===!0,n=Td(e.mode),r=e.residual,o=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(o=Math.floor(r)),t||(o=o??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:o}}i(Ya,"projectStatusArkOrder");var nr="1.0",fs="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",ms=["full","subset","unavailable"],gs=["doctor-facts","report-snapshot","none"],Gt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Ja=/^sha256:[a-f0-9]{64}$/;function ys(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!Ja.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let o=e.expectedRootRelation??"unknown";return o==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:o==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:o==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:o==="exact"||o==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}i(ys,"evaluateStatusBinding");function hs(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}i(hs,"classifyStatusWritePath");function As(e,t){let n=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${n} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${n}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}i(As,"defaultHonestLabel");function Rs(e,t,n,r,o){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:o.arkRulesLoaded&&(o.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through arkgate/runtime. Not a score."}:e.arkOrder?.present===!0&&(e.arkOrder.residual??0)>0?{id:"review-arkorder-residual",summary:"ArkOrder leftover remains \u2014 change that product choice through the valve (proposeRelease then apply), not a generic update. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}i(Rs,"resolveStatusNextAction");function Xa(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Ja.test(e.projectId)?e.projectId:null,r=ys({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),o=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",s=o&&o!=="unknown"?o:o==="unknown"?"unknown":null,a=hs({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:s}),c=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():As(a,s),l={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Ut(e.activeViolations),frozenResidual:Ut(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ut(e.rulesInventoried),underContract:Ut(e.rulesUnderContract),frozenResidual:Ut(e.rulesFrozenResidual)},p={writePath:a,host:s,honestLabel:c},g={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},f={schemaVersion:nr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:p,lastCheck:l,rules:u,nextAction:Rs(e,r,p,l,u)},m=ks(e.improvementCompass);return m&&(f.improvementCompass=m),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Qn(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(f.arkOrder=Ya(e.arkOrder)),f}i(Xa,"buildStatusManifest");var Za=new Set(ms),Nd=new Set(gs);function rr(e){let t=Za.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Nd.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let a={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:Gt.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let o=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],s={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:o};return t==="subset"?(s.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:Gt.FACTS_PARTIAL,s.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(s.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(s.reason=e.reason),n&&(s.factsSource=n),r&&(s.contractHash=r),s}i(rr,"projectStatusImprovementCompass");function Qa(e={}){return rr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??Gt.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --doctor or --report for residual lenses. Status never invents green.",factsSource:"none",contractHash:e.contractHash})}i(Qa,"unavailableStatusImprovementCompass");function ks(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let n;return typeof t.mode=="string"&&Za.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",rr({mode:n,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}i(ks,"normalizeStatusImprovementCompass");function ei(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let o of n)if(!(typeof o!="string"||o.length===0)&&!r.has(o))return!1;return!0}i(ei,"statusCompassResidualIsSubsetOfDoctor");function Ut(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ut,"numberOrNull");var ti={$schema:"https://json-schema.org/draft/2020-12/schema",$id:fs,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:nr},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},arkOrder:{type:"object",description:"ArkOrder extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var Bt="1.0",zt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Wt=5,we=["scalability","resilience","security"],st=new Set(we),Es={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},Ss={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},Is={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function bs(e){return Ss[e]??e}i(bs,"improvementCompassHumanLabel");function vs(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(vs,"smellIdOf");function Cs(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Cs,"violationRuleId");function K(e,t,n,r){if(!n||e.evidence.some(s=>s.source===t&&s.ref===n))return;let o={source:t,ref:n};r&&r.trim()&&(o.detail=r.trim().slice(0,240)),e.evidence.push(o)}i(K,"pushEvidence");function re(e,t,n){st.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(re,"markResidual");function ni(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${Ss[e]} \u2014 no residual from current sensors.`}}i(ni,"defaultOkSummary");function ri(){return zt.map(e=>st.has(e)?{id:e,status:"out-of-scope",summary:Is[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:ni(e),evidence:[]}:{id:e,status:"ok",summary:ni(e),evidence:[]})}i(ri,"createInitialImprovementCompassLenses");function wd(e,t){for(let n of t){let r=vs(n);if(!r)continue;let o=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],c=i((p,g,f)=>{let m=e.get(p);!m||st.has(p)||(K(m,"designSmells",r,o),a&&K(m,"designSmells",a,r),re(m,g,f))},"attach"),l={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":c("soc","Business rules still mix with UI or presentation surfaces.",l),c("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",l);break;case"facade-sql-in-routes":c("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",l),c("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":c("soc","Application/business code reaches I/O directly \u2014 separation is weak.",l),c("dip","I/O is not inverted behind ports/adapters.",u),c("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":c("soc","HTTP/transport handlers live under persistence folders.",l);break;case"god-module":c("cohesion","Large multi-responsibility modules reduce cohesion.",l),c("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":c("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),c("cohesion","Mixed layout styles scatter the same concern across patterns.",l);break;case"soft-contract":c("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),c("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:c("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",l);break}}}i(wd,"mapDesignSmells");function Pd(e){return e.failsStrict===!1||e.typeOnly===!0}i(Pd,"isTypeOnlyPlacementDebt");function Ld(e,t){for(let n of t){let r=Cs(n);if(!r)continue;let o=n.message,s=r.toUpperCase(),a=i((l,u,p)=>{let g=e.get(l);!g||st.has(l)||(K(g,"violations",r,o),n.file&&K(g,"violations",n.file,r),re(g,u,p))},"attach");if(Pd(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let c={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(s==="LAYER_IMPORT_VIOLATION"||s.includes("LAYER_IMPORT")||s==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",c);continue}if(s.includes("CYCLE")||s==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",c);continue}if(s.includes("PEER_ISOLATION")||s==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(s==="FORBIDDEN_GLOBAL"||s.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(s==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(s.startsWith("ARKRULE_")||s==="INVARIANT_UNCOVERED"||s==="INVARIANT_CATALOG_EMPTY"||s==="INVARIANT_TESTS_PATH_MISSING"||s==="INVARIANT_COVERAGE_ROOTS_MISSING"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}i(Ld,"mapViolations");function Dd(e,t){let n=Number(t.cycleCount)||0;if(n>0){let m=e.get("coupling");K(m,"cycles",`count:${n}`),re(m,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let m=e.get("coupling");K(m,"peerIsolation",`count:${r}`),re(m,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let o=Number(t.physicalCohesionFindingCount)||0;if(o>0){let m=e.get("cohesion");K(m,"physicalCohesion",`findings:${o}`),re(m,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let d=e.get("srp");K(d,"physicalCohesion",`findings:${o}`),re(d,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let s=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(s>0||a>0){let m=e.get("dip");s>0&&K(m,"capability",`residual:${s}`),a>0&&K(m,"forbiddenGlobals",`residual:${a}`),re(m,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let d=e.get("testability");s>0&&K(d,"capability",`residual:${s}`),a>0&&K(d,"forbiddenGlobals",`residual:${a}`),re(d,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let c=Number(t.arkRulesStructureResidual)||0;if(c>0){let m=e.get("encapsulation");K(m,"arkRules",`structureResidual:${c}`),re(m,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let d=e.get("domain");K(d,"arkRules",`structureResidual:${c}`),re(d,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let m=e.get("maintainability");K(m,"designFitness","design-weak"),re(m,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let m=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(m,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(m,"baseline",`stale:${t.baselineStale}`),re(m,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let l=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&l>=10&&e.get("maintainability").status!=="residual"){let m=e.get("maintainability");K(m,"baseline",`frozen:${l}`),re(m,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let u=Number(t.ungovernedDirCount)||0,p=Number(t.emptyLayerCount)||0;if(u>0||p>0){let m=e.get("modularity");u>0&&K(m,"coverage",`ungovernedDirs:${u}`),p>0&&K(m,"coverage",`emptyLayers:${p}`),re(m,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let m=e.get("modularity");K(m,"goldenPattern","absent"),re(m,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Dd,"mapCountsAndFlags");function si(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,o)=>vs(r).localeCompare(vs(o)));wd(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,o)=>{let s=Cs(r).localeCompare(Cs(o));return s!==0?s:String(r.file??"").localeCompare(String(o.file??""))});Ld(e,n)}Dd(e,t)}i(si,"projectImprovementCompassFacts");function oi(e){for(let t of we){let n=e.get(t);n.status="out-of-scope",n.summary=Is[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}i(oi,"lockImprovementCompassOutOfScope");function ai(e){for(let t of e)t.evidence.sort((n,r)=>{let o=n.source.localeCompare(r.source);return o!==0?o:n.ref.localeCompare(r.ref)})}i(ai,"sortImprovementCompassEvidence");function ii(e){return e.filter(n=>n.status==="residual"&&!st.has(n.id)).slice().sort((n,r)=>{let o=Es[n.id]??150,s=Es[r.id]??150;return o!==s?o-s:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(ii,"finalizeImprovementCompassTopResidual");function li(e={}){let t=ri(),n=new Map(t.map(o=>[o.id,o]));si(n,e),oi(n),ai(t);let r=ii(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(o=>{let s={id:o.id,status:o.status,summary:o.summary,evidence:o.evidence.map(a=>({...a}))};return o.nextAction&&(s.nextAction={...o.nextAction}),s}),topResidual:r}}i(li,"buildImprovementCompass");function _s(e){return e.topResidual.map(t=>bs(t))}i(_s,"formatImprovementCompassResidualLabels");function Os(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}i(Os,"primaryImprovementCompassNextAction");function ci(e){let t=_s(e),n=we.map(s=>bs(s)),r=Os(e),o=[];return t.length>0?o.push(`Residual: ${t.join(" \xB7 ")}`):o.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),o.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&o.push(`Next: ${r.ref} \u2014 ${r.summary}`),o}i(ci,"formatImprovementCompassDoctorLines");var Pe="1.0",xs="<!-- arkgate:agent-projection:begin",qt="<!-- arkgate:agent-projection:end -->",Yt="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",ot=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),Ts=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]);function Ue(e){let t=String(e??"").replace(/\r\n/g,`
|
|
14
|
+
`),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}i(Ue,"agentProjectionContentIdentity");function Xt(e){return String(e??"").replace(/\r\n/g,`
|
|
15
|
+
`)}i(Xt,"normalizeNewlines");function Ge(e){let t=Xt(e);return t.endsWith(`
|
|
16
16
|
`)?t:`${t}
|
|
17
|
-
`}i(
|
|
17
|
+
`}i(Ge,"ensureTrailingNewline");function Zt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(Zt,"safeVersion");function di(e){return e==="compact"?"compact":"full"}i(di,"resolveProfile");function sr(e){let t=Zt(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}i(sr,"buildAgentProjectionBeginMarker");function Jt(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
|
|
18
18
|
|-------|----------|-----------------|
|
|
19
|
-
${e.map(
|
|
20
|
-
`)}`}i(
|
|
19
|
+
${e.map(n=>{let r=n.name?.trim()||"Unknown",o=n.patterns??[],s=n.intentPrefixes??[],a=o.map(l=>`\`${l}\``).join(", ")||"\u2014",c=s.map(l=>`\`${l}\``).join(", ")||"\u2014";return`| ${r} | ${a} | ${c} |`}).join(`
|
|
20
|
+
`)}`}i(Jt,"formatAgentProjectionLayers");function or(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(o=>o&&typeof o.ruleId=="string"&&o.ruleId.length>0).map(o=>{let s=typeof o.title=="string"&&o.title.trim()?o.title.trim():o.ruleId;return`- \`${o.ruleId}\` \u2014 ${s}`}).join(`
|
|
21
21
|
`)}
|
|
22
22
|
|
|
23
|
-
Full catalog: \`${
|
|
23
|
+
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(or,"formatAgentProjectionCatalogShortList");function Qt(e){let t=Zt(e.arkgateVersion),n=di(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",o=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",s=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=s&&s!=="unknown"?s:null,c=Array.isArray(e.layers)?e.layers:[],l=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",Yt,"","Contener \xB7 Guiar \xB7 Ordenar \u2014 contain the write, guide the next step, order leftover mess. Skills never enforce.","",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,`- **projectionSchema:** \`${"1.0"}\``,`- **profile:** \`${n}\`${a?` \xB7 **host:** \`${a}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?u.push("### Primary path","","1. Run doctor (`ark-check --doctor`) \u2014 what is wrong and what to do first. Prefer the project-local CLI; do not wait on MCP \u201Cstill connecting\u201D.","2. Name leftover work in plain language; never \u201Cdone\u201D on green imports alone while leftover design work remains.","3. Identity handshake is optional when the CLI already resolved the project root. Call `ark_identity` only when using MCP evidence.","4. Read the rules file with `ark_manifest` (same expectation) or the local `ark.config.json`. `ark://manifest` is compatibility-only / unverified.","5. Place files inside configured layers; validate; run the check command above on violations \u2014 fix the import, do not weaken the rules file.","6. Single door: illegal imports \u2192 fix; leftover design work \u2192 map then one small refactor with user OK.","","### Layers (summary)","",Jt(c),""):u.push("### Contract layers","",Jt(c),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",or(l,o),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),u.push("### Enforcement surfaces (authoritative)","",ot.map(p=>`- \`${p}\``).join(`
|
|
24
24
|
`),""),u.join(`
|
|
25
25
|
`).replace(/\n{3,}/g,`
|
|
26
26
|
|
|
27
27
|
`).trimEnd()+`
|
|
28
|
-
`}i(
|
|
29
|
-
${t}${
|
|
30
|
-
`}i(
|
|
31
|
-
`)&&(u=u.slice(1));let p=t.slice(
|
|
32
|
-
`,s=Ue(o);if(e==null||!String(e).trim())return{content:
|
|
28
|
+
`}i(Qt,"buildAgentProjectionBody");function Ns(e){let t=Qt(e);return`${sr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
|
|
29
|
+
${t}${qt}
|
|
30
|
+
`}i(Ns,"buildAgentProjectionBlock");function ws(e){let t=Qt(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Zt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...ot],contentIdentity:Ue(t),layerCount:n.length,catalogCodeCount:r.filter(o=>o?.ruleId).length,profile:di(e.profile)}}i(ws,"buildAgentProjectionMeta");var Ps=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,ui=/<!--\s*arkgate:agent-projection:end\s*-->/i,Md=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Fd=/\bschema=([A-Za-z0-9._+-]+)/i;function en(e){let t=Xt(e??""),n=Ps.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,o=r+n[0].length,s=t.slice(o),a=ui.exec(s);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let c=a.index,l=c+a[0].length,u=s.slice(0,c);u.startsWith(`
|
|
31
|
+
`)&&(u=u.slice(1));let p=t.slice(r,o+l),g=s.slice(l);return{block:p,body:u,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}i(en,"extractAgentProjectionBlock");function ar(e){let t=String(e??""),r=Ps.exec(t)?.[1]??t,o=Md.exec(r),s=Fd.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:o?.[1]??null,schemaVersion:s?.[1]??null,nonAuthoritative:a}}i(ar,"parseAgentProjectionStamp");function Ls(e,t){let n=ar(e).arkgateVersion;return n?n===Zt(t):!1}i(Ls,"projectionMatchesPackageVersion");function Ds(e){return String(e??"").includes("non-authoritative")}i(Ds,"projectionHasNonEnforcementLabel");function Ms(e,t){let n=Ge(Xt(t)),o=en(n).body??n.replace(Ps,"").replace(ui,"").trim()+`
|
|
32
|
+
`,s=Ue(o);if(e==null||!String(e).trim())return{content:Ge(`# Ark Enforcement
|
|
33
33
|
|
|
34
|
-
${
|
|
34
|
+
${n}`),action:"created",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!1};let a=Xt(e),c=en(a);if(c.block!=null){let u=c.body??"";if(Ue(u)===s)return{content:Ge(a),action:"unchanged",previousBlock:c.block,contentIdentity:s,preservedOutsideBlock:!0};let p=c.before.replace(/\s*$/,`
|
|
35
35
|
|
|
36
36
|
`),g=c.after.replace(/^\s*/,`
|
|
37
|
-
`);return{content:
|
|
37
|
+
`);return{content:Ge(`${p}${n.trimEnd()}
|
|
38
38
|
${g}`),action:"block-replaced",previousBlock:c.block,contentIdentity:s,preservedOutsideBlock:!0}}let l=/^(#\s+[^\n]*\n)/m.exec(a);if(l&&l.index!=null){let u=l.index+l[1].length,p=a.slice(0,u).replace(/\s*$/,`
|
|
39
39
|
|
|
40
40
|
`),g=a.slice(u).replace(/^\s*/,`
|
|
41
|
-
`);return{content:
|
|
42
|
-
${g}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:
|
|
41
|
+
`);return{content:Ge(`${p}${n.trimEnd()}
|
|
42
|
+
${g}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}return{content:Ge(`${n.trimEnd()}
|
|
43
43
|
|
|
44
|
-
${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}i(
|
|
44
|
+
${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:s,preservedOutsideBlock:!0}}i(Ms,"mergeAgentProjectionDocument");var gi="1.0",Fs="templates/agent-skills",$s="templates/skills",Hs="SKILL.md",yi=Object.freeze(["Contener","Guiar","Ordenar"]),dr=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),ir=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),tn=Object.freeze({Layers:["ark-adopt","ark-place","ark-explore","ark-autopilot","ark-coverage","ark-explain"],ArkRules:["ark-adopt","ark-explore","ark-autopilot"],ArkRun:["ark-adopt","ark-runtime","ark-place","ark-autopilot"],ArkOrder:["ark-adopt","ark-order","ark-place","ark-autopilot"],Contener:["ark-adopt","ark-place","ark-upgrade"],Guiar:["ark-explore","ark-autopilot","ark-explain","ark-coverage","ark-runtime"],Ordenar:["ark-order"]}),nn=Object.freeze(["Layers","ArkRules","ArkRun","ArkOrder","Contener","Guiar","Ordenar"]),js=Object.freeze({ArkRun:"ark-runtime",ArkOrder:"ark-order",Ordenar:"ark-order"}),pi="Contener \xB7 Guiar \xB7 Ordenar",fi="Do not invent `/ark-order`",rn=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-order","ark-place","ark-runtime","ark-think","ark-upgrade"]),Ks=rn.length,$d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Vs(e){return typeof e!="string"||e.length<1||e.length>64?!1:$d.test(e)}i(Vs,"isValidAgentSkillName");function ur(e){return rn.includes(e)}i(ur,"isArkSkillName");function lr(e){return dr.includes(e)}i(lr,"isFirstClassArkSkillName");function hi(e){return e in ir?ir[e]:null}i(hi,"arkSkillStubRedirect");function Us(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
|
|
45
45
|
`)?`\r
|
|
46
46
|
`:`
|
|
47
|
-
`,
|
|
48
|
-
`)}i(
|
|
47
|
+
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let o=r.indexOf("---",1);if(o===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let s={};for(let p=1;p<o;p+=1){let g=r[p]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let f=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let m=f[1],d=f[2]??"";(d.startsWith('"')&&d.endsWith('"')&&d.length>=2||d.startsWith("'")&&d.endsWith("'")&&d.length>=2)&&(d=d.slice(1,-1)),s[m]=d}let a=r.slice(o+1).join(n),c=typeof s.name=="string"&&s.name.length>0?s.name:null,l=typeof s.description=="string"&&s.description.length>0?s.description:null,u=typeof s.license=="string"&&s.license.length>0?s.license:null;return{hasFrontmatter:!0,frontmatter:{fields:s,name:c,description:l,license:u},body:a}}i(Us,"parseSkillDocument");function Gs(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],o=String(e.directoryName??""),s=Us(e.content);if(!s.hasFrontmatter||!s.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${o}" is missing YAML frontmatter fences.`,skillName:o||void 0}),r;let{name:a,description:c}=s.frontmatter,l=a??(o||void 0);return!a||!Vs(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:l}):a!==o?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${o}".`,skillName:a}):t&&!ur(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:a}),c?c.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${o}" description exceeds 1024 characters (${c.length}).`,skillName:l}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${o}" is missing a non-empty description.`,skillName:l}),n&&s.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${o}" has an empty instruction body.`,skillName:l}),r}i(Gs,"validateAgentSkillDocument");function Ai(e){let t=[],n=new Set,r=[];for(let o of e){let s=String(o.name??"");if(n.has(s)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${s}".`,skillName:s});continue}n.add(s),r.push(s),t.push(...Gs({directoryName:s,content:o.content,requireArkSkillName:!0,requireBody:!0})),o.flatTemplateContent!=null&&cr(o.content)!==cr(o.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${s}" does not match flat template templates/skills/${s}.md.`,skillName:s})}for(let o of rn)n.has(o)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${o}" from Agent Skills package.`,skillName:o});for(let o of r)ur(o)||(t.some(s=>s.code==="UNKNOWN_SKILL_NAME"&&s.skillName===o)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${o}" is not in the closed Ark skill catalog.`,skillName:o}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:Ks,presentCount:r.length}}i(Ai,"validateAgentSkillsPackage");function pe(e,t){e.push(t)}i(pe,"pushCapacityIssue");function mi(e,t){return e.includes(t)}i(mi,"skillMentionsSurface");function Ri(e){let t=[],n=e.skills??{},r=Object.keys(tn);for(let s of nn)r.includes(s)||pe(t,{code:"CAPACITY_SURFACE_MISSING",surface:s,message:`The capacity table dropped ${s}. Skills must keep covering Layers, ArkRules, ArkRun, ArkOrder plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back on ARK_SKILL_CAPACITY.`});for(let s of r)nn.includes(s)||pe(t,{code:"CAPACITY_SURFACE_UNMAPPED",surface:s,message:`The capacity table lists ${s}, which is not a product surface. Keep the table to Layers, ArkRules, ArkRun, ArkOrder and Contener \xB7 Guiar \xB7 Ordenar.`});for(let s of nn){let a=tn[s];if(!a||a.length===0)continue;for(let l of a)lr(l)||pe(t,{code:"CAPACITY_DOOR_NOT_FIRST_CLASS",surface:s,skillName:l,message:`/${l} is listed for ${s} but is not a first-class door. Leftover names are shortcuts. Point ${s} at a first-class skill.`});a.filter(l=>{let u=n[l];return typeof u=="string"&&mi(u,s)}).length===0&&pe(t,{code:"CAPACITY_BODY_GAP",surface:s,message:`Skills no longer cover ${s}. The product has four parts (Layers, ArkRules, ArkRun, ArkOrder) plus Contener \xB7 Guiar \xB7 Ordenar. Put ${s} back in a first-class skill${s==="ArkOrder"||s==="Ordenar"?" \u2014 usually /ark-order":s==="ArkRun"?" \u2014 usually /ark-runtime":""} so agents still know when to use it.`})}for(let[s,a]of Object.entries(js)){if(!tn[s]?.includes(a)||!lr(a)){pe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} is the first-class door for ${s}. Keep it on that surface. Leftover names like /ark-think are shortcuts, not a replacement.`});continue}let l=n[a];(typeof l!="string"||!mi(l,s))&&pe(t,{code:"CAPACITY_DEDICATED_DOOR",surface:s,skillName:a,message:`/${a} no longer talks about ${s}. That door is how agents reach this part of the product. Put ${s} back in the skill body.`})}for(let s of dr){let a=n[s];if(typeof a!="string"){pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is a first-class door but has no skill body in this check. Ship the template so agents know when to use it.`});continue}let c=a.includes(pi),l=/When \/ not when|\*\*When:\*\*/.test(a),u=/Not when|Do \*\*not\*\* use|Prefer instead/.test(a),p=/Handoff|hand off|`\/ark-/i.test(a);(!c||!l||!u||!p)&&pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} is missing when / not when / handoff or Contener \xB7 Guiar \xB7 Ordenar. First-class skills must say when to use them and which sibling to call next.`}),a.includes(fi)&&pe(t,{code:"CAPACITY_ROUTING_GAP",skillName:s,message:`/${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}let o=e.hubs??{};for(let[s,a]of Object.entries(o)){let c=String(a??"");c.includes("/ark-order")||pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer names /ark-order. Host instructions must stay at 100% of the product. Add /ark-order back, or you left the order plane behind.`}),c.includes(pi)||pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} no longer says Contener \xB7 Guiar \xB7 Ordenar. Keep that filter in the living docs so agents pick the right sibling.`}),c.includes(fi)&&pe(t,{code:"CAPACITY_HUB_GAP",hub:s,message:`${s} still says not to invent /ark-order. That freeze is outdated \u2014 /ark-order is a first-class door.`})}return{ok:t.length===0,issues:t}}i(Ri,"validateSkillProductCapacity");var pr=/^arkgate@(\S+)\.\s/;function Bs(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(Bs,"skillDescriptionVersionPrefix");function zs(e){return String(e??"").replace(pr,"")}i(zs,"stripSkillDescriptionVersion");function ki(e){return String(e??"").match(pr)?.[1]??null}i(ki,"parseSkillDescriptionVersion");function Ei(e,t){let n=zs(e),r=typeof t=="string"?t.trim():"";return r?`${Bs(r)}${n}`:n}i(Ei,"stampSkillDescription");function cr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
48
|
+
`)}i(cr,"normalizeSkillContent");function Ws(e){return`${e}/${Hs}`}i(Ws,"agentSkillEntryRelativePath");function Si(e){return`${Fs}/${Ws(e)}`}i(Si,"agentSkillPackageFileRelativePath");function Ii(e){return`${$s}/${e}.md`}i(Ii,"flatSkillTemplateFileRelativePath");0&&(module.exports={ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,AGENT_PROJECTION_BEGIN_MARKER,AGENT_PROJECTION_END_MARKER,AGENT_PROJECTION_ENFORCEMENT_SURFACES,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,AGENT_SKILL_ENTRY_FILENAME,ANALYSIS_IR_SCHEMA_VERSION,ARKORDER_RULE_IDS,ARKORDER_TIER1_SENSOR_IDS,ARKRUN_INTERACTION_NAME_INCOMPLETE,ARKRUN_KERNEL_FACTORY_CALLEES,ARKRUN_KERNEL_INTERACTION_CALLEES,ARKRUN_RULE_IDS,ARKRUN_TIER1_SENSOR_IDS,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,ARK_AGENT_PROJECTION_SCHEMA_VERSION,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_FIRST_CLASS_SKILL_NAMES,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,ARK_PROJECT_IDENTITY_SCHEMA,ARK_PROJECT_IDENTITY_SCHEMA_URL,ARK_PROJECT_IDENTITY_SCHEMA_VERSION,ARK_RULES_SCHEMA,ARK_RULES_SCHEMA_VERSION,ARK_RULE_SENSORS,ARK_RUN_DOCTOR_SCHEMA_VERSION,ARK_SKILL_CAPACITY,ARK_SKILL_CAPACITY_DEDICATED_DOORS,ARK_SKILL_DESCRIPTION_VERSION_PATTERN,ARK_SKILL_NAMES,ARK_SKILL_NAME_COUNT,ARK_SKILL_NORTH_STAR,ARK_SKILL_REQUIRED_SURFACES,ARK_SKILL_STUB_REDIRECTS,ARK_STATUS_MANIFEST_SCHEMA,ARK_STATUS_MANIFEST_SCHEMA_URL,ARK_STATUS_MANIFEST_SCHEMA_VERSION,DEFAULT_AGENT_PROJECTION_RULE_IDS,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EXTRA_MERGE_TEETH_GOVERNED_FLOOR,EffectiveContractError,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,IMPROVEMENT_LENS_IDS,MERGE_PLANES_DUAL_STAMP,POLICY_DELTA_SCHEMA_VERSION,PROJECT_BINDING_SCHEMA,PROJECT_EXPECTATION_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,STATUS_COMPASS_FACTS_SOURCES,STATUS_COMPASS_MODES,STATUS_COMPASS_REASON_CODES,adapterDocsCodePath,adapterFindingOccurrenceTargetKeys,adapterFindingRefFromTargetKey,adapterFindingTargetKey,agentProjectionContentIdentity,agentSkillEntryRelativePath,agentSkillPackageFileRelativePath,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,arkRunKernelCallKind,arkSkillStubRedirect,buildAgentProjectionBeginMarker,buildAgentProjectionBlock,buildAgentProjectionBody,buildAgentProjectionMeta,buildArkRuleFileHints,buildEffectiveArkRules,buildImprovementCompass,buildRulesInventory,buildStatusManifest,canPromoteInvariant,catalogFixForRuleId,catalogWhyForRuleId,classifyArkPolicyDelta,classifyResolvedLayerCoverage,classifyStatusWritePath,collectAnalysisConfigWarnings,collectEmptyAppliesToFindings,collectForbiddenCapabilityUses,composeMergePlanesHonesty,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createProjectId,createProjectIdentity,createResolvedCandidateFacts,defaultHonestLabel,demoteExtraPlaneTeethUnderClassificationFloor,deriveArkRuleFileHints,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,effectiveContractPolicyPayload,elevenLayerProfile,emptyEffectiveArkRules,evaluateArchitectureGraph,evaluateArkOrderSensors,evaluateArkRuleSensors,evaluateArkRunEditorSensors,evaluateArkRunEditorSensorsFromSource,evaluateArkRunSensors,evaluateInvariantCoverage,evaluateStatusBinding,explainViolation,extraMergeTeethAllowed,extractAgentProjectionBlock,extractArkRunDeclarationsFromSource,extractArkRunImportedConstructorNamesFromSource,extractArkRunKernelCallsFromSource,extractArkRunManagedNewsFromSource,extractArkRunValueImportDependenciesFromSource,extractClassShapesFromSource,extractSemanticDependencies,flatSkillTemplateFileRelativePath,formatAgentProjectionCatalogShortList,formatAgentProjectionLayers,formatArkRunDoctorLines,formatImprovementCompassDoctorLines,formatImprovementCompassResidualLabels,getDiagnosticCatalogEntry,inventoryToExtractionCard,isArkOrderRuleId,isArkRunKernelModuleSpecifier,isArkRunRuleId,isArkRunTransportBypassSpecifier,isArkSkillName,isCataloguedOrArkRuleFamily,isExtraPlaneFinding,isFirstClassArkSkillName,isKnownDiagnosticCode,isValidAgentSkillName,loadArkConfigContract,loadArkRulesContract,loadContract,loadResolvedCandidateFacts,mergeAgentProjectionDocument,normalizeExtraMergeTeethClassification,normalizeSkillContent,normalizeStatusImprovementCompass,parseAgentProjectionStamp,parseArkConfigJson,parseArkRulesJson,parseSkillDescriptionVersion,parseSkillDocument,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,primaryImprovementCompassNextAction,projectStatusArkRun,projectStatusImprovementCompass,projectionHasNonEnforcementLabel,projectionMatchesPackageVersion,resolveEffectiveContract,resolveStatusNextAction,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,skillDescriptionVersionPrefix,stableSerialize,stampSkillDescription,statusCompassResidualIsSubsetOfDoctor,stripSkillDescriptionVersion,summarizeArkRunSection,toAdapterDiagnostic,unavailableStatusImprovementCompass,validateAgentSkillDocument,validateAgentSkillsPackage,validateSkillProductCapacity,version});
|