arkgate 4.8.11 → 4.8.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +125 -2
  2. package/README.md +39 -46
  3. package/SECURITY.md +5 -3
  4. package/bin/ark-check-runtime.mjs +11 -9
  5. package/bin/lib/agent-projection-formatters.mjs +2 -0
  6. package/bin/lib/agent-skills-package.mjs +63 -8
  7. package/bin/lib/analysis-engine.mjs +4 -4
  8. package/bin/lib/architecture-scan.mjs +8 -2
  9. package/bin/lib/ark-order-doctor.mjs +160 -0
  10. package/bin/lib/ark-order-report.mjs +65 -0
  11. package/bin/lib/ark-order-sensors.mjs +1 -1
  12. package/bin/lib/ci-and-commands.mjs +7 -2
  13. package/bin/lib/design-smells.mjs +21 -1
  14. package/bin/lib/diagnostic-catalog.mjs +4 -4
  15. package/bin/lib/doctor-advisories.mjs +99 -18
  16. package/bin/lib/doctor-human.mjs +4 -11
  17. package/bin/lib/doctor-plan.mjs +4 -3
  18. package/bin/lib/extra-merge-teeth.mjs +32 -4
  19. package/bin/lib/first-run-help.mjs +11 -2
  20. package/bin/lib/gate-files.mjs +40 -3
  21. package/bin/lib/html-report-advisories.mjs +2 -0
  22. package/bin/lib/html-report-depth.mjs +8 -18
  23. package/bin/lib/html-report.mjs +16 -0
  24. package/bin/lib/install-migrate.mjs +23 -0
  25. package/bin/lib/mcp-hook-payload.mjs +1 -1
  26. package/bin/lib/product-copy.mjs +4 -0
  27. package/bin/lib/remediation.mjs +7 -7
  28. package/bin/lib/resolved-candidate-facts.mjs +144 -36
  29. package/bin/lib/rules-under-contract.mjs +14 -0
  30. package/bin/lib/scan-files.mjs +39 -0
  31. package/bin/lib/start-preview.mjs +4 -0
  32. package/bin/lib/status-command.mjs +28 -0
  33. package/bin/lib/status-manifest.mjs +23 -0
  34. package/bin/lib/upgrade-whats-new.mjs +3 -3
  35. package/bin/lib/violations.mjs +40 -1
  36. package/dist/{diagnosticCatalog-DiflIock.d.ts → diagnosticCatalog-DVx_2RmF.d.ts} +1 -1
  37. package/dist/eslint/index.cjs +4 -4
  38. package/dist/eslint/index.js +4 -4
  39. package/dist/index.cjs +31 -31
  40. package/dist/index.d.ts +129 -15
  41. package/dist/index.js +31 -31
  42. package/dist/nestjs/index.cjs +1 -1
  43. package/dist/nestjs/index.js +1 -1
  44. package/dist/runtime/index.cjs +15 -15
  45. package/dist/runtime/index.d.ts +1 -1
  46. package/dist/runtime/index.js +15 -15
  47. package/docs/README.md +11 -8
  48. package/docs/agent-guide.md +30 -13
  49. package/docs/ai-gates.md +3 -1
  50. package/docs/arkorder.md +35 -10
  51. package/docs/configuration.md +7 -6
  52. package/docs/develop.md +3 -1
  53. package/docs/diagnostics.md +7 -7
  54. package/docs/enthusiast/README.md +6 -1
  55. package/docs/enthusiast/how-to-gallery-starter.md +2 -1
  56. package/docs/package-surface.md +8 -5
  57. package/docs/product-voice.md +40 -13
  58. package/docs/threat-model.md +2 -2
  59. package/docs/typescript-support.md +3 -3
  60. package/docs/use.md +18 -11
  61. package/package.json +1 -1
  62. package/schemas/ark.status-manifest.schema.json +47 -0
  63. package/server.json +2 -2
  64. package/templates/agent-skills/README.md +7 -4
  65. package/templates/agent-skills/ark-adopt/SKILL.md +9 -5
  66. package/templates/agent-skills/ark-architect/SKILL.md +5 -18
  67. package/templates/agent-skills/ark-autopilot/SKILL.md +8 -4
  68. package/templates/agent-skills/ark-contract/SKILL.md +9 -20
  69. package/templates/agent-skills/ark-coverage/SKILL.md +12 -8
  70. package/templates/agent-skills/ark-explain/SKILL.md +7 -3
  71. package/templates/agent-skills/ark-explore/SKILL.md +25 -4
  72. package/templates/agent-skills/ark-fix/SKILL.md +15 -20
  73. package/templates/agent-skills/ark-loop/SKILL.md +14 -20
  74. package/templates/agent-skills/ark-order/SKILL.md +200 -0
  75. package/templates/agent-skills/ark-place/SKILL.md +11 -8
  76. package/templates/agent-skills/ark-runtime/SKILL.md +17 -4
  77. package/templates/agent-skills/ark-think/SKILL.md +24 -126
  78. package/templates/agent-skills/ark-upgrade/SKILL.md +13 -2
  79. package/templates/skills/ark-adopt.md +9 -5
  80. package/templates/skills/ark-architect.md +5 -18
  81. package/templates/skills/ark-autopilot.md +8 -4
  82. package/templates/skills/ark-contract.md +9 -20
  83. package/templates/skills/ark-coverage.md +12 -8
  84. package/templates/skills/ark-explain.md +7 -3
  85. package/templates/skills/ark-explore.md +25 -4
  86. package/templates/skills/ark-fix.md +15 -20
  87. package/templates/skills/ark-loop.md +14 -20
  88. package/templates/skills/ark-order.md +200 -0
  89. package/templates/skills/ark-place.md +11 -8
  90. package/templates/skills/ark-runtime.md +17 -4
  91. package/templates/skills/ark-think.md +24 -126
  92. package/templates/skills/ark-upgrade.md +13 -2
  93. package/templates/tests/ark-adoption-gaps.test.ts +5 -4
package/dist/index.cjs CHANGED
@@ -1,48 +1,48 @@
1
- "use strict";var Qt=Object.defineProperty;var Wa=Object.getOwnPropertyDescriptor;var qa=Object.getOwnPropertyNames;var Ya=Object.prototype.hasOwnProperty;var i=(e,t)=>Qt(e,"name",{value:t,configurable:!0});var Ja=(e,t)=>{for(var n in t)Qt(e,n,{get:t[n],enumerable:!0})},Xa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qa(t))!Ya.call(e,s)&&s!==n&&Qt(e,s,{get:()=>t[s],enumerable:!(r=Wa(t,s))||r.enumerable});return e};var Za=e=>Xa(Qt({},"__esModule",{value:!0}),e);var Hc={};Ja(Hc,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>ot,AGENT_PROJECTION_BEGIN_MARKER:()=>hs,AGENT_PROJECTION_END_MARKER:()=>Ut,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>nt,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Kt,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>vs,AGENT_SKILL_ENTRY_FILENAME:()=>_s,ANALYSIS_IR_SCHEMA_VERSION:()=>mn,ARKORDER_RULE_IDS:()=>Bn,ARKORDER_TIER1_SENSOR_IDS:()=>ra,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>qr,ARKRUN_KERNEL_FACTORY_CALLEES:()=>zr,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>Wo,ARKRUN_RULE_IDS:()=>Gn,ARKRUN_TIER1_SENSOR_IDS:()=>Xo,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>Wr,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Oe,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Va,ARK_ANALYSIS_RESULT_SCHEMA:()=>ar,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>st,ARK_CONFIG_SCHEMA:()=>cn,ARK_CONFIG_SCHEMA_VERSION:()=>te,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ya,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>ga,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Ht,ARK_PROJECT_IDENTITY_SCHEMA:()=>Hs,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>ir,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>$s,ARK_RULES_SCHEMA:()=>yn,ARK_RULES_SCHEMA_VERSION:()=>Ro,ARK_RULE_SENSORS:()=>Tr,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>Zr,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>rr,ARK_SKILL_NAMES:()=>Yt,ARK_SKILL_NAME_COUNT:()=>Os,ARK_STATUS_MANIFEST_SCHEMA:()=>Ta,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>ts,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>Jn,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>As,DIAGNOSTIC_CATALOG:()=>Dt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ha,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Yn,DIAGNOSTIC_RULE_IDS:()=>Aa,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>Ko,EffectiveContractError:()=>bt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>Cs,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>_e,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Vt,IMPROVEMENT_LENS_IDS:()=>jt,MERGE_PLANES_DUAL_STAMP:()=>Gr,POLICY_DELTA_SCHEMA_VERSION:()=>In,PROJECT_BINDING_SCHEMA:()=>cr,PROJECT_EXPECTATION_SCHEMA:()=>lr,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>fn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Se,STATUS_COMPASS_FACTS_SOURCES:()=>rs,STATUS_COMPASS_MODES:()=>ns,STATUS_COMPASS_REASON_CODES:()=>$t,adapterDocsCodePath:()=>it,adapterFindingOccurrenceTargetKeys:()=>Ke,adapterFindingRefFromTargetKey:()=>at,adapterFindingTargetKey:()=>Ue,agentProjectionContentIdentity:()=>He,agentSkillEntryRelativePath:()=>ws,agentSkillPackageFileRelativePath:()=>Ba,analyzeArchitectureConvergence:()=>De,analyzeChange:()=>Ot,analyzePolicyDelta:()=>wr,analyzeProject:()=>Xe,analyzeResolvedProject:()=>et,arkRunKernelCallKind:()=>Fn,buildAgentProjectionBeginMarker:()=>Zn,buildAgentProjectionBlock:()=>Rs,buildAgentProjectionBody:()=>Wt,buildAgentProjectionMeta:()=>ks,buildArkRuleFileHints:()=>Pn,buildEffectiveArkRules:()=>hn,buildImprovementCompass:()=>Fa,buildRulesInventory:()=>fa,buildStatusManifest:()=>Ca,canPromoteInvariant:()=>kn,catalogFixForRuleId:()=>Sa,catalogWhyForRuleId:()=>ba,classifyArkPolicyDelta:()=>Sn,classifyResolvedLayerCoverage:()=>wn,classifyStatusWritePath:()=>os,collectAnalysisConfigWarnings:()=>wt,collectEmptyAppliesToFindings:()=>Nn,collectForbiddenCapabilityUses:()=>Pe,composeMergePlanesHonesty:()=>Mn,createAICodeGate:()=>vr,createAdapterResult:()=>Fs,createArchitectureProfile:()=>At,createArchitectureProfileFromArkConfig:()=>_r,createElevenLayerArkConfig:()=>Or,createProjectId:()=>js,createProjectIdentity:()=>Vs,createResolvedCandidateFacts:()=>pn,defaultHonestLabel:()=>as,demoteExtraPlaneTeethUnderClassificationFloor:()=>Bo,deriveArkRuleFileHints:()=>Ur,detectArchitectureCycles:()=>Cn,deterministicHash:()=>Y,diagnosticDocsFragment:()=>es,diagnosticDocsPath:()=>Ea,effectiveContractPolicyPayload:()=>An,elevenLayerProfile:()=>ht,emptyEffectiveArkRules:()=>be,evaluateArchitectureGraph:()=>$e,evaluateArkOrderSensors:()=>zn,evaluateArkRuleSensors:()=>Tn,evaluateArkRunEditorSensors:()=>Yr,evaluateArkRunEditorSensorsFromSource:()=>Qo,evaluateArkRunSensors:()=>Lt,evaluateInvariantCoverage:()=>Rn,evaluateStatusBinding:()=>ss,explainViolation:()=>Dr,extraMergeTeethAllowed:()=>fe,extractAgentProjectionBlock:()=>qt,extractArkRunDeclarationsFromSource:()=>qo,extractArkRunImportedConstructorNamesFromSource:()=>Vn,extractArkRunKernelCallsFromSource:()=>Un,extractArkRunManagedNewsFromSource:()=>Kn,extractArkRunValueImportDependenciesFromSource:()=>jn,extractClassShapesFromSource:()=>Uo,extractSemanticDependencies:()=>Ne,flatSkillTemplateFileRelativePath:()=>za,formatAgentProjectionCatalogShortList:()=>Qn,formatAgentProjectionLayers:()=>Gt,formatArkRunDoctorLines:()=>ca,formatImprovementCompassDoctorLines:()=>$a,formatImprovementCompassResidualLabels:()=>gs,getDiagnosticCatalogEntry:()=>Mt,inventoryToExtractionCard:()=>ma,isArkOrderRuleId:()=>Go,isArkRunKernelModuleSpecifier:()=>Qe,isArkRunRuleId:()=>Dn,isArkRunTransportBypassSpecifier:()=>$n,isArkSkillName:()=>nr,isCataloguedOrArkRuleFamily:()=>ka,isExtraPlaneFinding:()=>Kr,isKnownDiagnosticCode:()=>Ra,isValidAgentSkillName:()=>xs,loadArkConfigContract:()=>yt,loadArkRulesContract:()=>St,loadContract:()=>_t,loadResolvedCandidateFacts:()=>Re,mergeAgentProjectionDocument:()=>bs,normalizeExtraMergeTeethClassification:()=>Ln,normalizeSkillContent:()=>tr,normalizeStatusImprovementCompass:()=>ls,parseAgentProjectionStamp:()=>er,parseArkConfigJson:()=>un,parseArkRulesJson:()=>ko,parseSkillDescriptionVersion:()=>Ka,parseSkillDocument:()=>Ts,policyDeltaAcknowledgementMatches:()=>bn,preflightChange:()=>Jr,preflightResolvedChange:()=>Xr,primaryImprovementCompassNextAction:()=>ys,projectStatusArkRun:()=>Wn,projectStatusImprovementCompass:()=>Xn,projectionHasNonEnforcementLabel:()=>Ss,projectionMatchesPackageVersion:()=>Is,resolveEffectiveContract:()=>Io,resolveStatusNextAction:()=>is,resolvedFactsEvidenceRequirementsHash:()=>Je,serializeDiagnosticCatalog:()=>Ia,skillDescriptionVersionPrefix:()=>Ps,stableSerialize:()=>M,stampSkillDescription:()=>Ga,statusCompassResidualIsSubsetOfDoctor:()=>xa,stripSkillDescriptionVersion:()=>Ls,summarizeArkRunSection:()=>la,toAdapterDiagnostic:()=>en,unavailableStatusImprovementCompass:()=>Oa,validateAgentSkillDocument:()=>Ns,validateAgentSkillsPackage:()=>Ua,version:()=>Ds});module.exports=Za(Hc);var Ds="4.8.11";var Qa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ei=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,ti=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ni(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Qa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ei.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":ti.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(ni,"classifyLayerImportKind");function ri(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=ni(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(ri,"layerImportNextAction");function si(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(si,"arkRunCallSiteName");function oi(e){let t=si(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(oi,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ri(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"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 oi(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"Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.";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?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). 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(pe,"deterministicNextAction");var st="1.5",ot="docs/diagnostics.md",ar={$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 Ue(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,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",o??""].join("|")}i(Ue,"adapterFindingTargetKey");function Ke(e){let t=new Map;return e.map(n=>{let r=Ue(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}i(Ke,"adapterFindingOccurrenceTargetKeys");function at(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(at,"adapterFindingRefFromTargetKey");function it(e){return`${ot}#${e}`}i(it,"adapterDocsCodePath");function _(e){return typeof e=="string"&&e.length>0?e:void 0}i(_,"text");function Ms(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Ms,"positiveInteger");function ai(e,t,n){return pe({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0})}i(ai,"nextActionForDiagnostic");function en(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},..._(e.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{}},a=n??Ue(e),l=at(a);return{ruleId:r,severity:s,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:Ms(e.line,1),column:Ms(e.column,1)},evidence:o,nextAction:_(e.nextAction)??ai(r,o,e),findingRef:l,targetKey:a,docsCodePath:it(r)}}i(en,"toAdapterDiagnostic");function Fs(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(y=>({code:_(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(y.message)??`Analysis ${t}: required evidence is incomplete.`,..._(y.file)?{file:_(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],l=Ke(o),c=Ke(a),u=[...o.map((y,g)=>en(y,"error",l[g])),...a.map((y,g)=>en(y,"warning",c[g]))],f={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...s};let y={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...y}:{...f,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...s}:{...f,mode:n,valid:!1,completeness:t,...s}}i(Fs,"createAdapterResult");var $s="1.0",ir="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",tn="^sha256:[a-f0-9]{64}$",lr={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:tn,description:"Project id previously returned by ark_identity or ark_manifest."}}},cr={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:tn},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Hs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ir,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:tn},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:tn},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:lr,binding:cr}};function js(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(js,"createProjectId");function Vs(e){return{schemaVersion:"1.0",...e}}i(Vs,"createProjectIdentity");var ur=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),fr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),mr=Object.freeze(Object.keys(fr).sort()),dr=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"}),pr=Object.freeze({process:Object.freeze(["process","node:process"])});function lt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=dr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=dr[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:dr[e.slice(0,o)]??null}i(lt,"capabilityForModuleSpecifier");function Ie(e,t){for(let n of t)if(pr[n]?.includes(e))return n;return null}i(Ie,"forbiddenGlobalForModuleSpecifier");function nn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=fr[r];if(s)return s}return null}i(nn,"capabilityForAmbientName");function Ge(e){if(e?.pure===!0)return[...ur].sort();let n=(e?.capabilities?.deny??[]).filter(r=>ur.includes(r));return[...new Set(n)].sort()}i(Ge,"effectiveCapabilityDeny");function ct(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}i(ct,"ambientCoveredByForbiddenGlobals");function rn(e){let t=new Set,n=new Set,r=Object.keys(fr);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of pr[s]??[])t.add(`import-exact:${a}`)}for(let s of Ge(e)){if(t.add(`import:${s}`),s==="process")for(let o of pr.process)t.add(`import-exact:${o}`);for(let o of r)nn(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(rn,"loweredLayerCoverage");var Us=new Map;function Ks(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ks,"escapeLiteral");function sn(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}i(sn,"normalizeGlobSeparators");function ii(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(ii,"bracesBalanced");function ge(e){let t=Us.get(e);if(t)return t;let n=sn(e),r=ii(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=Ks(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=Ks(c)}let a=new RegExp(`^${s}$`);return Us.set(e,a),a}i(ge,"globToRegExp");function li(e){return sn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(li,"concreteGlobSegments");function gr(e,t){let n=sn(String(e)),r=li(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let l=0,c=-1;for(let u of r){let f=-1;for(let y=l;y<a.length;y+=1)if(a[y]===u){f=y;break}if(f<0)return o;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+s}i(gr,"patternSpecificity");function de(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>ge(a).test(n))){for(let a of o.patterns??[])if(ge(a).test(n)){let l=gr(a,n);l>s&&(s=l,r=o.name)}}return r}i(de,"layerForRelativePath");function Gs(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}i(Gs,"sliceIdForPath");function ci(e){let t=new Set;for(let n of e??[]){let s=sn(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let l=s[o-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(ci,"inferSliceFoldersFromPatterns");function di(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return ci(r?.patterns)}i(di,"resolveSliceFolders");function Bs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Bs,"normalizeSegments");function qs(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(qs,"trimTrailingSlashes");var ui=["src","app"];function pi(e){let t=qs(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(pi,"isBlanketRoot");function zs(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=Bs(n);for(let o of t){if(typeof o!="string"||o.length===0||pi(o))continue;if(o.includes("*")){let c=qs(o.toLowerCase());if(ge(c).test(r)||ge(`${c}/**`).test(r))return!0;continue}let a=Bs(o);if(a.length===0)continue;let l=ui.includes(s[0])&&a[0]!==s[0]?[0,1]:[0];for(let c of l){if(c+a.length>s.length)continue;let u=!0;for(let f=0;f<a.length;f+=1)if(s[c+f]!==a[f]){u=!1;break}if(u)return!0}}return!1}i(zs,"pathUnderSharedRoot");function Ws(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(Ws,"sliceMatchesDeclaration");function fi(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Ws(r.from,t)&&Ws(r.to,n))}i(fi,"crossSliceEdgeAllowed");function mi(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(mi,"peerIsolationDecision");function Be(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(s=>!!s);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(Be,"peerIsolationDenyExplanation");function on(e,t,n,r){return Te(e,t,n,r)?.rule}i(on,"findDeniedEdgeRule");function Te(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,l=di(s,t,r?.layers),c=o?Gs(o,l):void 0,u=a?Gs(a,l):void 0,f=mi({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&zs(o,s.sharedRoots),toShared:!u&&zs(a,s.sharedRoots),crossSliceAllowed:fi(s.allowedCrossSlice,c,u)});if(f.denied)return{rule:s,peerIsolationReason:f.reason,fromSlice:c,toSlice:u};continue}if(t!==n)return{rule:s}}}i(Te,"findDeniedEdgeDecision");function ze(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ze,"literalText");function Xs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Xs,"lineOf");function Ys(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.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(Ys,"isTypeOnlyReference");function Zs(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(Zs,"singleFileChecker");function yr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(yr,"symbolAt");function hr(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):yr(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(hr,"localDeclaration");function Ne(e,t){let n,r=[],s=i((a,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Xs(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",ze(e,a.moduleSpecifier),Ys(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",ze(e,a.moduleSpecifier),Ys(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",ze(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!hr(e,n??(n=Zs(e,t)),t,a.expression);(l||u)&&s(a,u?"require":"dynamic-import",ze(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i(Ne,"extractSemanticDependencies");function gi(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=ze(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(gi,"staticAccessPath");function yi(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(yi,"runtimeIdentifierReference");function Js(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}i(Js,"bestForbiddenMatch");function Pe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Zs(e,t),o=new Map,a=new Set;for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations)e.isIdentifier(p.name)&&a.add(p.name.text);let l=i(g=>{let p=gi(e,g);if(!p)return;let m=yr(s,p.root),A=m?o.get(m):void 0;return A?[...A,...p.segments.slice(1)]:hr(e,s,t,p.root)||a.has(p.root.text)?void 0:p.segments},"resolvePath");for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let m=l(p.initializer),A=yr(s,p.name);!m||!A||o.set(A,m)}let c=[],u=new Set,f=i((g,p)=>{let m=Xs(t,p),A=`${g}:${p.getStart(t)}`;u.has(A)||(u.add(A),c.push({name:g,line:m,node:p}))},"flag"),y=i(g=>{let p=g.parent&&(e.isPropertyAccessExpression(g.parent)||e.isElementAccessExpression(g.parent))&&g.parent.expression===g;if((e.isPropertyAccessExpression(g)||e.isElementAccessExpression(g))&&!p){let m=l(g),A=m?Js(r,m):void 0;A&&f(A,g)}else e.isIdentifier(g)&&r.has(g.text)&&yi(e,g)&&!hr(e,s,t,g)&&f(g.text,g);if(e.isVariableDeclaration(g)&&e.isObjectBindingPattern(g.name)&&g.initializer){let m=l(g.initializer);if(m)for(let A of g.name.elements){if(!e.isIdentifier(A.name))continue;let S=A.propertyName?ze(e,A.propertyName)??A.propertyName.text:A.name.text,O=Js(r,[...m,S]);O&&f(O,g.initializer)}}e.forEachChild(g,y)},"visit");return y(t),c}i(Pe,"collectForbiddenCapabilityUses");function Ar(e,t,n){let r=[];for(let s of n?.dependencies??Ne(e,t)){if(s.typeOnly||!s.specifier)continue;let o=lt(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Pe(e,t,mr)){let o=nn(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}i(Ar,"collectCapabilityUses");var Rr={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."},kr=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 Er(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}i(Er,"resolveIntentLayer");function Le(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Le,"looksLikeArkIntent");function dt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Le(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Rr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Rr.PUBLISH_MISSING_SOURCE}),t}i(dt,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function We(e,t){return e.slice(0,t).split(`
2
- `).length}i(We,"lineOf");var hi=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ai(e,t){return e.index+e[0].indexOf(t)}i(Ai,"captureIndex");function Ri(e){let t=[],n=new Set,r=i((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),s=i(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&r(u,Ai(c,u))}},"pushFrom");s(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),s(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let o=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=o.exec(e))!==null;){let l=a[1]??"",c=a.index+a[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=u.exec(l))!==null;){let y=f[1];y&&r(y,c+f.index+f[0].indexOf(y))}}return s(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),s(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}i(Ri,"extractQuotedStrings");function ki(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 s;for(;(s=r.re.exec(e))!==null;){let o=s.index+s[0].indexOf(s[1]),a=s[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:o,kind:r.kind,typeOnly:l})}}return t.sort((r,s)=>r.index-s.index)}i(ki,"extractModuleSpecifiers");function Ei(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(Ei,"isSyntaxWrapper");function Ir(e,t){let n=t;for(;n?.parent&&Ei(e,n.parent);)n=n.parent;return n}i(Ir,"unwrapWrappers");function Sr(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(Sr,"callCalleeName");function Ii(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Ir(e,n),s=r.parent;if(!s)return!1;if(e.isCallExpression(s)&&Sr(e,s)==="publish"){let o=s.arguments;return o[1]===r||o[2]===r}if(e.isPropertyAssignment(s)&&br(e,s.name)==="metadata"){let o=s.parent;if(!o)return!1;let l=Ir(e,o).parent;return!!(l&&e.isCallExpression(l)&&Sr(e,l)==="publish")}return!1}i(Ii,"isPublishMetadataSource");function Qs(e,t){let n=Ir(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let s=Sr(e,r);if(s&&hi.has(s)&&r.arguments.some(o=>o===n))return!0}if(e.isArrayLiteralExpression(r))return Qs(e,r);if(e.isPropertyAssignment(r)){let s=br(e,r.name);if(s==="intent"||s==="onEvent"||s==="reactsTo"||s==="source"&&Ii(e,r))return!0}return!1}i(Qs,"isDeclaredIntentSite");function Si(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(o=>{e.isStringLiteralLike(o)&&Qs(e,o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)},"visit");return s(n),r}i(Si,"extractQuotedStringsAst");function bi(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(bi,"hasInfrastructureToken");function vi(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(vi,"isKnownInfrastructurePackage");function Ci(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Ci,"layerHasInfrastructureRole");function pt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(pt,"tsStringLiteralText");function br(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(br,"tsPropertyName");function eo(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:br(e,r.name)===n)}i(eo,"tsObjectProperty");function ft(e,t,n){return eo(e,t,n)!==void 0}i(ft,"tsObjectHasProperty");function ut(e,t,n){let r=eo(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(ut,"tsObjectPropertyValue");function _i(e,t){let n=ut(e,t,"metadata");return ft(e,n,"source")}i(_i,"tsObjectHasMetadataSource");function to(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?to(e,t.name):!1:!1}i(to,"tsLooksLikeIntentCreatorExpression");function Oi(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(Oi,"tsIsPublishCall");function xi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=pt(e,n);return r!==void 0&&Le(r)||ft(e,n,"intent")||to(e,n)}i(xi,"tsIsArkPublishCandidate");function Ti(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return _i(e,n)||ft(e,r,"source")||ft(e,s,"source")}i(Ti,"tsPublishHasSource");function Ni(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=ut(e,n,"metadata");return pt(e,ut(e,o,"source"))??pt(e,ut(e,r,"source"))??pt(e,ut(e,s,"source"))}i(Ni,"tsPublishSourceLiteral");function Pi(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=n,a=o?.filePath,l=o?.layer,c=[],u=i(y=>s.getLineAndCharacterOfPosition(y.getStart(s)).line+1,"lineForNode"),f=i(y=>{if(Oi(e,y)){let g=y.arguments[0],p=pt(e,g);for(let A of dt({publishCall:!0,rawIntentName:p,objectHasIntent:ft(e,g,"intent"),arkPublishCandidate:xi(e,y),hasSource:Ti(e,y)}))c.push(W(A.ruleId,A.message,{line:u(y),filePath:a}));let m=Ni(e,y);if(r&&l&&m&&Le(m)){let A=r.resolveLayer(m);A&&A!==l&&c.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${m}" resolves to ${A}, but the target file is classified as ${l}.`,{line:u(y),filePath:a,target:m,fromLayer:l,toLayer:A}))}}e.forEachChild(y,f)},"visit");return f(s),c}i(Pi,"analyzePublishAst");function vr(e={}){let t=new Set((e.intents||[]).map(o=>typeof o=="string"?o:o.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(o,a){let l=[],c=a,u=c?.filePath,f=c?.layer,y=e.typescript,g=y?y.createSourceFile(u??"generated.ts",o,y.ScriptTarget.Latest,!0):void 0,p=g?Ne(e.typescript,g):void 0,m=p?p.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(g),kind:R.kind,typeOnly:R.typeOnly})):ki(o),A=e.typescript?Si(e.typescript,o):Ri(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let R of p?.filter(({unresolved:I})=>I)??[]){let I=R.kind==="require";l.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:R.line,filePath:u}))}let S=f!==void 0&&(r.has(f)||Ci(f)),O=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let R of n)if(R instanceof RegExp){R.lastIndex=0;let I=R.exec(o);R.lastIndex=0,I&&l.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:I.index===void 0?void 0:We(o,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+O}))}else o.includes(R)&&l.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:We(o,o.indexOf(R)),filePath:u}));for(let R of m){let I=e.resolveImportTarget?.(R.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,u)}:void 0),v=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,w=I?.layer;if(w&&f){let k=on(e.architectureProfile?.rules,f,w,{fromPath:v?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(k){if(R.typeOnly&&!k.peerIsolation)continue;let P=!!k.peerIsolation;l.push(W("LAYER_IMPORT_VIOLATION",k.message??(P?`Layer "${f}" must not import across slices into "${w}".`:`Layer "${f}" must not import "${w}".`),{line:We(o,R.index),source:R.value,target:R.value,filePath:u,fromLayer:f,toLayer:w,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:R.kind,peerIsolation:P,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}S||R.typeOnly||!bi(R.value)&&!vi(R.value)||l.push(W("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:We(o,R.index),source:R.value,target:R.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+O,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let I=R.check({source:o,context:a});if(I!==!0)if(Array.isArray(I))for(let v of I)l.push(W("POLICY_VIOLATION",v.message,{filePath:u,suggestion:`Fix violation of policy "${R.name}".`}));else I===!1?l.push(W("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(W("POLICY_VIOLATION",I.message))}if(s&&t.size>0)for(let R of A)Le(R.value)&&!t.has(R.value)&&l.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:We(o,R.index),filePath:u,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let R of A){if(!Le(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let v=Te(e.architectureProfile.rules,f,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(v){let w=v.rule.peerIsolation?Be(v.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:v.fromSlice,toSlice:v.toSlice}):void 0,k=`Layer "${f}" must not reference "${I}" through "${R.value}".`,P=w&&v.peerIsolationReason!=="cross-slice"?`${k} ${w}`:v.rule.message?w?`${v.rule.message} (${w})`:v.rule.message:k;l.push(W("LAYER_REFERENCE_VIOLATION",P,{line:We(o,R.index),filePath:u,target:R.value,fromLayer:f,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:v.rule,peerIsolationReason:v.peerIsolationReason}}))}}if(e.extensions)for(let R of e.extensions)try{let I=R.analyze(o,a);l.push(...I)}catch(I){l.push(W("EXTENSION_ERROR",`Extension "${R.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&g&&f&&e.forbiddenGlobals?.[f]?.length)try{let R=e.forbiddenGlobals[f];l.push(...Pe(e.typescript,g,R).map(I=>W("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of p??[]){if(I.typeOnly||!I.specifier)continue;let v=Ie(I.specifier,R);v&&l.push(W("FORBIDDEN_GLOBAL",`${f} must not use module "${I.specifier}" because it is the import form of forbidden global "${v}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:f,details:{importKind:I.kind,forbiddenGlobal:v},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&g&&f&&e.capabilityWalls?.[f]?.length)try{let R=new Set(e.capabilityWalls[f]),I=e.forbiddenGlobals?.[f]??[];for(let v of Ar(e.typescript,g))R.has(v.capability)&&(v.source==="ambient-global"&&ct(v.symbol,I)||v.source==="import-based"&&Ie(v.symbol,I)||l.push(W("CAPABILITY_VIOLATION",v.source==="import-based"?`${f} denies the ${v.capability} capability; found import of "${v.symbol}".`:`${f} denies the ${v.capability} capability; found ambient "${v.symbol}".`,{line:v.line,filePath:u,target:v.symbol,capability:v.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...Pi(e.typescript,o,a,e.architectureProfile))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(vr,"createAICodeGate");var we={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},no={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...we,default:[]},kernelRoots:{...we},managedLayers:{...we,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},ro={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...we,default:[]},managedLayers:{...we,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...we,default:[]},appliesTo:{...we,default:[]}}};function mt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(mt,"isObject");function so(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)mt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(so,"declaredLayerNames");function oo(e){if(!mt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(oo,"defaultedArkRun");function ao(e){if(!mt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(ao,"defaultedArkOrder");function io(e,t){let n=e.arkRun;if(n===void 0||!mt(n))return;let r=so(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(io,"validateArkRunExtra");function lo(e,t){let n=e.arkOrder;if(n===void 0||!mt(n))return;let r=so(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(lo,"validateArkOrderExtra");var te="1.3",ln="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",co=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Li=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function wi(){let e=[];for(let t of co)for(let n of co)t===n||Li.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(wi,"createDefaultRules");var dn=wi(),Cr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ie={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},cn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ln,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:ln,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:te,default:te},name:{type:"string",minLength:1},include:{...ie,minItems:1,default:["src"]},exclude:{...ie,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:dn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ie,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ie,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ie,minItems:1},exclude:ie,intentPrefixes:ie,description:{type:"string",minLength:1},forbiddenGlobals:ie,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...ie,minItems:1},sharedRoots:{...ie,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},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:{...ie,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...ie,minItems:1}}},arkRun:no,arkOrder:ro}},ye=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 uo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(uo,"isObject");function an(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(an,"propertyPath");function qe(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(qe,"valueType");function Di(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Di,"resolveSchemaRef");function gt(e,t,n,r,s){if(t.$ref){let o=Di(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}gt(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!uo(e)){s.push({path:n,message:`must be an object; received ${qe(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:an(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:an(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||gt(e[l],a,an(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&gt(e[a],l,an(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${qe(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>gt(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${qe(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${qe(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${qe(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(gt,"validateNode");function Mi(e){let t={...e,$schema:e.$schema===void 0?ln:e.$schema,schemaVersion:e.schemaVersion===void 0?te:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?dn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=oo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=ao(e.arkOrder)),t}i(Mi,"defaultedConfig");function Fi(e){return e===te?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Fi,"migratedFromOf");function $i(){let e=new Set([te]);for(let t of Cr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i($i,"knownInputVersions");function Hi(e,t="ark.config.json"){if(!uo(e))throw new ye(t,[{path:"$",message:`must be an object; received ${qe(e)}`}]);let n=$i(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${te}`}]);if(r!=="unversioned"&&!n.has(r))throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);let s=r,o={...e},a=0;for(;s!==te&&a<Cr.length+1;){a+=1;let l=Cr.find(c=>c.from===s);if(!l)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${te}`}]);s=l.to,o.schemaVersion=s}if(s!==te)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);return{candidate:Mi(o),migratedFrom:Fi(r)}}i(Hi,"migrateArkConfig");function yt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Hi(e,t),s=[];if(gt(n,cn,"$",cn,s),io(n,s),lo(n,s),s.length>0)throw new ye(t,s);return{config:n,migratedFrom:r}}i(yt,"loadArkConfigContract");function un(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ye(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return yt(n,t)}i(un,"parseArkConfigJson");function po(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:ln,schemaVersion:te};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(po,"withArkConfigMetadata");function ji(e){return e.endsWith(".")?e:`${e}.`}i(ji,"normalizePrefix");function Vi(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}i(Vi,"byLongestPrefix");function At(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(ji)})),n=[...t].sort(Vi),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(o=>o.match?.(s))?.name??n.find(o=>o.prefixes.some(a=>s.startsWith(a)))?.name}}}i(At,"createArchitectureProfile");function _r(e,t={}){return At({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}i(_r,"createArchitectureProfileFromArkConfig");var Ui=[{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}],ht=At({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ui,rules:dn.map(e=>({...e}))}),Ki={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 Or(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return po({include:e.include??[t],layers:ht.layers.map(s=>({name:s.name,patterns:(Ki[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...ht.rules]})}i(Or,"createElevenLayerArkConfig");function Y(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(Y,"deterministicHash");function M(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(M).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${M(t[n])}`).join(",")}}`}i(M,"stableSerialize");var Se="1.2";var fo=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=M(e),r=M(t);return n<r?-1:n>r?1:0}i(q,"compareCanonical");function X(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(X,"sortedUnique");function Je(e){let t={schemaVersion:"1.2",include:X(e.include??[]),exclude:X(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:X(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:X(n.patterns??[]),exclude:X(n.exclude??[]),forbiddenGlobals:X(n.forbiddenGlobals??[]),intentPrefixes:X(n.intentPrefixes??[]),capabilityDeny:X(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:X(e.arkRun.compositionRoots),managedLayers:X(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return Y(M(t))}i(Je,"resolvedFactsEvidenceRequirementsHash");function Gi(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(q),n=e.files.map(k=>({...k,typeOnlyExportNames:X(k.typeOnlyExportNames)})).sort((k,P)=>k.path<P.path?-1:k.path>P.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:X(k.namedBindings)}:{}})).sort(q),s=e.capabilityUses.map(k=>({...k})).sort(q),o=e.ambientUses.map(k=>({...k})).sort(q),a=e.publishCalls.map(k=>({...k})).sort(q),l=e.intentReferences.map(k=>({...k})).sort(q),c=e.safetyUses.map(k=>({...k})).sort(q),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(P=>({...P}))})).sort(q),f=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(q),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(q),g=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(q),p=(e.arkRunDeclarations??[]).map(k=>({...k,uses:X(k.uses),reactsTo:X(k.reactsTo),raises:X(k.raises),sends:X(k.sends)})).sort(q),m=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(q),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(q),S=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(q),O=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(q),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(q),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(q),v=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),w=Y(M(v));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:w,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:g,arkRunDeclarations:p,arkOrderPlaneCalls:m,arkOrderGenericUpdates:A,arkOrderRootHits:S,arkOrderXiFieldWrites:O,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:I}}i(Gi,"canonicalResolvedFactsInput");function mo(e){let t=Gi(e);return{...t,factsHash:Y(M(t))}}i(mo,"createCanonicalResolvedCandidateFacts");function pn(e){return mo(yo(F(e,"$"),!1))}i(pn,"createResolvedCandidateFacts");function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(F,"asRecord");function j(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}i(j,"assertOnlyKeys");function D(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(D,"requiredText");function he(e,t,n){if(e[t]!==void 0)return D(e,t,n)}i(he,"optionalText");function U(e,t,n){let r=D(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let o=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(l);let a=o.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(U,"requiredProjectPath");function K(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(K,"requiredBoolean");function go(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(go,"requiredInteger");function Q(e,t,n){let r=go(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Q,"requiredPositiveInteger");function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(G,"requiredArray");function Ae(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}i(Ae,"enumValue");function Ye(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(Ye,"parseStringArray");function Bi(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}i(Bi,"assertUnique");function yo(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=Ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ae(e,"completeness",["complete","partial","unavailable"],"$"),s=G(e,"completenessReasons","$").map((b,C)=>{let h=`$.completenessReasons[${C}]`,d=F(b,h);j(d,["code","message","file"],h);let L=d.file===void 0?void 0:U(d,"file",h);return{code:D(d,"code",h),message:D(d,"message",h),...L?{file:L}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=G(e,"files","$").map((b,C)=>{let h=`$.files[${C}]`,d=F(b,h);return j(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:U(d,"path",h),contentHash:D(d,"contentHash",h),parseStatus:Ae(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:go(d,"parseDiagnosticCount",h),exportsOnlyTypes:K(d,"exportsOnlyTypes",h),typeOnlyExportNames:Ye(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:K(d,"hasTopLevelSideEffects",h)}}),a=G(e,"dependencies","$").map((b,C)=>{let h=`$.dependencies[${C}]`,d=F(b,h);j(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let L=he(d,"specifier",h),H=he(d,"target",h),ae=Ae(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ae==="resolved-project"&&!H)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ae!=="resolved-project"&&H)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ae!=="dynamic"&&!L)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:U(d,"from",h),...L?{specifier:L}:{},kind:Ae(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:K(d,"typeOnly",h),line:Q(d,"line",h),resolution:ae,...H?{target:U(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Ye(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:K(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:K(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:K(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:K(d,"portProofEligible",h)}:{}}}),l=G(e,"capabilityUses","$").map((b,C)=>{let h=`$.capabilityUses[${C}]`,d=F(b,h);return j(d,["file","line","symbol","capability","source"],h),{file:U(d,"file",h),line:Q(d,"line",h),symbol:D(d,"symbol",h),capability:Ae(d,"capability",fo,h),source:Ae(d,"source",["ambient-global","import-based"],h)}}),c=G(e,"ambientUses","$").map((b,C)=>{let h=`$.ambientUses[${C}]`,d=F(b,h);return j(d,["file","line","symbol"],h),{file:U(d,"file",h),line:Q(d,"line",h),symbol:D(d,"symbol",h)}}),u=G(e,"publishCalls","$").map((b,C)=>{let h=`$.publishCalls[${C}]`,d=F(b,h);j(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let L=he(d,"rawIntentName",h),H=he(d,"sourceIntent",h);return{file:U(d,"file",h),line:Q(d,"line",h),...L?{rawIntentName:L}:{},objectHasIntent:K(d,"objectHasIntent",h),arkPublishCandidate:K(d,"arkPublishCandidate",h),hasSource:K(d,"hasSource",h),...H?{sourceIntent:H}:{}}}),f=G(e,"intentReferences","$").map((b,C)=>{let h=`$.intentReferences[${C}]`,d=F(b,h);return j(d,["file","line","intent"],h),{file:U(d,"file",h),line:Q(d,"line",h),intent:D(d,"intent",h)}}),y=G(e,"safetyUses","$").map((b,C)=>{let h=`$.safetyUses[${C}]`,d=F(b,h);j(d,["file","line","kind","symbol"],h);let L=he(d,"symbol",h),H=Ae(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(H==="in-memory-store"&&!L)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(H!=="in-memory-store"&&L)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:U(d,"file",h),line:Q(d,"line",h),kind:H,...L?{symbol:L}:{}}});Bi(o,b=>b.path,"$.files");let g=new Set(o.map(b=>b.path));for(let b of o){if(b.parseStatus==="parsed"&&b.parseDiagnosticCount!==0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(b.parseStatus==="invalid"&&b.parseDiagnosticCount===0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(b=>b.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let b of a)if(!g.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);let m=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((b,C)=>{let h=`$.arkRunKernelCalls[${C}]`,d=F(b,h);j(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let L=he(d,"receiver",h),H=he(d,"nameLiteral",h);return{file:U(d,"file",h),line:Q(d,"line",h),kind:Ae(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:D(d,"callee",h),viaImport:K(d,"viaImport",h),...L?{receiver:L}:{},...H?{nameLiteral:H}:{}}}),S=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((b,C)=>{let h=`$.arkRunManagedNews[${C}]`,d=F(b,h);j(d,["file","line","typeName","importedFrom"],h);let L=he(d,"importedFrom",h);return{file:U(d,"file",h),line:Q(d,"line",h),typeName:D(d,"typeName",h),...L?{importedFrom:L}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((b,C)=>{let h=`$.arkRunCompositionRootHits[${C}]`,d=F(b,h);return j(d,["file","matchedRoot","hasKernelFactory"],h),{file:U(d,"file",h),matchedRoot:D(d,"matchedRoot",h),hasKernelFactory:K(d,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),w=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((b,C)=>{let h=`$.arkOrderPlaneCalls[${C}]`,d=F(b,h);return j(d,["file","line","callee"],h),{file:U(d,"file",h),line:Q(d,"line",h),callee:D(d,"callee",h)}}),P=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((b,C)=>{let h=`$.arkOrderGenericUpdates[${C}]`,d=F(b,h);return j(d,["file","line","method"],h),{file:U(d,"file",h),line:Q(d,"line",h),method:D(d,"method",h)}}),T=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((b,C)=>{let h=`$.arkOrderRootHits[${C}]`,d=F(b,h);return j(d,["file","matchedRoot","hasPlaneFactory"],h),{file:U(d,"file",h),matchedRoot:D(d,"matchedRoot",h),hasPlaneFactory:K(d,"hasPlaneFactory",h)}}),$=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((b,C)=>{let h=`$.arkOrderXiFieldWrites[${C}]`,d=F(b,h);return j(d,["file","line","key"],h),{file:U(d,"file",h),line:Q(d,"line",h),key:D(d,"key",h)}}),me=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((b,C)=>{let h=`$.arkOrderIngestWritesXi[${C}]`,d=F(b,h);return j(d,["file","line"],h),{file:U(d,"file",h),line:Q(d,"line",h)}}),Ve=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((b,C)=>{let h=`$.arkOrderReleaseKeyCounts[${C}]`,d=F(b,h);return j(d,["file","line","keyCount"],h),{file:U(d,"file",h),line:Q(d,"line",h),keyCount:Q(d,"keyCount",h)}}),rt=I.map((b,C)=>{let h=`$.arkRunDeclarations[${C}]`,d=F(b,h);return j(d,["file","line","uses","reactsTo","raises","sends"],h),{file:U(d,"file",h),line:Q(d,"line",h),uses:Ye(d.uses,`${h}.uses`),reactsTo:Ye(d.reactsTo,`${h}.reactsTo`),raises:Ye(d.raises,`${h}.raises`),sends:Ye(d.sends,`${h}.sends`)}});for(let[b,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",m],["$.arkRunManagedNews",S],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",rt],["$.arkOrderPlaneCalls",w],["$.arkOrderGenericUpdates",P],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",$],["$.arkOrderIngestWritesXi",me],["$.arkOrderReleaseKeyCounts",Ve]])for(let h of C)if(!g.has(h.file))throw new Error(`${b} references missing file ${h.file}.`);let xe=he(e,"projectPackageName","$"),sr=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((b,C)=>{let h=`$.classShapes[${C}]`,d=F(b,h);j(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let L=G(d,"mutatingMethods",h).map((H,ae)=>{let Zt=`${h}.mutatingMethods[${ae}]`,or=F(H,Zt);return j(or,["name","referencesGuardOrPublish"],Zt),{name:D(or,"name",Zt),referencesGuardOrPublish:K(or,"referencesGuardOrPublish",Zt)}});return{file:U(d,"file",h),className:D(d,"className",h),exported:K(d,"exported",h),hasPublicMutableFields:K(d,"hasPublicMutableFields",h),hasPublicSetters:K(d,"hasPublicSetters",h),hasPublicConstructor:K(d,"hasPublicConstructor",h),hasStaticFactory:K(d,"hasStaticFactory",h),mutatingMethods:L,...d.dataOnly===void 0?{}:{dataOnly:K(d,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:D(e,"resolverIdentity","$"),compilerIdentity:D(e,"compilerIdentity","$"),compilerOptionsHash:D(e,"compilerOptionsHash","$"),tsconfigHash:D(e,"tsconfigHash","$"),evidenceRequirementsHash:D(e,"evidenceRequirementsHash","$"),...xe?{projectPackageName:xe}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:sr,arkRunKernelCalls:m,arkRunManagedNews:S,arkRunCompositionRootHits:R,arkRunDeclarations:rt,arkOrderPlaneCalls:w,arkOrderGenericUpdates:P,arkOrderRootHits:T,arkOrderXiFieldWrites:$,arkOrderIngestWritesXi:me,arkOrderReleaseKeyCounts:Ve}}i(yo,"parseResolvedFactsInput");function Re(e){let t=F(e,"$"),n=D(t,"factsHash","$"),r=D(t,"candidateTreeHash","$"),s=mo(yo(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}i(Re,"loadResolvedCandidateFacts");var zi=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},ne={type:"integer",minimum:1},B={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},fn={$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:x,message:x,file:B}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:B,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},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:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ne,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:B,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:B,line:ne,symbol:x,capability:{enum:zi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:B,line:ne,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:B,line:ne,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:B,line:ne,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:ne,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},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:x,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:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:B,line:ne,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:B,line:ne,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:B,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:B,line:ne,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:B,line:ne,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:B,line:ne,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:B,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:ne,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:B,line:ne}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:B,line:ne,keyCount:{type:"integer",minimum:1}}}},factsHash:x},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 mn="1.0";function se(e){return`${e.from}->${e.to}`}i(se,"dependencyKey");function Rt(e,t,n,r="dependency"){return{id:`${e}:${r}:${se(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${se(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${se(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${se(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${se(t)} from the candidate, then preflight again.`}:{}}}i(Rt,"dependencyFinding");function De(e){let t=[],n=new Map(e.changeMap.map.files.map(g=>[g.path,g])),r=new Map(e.changes.map(g=>[g.path,g])),s=new Map(e.changeMap.map.dependencies.map(g=>[se(g),g])),o=new Map(e.baseDependencies.map(g=>[se(g),g])),a=new Map(e.candidateDependencies.map(g=>[se(g),g]));for(let g of[...n.values()].sort((p,m)=>p.path.localeCompare(m.path))){let p=r.get(g.path);p?p.operation!==g.operation?t.push({id:`contradictory:file:${g.path}`,classification:"contradictory",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} was planned as ${g.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${g.path} to the planned ${g.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${g.path}`,classification:"satisfied",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} matches the planned ${g.operation} operation.`}):t.push({id:`missing:file:${g.path}`,classification:"missing",subject:"file",path:g.path,expectedOperation:g.operation,message:`${g.path} was planned as ${g.operation} but is absent from the actual change.`,nextAction:`${g.operation[0].toUpperCase()}${g.operation.slice(1)} ${g.path} in the complete change set, then preflight again.`})}for(let g of[...r.values()].sort((p,m)=>p.path.localeCompare(m.path)))n.has(g.path)||t.push({id:`unplanned:file:${g.path}`,classification:"unplanned",subject:"file",path:g.path,actualOperation:g.operation,message:`${g.path} has an unplanned ${g.operation} operation.`,nextAction:`Remove ${g.path} from the change set, then preflight again.`});let l=new Set;for(let g of[...s.values()].sort((p,m)=>se(p).localeCompare(se(m)))){if(a.has(se(g))){t.push(Rt("satisfied",g,`${g.from} -> ${g.to} exists in the candidate architecture.`));continue}let p={from:g.to,to:g.from};a.has(se(p))?(l.add(se(p)),t.push(Rt("contradictory",g,`${g.from} -> ${g.to} was planned, but the candidate contains the reverse edge.`))):t.push(Rt("missing",g,`${g.from} -> ${g.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[g,p]of[...a].sort(([m],[A])=>m.localeCompare(A)))o.has(g)||s.has(g)||l.has(g)||!c.has(p.from)&&!c.has(p.to)||t.push({...Rt("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(g=>g.operation==="delete").map(g=>g.path));for(let[g,p]of[...o].sort(([m],[A])=>m.localeCompare(A)))a.has(g)||u.has(p.from)||u.has(p.to)||!c.has(p.from)&&!c.has(p.to)||t.push({...Rt("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((g,p)=>f[g.classification]-f[p.classification]||(g.subject===p.subject?0:g.subject==="file"?-1:1)||g.id.localeCompare(p.id));let y={satisfied:t.filter(g=>g.classification==="satisfied").length,missing:t.filter(g=>g.classification==="missing").length,contradictory:t.filter(g=>g.classification==="contradictory").length,unplanned:t.filter(g=>g.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(De,"analyzeArchitectureConvergence");var Ro="1.0",xr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Tr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Wi=["no-anemic-model"],ho={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},yn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xr,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:xr},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:[...Tr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ho,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:ho}}}},Me=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 It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(It,"isObject");function gn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(gn,"propertyPath");function kt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(kt,"valueType");function qi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(qi,"resolveSchemaRef");function Et(e,t,n,r,s){if(t.$ref){let o=qi(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Et(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!It(e)){s.push({path:n,message:`must be an object; received ${kt(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:gn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:gn(n,a),message:"unknown field"});else if(It(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||Et(e[l],a,gn(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&Et(e[a],l,gn(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${kt(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>Et(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${kt(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${kt(e)}`})}i(Et,"validateNode");function Yi(e){return{...e,$schema:e.$schema===void 0?xr: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(Yi,"defaultedArkRules");function Ao(e){return e==="enforced"?"enforced":"advisory"}i(Ao,"normalizeMode");function Ji(e){return Wi.includes(e)}i(Ji,"isTier2Sensor");function Xi(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((o,a)=>{if(!It(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),typeof o.sensor=="string"&&Ji(o.sensor)&&o.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`${l?`rule ${JSON.stringify(l)} uses sensor `:"sensor "}${JSON.stringify(o.sensor)}, which is Tier-2 advisory-only and cannot be enforced${l?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(o.appliesTo)&&o.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((o,a)=>{if(!It(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),Array.isArray(o.appliesTo)&&o.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(Xi,"validateSemantics");function St(e,t="arkrules.json",n){if(!It(e))throw new Me(t,[{path:"$",message:`must be an object; received ${kt(e)}`}]);let r=Yi(e),s=[];if(Et(r,yn,"$",yn,s),Xi(r,s),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),s.length>0)throw new Me(t,s);return{config:r}}i(St,"loadArkRulesContract");function ko(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new Me(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return St(r,t,n)}i(ko,"parseArkRulesJson");function hn(e){let t={},n=[],r=[],s=[...e].sort((o,a)=>o.layer.localeCompare(a.layer));for(let o of s){let a=(o.file.structure??[]).map(c=>({...c,mode:Ao(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}})),l=(o.file.invariants??[]).map(c=>({...c,mode:Ao(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}}));t[o.layer]={sourceFile:o.sourceFile,structure:a,invariants:l},n.push(...a),r.push(...l)}return n.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),r.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(hn,"buildEffectiveArkRules");function be(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(be,"emptyEffectiveArkRules");var bt=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 Eo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Eo,"normalizeRel");function Io(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let c of[...e.discoveredArkRulesFiles].sort())r.push({path:c,message:`ArkRules file ${JSON.stringify(c)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:be(),warnings:r}}let s=new Set(e.config.layers.map(c=>c.name)),o=[],a=[],l=new Set;for(let c of Object.keys(n).sort()){let u=n[c],f=`$.arkRules[${JSON.stringify(c)}]`;if(typeof u!="string"||u.length===0){o.push({path:f,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){o.push({path:f,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){o.push({path:f,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let y=Eo(u);l.add(y);let g=e.fileContents[y]??e.fileContents[u];if(g===void 0){o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let p=St(JSON.parse(g),y,c);a.push({layer:c,sourceFile:y,file:p.config})}catch(p){if(p instanceof Me)for(let m of p.issues)o.push({path:`${f}${m.path==="$"?"":m.path.replace(/^\$/,"")}`,message:`${y}: ${m.message}`});else p instanceof SyntaxError?o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${p.message}`}):o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} failed to load: ${p instanceof Error?p.message:String(p)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let u=Eo(c);l.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(o.length>0)throw new bt(t,o);return{config:e.config,arkRules:hn(a),warnings:r}}i(Io,"resolveEffectiveContract");function Nr(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}i(Nr,"omitLayerDescriptions");function An(e){let{stewards:t,...n}=Nr(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(An,"effectiveContractPolicyPayload");function So(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 s=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${s}.`}i(So,"formatCoverageDiscards");function Zi(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let s=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return s===""||s==="."?!0:n===s||n.startsWith(`${s}/`)})}i(Zi,"isUnderCoverageRoot");function Qi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Qi,"titleMatchesInvariant");function el(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let o of Object.values(e))if(!(s&&!o.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(o)||o.includes(t)))return!0;return!1}i(el,"symbolPresent");function Rn(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,s=e.coverageBudgetExhausted===!0,o=e.coverageStats,a=So(o),l=So(o,!0),c=o?`coverage file budget exhausted: ${o.filesLoaded} files loaded at the ${o.maxFiles}-file cap, ${o.testFilesRetained} tests retained, ${o.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof o.filesRead=="number"?`; ${o.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),f=u.length>0,y=u.join(", "),g=[],p=[];for(let m of t){let A=[],S=m.coverage?.test!==!1,O=m.coverage?.symbol,R,I;if(!r&&S){let P;for(let z of n){let T=e.fileContents[z];if(!(!T||!Qi(T,m.id))){if(!f||Zi(z,u)){R=z,I=f?!1:void 0;break}P??=z}}R===void 0&&P!==void 0&&(R=P,I=!0),R!==void 0&&A.push("test-title")}O&&el(e.fileContents,O)&&A.push("symbol");let w=(m.coverage?.test===!0||!!O||m.coverage===void 0)&&A.length>0||m.coverage?.test===!1&&!O?!0:A.length>0,k=r&&S&&A.length===0;if(g.push({invariantId:m.id,layer:m.provenance.layer,sourceFile:m.provenance.sourceFile,mode:m.mode,covered:w&&!k,evidence:A,partial:k,description:m.description,...R!==void 0?{testEvidenceFile:R}:{},...I!==void 0?{outsideDeclaredRoots:I}:{}}),I===!0&&R!==void 0&&p.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${m.id} is covered only by ${R}, which is outside the declared coverage roots (${y}). 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:R,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:"warning",failsStrict:!1}),!w||k){let P=m.mode==="enforced"&&!k,z=r||n.length===0?"never-had-tests":"tests-disappeared";p.push({ruleId:"INVARIANT_UNCOVERED",message:(k?s?`Invariant ${m.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${m.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:z==="tests-disappeared"?`Invariant ${m.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 ${m.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&&s?l:a),file:m.provenance.sourceFile,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:P?"error":"warning",failsStrict:P,kind:z})}}return{coverage:g,violations:p,partial:g.some(m=>m.partial)}}i(Rn,"evaluateInvariantCoverage");function kn(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(kn,"canPromoteInvariant");var In="1.0";function N(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(N,"addFinding");function Z(e){return[...new Set(e??[])].sort()}i(Z,"sortedUnique");function ue(e,t,n,r,s){let o=Z(n),a=Z(r),l=new Set(o),c=new Set(a),u=a.filter(y=>!l.has(y)),f=o.filter(y=>!c.has(y));u.length===0&&f.length===0||(u.length>0&&N(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),f.length>0&&N(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(ue,"compareStringSets");function vt(e,t,n,r,s,o,a){if(n===r)return;N(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:a,before:n,after:r})}i(vt,"compareBoolean");function En(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}i(En,"keyed");function tl(e,t,n){let r=En(t,o=>o.name),s=En(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&N(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(o),l=s.values.get(o),c=`$.layers[${o}]`;if(!a&&l){N(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){N(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;ue(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ue(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=rn(a),f=rn(l);ue(e,`${c}.forbiddenGlobals`,u.rawGlobals,f.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ue(e,`${c}.capabilities`,u.atoms,f.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Z(a.intentPrefixes).join("\0")!==Z(l.intentPrefixes).join("\0")&&N(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Z(a.intentPrefixes),after:Z(l.intentPrefixes)}),vt(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),vt(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(tl,"compareLayers");function nl(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=En(t,r),o=En(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&N(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let a of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let l=s.values.get(a),c=o.values.get(a),u=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&N(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&N(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&N(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let f=l.peerIsolation===!0,y=c.peerIsolation===!0;if(f!==y){let g=l.from===l.to&&c.from===c.to;N(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:g?y?"strengthening":"weakening":"judgment-required",message:g?y?"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:f,after:y})}Z(l.sliceFolders).join("\0")!==Z(c.sliceFolders).join("\0")&&N(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Z(l.sliceFolders),after:Z(c.sliceFolders)}),!(!f&&!y)&&(vo(e,`${u}.sharedRoots`,"shared-roots",Z(l.sharedRoots),Z(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),vo(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(bo)),Z((c.allowedCrossSlice??[]).map(bo)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(nl,"compareRules");function bo(e){return JSON.stringify([e.from,e.to])}i(bo,"crossSliceKey");function vo(e,t,n,r,s,o,a){if(JSON.stringify(r)===JSON.stringify(s))return;let l=s.filter(f=>!r.includes(f)),c=r.filter(f=>!s.includes(f)),u=l.length>0&&c.length>0;N(e,{kind:u?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${o} Entries were added and removed in the same change.`:l.length>0?o:a,before:r,after:s})}i(vo,"compareDeclaredExceptions");function rl(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let a=r[o]??0,l=s[o]??0;a!==l&&N(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])vt(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(rl,"compareSafety");function Pr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Pr,"arkRunMode");function Lr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Lr,"arkOrderMode");function sl(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){N(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${Lr(s)}).`,after:s});return}if(r&&!s){N(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let a=Lr(r),l=Lr(s);if(a!==l){let c=a==="advisory"&&l==="enforced";N(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}ue(e,`${o}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ue(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(sl,"compareArkOrder");function ol(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){N(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${Pr(s)}).`,after:s});return}if(r&&!s){N(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=Pr(r),l=Pr(s);if(a!==l){let c=a==="advisory"&&l==="enforced";N(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}ue(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ue(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),vt(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(ol,"compareArkRun");function al(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(al,"overallClassification");function Co(e,t){return`${e}::${t}`}i(Co,"ruleKey");function _o(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Co(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Co(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(_o,"indexEffectiveRules");function il(e,t,n,r,s,o){let a=new Map((o??[]).map(g=>[g.invariantId,g])),l=t.arkRules??{},c=n.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let g of u){let p=l[g],m=c[g],A=`$.arkRules[${g}]`;if(p===void 0&&m!==void 0){N(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${g} was added.`,after:m});continue}if(p!==void 0&&m===void 0){N(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${g} was removed.`,before:p});continue}p!==m&&N(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${g} changed; verify the effective rules still match intent.`,before:p,after:m})}let f=_o(r),y=_o(s);for(let g of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let p=f.structure.get(g),m=y.structure.get(g),A=`$.arkRules.structure[${g}]`;if(!p&&m){N(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${m.id} was added (${m.mode}).`,after:m});continue}if(p&&!m){N(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!m)){if(p.mode!==m.mode){let S=p.mode==="advisory"&&m.mode==="enforced";N(e,{kind:S?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:S?"strengthening":"weakening",message:S?`Structure ArkRule ${m.id} was promoted to enforced.`:`Structure ArkRule ${m.id} was demoted to advisory.`,before:p.mode,after:m.mode})}p.sensor!==m.sensor&&N(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${m.id} changed sensor identity.`,before:p.sensor,after:m.sensor})}}for(let g of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let p=f.invariants.get(g),m=y.invariants.get(g),A=`$.arkRules.invariants[${g}]`;if(!p&&m){N(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${m.id} was added (${m.mode}).`,after:m});continue}if(p&&!m){N(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!m)&&p.mode!==m.mode)if(p.mode==="advisory"&&m.mode==="enforced"){let O=a?.get(m.id),R=kn(O);R.ok?N(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${m.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:m.mode}):N(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${m.id} cannot be promoted to enforced: ${R.reason}`,before:p.mode,after:m.mode})}else N(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${m.id} was demoted to advisory.`,before:p.mode,after:m.mode})}}i(il,"compareArkRules");function Sn(e,t,n){let r=[];ue(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ue(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."}),ue(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."}),vt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},o=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(o!==a){let l=s[a]===s[o]?"judgment-required":s[a]>s[o]?"strengthening":"weakening";N(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:o,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&N(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}),tl(r,e.layers,t.layers),nl(r,e.rules,t.rules),rl(r,e,t),il(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),ol(r,e,t),sl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:In,classification:al(r),findings:r}}i(Sn,"classifyArkPolicyDelta");function bn(e,t){if(!e||e.schemaVersion!==In||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=Z(e.findingIds),r=Z(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}i(bn,"policyDeltaAcknowledgementMatches");function Fe(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(Fe,"normalizePath");function Oo(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Oo,"isIdentifierStart");function vn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(vn,"isIdentifierCharacter");function oe(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(oe,"skipWhitespace");function Ct(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}i(Ct,"readString");function le(e,t,n){return e.startsWith(t,n)&&!vn(e[n-1])&&!vn(e[n+t.length])}i(le,"isWordAt");function xo(e,t){let n=oe(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=oe(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!le(e,"type",n))return!1;let s=oe(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||le(e,"as",s)||!Oo(e[s]))return!1;for(n=s;n<e.length&&vn(e[n]);)n+=1;if(n=oe(e,n),le(e,"as",n)){if(n=oe(e,n+2),!Oo(e[n]))return!1;for(;n<e.length&&vn(e[n]);)n+=1}r=!0}return!1}i(xo,"bracedNamedBindingsAreTypeOnly");function ll(e,t){if(t=oe(e,t+6),e[t]==="(")return Ct(e,oe(e,t+1));let n=!1;if(le(e,"type",t)){let s=oe(e,t+4);e[s]!==","&&!le(e,"from",s)&&(n=!0)}else xo(e,t)&&(n=!0);let r=To(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(ll,"specifierAfterImport");function cl(e,t){t=t+6;let n=oe(e,t),r=!1;if(le(e,"type",n)){let o=oe(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else xo(e,n)&&(r=!0);let s=To(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(cl,"specifierAfterExport");function To(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return Ct(e,oe(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ct(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(To,"specifierInStaticStatement");function dl(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(dl,"skipTemplateLiteral");function ul(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=oe(e,t+7);if(e[r]!=="(")return;r=oe(e,r+1);let s=Ct(e,r);return s?{...s,requireCall:!0}:void 0}i(ul,"specifierAfterRequire");function pl(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 o=e.indexOf("*/",n+2);if(o<0)break;n=o+1;continue}if(r==="`"){n=dl(e,n);continue}if(r==="'"||r==='"'){let o=Ct(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&le(e,"import",n)?ll(e,n):r==="e"&&le(e,"export",n)?cl(e,n):r==="r"&&le(e,"require",n)?ul(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(pl,"moduleSpecifiers");function No(e,t){let n=[],r=[];for(let s of pl(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let u=lt(o);if(!u)continue;let f=e.content.slice(0,s.offset).split(`
10
- `).length;r.push({file:e.path,symbol:o,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
11
- `).length,l={kind:"import",file:e.path,line:a,excerpt:s.excerpt},c=fl(e.path,o,t);n.push({from:e.path,specifier:o,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(No,"moduleFactsFor");function fl(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(o);if(a)return a}}i(fl,"resolveSpecifier");function Po(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=on(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}i(Po,"violationsFor");var ml={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 gl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(gl,"hasActiveArkRules");function yl(e,t){return gl(e,t)?Y(M(An({config:e,arkRules:t,warnings:[]}))):Y(M(Nr(e)))}i(yl,"policyHashFor");function _t(e,t,n){let r=typeof e=="string"?un(e,t):yt(e,t),s=n?.arkRules??be();return{...r,arkRules:s,policyHash:yl(r.config,s)}}i(_t,"loadContract");function wr(e){let t=_t(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=_t(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Sn(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),o=s.length>0,a=o&&bn(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:o,acknowledged:a,valid:!o||a}}i(wr,"analyzePolicyDelta");function Xe(e){let t=e.files.map(y=>{let g=Fe(y.path);return{path:g,content:y.content,contentHash:Y(y.content),layer:de(g,e.contract.config.layers)??null}}).sort((y,g)=>y.path.localeCompare(g.path)),n=new Map(t.map(y=>[y.path,y])),r=[],s=[];for(let y of t){let g=No(y,n);r.push(...g.edges),s.push(...g.capabilityUses)}let o=Po(r,e.contract.config),a=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(Ge(y))]));for(let y of s){let g=n.get(y.file)?.layer;if(!g)continue;let p=a.get(g),m=Ie(y.symbol,p?.forbiddenGlobals??[]);if(m){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${g} must not use module "${y.symbol}" because it is the import form of forbidden global "${m}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(g)?.has(y.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${g} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...ml}],f={schemaVersion:mn,policyHash:e.contract.policyHash,compilerOptionsHash:Y(M(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&o.length===0,ir:f}}i(Xe,"analyzeProject");function Ot(e){let t=new Map(e.files.map(n=>[Fe(n.path),n]));for(let n of e.changes){let r=Fe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Xe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Ot,"analyzeChange");function Dr(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(Dr,"explainViolation");function Cn(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,o.push(c),s.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?s.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;s.delete(f),u.push(f)}while(f!==c);u.length>1&&a.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(Cn,"detectArchitectureCycles");function $e(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let a=Te(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,u=!c&&!!(o.typeOnly||o.namedBindingsTypeOnly),f=c?Be(a.peerIsolationReason??"cross-slice",{fromPath:o.from,toPath:o.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?f?`${l.message} (${f})`:l.message:f?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}): ${f}`:`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...c?{peerIsolation:!0}:{},message:u?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...u?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Cn(r);s==="soft"||s==="framework-soft"?n.push(...o.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}i($e,"evaluateArchitectureGraph");function Lo(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(Lo,"structureFreezeTarget");var hl=["no-anemic-model"],$o=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],$r=new RegExp(`\\b(${$o.join("|")})\\b`),Ho="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Hr=new RegExp(`\\bthis\\.${Ho}\\.push\\s*\\(`),Al=new RegExp(`^this\\.${Ho}\\s*=\\s*\\[\\s*\\]`),Rl=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,kl=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,jo="truncatedUntil";function jr(){return`${$o.join(", ")}, or events-array .push(`}i(jr,"expectedDomainInvariantWordsPhrase");function El(e){return $r.test(e)||Hr.test(e)}i(El,"referencesGuardOrPublish");function Vr(e,t,n){let r=e.slice(t);if(Al.test(r))return!0;if(!Rl.test(r))return!1;if(n&&/^pullEvents$/i.test(n))return!0;let s=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(s,t+200))}i(Vr,"isIdiomaticEventsReset");function Il(e,t){let n=new RegExp(kl.source,"g"),r;for(;(r=n.exec(t))!==null;)if(!Vr(t,r.index,e))return!0;return!1}i(Il,"methodAssignsThis");function Sl(e,t){return t==null||Object.defineProperty(e,jo,{value:t,enumerable:!1,configurable:!0}),e}i(Sl,"attachShapeTruncation");function Fr(e){let t=Object.getOwnPropertyDescriptor(e,jo)?.value;return typeof t=="number"?t:void 0}i(Fr,"shapeTruncatedUntil");function bl(e){let t=Fr(e);return t==null?"":` shape analysed until character ${t}`}i(bl,"shapeTruncationSuffix");function wo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(wo,"escapeGlobLiteral");function vl(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=wo(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=wo(s)}return new RegExp(`^${n}$`)}i(vl,"globToRegExp");function Ze(e,t){return!t||t.length===0?!0:t.some(n=>vl(n).test(e))}i(Ze,"matchesAppliesTo");function Cl(e){return hl.includes(e)}i(Cl,"isTier2");function Vo(e){return e.mode==="enforced"&&!Cl(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Vo,"severityFor");function ve(e,t,n,r=1){let{severity:s,failsStrict:o}=Vo(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:s,sensor:e.sensor,failsStrict:o}}i(ve,"baseViolation");function On(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(On,"isInRuleLayer");function xn(e,t,n){return t.filter(r=>!(!r.exported||!Ze(r.file,e.appliesTo)||!On(r.file,e,n)))}i(xn,"shapesForRule");function _l(e,t,n){let r=[];for(let s of xn(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(ve(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(_l,"evaluateAggregatePrivateState");function Ol(e,t,n){let r=[];for(let s of xn(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(ve(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Ol,"evaluateAlwaysValidFactory");function xl(e,t,n){let r=[],s=jr();for(let o of xn(e,t,n)){let a=bl(o);Fr(o)!=null&&r.push(ve(e,o.file,`Exported class ${o.className} shape analysed until character ${Fr(o)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of o.mutatingMethods)l.referencesGuardOrPublish||r.push(ve(e,o.file,`Mutating method ${o.className}.${l.name} does not reference ${s} (sensor domain-event-on-mutation).${a}`))}return r}i(xl,"evaluateDomainEventOnMutation");function Tl(e,t){let n=[];for(let r of t.files)Ze(r,e.appliesTo)&&On(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(ve(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Tl,"evaluateOrchestrationOnly");function Nl(e,t){let n=[];for(let r of t.files)Ze(r,e.appliesTo)&&On(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(ve(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Nl,"evaluateThinAdapter");function Pl(e,t){let n=[];for(let r of t.files)Ze(r,e.appliesTo)&&On(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(ve(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(Pl,"evaluateWritesViaAggregate");function Ll(e,t,n){let r=[];for(let s of xn(e,t,n))if(s.dataOnly===!0){let o=ve(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}i(Ll,"evaluateNoAnemicModel");function Tn(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(..._l(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Ol(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...xl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Tl(n,e));break;case"thin-adapter":t.push(...Nl(n,e));break;case"writes-via-aggregate":t.push(...Pl(n,e));break;case"no-anemic-model":t.push(...Ll(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(Tn,"evaluateArkRuleSensors");function Nn(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(c=>Ze(c,s.appliesTo)))continue;let{severity:a,failsStrict:l}=Vo(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>Ze(l,s.appliesTo)))continue;let a=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((s,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}i(Nn,"collectEmptyAppliesToFindings");var Do=/\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)/,Mo=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,wl=/\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 Dl(e){return e==="PersistenceAdapters"}i(Dl,"isPersistenceDriverLayer");function Ml(e,t){if(Do.test(e)||Mo.test(e))return!0;if(!t)return!1;for(let n of t){if(Dl(n.layer))return!0;let r=n.specifier;if(!r)continue;let s=`from '${r}'`;if(Do.test(s)||Mo.test(s))return!0}return!1}i(Ml,"sourceImportsPersistenceDriver");var Fl=/\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*=)/,$l=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Hl=/\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*=/,jl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Ur(e,t,n){if(!t)return null;let r=Ml(t,n),s=r&&wl.test(t);if(t.length<40)return s?{persistenceWrite:!0}:null;let o=t.match(new RegExp(Hl.source,"g"))??[],a=t.match(new RegExp(jl.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=o.length>=2||o.length>=1&&a.length>=2||a.length>=3&&l+c>=6,f=Fl.test(t)||$l.test(t),y=o.length>=1||a.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),p=r&&y||f&&y||r&&g&&(l>=4||o.length>=1)||f&&r;return!u&&!p&&!s?null:{...u?{orchestrationHeavy:!0}:{},...p?{adapterThick:!0}:{},...s?{persistenceWrite:!0}:{}}}i(Ur,"deriveArkRuleFileHints");function Pn(e,t){let n={};for(let[r,s]of Object.entries(e)){let o=r.replace(/\\/g,"/"),a=Ur(r,s,t?.[o]);a&&(n[o]=a)}return n}i(Pn,"buildArkRuleFileHints");var Vl=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Ul=new Set(["if","match","when"]);function _n(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(_n,"skipStringOrComment");function xt(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=_n(e,n);continue}break}return n}i(xt,"skipWsAndComments");function Fo(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(Fo,"readIdent");function Mr(e,t,n,r){if(e[t]!==n)return null;let s=1,o=t+1;for(;o<e.length&&s>0;){let a=_n(e,o);if(a!==o){o=a;continue}let l=e[o];l===n?s+=1:l===r&&(s-=1),o+=1}return s===0?o:null}i(Mr,"skipBalanced");function Kl(e){let t=[],n=0,r;for(;n<e.length&&(n=xt(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let s=[],o=n;for(;;){let f=Fo(e,o);if(!f||!Vl.has(f.ident))break;s.push(f.ident),o=xt(e,f.end)}let a=Fo(e,o);if(!a){n+=1;continue}if(o=xt(e,a.end),e[o]==="<"){let f=Mr(e,o,"<",">");if(f==null){r=e.length;break}o=xt(e,f)}if(e[o]==="("){let f=Mr(e,o,"(",")");if(f==null){r=e.length;break}if(o=xt(e,f),e[o]===":")for(o+=1;o<e.length&&e[o]!=="{"&&e[o]!==";";){let y=_n(e,o);if(y!==o){o=y;continue}o+=1}if(e[o]==="{"){let y=Mr(e,o,"{","}");if(y==null){r=e.length;break}t.push({name:a.ident,modifiers:s,kind:"method",body:e.slice(o+1,y-1)}),n=y;continue}if(e[o]===";"){n=o+1;continue}n=o+1;continue}let l=0,c=0,u=0;for(;o<e.length;){let f=_n(e,o);if(f!==o){o=f;continue}let y=e[o];if(y==="{")l+=1;else if(y==="}"){if(l===0)break;l-=1}else if(y==="(")c+=1;else if(y===")")c-=1;else if(y==="[")u+=1;else if(y==="]")u-=1;else if(y===";"&&l===0&&c===0&&u===0){o+=1;break}o+=1}t.push({name:a.ident,modifiers:s,kind:"field",body:""}),n=o}return{members:t,truncatedAt:r}}i(Kl,"scanClassMembers");function Uo(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let o=s[1],a=s.index+s[0].length,l=1,c=a;for(;c<t.length&&l>0;){let k=t[c];k==="{"?l+=1:k==="}"&&(l-=1),c+=1}let u=t.slice(a,c-1),f=l>0,y=Kl(u),g=f?t.length:y.truncatedAt==null?void 0:a+y.truncatedAt,p=y.members.filter(k=>!(k.kind!=="field"||k.name==="constructor"||k.modifiers.includes("private")||k.modifiers.includes("protected")||k.modifiers.includes("readonly")||k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set"))),m=p.length>0,A=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),S=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),O=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!S,R=/(?:^|[\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 y.members)k.kind==="method"&&k.name!=="constructor"&&(k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set")||Ul.has(k.name)||Il(k.name,k.body)&&I.push({name:k.name,referencesGuardOrPublish:El(k.body)}));let w=y.members.filter(k=>k.kind==="method").length<=1&&p.length>=2&&m;n.push(Sl({file:e,className:o,exported:!0,hasPublicMutableFields:m,hasPublicSetters:A,hasPublicConstructor:O,hasStaticFactory:R,mutatingMethods:[...I],dataOnly:w},g))}return n}i(Uo,"extractClassShapesFromSource");var Ko=50;function Ln(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(Ln,"normalizeExtraMergeTeethClassification");function fe(e){let t=Ln(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(fe,"extraMergeTeethAllowed");function wn(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(wn,"classifyResolvedLayerCoverage");function Dn(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Dn,"isArkRunRuleId");function Go(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(Go,"isArkOrderRuleId");function Kr(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(Kr,"isExtraPlaneFinding");function Bo(e,t={}){if(!Array.isArray(e)||fe(t))return e;for(let n of e)Kr(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Bo,"demoteExtraPlaneTeethUnderClassificationFloor");var Gr="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score); ArkOrder = pattern slaving (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth. Advisory ArkOrder \u2260 merge teeth.";function ke(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(ke,"countOrZero");function Mn(e={}){let t=Ln(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=fe(t),a=e.arkRules,l=ke(a?.structureEnforced),c=ke(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?ke(a.structureAdvisory):Math.max(0,c-l),f=ke(a?.invariantEnforced),y=ke(a?.invariantTotal),g=typeof a?.invariantAdvisory=="number"?ke(a.invariantAdvisory):Math.max(0,y-f),p=l>0||f>0,m=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,S=ke(e.arkRun?.residualCount),O=m&&A==="enforced",R=O&&o,I=p||O,v=I&&o,w=I&&s&&!o,k;if(v){let z=[];p&&z.push("enforced structure/invariant findings"),O&&z.push("enforced ArkRun skip findings"),k=`Layer graph failures plus ${z.join(" and ")} (advisory extras never fail merge alone).`}else w?k=`Layer graph only \u2014 enforced ${[p?"ArkRules structure/invariant":null,O?"ArkRun":null].filter(T=>!!T).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.`:k="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+(m?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let P={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent arkRules or arkRun changes nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:y,enforced:f,advisory:g,covered:ke(a?.covered),uncovered:ke(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:m,mode:A,residualCount:S,extraMergeTeeth:R,note:m?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."},extraMergeTeeth:v,dualPlaneStamp:Gr,failMergeWhen:k};return s&&(P.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),P}i(Mn,"composeMergePlanesHonesty");var zr=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],Wo=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Gl=new Set(zr),Bl=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"]),zl=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function Qe(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Qe,"isArkRunKernelModuleSpecifier");var Wr=["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"],Br=new Set(Wr);function $n(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Br.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Br.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Br.has(e.slice(0,r))}i($n,"isArkRunTransportBypassSpecifier");function Fn(e){if(Gl.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(Fn,"arkRunKernelCallKind");function Nt(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(Nt,"lineAt");function Pt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(Pt,"stripCommentsPreservingLines");function Wl(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let s=r[2]??"";return s.length>0?s:void 0}i(Wl,"firstStringLiteralArg");function zo(e,t,n){let r=Math.max(0,t-n.length-8),s=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(s)}i(zo,"keywordBefore");function Hn(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(Hn,"parseValueImportClause");function ql(e,t){Hn(Pt(e),t)}i(ql,"forEachArkRunValueImportClause");function jn(e,t){let n=Pt(t),r=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,o;for(;(o=s.exec(n))!==null;){let l=o[3]??"";if(!l)continue;let c=o[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!o[1],line:Nt(t,o.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(o=a.exec(n))!==null;){let l=o[1]??"";if(!l)continue;let c=o[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:Nt(t,o.index),resolution:"resolved-external"})}return r}i(jn,"extractArkRunValueImportDependenciesFromSource");function Vn(e){let t=[];return ql(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let s of r[1].split(",")){let o=s.trim();if(!o||o.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),l=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],c=a?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),Tt(t)}i(Vn,"extractArkRunImportedConstructorNamesFromSource");function Yl(e){let t=new Map,n=new Set;return Hn(e,(r,s)=>{if(!Qe(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);o?.[1]&&n.add(o[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let l=/\{([^}]*)\}/.exec(r);if(l?.[1])for(let c of l[1].split(",")){let u=c.trim();if(!u||u.startsWith("type "))continue;let f=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(f){t.set(f[2],f[1]);continue}let y=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);y?.[1]&&t.set(y[1],y[1])}}),{named:t,namespaces:n}}i(Yl,"collectKernelImportBindings");function Jl(e,t){let n=new Set(t);return Hn(e,(r,s)=>{let o=/\{([^}]*)\}/.exec(r);if(o?.[1])for(let a of o[1].split(",")){let l=a.trim();if(!l||l.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(l),u=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],f=c?.[1]??u;!u||!f||!/^[A-Z]/.test(f)||(Qe(s)||t.has(f)||t.has(u))&&(n.add(u),n.add(f))}}),n}i(Jl,"collectImportedConstructors");function Xl(e,t){let n;return Hn(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(Xl,"importedFromForName");function Un(e,t){let n=Pt(t),r=Yl(n),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=o.exec(n))!==null;){let l=a[1],c=a.index;if(zo(n,c,"function")||zo(n,c,"class"))continue;let f=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],y=r.named.get(l)??l,g=Fn(y)??Fn(l);if(!g)continue;let p=r.named.has(l)||f!==void 0&&r.namespaces.has(f);if(g!=="factory"&&(!p&&f===void 0||f&&zl.has(f)&&!p))continue;let m=Wl(n,c+a[0].length);s.push({file:e,line:Nt(t,c),kind:g,callee:l,viaImport:p,...f?{receiver:f}:{},...m?{nameLiteral:m}:{}})}return s}i(Un,"extractArkRunKernelCallsFromSource");function Kn(e,t,n){let r=Pt(t),s=Jl(r,n),o=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=a.exec(r))!==null;){let c=l[1];if(Bl.has(c)||!s.has(c))continue;let u=Xl(r,c);o.push({file:e,line:Nt(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return o}i(Kn,"extractArkRunManagedNewsFromSource");function Zl(e,t){let n=0,r;for(let s=t;s<e.length;s+=1){let o=e[s];if(r){if(o==="\\"){s+=1;continue}o===r&&(r=void 0);continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if(o==="[")n+=1;else if(o==="]"&&(n-=1,n===0))return s}return-1}i(Zl,"matchingBracketEnd");function Ql(e,t,n){let r=e.slice(t+1,n),s=[],o=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=o.exec(r))!==null;){let l=a[2]??"";l.length>0&&s.push(l)}return s}i(Ql,"stringLiteralsInList");function Tt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Tt,"uniqueSorted");function qo(e,t){let n=Pt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],l=[],c,u;for(;(u=r.exec(n))!==null;){let f=n.slice(u.index+u[0].length),y=/^\s*\[/.exec(f);if(!y)continue;let g=u.index+u[0].length+(y[0].length-1),p=Zl(n,g);if(p<0)continue;let m=Ql(n,g,p);if(m.length===0)continue;c===void 0&&(c=u.index);let A=u[1];A==="uses"?s.push(...m):A==="reactsTo"?o.push(...m):A==="raises"?a.push(...m):l.push(...m)}return c===void 0?[]:[{file:e,line:Nt(t,c),uses:Tt(s),reactsTo:Tt(o),raises:Tt(a),sends:Tt(l)}]}i(qo,"extractArkRunDeclarationsFromSource");var Xo=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],ec=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],tc=new Set(ec);function nc(e){return tc.has(e)}i(nc,"isArkRunEditorSensor");var Gn={"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"},qr="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Zo(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 s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(Zo,"isDomainRoleLayer");function rc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(rc,"compareFindings");function Ee(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Gn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Gn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Ee,"finding");function sc(e,t){let n=[],r=[],s=[],o=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),s.push(...a.raises),o.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}i(sc,"bagForFile");function Yo(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Yo,"emitKinds");function Jo(e){return e==="subscribe"||e==="register-handler"}i(Jo,"handleKinds");function oc(e){return e==="resolve"||e==="resolve-singleton"}i(oc,"dependKinds");function ac(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(Ee(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let a of t){let l=o.get(a.matchedRoot)??[];l.push(a),o.set(a.matchedRoot,l)}for(let a of s){let l=[...o.get(a)??[]].sort((u,f)=>u.file.localeCompare(f.file));if(l.length===0){r.push(Ee(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(u=>u.hasKernelFactory))continue;let c=l[0];r.push(Ee(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(ac,"evaluateMissingRoot");function ic(e,t,n,r,s){let o=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!Qe(c))continue;let u=r(l.from);u&&Zo(u,o.get(u)??[])&&a.push(Ee(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},s))}return a}i(ic,"evaluateKernelInDomain");function lc(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(f=>[f.name,f.intentPrefixes??[]])),c=new Set(r.filter(f=>f.hasKernelFactory).map(f=>f.file)),u=[];for(let f of n){if(c.has(f.file))continue;let y=f.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let g=s(f.file);!g||!a.has(g)||Zo(g,l.get(g)??[])||u.push(Ee(e,"arkrun-direct-new",f.file,f.line,`${g} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:g,target:f.typeName},o))}return u}i(lc,"evaluateDirectNew");function cc(e,t,n,r,s){let o=[],a=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:o,completenessReasons:a};for(let c of t){if(!Yo(c.kind)&&!Jo(c.kind)&&!oc(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:qr,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let f=sc(n,c.file);if(Yo(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;o.push(Ee(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},s));continue}if(Jo(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;o.push(Ee(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},s));continue}f.uses.has(c.nameLiteral)||o.push(Ee(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},s))}return{findings:o,completenessReasons:a}}i(cc,"evaluateUndeclared");function dc(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!$n(l))continue;let c=n(a.from);!c||!s.has(c)||o.push(Ee(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return o}i(dc,"evaluateTransportBypass");function Lt(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=fe(e.classification),r=cc(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...ac(t,e.compositionRootHits,n),...ic(t,e.layers,e.dependencies,e.layerForFile,n),...lc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...dc(t,e.dependencies,e.layerForFile,n)].sort(rc),o=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:s,completenessReasons:o}}i(Lt,"evaluateArkRunSensors");function Yr(e){return{findings:Lt(e).findings.filter(n=>nc(n.sensor)),completenessReasons:[]}}i(Yr,"evaluateArkRunEditorSensors");function uc(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(uc,"fileMatchesCompositionRoot");function pc(e,t,n){let r=Un(t,n).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)uc(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:r});return s}i(pc,"compositionRootHitsForSource");function Qo(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(Vn(e.source));return Yr({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Kn(e.file,e.source,n),compositionRootHits:pc(t,e.file,e.source),declarations:[],dependencies:jn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Qo,"evaluateArkRunEditorSensorsFromSource");function ea(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(ea,"isArkOrderModuleSpecifier");var ta=new Map;function na(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(na,"escapeAppliesToLiteral");function fc(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}i(fc,"normalizeAppliesToGlob");function mc(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(mc,"appliesToBracesBalanced");function gc(e){let t=ta.get(e);if(t)return t;let n=fc(e),r=mc(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=na(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=na(c)}let a=new RegExp(`^${s}$`);return ta.set(e,a),a}i(gc,"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"],Bn={"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 yc(e,t){return!t||t.length===0?!0:t.some(n=>gc(n).test(e))}i(yc,"matchesArkOrderAppliesTo");function hc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(hc,"isDomainRoleLayer");function Ce(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Bn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Bn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Ce,"finding");function zn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=fe(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(Ce(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let u of e.planeRootHits){let f=c.get(u.matchedRoot)??[];f.push(u),c.set(u.matchedRoot,f)}for(let u of s){let f=c.get(u)??[];if(f.length===0){r.push(Ce(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}f.some(y=>y.hasPlaneFactory)||r.push(Ce(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!ea(u))continue;let f=e.layerForFile(c.from);f&&hc(f,o.get(f)??[])&&r.push(Ce(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:u},n))}for(let c of e.genericUpdates)r.push(Ce(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Ce(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(Ce(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||yc(c.file,t.appliesTo)&&r.push(Ce(t,"arkorder-xi-field-write",c.file,c.line,`File writes slow key ${JSON.stringify(c.key)} through a persistence driver; route the field through ingest or a pattern change through proposeRelease.`,{fromLayer:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}i(zn,"evaluateArkOrderSensors");function re(e,t,n={}){return{ruleId:e,message:t,...n}}i(re,"configWarning");function wt(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(p=>typeof p!="string"))&&o.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)))o.push(re("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let p of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[p];m!==void 0&&(!Number.isInteger(m)||m<0)&&o.push(re("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${p} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...a.map(p=>p.name).filter(Boolean),...l.map(p=>p.name).filter(p=>!!p)]);a.length===0&&o.push(re("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,f=new Set;for(let p of a){if(!p.name){o.push(re("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(p.name)&&f.add(p.name),u.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(A=>typeof A!="string"))&&o.push(re("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${p.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:p.name}));let m=Array.isArray(p.patterns)?p.patterns:[];if(m.length===0){o.push(re("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let A of m){let S;try{S=ge(A)}catch(R){o.push(re("CONFIG_INVALID_LAYER_PATTERN",`Layer "${p.name}" has an invalid pattern "${A}": ${R instanceof Error?R.message:String(R)}`,{layer:p.name,pattern:A}));continue}let O=p.optional===!0||p.reserved===!0||p.allowEmpty===!0;!r.some(R=>S.test(R))&&!O&&o.push(re("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${p.name}" pattern "${A}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:p.name,pattern:A,failsStrict:!1,reserved:!1}))}}for(let p of f)o.push(re("CONFIG_DUPLICATE_LAYER",`Layer "${p}" is configured more than once.`,{layer:p}));if(c.size>0)for(let p of n??[])p.from&&!c.has(p.from)&&o.push(re("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${p.from}".`,{fromLayer:p.from,toLayer:p.to})),p.to&&!c.has(p.to)&&o.push(re("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${p.to}".`,{fromLayer:p.from,toLayer:p.to}));let y=new Set;if(a.length>1)for(let p of r){let m=-1,A=[];for(let S of a)for(let O of S.patterns??[]){if(!ge(O).test(p))continue;let R=gr(O,p);R>m?(m=R,A=[S.name]):R===m&&!A.includes(S.name)&&A.push(S.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&o.push(re("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let g=r.filter(p=>!de(p,a));return g.length>0&&o.push(re("CONFIG_UNCLASSIFIED_FILES",`${g.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:g.length,samples:g.slice(0,5)})),o}i(wt,"collectAnalysisConfigWarnings");function sa(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_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:Lo({sensor:e.sensor,code:e.code})}:{},...r?{freezable:!1}:{},nextAction:t}}i(sa,"toArkRuleEngineViolation");function Ac(e,t){return t.some(n=>{try{return ge(n).test(e)}catch{return!1}})}i(Ac,"matchesAny");function Rc(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,o=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:S})=>({file:A,line:S})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:S})=>({file:A,line:S})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Ac(A.file,o)).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"})),f=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})),y={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},g=[],p=c.filter(A=>A.kind==="import");if(p.length>0){let A=p[0];g.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let m=c.filter(A=>A.kind==="require");if(m.length>0){let A=m[0];g.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let A=a[0];g.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(l.length>s){let A=l[0];g.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(u.length>0){let A=u[0];g.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 f.length>0&&g.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${f.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:g}}i(Rc,"evaluateSafety");function kc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(kc,"ambientForbiddenGlobal");function oa(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Er(e,n.length>0?n:kr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(oa,"intentLayer");function Ec(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let a=n.get(o.file);!a||!kc(o.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,message:`${a} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let a=n.get(o.file);if(!a)continue;let l=s.get(a),c=l?.forbiddenGlobals??[],u=o.source==="import-based"?t.dependencies.find(f=>f.from===o.file&&f.line===o.line&&f.specifier===o.symbol&&!f.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&ct(o.symbol,c))){if(o.source==="import-based"){let f=Ie(o.symbol,c);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${f}".`});continue}}Ge(l).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...u?{edgeKind:u}:{},message:o.source==="import-based"?`${a} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${a} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let a=n.get(o.file);if(!a)continue;for(let c of dt({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:c.ruleId,file:o.file,line:o.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!o.sourceIntent)continue;let l=oa(o.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let o of t.intentReferences){let a=n.get(o.file);if(!a)continue;let l=oa(o.intent,e.contract);if(!l)continue;let c=Te(e.contract.config.rules,a,l,{fromPath:o.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?Be(c.peerIsolationReason??"cross-slice",{fromPath:o.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,f=`${a} must not reference ${l} intent ${o.intent}.`,y=u&&c.peerIsolationReason!=="cross-slice"?`${f} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:f;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:y})}return r}i(Ec,"contentViolations");function Ic(e){let{facts:t}=e,n=Je(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,L)=>{let H=`${d.code}\0${d.file??""}\0${d.message}`,ae=`${L.code}\0${L.file??""}\0${L.message}`;return H<ae?-1:H>ae?1:0}),a=t.files.map(d=>({...d,layer:de(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let L=d.target?l.get(d.target)??de(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...L?{toLayer:L}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),u=wt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),f=Rc(e,t),y=e.contract.arkRules??be(),g=a.map(d=>d.path),m={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Pn(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=[...Tn({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:g,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),fileHints:m}),...Nn(y,g)],S=A.filter(d=>d.failsStrict).map(d=>sa(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.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.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`)),O=A.filter(d=>!d.failsStrict).map(d=>({...sa(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`),failsStrict:!1})),I=(y.invariants?.length??0)>0?Rn({arkRules:y,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},v=I.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),w=I.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${d.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),k=wn(a),P=Lt({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(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),classification:k}),z=e.contract.config.arkRun?.mode,T=P.findings.filter(()=>z==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),J=P.findings.filter(()=>z!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),$=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(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),classification:k}),ce=e.contract.config.arkOrder?.mode,me=$.findings.filter(()=>ce==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Jt=$.findings.filter(()=>ce!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),rt=[...I.partial&&I.coverage.some(d=>d.mode==="enforced"&&d.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...P.completenessReasons,...$.completenessReasons],xe=$e({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Ec(e,t,l),...S,...v,...T,...me],edges:c,warnings:[...u,...f.warnings,...O,...w,...J,...Jt],safety:f.report}),Xt=s==="complete"&&rt.length>0?"partial":s,sr=Xt==="complete"?o:[...o,...rt].sort((d,L)=>{let H=`${d.code}\0${d.file??""}\0${d.message}`,ae=`${L.code}\0${L.file??""}\0${L.message}`;return H<ae?-1:H>ae?1:0}),b=xe.violations.filter(d=>d.failsStrict!==!1),C=Xt==="complete"&&b.length===0,h=C&&xe.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Xt,completenessReasons:sr,valid:C,strictValid:h,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:f.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:xe.violations,warnings:xe.warnings}}}i(Ic,"analyzeCanonicalResolvedProject");function et(e){return Ic({contract:e.contract,facts:Re(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(et,"analyzeResolvedProject");function aa(e){return Y(M(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(aa,"analysisTreeHash");function Jr(e){let t=Xe(e),n=new Map(t.ir.files.map(m=>[m.path,m])),r=[],s=new Set,o=[];for(let m of e.changes){let A=m.path.replace(/\\/g,"/"),S=Fe(m.path);if(!S||S===".."||S.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(S)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:S,line:1,message:`The atomic change set contains more than one operation for ${S}.`});continue}s.add(S),"delete"in m&&m.delete&&!n.has(S)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:S,line:1,message:`Cannot delete ${S} because it is not present in the supplied base tree.`}),r.push("delete"in m&&m.delete?{path:S,delete:!0}:{path:S,content:"content"in m?m.content:""})}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Ot({...e,changes:r}),l=new Map(a.ir.files.map(m=>[m.path,m])),c=a.ir.violations.filter(m=>m.ruleId==="CAPABILITY_VIOLATION"||m.ruleId==="FORBIDDEN_GLOBAL").map(m=>{let A=l.get(m.evidence.file)?.layer;return{ruleId:m.ruleId,file:m.evidence.file,line:m.evidence.line,target:m.symbol,...m.capability?{capability:m.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:m.message}}),u=$e({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(m=>m.path),contentViolations:c,edges:a.ir.edges.filter(m=>!!m.fromLayer).map(m=>({from:m.from,fromLayer:m.fromLayer,...m.to?{to:m.to}:{},...m.toLayer?{toLayer:m.toLayer}:{},line:m.evidence.line,kind:"import",...m.typeOnly?{typeOnly:!0}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(m=>{let A=Fe(m.path),S=n.get(A),O=l.get(A);return{path:A,operation:"delete"in m&&m.delete?"delete":S?"update":"create",...S?{beforeContentHash:S.contentHash}:{},...O?{candidateContentHash:O.contentHash}:{}}}).sort((m,A)=>m.path.localeCompare(A.path)),y=[...o,...u.violations].map(m=>({...m,nextAction:pe(m)})),g=y.filter(m=>m.failsStrict!==!1),p=e.changeMap?De({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:a.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&g.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:aa(t.ir.files),candidateTreeHash:aa(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:f,violations:y,warnings:u.warnings}}i(Jr,"preflightChange");function Sc(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}i(Sc,"canonicalChangePath");function bc(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,s])=>r!==s).map(([r,s,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}i(bc,"identityViolations");function vc(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}i(vc,"preparedChange");function Xr(e){let t=Re(e.baseFacts),n=Re(e.candidateFacts),r=et({contract:e.contract,facts:t}),s=et({contract:e.contract,facts:n}),o=new Map(t.files.map(p=>[p.path,p])),a=new Map(n.files.map(p=>[p.path,p])),l=bc(t,n),c=new Map,u=[];for(let p of e.changes){let m=Sc(p.path);if(!m){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(m)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:m,line:1,message:`The atomic change set contains more than one operation for ${m}.`});continue}c.set(m,p);let A=o.get(m),S=a.get(m);if("delete"in p&&p.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:m,line:1,message:`Cannot delete ${m} because it is not present in the supplied base facts.`}),S&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:m,line:1,message:`Candidate facts still contain deleted file ${m}.`});else{let O="content"in p?p.content:"",R=Y(O);S?S.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:m,line:1,expectedContentHash:R,candidateContentHash:S.contentHash,message:`Candidate facts for ${m} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:m,line:1,message:`Candidate facts do not contain changed file ${m}.`})}u.push(vc(p,m,o,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...o.keys(),...a.keys()])){if(c.has(p))continue;let m=o.get(p),A=a.get(p);m&&A&&M(m)===M(A)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let f=e.changeMap?De({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:s.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,y=[...l,...s.ir.violations].map(p=>({...p,nextAction:pe(p)})),g=y.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&g.length===0&&(f?.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:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:u.sort((p,m)=>p.path<m.path?-1:p.path>m.path?1:0),violations:y,warnings:s.ir.warnings}}i(Xr,"preflightResolvedChange");var Zr="1.0",Cc=12;function ia(e){return e==="enforced"||e==="advisory"?e:null}i(ia,"closedMode");function _c(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Dn(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(_c,"uniqueArkRunRuleIds");function Oc(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:ia(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(Oc,"extraFromConfig");function la(e={}){let t=Oc(e.arkRun),n=t.present?_c(e.findings):[],r=n.slice(0,Cc),s=n.length,o=Mn({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),a=t.present&&t.mode==="enforced"&&fe(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?l="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":l="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":l="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:Zr,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:r},extraMergeTeeth:a,failMergeWhen:o.failMergeWhen,note:l,mergePlanes:o}}i(la,"summarizeArkRunSection");function Wn(e={}){let t=e.present===!0,n=ia(e.mode),r=e.residual,s=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(s=Math.floor(r)),t||(s=s??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:s}}i(Wn,"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",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),o=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${o}`)}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(ca,"formatArkRunDoctorLines");function qn(e,t){return e.slice(0,t).split(`
13
- `).length}i(qn,"lineOf");function da(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(da,"normalizeInventoryPath");function pa(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(pa,"ownsIntent");function ua(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||pa(t,["Domain"])}i(ua,"isDomainLayer");function xc(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||pa(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(xc,"isControllerEligibleLayer");function Tc(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(Tc,"isNonPilotSurface");function fa(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[da(c),u])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>ua(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([f],[y])=>f.localeCompare(y))){let f=da(c);if(Tc(f)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let y=r.has(f),g=r.get(f),p=g?s.get(g)??[]:[],m=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(f)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(f)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(f),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(f),S=/(?:^|\/)actions?(?:\/|\.|$)/i.test(f)||/['"]use server['"]/.test(u),O=/controller|handler|resolver/i.test(c)||A||S||/route\.(?:ts|js|tsx|jsx)$/i.test(f)&&!m||/@(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),R=y?!!(g&&xc(g,p)&&O):O,I=y?!!(g&&ua(g,p)):/domain|entity|aggregate|model/i.test(c),v=!y||I||R;if(R&&!m){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,J;for(;(J=T.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:qn(u,J.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let w=/\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"),z=i((T,J)=>{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 $=J.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(J)&&(/\s/.test($)||/[.!?…]$/.test($))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(T))},"isUxMessageConstant");for(;(k=w.exec(u))!==null;){let T=k[2],J=k[3]??"";!v||P(T)||z(T,J)||m&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(f)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:qn(u,k.index),message:`Magic business constant ${T} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-${T}`},neverMechanicalSafe:!0}))}if(I){let T=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,J;for(;(J=T.exec(u))!==null;){let $=J[2]??"",ce=($.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;($.match(/:\s*[A-Za-z]/g)??[]).length>=2&&ce<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:qn(u,J.index),message:`Class ${J[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(f)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(f)||/(?:^|\/)errors?(?:\/|$)/i.test(f))){let J=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,$;for(;($=J.exec(u))!==null;){let ce=u.lastIndexOf("class ",$.index),me=ce>=0?u.indexOf("{",ce):-1,Jt=ce>=0&&me>=ce&&me<$.index?u.slice(ce,me):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(Jt)||Vr(u,$.index))continue;let Ve=u.slice(Math.max(0,$.index-200),$.index+200);if(!$r.test(Ve)&&!Hr.test(Ve)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:qn(u,$.index),message:`Domain field mutation without nearby ${jr()}.`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((c,u)=>+(u.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(u.file)||c.line-u.line||c.kind.localeCompare(u.kind)||c.id.localeCompare(u.id));let l=t.filter(c=>c.suggestedArkRule?.invariantId&&a.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&a.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(fa,"buildRulesInventory");function ma(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(ma,"inventoryToExtractionCard");var ga="1.1";var ya="1.0";var Yn="docs/diagnostics.md",ha="1.0";function E(e,t,n,r,s,o){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...o?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var Dt=Object.freeze([E("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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}),E("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."),E("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."),E("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}),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe."),E("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."),E("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."),E("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease then apply(ProposeResult), then preflight again. Never mechanical-safe."),E("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."),E("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."),E("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."),E("ARKORDER_UNVALVED_RELEASE","arkorder","Unvalved second freeze of \u03BE","release() ran after a pattern was already frozen and the new \u03BE differs. First freeze is release(); later pattern change is proposeRelease then apply.","Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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."),E("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}),E("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Qr=new Map(Dt.map(e=>[e.ruleId,e])),Aa=Object.freeze(Dt.map(e=>e.ruleId));function Ra(e){return typeof e=="string"&&e.length>0&&Qr.has(e)}i(Ra,"isKnownDiagnosticCode");function ka(e){return typeof e!="string"||e.length===0?!1:Qr.has(e)?!0:e.startsWith("ARKRULE_")}i(ka,"isCataloguedOrArkRuleFamily");function Mt(e){if(!(typeof e!="string"||e.length===0))return Qr.get(e)}i(Mt,"getDiagnosticCatalogEntry");function es(e){return`#${Mt(e)?.docsAnchor??e}`}i(es,"diagnosticDocsFragment");function Ea(e){return`${Yn}${es(e)}`}i(Ea,"diagnosticDocsPath");function Ia(){return{schemaVersion:"1.0",docsPath:Yn,codes:Dt}}i(Ia,"serializeDiagnosticCatalog");function Sa(e){return Mt(e)?.fix}i(Sa,"catalogFixForRuleId");function ba(e){return Mt(e)?.why}i(ba,"catalogWhyForRuleId");var Jn="1.0",ts="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",ns=["full","subset","unavailable"],rs=["doctor-facts","report-snapshot","none"],$t={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},va=/^sha256:[a-f0-9]{64}$/;function ss(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"||!va.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 s=e.expectedRootRelation??"unknown";return s==="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}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="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}.`}:s==="exact"||s==="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(ss,"evaluateStatusBinding");function os(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(os,"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 is(e,t,n,r,s){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."}:s.arkRulesLoaded&&(s.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.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(is,"resolveStatusNextAction");function Ca(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&va.test(e.projectId)?e.projectId:null,r=ss({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",o=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,a=os({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():as(a,o),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Ft(e.activeViolations),frozenResidual:Ft(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ft(e.rulesInventoried),underContract:Ft(e.rulesUnderContract),frozenResidual:Ft(e.rulesFrozenResidual)},f={writePath:a,host:o,honestLabel:l},y={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}:{}},g={schemaVersion:Jn,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:f,lastCheck:c,rules:u,nextAction:is(e,r,f,c,u)},p=ls(e.improvementCompass);return p&&(g.improvementCompass=p),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(g.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(g.arkRun=Wn(e.arkRun)),g}i(Ca,"buildStatusManifest");var _a=new Set(ns),Nc=new Set(rs);function Xn(e){let t=_a.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Nc.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:$t.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 s=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],o={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(o.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:$t.FACTS_PARTIAL,o.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&&(o.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(o.reason=e.reason),n&&(o.factsSource=n),r&&(o.contractHash=r),o}i(Xn,"projectStatusImprovementCompass");function Oa(e={}){return Xn({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??$t.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(Oa,"unavailableStatusImprovementCompass");function ls(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"&&_a.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Xn({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(ls,"normalizeStatusImprovementCompass");function xa(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}i(xa,"statusCompassResidualIsSubsetOfDoctor");function Ft(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ft,"numberOrNull");var Ta={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ts,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:Jn},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"}]}}}}};var Ht="1.0",jt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Vt=5,_e=["scalability","resilience","security"],tt=new Set(_e),cs={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},ds={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"},us={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 ps(e){return ds[e]??e}i(ps,"improvementCompassHumanLabel");function fs(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(fs,"smellIdOf");function ms(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(ms,"violationRuleId");function V(e,t,n,r){if(!n||e.evidence.some(o=>o.source===t&&o.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}i(V,"pushEvidence");function ee(e,t,n){tt.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(ee,"markResidual");function Na(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`${ds[e]} \u2014 no residual from current sensors.`}}i(Na,"defaultOkSummary");function Pa(){return jt.map(e=>tt.has(e)?{id:e,status:"out-of-scope",summary:us[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:Na(e),evidence:[]}:{id:e,status:"ok",summary:Na(e),evidence:[]})}i(Pa,"createInitialImprovementCompassLenses");function Pc(e,t){for(let n of t){let r=fs(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((f,y,g)=>{let p=e.get(f);!p||tt.has(f)||(V(p,"designSmells",r,s),a&&V(p,"designSmells",a,r),ee(p,y,g))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":l("soc","Business rules still mix with UI or presentation surfaces.",c),l("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",c);break;case"facade-sql-in-routes":l("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",c),l("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":l("soc","Application/business code reaches I/O directly \u2014 separation is weak.",c),l("dip","I/O is not inverted behind ports/adapters.",u),l("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}i(Pc,"mapDesignSmells");function Lc(e){return e.failsStrict===!1||e.typeOnly===!0}i(Lc,"isTypeOnlyPlacementDebt");function wc(e,t){for(let n of t){let r=ms(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=i((c,u,f)=>{let y=e.get(c);!y||tt.has(c)||(V(y,"violations",r,s),n.file&&V(y,"violations",n.file,r),ee(y,u,f))},"attach");if(Lc(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let l={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(o==="LAYER_IMPORT_VIOLATION"||o.includes("LAYER_IMPORT")||o==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",l);continue}if(o.includes("CYCLE")||o==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",l);continue}if(o.includes("PEER_ISOLATION")||o==="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(o==="FORBIDDEN_GLOBAL"||o.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(o==="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(o.startsWith("ARKRULE_")||o==="INVARIANT_UNCOVERED"){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(wc,"mapViolations");function Dc(e,t){let n=Number(t.cycleCount)||0;if(n>0){let p=e.get("coupling");V(p,"cycles",`count:${n}`),ee(p,"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 p=e.get("coupling");V(p,"peerIsolation",`count:${r}`),ee(p,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let p=e.get("cohesion");V(p,"physicalCohesion",`findings:${s}`),ee(p,"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 m=e.get("srp");V(m,"physicalCohesion",`findings:${s}`),ee(m,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let o=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(o>0||a>0){let p=e.get("dip");o>0&&V(p,"capability",`residual:${o}`),a>0&&V(p,"forbiddenGlobals",`residual:${a}`),ee(p,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let m=e.get("testability");o>0&&V(m,"capability",`residual:${o}`),a>0&&V(m,"forbiddenGlobals",`residual:${a}`),ee(m,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let p=e.get("encapsulation");V(p,"arkRules",`structureResidual:${l}`),ee(p,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let m=e.get("domain");V(m,"arkRules",`structureResidual:${l}`),ee(m,"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 p=e.get("maintainability");V(p,"designFitness","design-weak"),ee(p,"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 p=e.get("maintainability");t.dirtyBaselineRisk===!0&&V(p,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&V(p,"baseline",`stale:${t.baselineStale}`),ee(p,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let c=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&c>=10&&e.get("maintainability").status!=="residual"){let p=e.get("maintainability");V(p,"baseline",`frozen:${c}`),ee(p,"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,f=Number(t.emptyLayerCount)||0;if(u>0||f>0){let p=e.get("modularity");u>0&&V(p,"coverage",`ungovernedDirs:${u}`),f>0&&V(p,"coverage",`emptyLayers:${f}`),ee(p,"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 p=e.get("modularity");V(p,"goldenPattern","absent"),ee(p,"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 y=e.get("stack");(t.stackKind??null)==="typescript"?y.status==="ok"&&(y.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(y.status="not-instrumented",y.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",y.evidence=[],y.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Dc,"mapCountsAndFlags");function La(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>fs(r).localeCompare(fs(s)));Pc(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=ms(r).localeCompare(ms(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});wc(e,n)}Dc(e,t)}i(La,"projectImprovementCompassFacts");function wa(e){for(let t of _e){let n=e.get(t);n.status="out-of-scope",n.summary=us[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(wa,"lockImprovementCompassOutOfScope");function Da(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}i(Da,"sortImprovementCompassEvidence");function Ma(e){return e.filter(n=>n.status==="residual"&&!tt.has(n.id)).slice().sort((n,r)=>{let s=cs[n.id]??150,o=cs[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(Ma,"finalizeImprovementCompassTopResidual");function Fa(e={}){let t=Pa(),n=new Map(t.map(s=>[s.id,s]));La(n,e),wa(n),Da(t);let r=Ma(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let o={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(a=>({...a}))};return s.nextAction&&(o.nextAction={...s.nextAction}),o}),topResidual:r}}i(Fa,"buildImprovementCompass");function gs(e){return e.topResidual.map(t=>ps(t))}i(gs,"formatImprovementCompassResidualLabels");function ys(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(ys,"primaryImprovementCompassNextAction");function $a(e){let t=gs(e),n=_e.map(o=>ps(o)),r=ys(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}i($a,"formatImprovementCompassDoctorLines");var Oe="1.0",hs="<!-- arkgate:agent-projection:begin",Ut="<!-- arkgate:agent-projection:end -->",Kt="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",nt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),As=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 He(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(He,"agentProjectionContentIdentity");function Bt(e){return String(e??"").replace(/\r\n/g,`
15
- `)}i(Bt,"normalizeNewlines");function je(e){let t=Bt(e);return t.endsWith(`
1
+ "use strict";var er=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ti=Object.getOwnPropertyNames;var ri=Object.prototype.hasOwnProperty;var i=(e,t)=>er(e,"name",{value:t,configurable:!0});var ni=(e,t)=>{for(var r in t)er(e,r,{get:t[r],enumerable:!0})},si=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ti(t))!ri.call(e,s)&&s!==r&&er(e,s,{get:()=>t[s],enumerable:!(n=ei(t,s))||n.enumerable});return e};var oi=e=>si(er({},"__esModule",{value:!0}),e);var Wc={};ni(Wc,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>at,AGENT_PROJECTION_BEGIN_MARKER:()=>Rs,AGENT_PROJECTION_END_MARKER:()=>Gt,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>nt,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Bt,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>Os,AGENT_SKILL_ENTRY_FILENAME:()=>xs,ANALYSIS_IR_SCHEMA_VERSION:()=>mr,ARKORDER_RULE_IDS:()=>Gr,ARKORDER_TIER1_SENSOR_IDS:()=>oa,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>Jn,ARKRUN_KERNEL_FACTORY_CALLEES:()=>qn,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>Yo,ARKRUN_RULE_IDS:()=>Ur,ARKRUN_TIER1_SENSOR_IDS:()=>Qo,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>Yn,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>xe,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Ga,ARK_ANALYSIS_RESULT_SCHEMA:()=>an,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>ot,ARK_CONFIG_SCHEMA:()=>cr,ARK_CONFIG_SCHEMA_VERSION:()=>ne,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Aa,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>ha,ARK_FIRST_CLASS_SKILL_NAMES:()=>Ts,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Kt,ARK_PROJECT_IDENTITY_SCHEMA:()=>Vs,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>ln,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>Ks,ARK_RULES_SCHEMA:()=>yr,ARK_RULES_SCHEMA_VERSION:()=>So,ARK_RULE_SENSORS:()=>Nn,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>es,ARK_SKILL_CAPACITY:()=>za,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>nn,ARK_SKILL_NAMES:()=>Xt,ARK_SKILL_NAME_COUNT:()=>Ns,ARK_SKILL_NORTH_STAR:()=>Ba,ARK_SKILL_STUB_REDIRECTS:()=>en,ARK_STATUS_MANIFEST_SCHEMA:()=>Pa,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>ns,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>Yr,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>ks,DIAGNOSTIC_CATALOG:()=>Ft,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ra,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>qr,DIAGNOSTIC_RULE_IDS:()=>ka,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>zo,EffectiveContractError:()=>bt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>_s,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>_e,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Ut,IMPROVEMENT_LENS_IDS:()=>Vt,MERGE_PLANES_DUAL_STAMP:()=>zn,POLICY_DELTA_SCHEMA_VERSION:()=>Sr,PROJECT_BINDING_SCHEMA:()=>dn,PROJECT_EXPECTATION_SCHEMA:()=>cn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>fr,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>ve,STATUS_COMPASS_FACTS_SOURCES:()=>os,STATUS_COMPASS_MODES:()=>ss,STATUS_COMPASS_REASON_CODES:()=>jt,adapterDocsCodePath:()=>lt,adapterFindingOccurrenceTargetKeys:()=>Ge,adapterFindingRefFromTargetKey:()=>it,adapterFindingTargetKey:()=>Ue,agentProjectionContentIdentity:()=>je,agentSkillEntryRelativePath:()=>Fs,agentSkillPackageFileRelativePath:()=>Za,analyzeArchitectureConvergence:()=>Me,analyzeChange:()=>xt,analyzePolicyDelta:()=>Dn,analyzeProject:()=>Ze,analyzeResolvedProject:()=>tt,arkRunKernelCallKind:()=>Mr,arkSkillStubRedirect:()=>qa,buildAgentProjectionBeginMarker:()=>Xr,buildAgentProjectionBlock:()=>Es,buildAgentProjectionBody:()=>Yt,buildAgentProjectionMeta:()=>Ss,buildArkRuleFileHints:()=>Lr,buildEffectiveArkRules:()=>hr,buildImprovementCompass:()=>ja,buildRulesInventory:()=>ga,buildStatusManifest:()=>xa,canPromoteInvariant:()=>kr,catalogFixForRuleId:()=>ba,catalogWhyForRuleId:()=>Ca,classifyArkPolicyDelta:()=>Ir,classifyResolvedLayerCoverage:()=>wr,classifyStatusWritePath:()=>is,collectAnalysisConfigWarnings:()=>Mt,collectEmptyAppliesToFindings:()=>Nr,collectForbiddenCapabilityUses:()=>Pe,composeMergePlanesHonesty:()=>Nt,createAICodeGate:()=>Cn,createAdapterResult:()=>js,createArchitectureProfile:()=>Rt,createArchitectureProfileFromArkConfig:()=>_n,createElevenLayerArkConfig:()=>xn,createProjectId:()=>Us,createProjectIdentity:()=>Gs,createResolvedCandidateFacts:()=>pr,defaultHonestLabel:()=>ls,demoteExtraPlaneTeethUnderClassificationFloor:()=>Wo,deriveArkRuleFileHints:()=>Un,detectArchitectureCycles:()=>Cr,deterministicHash:()=>Y,diagnosticDocsFragment:()=>rs,diagnosticDocsPath:()=>Ia,effectiveContractPolicyPayload:()=>Ar,elevenLayerProfile:()=>At,emptyEffectiveArkRules:()=>be,evaluateArchitectureGraph:()=>He,evaluateArkOrderSensors:()=>Br,evaluateArkRuleSensors:()=>Tr,evaluateArkRunEditorSensors:()=>Xn,evaluateArkRunEditorSensorsFromSource:()=>ta,evaluateArkRunSensors:()=>Dt,evaluateInvariantCoverage:()=>Rr,evaluateStatusBinding:()=>as,explainViolation:()=>Mn,extraMergeTeethAllowed:()=>fe,extractAgentProjectionBlock:()=>Jt,extractArkRunDeclarationsFromSource:()=>Jo,extractArkRunImportedConstructorNamesFromSource:()=>jr,extractArkRunKernelCallsFromSource:()=>Kr,extractArkRunManagedNewsFromSource:()=>Vr,extractArkRunValueImportDependenciesFromSource:()=>Hr,extractClassShapesFromSource:()=>Bo,extractSemanticDependencies:()=>Le,flatSkillTemplateFileRelativePath:()=>Qa,formatAgentProjectionCatalogShortList:()=>Zr,formatAgentProjectionLayers:()=>zt,formatArkRunDoctorLines:()=>ua,formatImprovementCompassDoctorLines:()=>Ka,formatImprovementCompassResidualLabels:()=>hs,getDiagnosticCatalogEntry:()=>$t,inventoryToExtractionCard:()=>ya,isArkOrderRuleId:()=>Gn,isArkRunKernelModuleSpecifier:()=>et,isArkRunRuleId:()=>Dr,isArkRunTransportBypassSpecifier:()=>Fr,isArkSkillName:()=>rn,isCataloguedOrArkRuleFamily:()=>Sa,isExtraPlaneFinding:()=>Bn,isFirstClassArkSkillName:()=>Wa,isKnownDiagnosticCode:()=>Ea,isValidAgentSkillName:()=>Ls,loadArkConfigContract:()=>ht,loadArkRulesContract:()=>vt,loadContract:()=>_t,loadResolvedCandidateFacts:()=>ke,mergeAgentProjectionDocument:()=>Cs,normalizeExtraMergeTeethClassification:()=>Pr,normalizeSkillContent:()=>tn,normalizeStatusImprovementCompass:()=>ds,parseAgentProjectionStamp:()=>Qr,parseArkConfigJson:()=>ur,parseArkRulesJson:()=>Io,parseSkillDescriptionVersion:()=>Ja,parseSkillDocument:()=>Ps,policyDeltaAcknowledgementMatches:()=>vr,preflightChange:()=>Zn,preflightResolvedChange:()=>Qn,primaryImprovementCompassNextAction:()=>As,projectStatusArkRun:()=>zr,projectStatusImprovementCompass:()=>Jr,projectionHasNonEnforcementLabel:()=>bs,projectionMatchesPackageVersion:()=>vs,resolveEffectiveContract:()=>bo,resolveStatusNextAction:()=>cs,resolvedFactsEvidenceRequirementsHash:()=>Xe,serializeDiagnosticCatalog:()=>va,skillDescriptionVersionPrefix:()=>Ds,stableSerialize:()=>F,stampSkillDescription:()=>Xa,statusCompassResidualIsSubsetOfDoctor:()=>La,stripSkillDescriptionVersion:()=>Ms,summarizeArkRunSection:()=>da,toAdapterDiagnostic:()=>tr,unavailableStatusImprovementCompass:()=>Na,validateAgentSkillDocument:()=>ws,validateAgentSkillsPackage:()=>Ya,version:()=>$s});module.exports=oi(Wc);var $s="4.8.14";var ai=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ii=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,li=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ci(e,t){let r=String(e??"").replace(/\\/g,"/").trim(),n=String(t?.fromLayer??""),s=String(t?.toLayer??"");return ai.test(r)?"pure-shared":n==="PersistenceAdapters"&&(ii.test(r)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${r}`))?"kernel-emit":li.test(r)||(n==="DomainModel"||n==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(ci,"classifyLayerImportKind");function di(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(di,"layerImportNextAction");function ui(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(ui,"arkRunCallSiteName");function pi(e){let t=ui(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(pi,"arkRunNextAction");function me(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return di(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"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 pi(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(me,"deterministicNextAction");var ot="1.5",at="docs/diagnostics.md",an={$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 Ue(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,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,r,n??"",s??"",o??""].join("|")}i(Ue,"adapterFindingTargetKey");function Ge(e){let t=new Map;return e.map(r=>{let n=Ue(r),s=(t.get(n)??0)+1;return t.set(n,s),s===1?n:`${n}#${s}`})}i(Ge,"adapterFindingOccurrenceTargetKeys");function it(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(it,"adapterFindingRefFromTargetKey");function lt(e){return`${at}#${e}`}i(lt,"adapterDocsCodePath");function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function Hs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Hs,"positiveInteger");function fi(e,t,r){return me({ruleId:e,target:O(t.target)??O(r.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(r.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(fi,"nextActionForDiagnostic");function tr(e,t="error",r){let n=O(e.ruleId)??O(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={...O(e.target)?{target:O(e.target)}:{},...O(e.fromLayer)?{fromLayer:O(e.fromLayer)}:{},...O(e.toLayer)?{toLayer:O(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...O(e.capability)?{capability:O(e.capability)}:{},...O(e.edgeKind)?{edgeKind:O(e.edgeKind)}:{},...O(e.arkruleId)?{arkruleId:O(e.arkruleId)}:{},...O(e.arkruleSource)?{arkruleSource:O(e.arkruleSource)}:{}},a=r??Ue(e),l=it(a);return{ruleId:n,severity:s,message:O(e.message)??n,location:{file:O(e.file)??"<unknown>",line:Hs(e.line,1),column:Hs(e.column,1)},evidence:o,nextAction:O(e.nextAction)??fi(n,o,e),findingRef:l,targetKey:a,docsCodePath:lt(n)}}i(tr,"toAdapterDiagnostic");function js(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(y=>({code:O(y.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:O(y.message)??`Analysis ${t}: required evidence is incomplete.`,...O(y.file)?{file:O(y.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...O(e.policyHash)?{policyHash:O(e.policyHash)}:{},...O(e.resolverIdentity)?{resolverIdentity:O(e.resolverIdentity)}:{},...O(e.factsHash)?{factsHash:O(e.factsHash)}:{},...O(e.candidateTreeHash)?{candidateTreeHash:O(e.candidateTreeHash)}:{}};if(r==="resolved-candidate-facts"&&t!=="unavailable"){for(let y of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[y])throw new Error(`${y} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],l=Ge(o),c=Ge(a),u=[...o.map((y,g)=>tr(y,"error",l[g])),...a.map((y,g)=>tr(y,"warning",c[g]))],f={schemaVersion:"1.5",completenessReasons:n,diagnostics:u};if(r==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:r,valid:!1,completeness:t,...s};let y={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...f,mode:r,valid:e.valid,completeness:t,...y}:{...f,mode:r,valid:!1,completeness:t,...y}}return t==="complete"?{...f,mode:r,valid:e.valid,completeness:t,...s}:{...f,mode:r,valid:!1,completeness:t,...s}}i(js,"createAdapterResult");var Ks="1.0",ln="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",rr="^sha256:[a-f0-9]{64}$",cn={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:rr,description:"Project id previously returned by ark_identity or ark_manifest."}}},dn={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:rr},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Vs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ln,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:rr},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:rr},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:cn,binding:dn}};function Us(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(Us,"createProjectId");function Gs(e){return{schemaVersion:"1.0",...e}}i(Gs,"createProjectIdentity");var pn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),mn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),gn=Object.freeze(Object.keys(mn).sort()),un=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"}),fn=Object.freeze({process:Object.freeze(["process","node:process"])});function ct(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=un[e];if(t)return t;let r=e.indexOf("/");if(r<0)return null;let n=e.slice(0,r),s=un[n];if(s)return s;let o=e.indexOf("/",r+1);return o<0?null:un[e.slice(0,o)]??null}i(ct,"capabilityForModuleSpecifier");function Ie(e,t){for(let r of t)if(fn[r]?.includes(e))return r;return null}i(Ie,"forbiddenGlobalForModuleSpecifier");function nr(e){let t=e.split(".");for(let r=t.length;r>=1;r-=1){let n=t.slice(0,r).join("."),s=mn[n];if(s)return s}return null}i(nr,"capabilityForAmbientName");function Be(e){if(e?.pure===!0)return[...pn].sort();let r=(e?.capabilities?.deny??[]).filter(n=>pn.includes(n));return[...new Set(r)].sort()}i(Be,"effectiveCapabilityDeny");function dt(e,t){if(t.length===0)return!1;let r=new Set(t),n=e.split(".");for(let s=n.length;s>=1;s-=1)if(r.has(n.slice(0,s).join(".")))return!0;return!1}i(dt,"ambientCoveredByForbiddenGlobals");function sr(e){let t=new Set,r=new Set,n=Object.keys(mn);for(let s of e?.forbiddenGlobals??[]){let o=n.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)r.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of fn[s]??[])t.add(`import-exact:${a}`)}for(let s of Be(e)){if(t.add(`import:${s}`),s==="process")for(let o of fn.process)t.add(`import-exact:${o}`);for(let o of n)nr(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...r].sort()}}i(sr,"loweredLayerCoverage");var Bs=new Map;function zs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(zs,"escapeLiteral");function or(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=n}return t}i(or,"normalizeGlobSeparators");function mi(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(mi,"bracesBalanced");function ye(e){let t=Bs.get(e);if(t)return t;let r=or(e),n=mi(r),s="",o=0;for(let l=0;l<r.length;l+=1){let c=r[l];c==="\\"&&l+1<r.length?(s+=zs(r[l+1]),l+=1):c==="*"?r[l+1]==="*"?r[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&n?(s+="(?:",o+=1):c==="}"&&n&&o>0?(s+=")",o-=1):c===","&&n&&o>0?s+="|":s+=zs(c)}let a=new RegExp(`^${s}$`);return Bs.set(e,a),a}i(ye,"globToRegExp");function gi(e){return or(String(e)).split("/").filter(Boolean).filter(r=>r!=="**"&&r!=="*"&&!r.includes("*")&&!r.includes("?")&&!r.includes("{")&&!r.includes("["))}i(gi,"concreteGlobSegments");function yn(e,t){let r=or(String(e)),n=gi(r),s=r.replace(/\*/g,"").length,o=n.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(n.length===0)return s;let l=0,c=-1;for(let u of n){let f=-1;for(let y=l;y<a.length;y+=1)if(a[y]===u){f=y;break}if(f<0)return o;c=f,l=f+1}return(c+1)*1e6+n.length*1e4+s}i(yn,"patternSpecificity");function ue(e,t){let r=String(e).split(/[/\\]/).join("/"),n,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>ye(a).test(r))){for(let a of o.patterns??[])if(ye(a).test(r)){let l=yn(a,r);l>s&&(s=l,n=o.name)}}return n}i(ue,"layerForRelativePath");function Ws(e,t){if(!t?.length)return;let r=String(e).split(/[/\\]/).filter(Boolean),n=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<r.length-1;s+=1)if(n.has(r[s].toLowerCase()))return`${r[s].toLowerCase()}/${r[s+1].toLowerCase()}`}i(Ws,"sliceIdForPath");function yi(e){let t=new Set;for(let r of e??[]){let s=or(String(r)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let l=s[o-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(yi,"inferSliceFoldersFromPatterns");function hi(e,t,r){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let n=(r??[]).find(s=>s.name===t);return yi(n?.patterns)}i(hi,"resolveSliceFolders");function qs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(qs,"normalizeSegments");function Xs(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(Xs,"trimTrailingSlashes");var Ai=["src","app"];function Ri(e){let t=Xs(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Ri,"isBlanketRoot");function Ys(e,t){if(!e||!t?.length)return!1;let r=String(e).split(/[/\\]/).join("/"),n=r.toLowerCase(),s=qs(r);for(let o of t){if(typeof o!="string"||o.length===0||Ri(o))continue;if(o.includes("*")){let c=Xs(o.toLowerCase());if(ye(c).test(n)||ye(`${c}/**`).test(n))return!0;continue}let a=qs(o);if(a.length===0)continue;let l=Ai.includes(s[0])&&a[0]!==s[0]?[0,1]:[0];for(let c of l){if(c+a.length>s.length)continue;let u=!0;for(let f=0;f<a.length;f+=1)if(s[c+f]!==a[f]){u=!1;break}if(u)return!0}}return!1}i(Ys,"pathUnderSharedRoot");function Js(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(Js,"sliceMatchesDeclaration");function ki(e,t,r){return!e?.length||!t||!r?!1:e.some(n=>n&&typeof n.from=="string"&&typeof n.to=="string"&&Js(n.from,t)&&Js(n.to,r))}i(ki,"crossSliceEdgeAllowed");function Ei(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(Ei,"peerIsolationDecision");function ze(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(s=>!!s);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(ze,"peerIsolationDenyExplanation");function ar(e,t,r,n){return Ne(e,t,r,n)?.rule}i(ar,"findDeniedEdgeRule");function Ne(e,t,r,n){for(let s of e??[])if(!(s.from!==t||s.to!==r)&&s.allowed===!1){if(s.peerIsolation){let o=n?.fromPath,a=n?.toPath,l=hi(s,t,n?.layers),c=o?Ws(o,l):void 0,u=a?Ws(a,l):void 0,f=Ei({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&Ys(o,s.sharedRoots),toShared:!u&&Ys(a,s.sharedRoots),crossSliceAllowed:ki(s.allowedCrossSlice,c,u)});if(f.denied)return{rule:s,peerIsolationReason:f.reason,fromSlice:c,toSlice:u};continue}if(t!==r)return{rule:s}}}i(Ne,"findDeniedEdgeDecision");function We(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(We,"literalText");function eo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(eo,"lineOf");function Zs(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let s=n.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.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(Zs,"isTypeOnlyReference");function to(e,t){let r={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},n=e.createCompilerHost(r,!0);return n.getSourceFile=s=>s===t.fileName?t:void 0,n.fileExists=s=>s===t.fileName,n.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],r,n).getTypeChecker()}i(to,"singleFileChecker");function hn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(hn,"symbolAt");function An(e,t,r,n){let s=n.parent&&e.isShorthandPropertyAssignment(n.parent)&&n.parent.name===n,o;try{o=s?t.getShorthandAssignmentValueSymbol(n.parent):hn(t,n)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===r.fileName)}i(An,"localDeclaration");function Le(e,t){let r,n=[],s=i((a,l,c,u=!1)=>n.push({specifier:c,kind:l,line:eo(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",We(e,a.moduleSpecifier),Zs(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",We(e,a.moduleSpecifier),Zs(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",We(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!An(e,r??(r=to(e,t)),t,a.expression);(l||u)&&s(a,u?"require":"dynamic-import",We(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),n}i(Le,"extractSemanticDependencies");function Si(e,t){let r=[],n=t;for(;e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n);){if(e.isPropertyAccessExpression(n))r.unshift(n.name.text);else{let s=We(e,n.argumentExpression);if(s===void 0)return;r.unshift(s)}n=n.expression}if(e.isIdentifier(n))return r.unshift(n.text),{root:n,segments:r}}i(Si,"staticAccessPath");function Ii(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(Ii,"runtimeIdentifierReference");function Qs(e,t){let r=t[0]==="globalThis"?t.slice(1):t;for(let n=r.length;n>=1;n-=1){let s=r.slice(0,n).join(".");if(e.has(s))return s}}i(Qs,"bestForbiddenMatch");function Pe(e,t,r){if(r.length===0)return[];let n=new Set(r),s=to(e,t),o=new Map,a=new Set;for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations)e.isIdentifier(p.name)&&a.add(p.name.text);let l=i(g=>{let p=Si(e,g);if(!p)return;let m=hn(s,p.root),A=m?o.get(m):void 0;return A?[...A,...p.segments.slice(1)]:An(e,s,t,p.root)||a.has(p.root.text)?void 0:p.segments},"resolvePath");for(let g of t.statements)if(e.isVariableStatement(g))for(let p of g.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let m=l(p.initializer),A=hn(s,p.name);!m||!A||o.set(A,m)}let c=[],u=new Set,f=i((g,p)=>{let m=eo(t,p),A=`${g}:${p.getStart(t)}`;u.has(A)||(u.add(A),c.push({name:g,line:m,node:p}))},"flag"),y=i(g=>{let p=g.parent&&(e.isPropertyAccessExpression(g.parent)||e.isElementAccessExpression(g.parent))&&g.parent.expression===g;if((e.isPropertyAccessExpression(g)||e.isElementAccessExpression(g))&&!p){let m=l(g),A=m?Qs(n,m):void 0;A&&f(A,g)}else e.isIdentifier(g)&&n.has(g.text)&&Ii(e,g)&&!An(e,s,t,g)&&f(g.text,g);if(e.isVariableDeclaration(g)&&e.isObjectBindingPattern(g.name)&&g.initializer){let m=l(g.initializer);if(m)for(let A of g.name.elements){if(!e.isIdentifier(A.name))continue;let I=A.propertyName?We(e,A.propertyName)??A.propertyName.text:A.name.text,_=Qs(n,[...m,I]);_&&f(_,g.initializer)}}e.forEachChild(g,y)},"visit");return y(t),c}i(Pe,"collectForbiddenCapabilityUses");function Rn(e,t,r){let n=[];for(let s of r?.dependencies??Le(e,t)){if(s.typeOnly||!s.specifier)continue;let o=ct(s.specifier);o&&n.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of r?.ambientUses??Pe(e,t,gn)){let o=nr(s.name);o&&n.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return n.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}i(Rn,"collectCapabilityUses");var kn={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."},En=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 Sn(e,t){return t.flatMap((n,s)=>(n.prefixes??n.intentPrefixes??[]).map(o=>({layer:n.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:n})=>e.startsWith(n)).sort((n,s)=>s.prefix.length-n.prefix.length||n.layerIndex-s.layerIndex)[0]?.layer}i(Sn,"resolveIntentLayer");function we(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(we,"looksLikeArkIntent");function ut(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&we(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:kn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:kn.PUBLISH_MISSING_SOURCE}),t}i(ut,"classifyPublishFacts");function W(e,t,r){return{ruleId:e,code:e,message:t,...r}}i(W,"violation");function qe(e,t){return e.slice(0,t).split(`
2
+ `).length}i(qe,"lineOf");var vi=new Set(["publish","subscribe","defineIntent","registerHandler"]);function bi(e,t){return e.index+e[0].indexOf(t)}i(bi,"captureIndex");function Ci(e){let t=[],r=new Set,n=i((l,c)=>{!l||r.has(c)||(r.add(c),t.push({value:l,index:c}))},"push"),s=i(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let u=c[1];u&&n(u,bi(c,u))}},"pushFrom");s(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),s(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let o=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=o.exec(e))!==null;){let l=a[1]??"",c=a.index+a[0].indexOf(l),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,f;for(;(f=u.exec(l))!==null;){let y=f[1];y&&n(y,c+f.index+f[0].indexOf(y))}}return s(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),s(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}i(Ci,"extractQuotedStrings");function Oi(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 s;for(;(s=n.re.exec(e))!==null;){let o=s.index+s[0].indexOf(s[1]),a=s[0],l=n.kind==="import"&&/\bimport\s+type\b/.test(a)||n.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:o,kind:n.kind,typeOnly:l})}}return t.sort((n,s)=>n.index-s.index)}i(Oi,"extractModuleSpecifiers");function _i(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(_i,"isSyntaxWrapper");function In(e,t){let r=t;for(;r?.parent&&_i(e,r.parent);)r=r.parent;return r}i(In,"unwrapWrappers");function vn(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(vn,"callCalleeName");function xi(e,t){let r=t.parent;if(!r||!e.isObjectLiteralExpression(r))return!1;let n=In(e,r),s=n.parent;if(!s)return!1;if(e.isCallExpression(s)&&vn(e,s)==="publish"){let o=s.arguments;return o[1]===n||o[2]===n}if(e.isPropertyAssignment(s)&&bn(e,s.name)==="metadata"){let o=s.parent;if(!o)return!1;let l=In(e,o).parent;return!!(l&&e.isCallExpression(l)&&vn(e,l)==="publish")}return!1}i(xi,"isPublishMetadataSource");function ro(e,t){let r=In(e,t),n=r.parent;if(!n)return!1;if(e.isCallExpression(n)){let s=vn(e,n);if(s&&vi.has(s)&&n.arguments.some(o=>o===r))return!0}if(e.isArrayLiteralExpression(n))return ro(e,n);if(e.isPropertyAssignment(n)){let s=bn(e,n.name);if(s==="intent"||s==="onEvent"||s==="reactsTo"||s==="source"&&xi(e,n))return!0}return!1}i(ro,"isDeclaredIntentSite");function Ti(e,t){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),n=[],s=i(o=>{e.isStringLiteralLike(o)&&ro(e,o)&&n.push({value:o.text,index:o.getStart(r)}),e.forEachChild(o,s)},"visit");return s(r),n}i(Ti,"extractQuotedStringsAst");function Ni(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(Ni,"hasInfrastructureToken");function Li(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(r=>t===r||t.startsWith(`${r}/`))}i(Li,"isKnownInfrastructurePackage");function Pi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(r=>t.includes(r))}i(Pi,"layerHasInfrastructureRole");function ft(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ft,"tsStringLiteralText");function bn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(bn,"tsPropertyName");function no(e,t,r){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(n=>!e.isPropertyAssignment(n)&&!e.isShorthandPropertyAssignment(n)?!1:bn(e,n.name)===r)}i(no,"tsObjectProperty");function mt(e,t,r){return no(e,t,r)!==void 0}i(mt,"tsObjectHasProperty");function pt(e,t,r){let n=no(e,t,r);return n&&e.isPropertyAssignment(n)?n.initializer:void 0}i(pt,"tsObjectPropertyValue");function wi(e,t){let r=pt(e,t,"metadata");return mt(e,r,"source")}i(wi,"tsObjectHasMetadataSource");function so(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?so(e,t.name):!1:!1}i(so,"tsLooksLikeIntentCreatorExpression");function Di(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(Di,"tsIsPublishCall");function Mi(e,t){if(!e.isCallExpression(t))return!1;let r=t.arguments[0],n=ft(e,r);return n!==void 0&&we(n)||mt(e,r,"intent")||so(e,r)}i(Mi,"tsIsArkPublishCandidate");function Fi(e,t){if(!e.isCallExpression(t))return!1;let[r,n,s]=t.arguments;return wi(e,r)||mt(e,n,"source")||mt(e,s,"source")}i(Fi,"tsPublishHasSource");function $i(e,t){if(!e.isCallExpression(t))return;let[r,n,s]=t.arguments,o=pt(e,r,"metadata");return ft(e,pt(e,o,"source"))??ft(e,pt(e,n,"source"))??ft(e,pt(e,s,"source"))}i($i,"tsPublishSourceLiteral");function Hi(e,t,r,n){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=r,a=o?.filePath,l=o?.layer,c=[],u=i(y=>s.getLineAndCharacterOfPosition(y.getStart(s)).line+1,"lineForNode"),f=i(y=>{if(Di(e,y)){let g=y.arguments[0],p=ft(e,g);for(let A of ut({publishCall:!0,rawIntentName:p,objectHasIntent:mt(e,g,"intent"),arkPublishCandidate:Mi(e,y),hasSource:Fi(e,y)}))c.push(W(A.ruleId,A.message,{line:u(y),filePath:a}));let m=$i(e,y);if(n&&l&&m&&we(m)){let A=n.resolveLayer(m);A&&A!==l&&c.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${m}" resolves to ${A}, but the target file is classified as ${l}.`,{line:u(y),filePath:a,target:m,fromLayer:l,toLayer:A}))}}e.forEachChild(y,f)},"visit");return f(s),c}i(Hi,"analyzePublishAst");function Cn(e={}){let t=new Set((e.intents||[]).map(o=>typeof o=="string"?o:o.name)),r=e.forbiddenPatterns||[],n=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(o,a){let l=[],c=a,u=c?.filePath,f=c?.layer,y=e.typescript,g=y?y.createSourceFile(u??"generated.ts",o,y.ScriptTarget.Latest,!0):void 0,p=g?Le(e.typescript,g):void 0,m=p?p.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(g),kind:R.kind,typeOnly:R.typeOnly})):Oi(o),A=e.typescript?Ti(e.typescript,o):Ci(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let R of p?.filter(({unresolved:S})=>S)??[]){let S=R.kind==="require";l.push(W(S?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${S?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:R.line,filePath:u}))}let I=f!==void 0&&(n.has(f)||Pi(f)),_=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let R of r)if(R instanceof RegExp){R.lastIndex=0;let S=R.exec(o);R.lastIndex=0,S&&l.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:S.index===void 0?void 0:qe(o,S.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+_}))}else o.includes(R)&&l.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:qe(o,o.indexOf(R)),filePath:u}));for(let R of m){let S=e.resolveImportTarget?.(R.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,u)}:void 0),b=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,w=S?.layer;if(w&&f){let k=ar(e.architectureProfile?.rules,f,w,{fromPath:b?.relPath,toPath:S?.relPath,layers:e.architectureLayers});if(k){if(R.typeOnly&&!k.peerIsolation)continue;let L=!!k.peerIsolation;l.push(W("LAYER_IMPORT_VIOLATION",k.message??(L?`Layer "${f}" must not import across slices into "${w}".`:`Layer "${f}" must not import "${w}".`),{line:qe(o,R.index),source:R.value,target:R.value,filePath:u,fromLayer:f,toLayer:w,suggestion:L?"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:R.kind,peerIsolation:L,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}I||R.typeOnly||!Ni(R.value)&&!Li(R.value)||l.push(W("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:qe(o,R.index),source:R.value,target:R.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+_,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let S=R.check({source:o,context:a});if(S!==!0)if(Array.isArray(S))for(let b of S)l.push(W("POLICY_VIOLATION",b.message,{filePath:u,suggestion:`Fix violation of policy "${R.name}".`}));else S===!1?l.push(W("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(W("POLICY_VIOLATION",S.message))}if(s&&t.size>0)for(let R of A)we(R.value)&&!t.has(R.value)&&l.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:qe(o,R.index),filePath:u,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let R of A){if(!we(R.value))continue;let S=e.architectureProfile.resolveLayer(R.value);if(!S)continue;let b=Ne(e.architectureProfile.rules,f,S,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(b){let w=b.rule.peerIsolation?ze(b.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:b.fromSlice,toSlice:b.toSlice}):void 0,k=`Layer "${f}" must not reference "${S}" through "${R.value}".`,L=w&&b.peerIsolationReason!=="cross-slice"?`${k} ${w}`:b.rule.message?w?`${b.rule.message} (${w})`:b.rule.message:k;l.push(W("LAYER_REFERENCE_VIOLATION",L,{line:qe(o,R.index),filePath:u,target:R.value,fromLayer:f,toLayer:S,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:b.rule,peerIsolationReason:b.peerIsolationReason}}))}}if(e.extensions)for(let R of e.extensions)try{let S=R.analyze(o,a);l.push(...S)}catch(S){l.push(W("EXTENSION_ERROR",`Extension "${R.name}" failed: ${S instanceof Error?S.message:String(S)}`))}if(e.typescript&&g&&f&&e.forbiddenGlobals?.[f]?.length)try{let R=e.forbiddenGlobals[f];l.push(...Pe(e.typescript,g,R).map(S=>W("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${S.name}".`,{line:S.line,filePath:u,target:S.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let S of p??[]){if(S.typeOnly||!S.specifier)continue;let b=Ie(S.specifier,R);b&&l.push(W("FORBIDDEN_GLOBAL",`${f} must not use module "${S.specifier}" because it is the import form of forbidden global "${b}".`,{line:S.line,filePath:u,source:S.specifier,target:S.specifier,fromLayer:f,details:{importKind:S.kind,forbiddenGlobal:b},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&g&&f&&e.capabilityWalls?.[f]?.length)try{let R=new Set(e.capabilityWalls[f]),S=e.forbiddenGlobals?.[f]??[];for(let b of Rn(e.typescript,g))R.has(b.capability)&&(b.source==="ambient-global"&&dt(b.symbol,S)||b.source==="import-based"&&Ie(b.symbol,S)||l.push(W("CAPABILITY_VIOLATION",b.source==="import-based"?`${f} denies the ${b.capability} capability; found import of "${b.symbol}".`:`${f} denies the ${b.capability} capability; found ambient "${b.symbol}".`,{line:b.line,filePath:u,target:b.symbol,capability:b.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...Hi(e.typescript,o,a,e.architectureProfile))}catch(R){l.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(Cn,"createAICodeGate");var De={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},oo={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...De,default:[]},kernelRoots:{...De},managedLayers:{...De,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},ao={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...De,default:[]},managedLayers:{...De,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...De,default:[]},appliesTo:{...De,default:[]}}};function gt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(gt,"isObject");function io(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let r of e.layers)gt(r)&&typeof r.name=="string"&&r.name.length>0&&t.add(r.name);return t}i(io,"declaredLayerNames");function lo(e){if(!gt(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(lo,"defaultedArkRun");function co(e){if(!gt(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(co,"defaultedArkOrder");function uo(e,t){let r=e.arkRun;if(r===void 0||!gt(r))return;let n=io(e),s=r.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),r.mode==="enforced"){let o=r.kernelRoots??r.compositionRoots;(!Array.isArray(o)||o.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(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(uo,"validateArkRunExtra");function po(e,t){let r=e.arkOrder;if(r===void 0||!gt(r))return;let n=io(e),s=r.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!n.has(o)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),r.mode==="enforced"){let o=r.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(po,"validateArkOrderExtra");var ne="1.3",lr="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",fo=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],ji=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ki(){let e=[];for(let t of fo)for(let r of fo)t===r||ji.has(`${t}->${r}`)||e.push({from:t,to:r,allowed:!1});return e}i(Ki,"createDefaultRules");var dr=Ki(),On=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ce={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},cr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:lr,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:lr,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ne,default:ne},name:{type:"string",minLength:1},include:{...ce,minItems:1,default:["src"]},exclude:{...ce,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:dr,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ce,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:{...ce,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ce,minItems:1},exclude:ce,intentPrefixes:ce,description:{type:"string",minLength:1},forbiddenGlobals:ce,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:{...ce,minItems:1},sharedRoots:{...ce,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:{...ce,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:{...ce,minItems:1}}},arkRun:oo,arkOrder:ao}},he=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,r){super(`Invalid ArkGate config (${t}):
3
+ ${r.map(n=>`- ${n.path}: ${n.message}`).join(`
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=r}};function mo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(mo,"isObject");function ir(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(ir,"propertyPath");function Ye(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Ye,"valueType");function Vi(e,t){let r="#/$defs/";if(e.startsWith(r))return t.$defs[e.slice(r.length)]}i(Vi,"resolveSchemaRef");function yt(e,t,r,n,s){if(t.$ref){let o=Vi(t.$ref,n);if(!o){s.push({path:r,message:`schema reference ${t.$ref} cannot be resolved`});return}yt(e,o,r,n,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:r,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:r,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!mo(e)){s.push({path:r,message:`must be an object; received ${Ye(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:ir(r,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:ir(r,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||yt(e[l],a,ir(r,l),n,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&yt(e[a],l,ir(r,a),n,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:r,message:`must be an array; received ${Ye(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:r,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:r,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>yt(o,t.items,`${r}[${a}]`,n,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:r,message:`must be a string; received ${Ye(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:r,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:r,message:`must be a boolean; received ${Ye(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:r,message:`must be an integer; received ${Ye(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:r,message:`must be at least ${t.minimum}`})}}i(yt,"validateNode");function Ui(e){let t={...e,$schema:e.$schema===void 0?lr:e.$schema,schemaVersion:e.schemaVersion===void 0?ne:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?dr.map(r=>({...r})):e.rules};return e.arkRun!==void 0&&(t.arkRun=lo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=co(e.arkOrder)),t}i(Ui,"defaultedConfig");function Gi(e){return e===ne?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Gi,"migratedFromOf");function Bi(){let e=new Set([ne]);for(let t of On)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Bi,"knownInputVersions");function zi(e,t="ark.config.json"){if(!mo(e))throw new he(t,[{path:"$",message:`must be an object; received ${Ye(e)}`}]);let r=Bi(),n=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(n===null)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ne}`}]);if(n!=="unversioned"&&!r.has(n))throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${ne}`}]);let s=n,o={...e},a=0;for(;s!==ne&&a<On.length+1;){a+=1;let l=On.find(c=>c.from===s);if(!l)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${ne}`}]);s=l.to,o.schemaVersion=s}if(s!==ne)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(n)}; expected ${ne}`}]);return{candidate:Ui(o),migratedFrom:Gi(n)}}i(zi,"migrateArkConfig");function ht(e,t="ark.config.json"){let{candidate:r,migratedFrom:n}=zi(e,t),s=[];if(yt(r,cr,"$",cr,s),uo(r,s),po(r,s),s.length>0)throw new he(t,s);return{config:r,migratedFrom:n}}i(ht,"loadArkConfigContract");function ur(e,t="ark.config.json"){let r;try{r=JSON.parse(e)}catch(n){throw new he(t,[{path:"$",message:`invalid JSON: ${n instanceof Error?n.message:String(n)}`}])}return ht(r,t)}i(ur,"parseArkConfigJson");function go(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:lr,schemaVersion:ne};for(let[r,n]of Object.entries(e))r!=="$schema"&&r!=="schemaVersion"&&(t[r]=n);return t}i(go,"withArkConfigMetadata");function Wi(e){return e.endsWith(".")?e:`${e}.`}i(Wi,"normalizePrefix");function qi(e,t){let r=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-r}i(qi,"byLongestPrefix");function Rt(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Wi)})),r=[...t].sort(qi),n=[...e.rules??[]];return{name:e.name,layers:t,rules:n,resolveLayer(s){return t.find(o=>o.match?.(s))?.name??r.find(o=>o.prefixes.some(a=>s.startsWith(a)))?.name}}}i(Rt,"createArchitectureProfile");function _n(e,t={}){return Rt({name:t.name??e.name??"ark.config.json",layers:e.layers.map((r,n)=>({name:r.name,prefixes:r.intentPrefixes??[],description:r.description,order:n+1})),rules:e.rules??[]})}i(_n,"createArchitectureProfileFromArkConfig");var Yi=[{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}],At=Rt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Yi,rules:dr.map(e=>({...e}))}),Ji={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 xn(e={}){let t=e.rootDir??"src",r=e.optionalLayers??!0,n=t==="."?"":`${t}/`;return go({include:e.include??[t],layers:At.layers.map(s=>({name:s.name,patterns:(Ji[s.name]??[s.name]).map(o=>`${n}${o}/**`),intentPrefixes:s.prefixes,optional:r})),rules:[...At.rules]})}i(xn,"createElevenLayerArkConfig");function Y(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(Y,"deterministicHash");function F(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(F).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${F(t[r])}`).join(",")}}`}i(F,"stableSerialize");var ve="1.2";var yo=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let r=F(e),n=F(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 Xe(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 Y(F(t))}i(Xe,"resolvedFactsEvidenceRequirementsHash");function Xi(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,L)=>k.path<L.path?-1:k.path>L.path?1:0),n=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:Z(k.namedBindings)}:{}})).sort(q),s=e.capabilityUses.map(k=>({...k})).sort(q),o=e.ambientUses.map(k=>({...k})).sort(q),a=e.publishCalls.map(k=>({...k})).sort(q),l=e.intentReferences.map(k=>({...k})).sort(q),c=e.safetyUses.map(k=>({...k})).sort(q),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(L=>({...L}))})).sort(q),f=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(q),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(q),g=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(q),p=(e.arkRunDeclarations??[]).map(k=>({...k,uses:Z(k.uses),reactsTo:Z(k.reactsTo),raises:Z(k.raises),sends:Z(k.sends)})).sort(q),m=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(q),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(q),I=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(q),_=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(q),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(q),S=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(q),b=e.files.map(({path:k,contentHash:L})=>({path:k,contentHash:L})).sort((k,L)=>k.path<L.path?-1:k.path>L.path?1:0),w=Y(F(b));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:w,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:r,dependencies:n,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:y,arkRunCompositionRootHits:g,arkRunDeclarations:p,arkOrderPlaneCalls:m,arkOrderGenericUpdates:A,arkOrderRootHits:I,arkOrderXiFieldWrites:_,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:S}}i(Xi,"canonicalResolvedFactsInput");function ho(e){let t=Xi(e);return{...t,factsHash:Y(F(t))}}i(ho,"createCanonicalResolvedCandidateFacts");function pr(e){return ho(Ro($(e,"$"),!1))}i(pr,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i($,"asRecord");function j(e,t,r){let n=new Set(t),s=Object.keys(e).find(o=>!n.has(o));if(s)throw new Error(`${r}.${s} is not part of schema ${"1.2"}.`)}i(j,"assertOnlyKeys");function M(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(M,"requiredText");function Ae(e,t,r){if(e[t]!==void 0)return M(e,t,r)}i(Ae,"optionalText");function V(e,t,r){let n=M(e,t,r),s=n.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${r}.${t} must be a canonical project-relative path.`);let o=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)throw new Error(`${r}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(l);let a=o.join("/");if(!a||a!==n)throw new Error(`${r}.${t} must be a canonical project-relative path.`);return a}i(V,"requiredProjectPath");function U(e,t,r){if(typeof e[t]!="boolean")throw new Error(`${r}.${t} must be a boolean.`);return e[t]}i(U,"requiredBoolean");function Ao(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(Ao,"requiredInteger");function ee(e,t,r){let n=Ao(e,t,r);if(n===0)throw new Error(`${r}.${t} must be a positive integer.`);return n}i(ee,"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 Re(e,t,r,n){let s=e[t];if(typeof s!="string"||!r.includes(s))throw new Error(`${n}.${t} must be one of ${r.join(", ")}.`);return s}i(Re,"enumValue");function Je(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(Je,"parseStringArray");function Zi(e,t,r){let n=new Set;for(let s of e){let o=t(s);if(n.has(o))throw new Error(`${r} must not contain duplicate facts (${o}).`);n.add(o)}}i(Zi,"assertUnique");function Ro(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=Re(e,"schemaVersion",["1.0","1.1","1.2"],"$"),n=Re(e,"completeness",["complete","partial","unavailable"],"$"),s=G(e,"completenessReasons","$").map((v,C)=>{let h=`$.completenessReasons[${C}]`,d=$(v,h);j(d,["code","message","file"],h);let P=d.file===void 0?void 0:V(d,"file",h);return{code:M(d,"code",h),message:M(d,"message",h),...P?{file:P}:{}}});if(n==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(n!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=G(e,"files","$").map((v,C)=>{let h=`$.files[${C}]`,d=$(v,h);return j(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:V(d,"path",h),contentHash:M(d,"contentHash",h),parseStatus:Re(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Ao(d,"parseDiagnosticCount",h),exportsOnlyTypes:U(d,"exportsOnlyTypes",h),typeOnlyExportNames:Je(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:U(d,"hasTopLevelSideEffects",h)}}),a=G(e,"dependencies","$").map((v,C)=>{let h=`$.dependencies[${C}]`,d=$(v,h);j(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let P=Ae(d,"specifier",h),H=Ae(d,"target",h),le=Re(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(le==="resolved-project"&&!H)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(le!=="resolved-project"&&H)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(le!=="dynamic"&&!P)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:V(d,"from",h),...P?{specifier:P}:{},kind:Re(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:U(d,"typeOnly",h),line:ee(d,"line",h),resolution:le,...H?{target:V(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Je(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:U(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:U(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:U(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:U(d,"portProofEligible",h)}:{}}}),l=G(e,"capabilityUses","$").map((v,C)=>{let h=`$.capabilityUses[${C}]`,d=$(v,h);return j(d,["file","line","symbol","capability","source"],h),{file:V(d,"file",h),line:ee(d,"line",h),symbol:M(d,"symbol",h),capability:Re(d,"capability",yo,h),source:Re(d,"source",["ambient-global","import-based"],h)}}),c=G(e,"ambientUses","$").map((v,C)=>{let h=`$.ambientUses[${C}]`,d=$(v,h);return j(d,["file","line","symbol"],h),{file:V(d,"file",h),line:ee(d,"line",h),symbol:M(d,"symbol",h)}}),u=G(e,"publishCalls","$").map((v,C)=>{let h=`$.publishCalls[${C}]`,d=$(v,h);j(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let P=Ae(d,"rawIntentName",h),H=Ae(d,"sourceIntent",h);return{file:V(d,"file",h),line:ee(d,"line",h),...P?{rawIntentName:P}:{},objectHasIntent:U(d,"objectHasIntent",h),arkPublishCandidate:U(d,"arkPublishCandidate",h),hasSource:U(d,"hasSource",h),...H?{sourceIntent:H}:{}}}),f=G(e,"intentReferences","$").map((v,C)=>{let h=`$.intentReferences[${C}]`,d=$(v,h);return j(d,["file","line","intent"],h),{file:V(d,"file",h),line:ee(d,"line",h),intent:M(d,"intent",h)}}),y=G(e,"safetyUses","$").map((v,C)=>{let h=`$.safetyUses[${C}]`,d=$(v,h);j(d,["file","line","kind","symbol"],h);let P=Ae(d,"symbol",h),H=Re(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(H==="in-memory-store"&&!P)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(H!=="in-memory-store"&&P)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:V(d,"file",h),line:ee(d,"line",h),kind:H,...P?{symbol:P}:{}}});Zi(o,v=>v.path,"$.files");let g=new Set(o.map(v=>v.path));for(let v of o){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"&&o.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(!g.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let m=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((v,C)=>{let h=`$.arkRunKernelCalls[${C}]`,d=$(v,h);j(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let P=Ae(d,"receiver",h),H=Ae(d,"nameLiteral",h);return{file:V(d,"file",h),line:ee(d,"line",h),kind:Re(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:M(d,"callee",h),viaImport:U(d,"viaImport",h),...P?{receiver:P}:{},...H?{nameLiteral:H}:{}}}),I=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((v,C)=>{let h=`$.arkRunManagedNews[${C}]`,d=$(v,h);j(d,["file","line","typeName","importedFrom"],h);let P=Ae(d,"importedFrom",h);return{file:V(d,"file",h),line:ee(d,"line",h),typeName:M(d,"typeName",h),...P?{importedFrom:P}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((v,C)=>{let h=`$.arkRunCompositionRootHits[${C}]`,d=$(v,h);return j(d,["file","matchedRoot","hasKernelFactory"],h),{file:V(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasKernelFactory:U(d,"hasKernelFactory",h)}}),S=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),w=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((v,C)=>{let h=`$.arkOrderPlaneCalls[${C}]`,d=$(v,h);return j(d,["file","line","callee"],h),{file:V(d,"file",h),line:ee(d,"line",h),callee:M(d,"callee",h)}}),L=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((v,C)=>{let h=`$.arkOrderGenericUpdates[${C}]`,d=$(v,h);return j(d,["file","line","method"],h),{file:V(d,"file",h),line:ee(d,"line",h),method:M(d,"method",h)}}),x=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((v,C)=>{let h=`$.arkOrderRootHits[${C}]`,d=$(v,h);return j(d,["file","matchedRoot","hasPlaneFactory"],h),{file:V(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasPlaneFactory:U(d,"hasPlaneFactory",h)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((v,C)=>{let h=`$.arkOrderXiFieldWrites[${C}]`,d=$(v,h);return j(d,["file","line","key"],h),{file:V(d,"file",h),line:ee(d,"line",h),key:M(d,"key",h)}}),J=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((v,C)=>{let h=`$.arkOrderIngestWritesXi[${C}]`,d=$(v,h);return j(d,["file","line"],h),{file:V(d,"file",h),line:ee(d,"line",h)}}),Ve=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((v,C)=>{let h=`$.arkOrderReleaseKeyCounts[${C}]`,d=$(v,h);return j(d,["file","line","keyCount"],h),{file:V(d,"file",h),line:ee(d,"line",h),keyCount:ee(d,"keyCount",h)}}),st=S.map((v,C)=>{let h=`$.arkRunDeclarations[${C}]`,d=$(v,h);return j(d,["file","line","uses","reactsTo","raises","sends"],h),{file:V(d,"file",h),line:ee(d,"line",h),uses:Je(d.uses,`${h}.uses`),reactsTo:Je(d.reactsTo,`${h}.reactsTo`),raises:Je(d.raises,`${h}.raises`),sends:Je(d.sends,`${h}.sends`)}});for(let[v,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",y],["$.arkRunKernelCalls",m],["$.arkRunManagedNews",I],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",st],["$.arkOrderPlaneCalls",w],["$.arkOrderGenericUpdates",L],["$.arkOrderRootHits",x],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",J],["$.arkOrderReleaseKeyCounts",Ve]])for(let h of C)if(!g.has(h.file))throw new Error(`${v} references missing file ${h.file}.`);let Te=Ae(e,"projectPackageName","$"),sn=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((v,C)=>{let h=`$.classShapes[${C}]`,d=$(v,h);j(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let P=G(d,"mutatingMethods",h).map((H,le)=>{let Qt=`${h}.mutatingMethods[${le}]`,on=$(H,Qt);return j(on,["name","referencesGuardOrPublish"],Qt),{name:M(on,"name",Qt),referencesGuardOrPublish:U(on,"referencesGuardOrPublish",Qt)}});return{file:V(d,"file",h),className:M(d,"className",h),exported:U(d,"exported",h),hasPublicMutableFields:U(d,"hasPublicMutableFields",h),hasPublicSetters:U(d,"hasPublicSetters",h),hasPublicConstructor:U(d,"hasPublicConstructor",h),hasStaticFactory:U(d,"hasStaticFactory",h),mutatingMethods:P,...d.dataOnly===void 0?{}:{dataOnly:U(d,"dataOnly",h)}}});return{schemaVersion:r,completeness:n,completenessReasons:s,resolverIdentity:M(e,"resolverIdentity","$"),compilerIdentity:M(e,"compilerIdentity","$"),compilerOptionsHash:M(e,"compilerOptionsHash","$"),tsconfigHash:M(e,"tsconfigHash","$"),evidenceRequirementsHash:M(e,"evidenceRequirementsHash","$"),...Te?{projectPackageName:Te}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:f,safetyUses:y,classShapes:sn,arkRunKernelCalls:m,arkRunManagedNews:I,arkRunCompositionRootHits:R,arkRunDeclarations:st,arkOrderPlaneCalls:w,arkOrderGenericUpdates:L,arkOrderRootHits:x,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:J,arkOrderReleaseKeyCounts:Ve}}i(Ro,"parseResolvedFactsInput");function ke(e){let t=$(e,"$"),r=M(t,"factsHash","$"),n=M(t,"candidateTreeHash","$"),s=ho(Ro(t,!0));if(s.factsHash!==r)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(n!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}i(ke,"loadResolvedCandidateFacts");var Qi=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},se={type:"integer",minimum:1},B={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},fr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:T,message:T,file:B}}},resolverIdentity:T,compilerIdentity:T,compilerOptionsHash:T,tsconfigHash:T,candidateTreeHash:T,evidenceRequirementsHash:T,projectPackageName:T,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:B,contentHash:T,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:T},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:B,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:se,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:B,namedBindings:{type:"array",items:T},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:B,line:se,symbol:T,capability:{enum:Qi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:B,line:se,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:B,line:se,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:B,line:se,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:B,line:se,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:B,className:T,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:T,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:B,line:se,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:T,viaImport:{type:"boolean"},receiver:T,nameLiteral:T}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:B,line:se,typeName:T,importedFrom:T}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:B,matchedRoot:T,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:B,line:se,uses:{type:"array",items:T},reactsTo:{type:"array",items:T},raises:{type:"array",items:T},sends:{type:"array",items:T}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:B,line:se,callee:T}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:B,line:se,method:T}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:B,matchedRoot:T,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:B,line:se,key:T}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:B,line:se}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:B,line:se,keyCount:{type:"integer",minimum:1}}}},factsHash:T},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var mr="1.0";function ae(e){return`${e.from}->${e.to}`}i(ae,"dependencyKey");function kt(e,t,r,n="dependency"){return{id:`${e}:${n}:${ae(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:r,...e==="missing"?{nextAction:`Add the planned dependency ${ae(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ae(t)}, then preflight again.`}:e==="unplanned"?{nextAction:n==="dependency-removed"?`Restore the removed dependency ${ae(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ae(t)} from the candidate, then preflight again.`}:{}}}i(kt,"dependencyFinding");function Me(e){let t=[],r=new Map(e.changeMap.map.files.map(g=>[g.path,g])),n=new Map(e.changes.map(g=>[g.path,g])),s=new Map(e.changeMap.map.dependencies.map(g=>[ae(g),g])),o=new Map(e.baseDependencies.map(g=>[ae(g),g])),a=new Map(e.candidateDependencies.map(g=>[ae(g),g]));for(let g of[...r.values()].sort((p,m)=>p.path.localeCompare(m.path))){let p=n.get(g.path);p?p.operation!==g.operation?t.push({id:`contradictory:file:${g.path}`,classification:"contradictory",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} was planned as ${g.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${g.path} to the planned ${g.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${g.path}`,classification:"satisfied",subject:"file",path:g.path,expectedOperation:g.operation,actualOperation:p.operation,message:`${g.path} matches the planned ${g.operation} operation.`}):t.push({id:`missing:file:${g.path}`,classification:"missing",subject:"file",path:g.path,expectedOperation:g.operation,message:`${g.path} was planned as ${g.operation} but is absent from the actual change.`,nextAction:`${g.operation[0].toUpperCase()}${g.operation.slice(1)} ${g.path} in the complete change set, then preflight again.`})}for(let g of[...n.values()].sort((p,m)=>p.path.localeCompare(m.path)))r.has(g.path)||t.push({id:`unplanned:file:${g.path}`,classification:"unplanned",subject:"file",path:g.path,actualOperation:g.operation,message:`${g.path} has an unplanned ${g.operation} operation.`,nextAction:`Remove ${g.path} from the change set, then preflight again.`});let l=new Set;for(let g of[...s.values()].sort((p,m)=>ae(p).localeCompare(ae(m)))){if(a.has(ae(g))){t.push(kt("satisfied",g,`${g.from} -> ${g.to} exists in the candidate architecture.`));continue}let p={from:g.to,to:g.from};a.has(ae(p))?(l.add(ae(p)),t.push(kt("contradictory",g,`${g.from} -> ${g.to} was planned, but the candidate contains the reverse edge.`))):t.push(kt("missing",g,`${g.from} -> ${g.to} is absent from the candidate architecture.`))}let c=new Set([...r.keys(),...n.keys()]);for(let[g,p]of[...a].sort(([m],[A])=>m.localeCompare(A)))o.has(g)||s.has(g)||l.has(g)||!c.has(p.from)&&!c.has(p.to)||t.push({...kt("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(g=>g.operation==="delete").map(g=>g.path));for(let[g,p]of[...o].sort(([m],[A])=>m.localeCompare(A)))a.has(g)||u.has(p.from)||u.has(p.to)||!c.has(p.from)&&!c.has(p.to)||t.push({...kt("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((g,p)=>f[g.classification]-f[p.classification]||(g.subject===p.subject?0:g.subject==="file"?-1:1)||g.id.localeCompare(p.id));let y={satisfied:t.filter(g=>g.classification==="satisfied").length,missing:t.filter(g=>g.classification==="missing").length,contradictory:t.filter(g=>g.classification==="contradictory").length,unplanned:t.filter(g=>g.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(Me,"analyzeArchitectureConvergence");var So="1.0",Tn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Nn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],el=["no-anemic-model"],ko={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},yr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Tn,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:Tn},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:[...Nn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:ko,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:ko}}}},Fe=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,r){super(`Invalid ArkRules (${t}):
5
+ ${r.map(n=>`- ${n.path}: ${n.message}`).join(`
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=r}};function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(It,"isObject");function gr(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(gr,"propertyPath");function Et(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Et,"valueType");function tl(e,t){let r="#/$defs/";if(e.startsWith(r))return t.$defs[e.slice(r.length)]}i(tl,"resolveSchemaRef");function St(e,t,r,n,s){if(t.$ref){let o=tl(t.$ref,n);if(!o){s.push({path:r,message:`schema reference ${t.$ref} cannot be resolved`});return}St(e,o,r,n,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:r,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:r,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!It(e)){s.push({path:r,message:`must be an object; received ${Et(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:gr(r,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:gr(r,a),message:"unknown field"});else if(It(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||St(e[l],a,gr(r,l),n,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&St(e[a],l,gr(r,a),n,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:r,message:`must be an array; received ${Et(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:r,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:r,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>St(o,t.items,`${r}[${a}]`,n,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:r,message:`must be a string; received ${Et(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:r,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:r,message:`must be a boolean; received ${Et(e)}`})}i(St,"validateNode");function rl(e){return{...e,$schema:e.$schema===void 0?Tn: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(rl,"defaultedArkRules");function Eo(e){return e==="enforced"?"enforced":"advisory"}i(Eo,"normalizeMode");function nl(e){return el.includes(e)}i(nl,"isTier2Sensor");function sl(e,t){let r=Array.isArray(e.structure)?e.structure:[],n=Array.isArray(e.invariants)?e.invariants:[],s=new Set;r.forEach((o,a)=>{if(!It(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),typeof o.sensor=="string"&&nl(o.sensor)&&o.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`${l?`rule ${JSON.stringify(l)} uses sensor `:"sensor "}${JSON.stringify(o.sensor)}, which is Tier-2 advisory-only and cannot be enforced${l?" (arkgate-check --sensors lists which sensors can)":""}`}),Array.isArray(o.appliesTo)&&o.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)"})}),n.forEach((o,a)=>{if(!It(o))return;let l=typeof o.id=="string"?o.id:"";l&&(s.has(l)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),Array.isArray(o.appliesTo)&&o.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(sl,"validateSemantics");function vt(e,t="arkrules.json",r){if(!It(e))throw new Fe(t,[{path:"$",message:`must be an object; received ${Et(e)}`}]);let n=rl(e),s=[];if(St(n,yr,"$",yr,s),sl(n,s),r!==void 0&&typeof n.layer=="string"&&n.layer!==r&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(r)}; received ${JSON.stringify(n.layer)}`}),s.length>0)throw new Fe(t,s);return{config:n}}i(vt,"loadArkRulesContract");function Io(e,t="arkrules.json",r){let n;try{n=JSON.parse(e)}catch(s){throw new Fe(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return vt(n,t,r)}i(Io,"parseArkRulesJson");function hr(e){let t={},r=[],n=[],s=[...e].sort((o,a)=>o.layer.localeCompare(a.layer));for(let o of s){let a=(o.file.structure??[]).map(c=>({...c,mode:Eo(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}})),l=(o.file.invariants??[]).map(c=>({...c,mode:Eo(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}}));t[o.layer]={sourceFile:o.sourceFile,structure:a,invariants:l},r.push(...a),n.push(...l)}return r.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),n.sort((o,a)=>{let l=o.provenance.layer.localeCompare(a.provenance.layer);return l!==0?l:o.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:r,invariants:n}}i(hr,"buildEffectiveArkRules");function be(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(be,"emptyEffectiveArkRules");var bt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,r){super(`Invalid Effective Contract (${t}):
7
+ ${r.map(n=>`- ${n.path}: ${n.message}`).join(`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=r}};function vo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(vo,"normalizeRel");function bo(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 c of[...e.discoveredArkRulesFiles].sort())n.push({path:c,message:`ArkRules file ${JSON.stringify(c)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:be(),warnings:n}}let s=new Set(e.config.layers.map(c=>c.name)),o=[],a=[],l=new Set;for(let c of Object.keys(r).sort()){let u=r[c],f=`$.arkRules[${JSON.stringify(c)}]`;if(typeof u!="string"||u.length===0){o.push({path:f,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){o.push({path:f,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){o.push({path:f,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let y=vo(u);l.add(y);let g=e.fileContents[y]??e.fileContents[u];if(g===void 0){o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let p=vt(JSON.parse(g),y,c);a.push({layer:c,sourceFile:y,file:p.config})}catch(p){if(p instanceof Fe)for(let m of p.issues)o.push({path:`${f}${m.path==="$"?"":m.path.replace(/^\$/,"")}`,message:`${y}: ${m.message}`});else p instanceof SyntaxError?o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${p.message}`}):o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(y)} failed to load: ${p instanceof Error?p.message:String(p)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let u=vo(c);l.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(o.length>0)throw new bt(t,o);return{config:e.config,arkRules:hr(a),warnings:n}}i(bo,"resolveEffectiveContract");function Ln(e){return{...e,layers:e.layers.map(t=>{let{description:r,...n}=t;return n})}}i(Ln,"omitLayerDescriptions");function Ar(e){let{stewards:t,...r}=Ln(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(Ar,"effectiveContractPolicyPayload");function Co(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 s=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${n.join(", ")}${s}.`}i(Co,"formatCoverageDiscards");function ol(e,t){let r=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(n=>{let s=n.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return s===""||s==="."?!0:r===s||r.startsWith(`${s}/`)})}i(ol,"isUnderCoverageRoot");function al(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${r}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(al,"titleMatchesInvariant");function il(e,t){if(!t)return!1;let r=t.split("."),n=r[r.length-1],s=r.length>1?r[0]:null;for(let o of Object.values(e))if(!(s&&!o.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(o)||o.includes(t)))return!0;return!1}i(il,"symbolPresent");function Rr(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,s=e.coverageBudgetExhausted===!0,o=e.coverageStats,a=Co(o),l=Co(o,!0),c=o?`coverage file budget exhausted: ${o.filesLoaded} files loaded at the ${o.maxFiles}-file cap, ${o.testFilesRetained} tests retained, ${o.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof o.filesRead=="number"?`; ${o.filesRead} were read`:""})`:"coverage file budget exhausted",u=(e.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),f=u.length>0,y=u.join(", "),g=[],p=[];for(let m of t){let A=[],I=m.coverage?.test!==!1,_=m.coverage?.symbol,R,S;if(!n&&I){let L;for(let X of r){let x=e.fileContents[X];if(!(!x||!al(x,m.id))){if(!f||ol(X,u)){R=X,S=f?!1:void 0;break}L??=X}}R===void 0&&L!==void 0&&(R=L,S=!0),R!==void 0&&A.push("test-title")}_&&il(e.fileContents,_)&&A.push("symbol");let w=(m.coverage?.test===!0||!!_||m.coverage===void 0)&&A.length>0||m.coverage?.test===!1&&!_?!0:A.length>0,k=n&&I&&A.length===0;if(g.push({invariantId:m.id,layer:m.provenance.layer,sourceFile:m.provenance.sourceFile,mode:m.mode,covered:w&&!k,evidence:A,partial:k,description:m.description,...R!==void 0?{testEvidenceFile:R}:{},...S!==void 0?{outsideDeclaredRoots:S}:{}}),S===!0&&R!==void 0&&p.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${m.id} is covered only by ${R}, which is outside the declared coverage roots (${y}). 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:R,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:"warning",failsStrict:!1}),!w||k){let L=m.mode==="enforced"&&!k,X=n||r.length===0?"never-had-tests":"tests-disappeared";p.push({ruleId:"INVARIANT_UNCOVERED",message:(k?s?`Invariant ${m.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${m.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:X==="tests-disappeared"?`Invariant ${m.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 ${m.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&&s?l:a),file:m.provenance.sourceFile,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:L?"error":"warning",failsStrict:L,kind:X})}}return{coverage:g,violations:p,partial:g.some(m=>m.partial)}}i(Rr,"evaluateInvariantCoverage");function kr(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(kr,"canPromoteInvariant");var Sr="1.0";function N(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(N,"addFinding");function Q(e){return[...new Set(e??[])].sort()}i(Q,"sortedUnique");function pe(e,t,r,n,s){let o=Q(r),a=Q(n),l=new Set(o),c=new Set(a),u=a.filter(y=>!l.has(y)),f=o.filter(y=>!c.has(y));u.length===0&&f.length===0||(u.length>0&&N(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),f.length>0&&N(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(pe,"compareStringSets");function Ct(e,t,r,n,s,o,a){if(r===n)return;N(e,{kind:n?"enabled":"disabled",path:t,classification:n?s:s==="strengthening"?"weakening":"strengthening",message:n?o:a,before:r,after:n})}i(Ct,"compareBoolean");function Er(e,t){let r=new Map,n=new Set;for(let s of e){let o=t(s);r.has(o)?n.add(o):r.set(o,s)}return{values:r,duplicates:[...n].sort()}}i(Er,"keyed");function ll(e,t,r){let n=Er(t,o=>o.name),s=Er(r,o=>o.name);(n.duplicates.length>0||s.duplicates.length>0)&&N(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:n.duplicates,after:s.duplicates});for(let o of[...new Set([...n.values.keys(),...s.values.keys()])].sort()){let a=n.values.get(o),l=s.values.get(o),c=`$.layers[${o}]`;if(!a&&l){N(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){N(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;pe(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),pe(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=sr(a),f=sr(l);pe(e,`${c}.forbiddenGlobals`,u.rawGlobals,f.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),pe(e,`${c}.capabilities`,u.atoms,f.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(l.intentPrefixes).join("\0")&&N(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Q(a.intentPrefixes),after:Q(l.intentPrefixes)}),Ct(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Ct(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(ll,"compareLayers");function cl(e,t,r){let n=i(a=>`${a.from}->${a.to}`,"keyOf"),s=Er(t,n),o=Er(r,n);(s.duplicates.length>0||o.duplicates.length>0)&&N(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let a of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let l=s.values.get(a),c=o.values.get(a),u=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&N(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&N(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&N(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let f=l.peerIsolation===!0,y=c.peerIsolation===!0;if(f!==y){let g=l.from===l.to&&c.from===c.to;N(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:g?y?"strengthening":"weakening":"judgment-required",message:g?y?"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:f,after:y})}Q(l.sliceFolders).join("\0")!==Q(c.sliceFolders).join("\0")&&N(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Q(l.sliceFolders),after:Q(c.sliceFolders)}),!(!f&&!y)&&(_o(e,`${u}.sharedRoots`,"shared-roots",Q(l.sharedRoots),Q(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),_o(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Q((l.allowedCrossSlice??[]).map(Oo)),Q((c.allowedCrossSlice??[]).map(Oo)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(cl,"compareRules");function Oo(e){return JSON.stringify([e.from,e.to])}i(Oo,"crossSliceKey");function _o(e,t,r,n,s,o,a){if(JSON.stringify(n)===JSON.stringify(s))return;let l=s.filter(f=>!n.includes(f)),c=n.filter(f=>!s.includes(f)),u=l.length>0&&c.length>0;N(e,{kind:u?`${r}-changed`:l.length>0?`${r}-added`:`${r}-removed`,path:t,classification:u?"judgment-required":l.length>0?"weakening":"strengthening",message:u?`${o} Entries were added and removed in the same change.`:l.length>0?o:a,before:n,after:s})}i(_o,"compareDeclaredExceptions");function dl(e,t,r){let n=t.safety??{},s=r.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let a=n[o]??0,l=s[o]??0;a!==l&&N(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])Ct(e,`$.safety.${o}`,n[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(dl,"compareSafety");function Pn(e){return e.mode==="enforced"?"enforced":"advisory"}i(Pn,"arkRunMode");function wn(e){return e.mode==="enforced"?"enforced":"advisory"}i(wn,"arkOrderMode");function ul(e,t,r){let n=t.arkOrder,s=r.arkOrder,o="$.arkOrder";if(!n&&!s)return;if(!n&&s){N(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${wn(s)}).`,after:s});return}if(n&&!s){N(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:n});return}if(!n||!s)return;let a=wn(n),l=wn(s);if(a!==l){let c=a==="advisory"&&l==="enforced";N(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}pe(e,`${o}.planeRoots`,n.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),pe(e,`${o}.managedLayers`,n.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(ul,"compareArkOrder");function pl(e,t,r){let n=t.arkRun,s=r.arkRun,o="$.arkRun";if(!n&&!s)return;if(!n&&s){N(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${Pn(s)}).`,after:s});return}if(n&&!s){N(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:n});return}if(!n||!s)return;let a=Pn(n),l=Pn(s);if(a!==l){let c=a==="advisory"&&l==="enforced";N(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}pe(e,`${o}.compositionRoots`,n.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),pe(e,`${o}.managedLayers`,n.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Ct(e,`${o}.requireDeclarations`,n.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(pl,"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 xo(e,t){return`${e}::${t}`}i(xo,"ruleKey");function To(e){let t=new Map,r=new Map;if(!e)return{structure:t,invariants:r};for(let n of e.structure)t.set(xo(n.provenance.layer,n.id),n);for(let n of e.invariants)r.set(xo(n.provenance.layer,n.id),n);return{structure:t,invariants:r}}i(To,"indexEffectiveRules");function ml(e,t,r,n,s,o){let a=new Map((o??[]).map(g=>[g.invariantId,g])),l=t.arkRules??{},c=r.arkRules??{},u=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let g of u){let p=l[g],m=c[g],A=`$.arkRules[${g}]`;if(p===void 0&&m!==void 0){N(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${g} was added.`,after:m});continue}if(p!==void 0&&m===void 0){N(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${g} was removed.`,before:p});continue}p!==m&&N(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${g} changed; verify the effective rules still match intent.`,before:p,after:m})}let f=To(n),y=To(s);for(let g of[...new Set([...f.structure.keys(),...y.structure.keys()])].sort()){let p=f.structure.get(g),m=y.structure.get(g),A=`$.arkRules.structure[${g}]`;if(!p&&m){N(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${m.id} was added (${m.mode}).`,after:m});continue}if(p&&!m){N(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!m)){if(p.mode!==m.mode){let I=p.mode==="advisory"&&m.mode==="enforced";N(e,{kind:I?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:I?"strengthening":"weakening",message:I?`Structure ArkRule ${m.id} was promoted to enforced.`:`Structure ArkRule ${m.id} was demoted to advisory.`,before:p.mode,after:m.mode})}p.sensor!==m.sensor&&N(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${m.id} changed sensor identity.`,before:p.sensor,after:m.sensor})}}for(let g of[...new Set([...f.invariants.keys(),...y.invariants.keys()])].sort()){let p=f.invariants.get(g),m=y.invariants.get(g),A=`$.arkRules.invariants[${g}]`;if(!p&&m){N(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${m.id} was added (${m.mode}).`,after:m});continue}if(p&&!m){N(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!m)&&p.mode!==m.mode)if(p.mode==="advisory"&&m.mode==="enforced"){let _=a?.get(m.id),R=kr(_);R.ok?N(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${m.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:m.mode}):N(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${m.id} cannot be promoted to enforced: ${R.reason}`,before:p.mode,after:m.mode})}else N(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${m.id} was demoted to advisory.`,before:p.mode,after:m.mode})}}i(ml,"compareArkRules");function Ir(e,t,r){let n=[];pe(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),pe(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."}),pe(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."}),Ct(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},o=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(o!==a){let l=s[a]===s[o]?"judgment-required":s[a]>s[o]?"strengthening":"weakening";N(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:o,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&N(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}),ll(n,e.layers,t.layers),cl(n,e.rules,t.rules),dl(n,e,t),ml(n,e,t,r?.baseArkRules,r?.candidateArkRules,r?.candidateInvariantCoverage),pl(n,e,t),ul(n,e,t),n.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Sr,classification:fl(n),findings:n}}i(Ir,"classifyArkPolicyDelta");function vr(e,t){if(!e||e.schemaVersion!==Sr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="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((s,o)=>s===n[o])}i(vr,"policyDeltaAcknowledgementMatches");function $e(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($e,"normalizePath");function No(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(No,"isIdentifierStart");function br(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(br,"isIdentifierCharacter");function ie(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ie,"skipWhitespace");function Ot(e,t){let r=e[t];if(r!=="'"&&r!=='"')return;let n=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===r)return{value:s,offset:n,excerpt:e.slice(n,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}i(Ot,"readString");function de(e,t,r){return e.startsWith(t,r)&&!br(e[r-1])&&!br(e[r+t.length])}i(de,"isWordAt");function Lo(e,t){let r=ie(e,t);if(e[r]!=="{")return!1;r+=1;let n=!1;for(;r<e.length;){if(r=ie(e,r),e[r]==="}")return n;if(e[r]===","){r+=1;continue}if(!de(e,"type",r))return!1;let s=ie(e,r+4);if(s>=e.length||e[s]===","||e[s]==="}"||de(e,"as",s)||!No(e[s]))return!1;for(r=s;r<e.length&&br(e[r]);)r+=1;if(r=ie(e,r),de(e,"as",r)){if(r=ie(e,r+2),!No(e[r]))return!1;for(;r<e.length&&br(e[r]);)r+=1}n=!0}return!1}i(Lo,"bracedNamedBindingsAreTypeOnly");function gl(e,t){if(t=ie(e,t+6),e[t]==="(")return Ot(e,ie(e,t+1));let r=!1;if(de(e,"type",t)){let s=ie(e,t+4);e[s]!==","&&!de(e,"from",s)&&(r=!0)}else Lo(e,t)&&(r=!0);let n=Po(e,t,!0);return n&&r?{...n,typeOnly:!0}:n}i(gl,"specifierAfterImport");function yl(e,t){t=t+6;let r=ie(e,t),n=!1;if(de(e,"type",r)){let o=ie(e,r+4);(e[o]==="{"||e[o]==="*")&&(n=!0)}else Lo(e,r)&&(n=!0);let s=Po(e,t,!1);return s&&n?{...s,typeOnly:!0}:s}i(yl,"specifierAfterExport");function Po(e,t,r){for(;t<e.length;t+=1){if(e[t]===";")return;if(de(e,"from",t))return Ot(e,ie(e,t+4));if(r&&(e[t]==="'"||e[t]==='"'))return Ot(e,t);if(t>0&&(de(e,"import",t)||de(e,"export",t)))return}}i(Po,"specifierInStaticStatement");function hl(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(hl,"skipTemplateLiteral");function Al(e,t){let r=t-1;for(;r>=0&&/\s/.test(e[r]);)r-=1;if(e[r]===".")return;let n=ie(e,t+7);if(e[n]!=="(")return;n=ie(e,n+1);let s=Ot(e,n);return s?{...s,requireCall:!0}:void 0}i(Al,"specifierAfterRequire");function Rl(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
+ `,r+2),r<0)break;continue}if(n==="/"&&e[r+1]==="*"){let o=e.indexOf("*/",r+2);if(o<0)break;r=o+1;continue}if(n==="`"){r=hl(e,r);continue}if(n==="'"||n==='"'){let o=Ot(e,r);o&&(r=o.offset+o.excerpt.length-1);continue}let s=n==="i"&&de(e,"import",r)?gl(e,r):n==="e"&&de(e,"export",r)?yl(e,r):n==="r"&&de(e,"require",r)?Al(e,r):void 0;s&&(t.push(s),r=s.offset+s.excerpt.length-1)}return t}i(Rl,"moduleSpecifiers");function wo(e,t){let r=[],n=[];for(let s of Rl(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let u=ct(o);if(!u)continue;let f=e.content.slice(0,s.offset).split(`
10
+ `).length;n.push({file:e.path,symbol:o,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
11
+ `).length,l={kind:"import",file:e.path,line:a,excerpt:s.excerpt},c=kl(e.path,o,t);r.push({from:e.path,specifier:o,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:r,capabilityUses:n}}i(wo,"moduleFactsFor");function kl(e,t,r){let n=e.split("/");n.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?n.pop():n.push(o));let s=n.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=r.get(o);if(a)return a}}i(kl,"resolveSpecifier");function Do(e,t){let r=[];for(let n of e){if(!n.to||!n.fromLayer||!n.toLayer)continue;let s=ar(t.rules,n.fromLayer,n.toLayer,{fromPath:n.from,toPath:n.to,layers:t.layers});s&&r.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:n,evidence:n.evidence})}return r}i(Do,"violationsFor");var El={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 Sl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Sl,"hasActiveArkRules");function Il(e,t){return Sl(e,t)?Y(F(Ar({config:e,arkRules:t,warnings:[]}))):Y(F(Ln(e)))}i(Il,"policyHashFor");function _t(e,t,r){let n=typeof e=="string"?ur(e,t):ht(e,t),s=r?.arkRules??be();return{...n,arkRules:s,policyHash:Il(n.config,s)}}i(_t,"loadContract");function Dn(e){let t=_t(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),r=_t(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),n=Ir(t.config,r.config,{baseArkRules:t.arkRules,candidateArkRules:r.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=n.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),o=s.length>0,a=o&&vr(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:r.policyHash,findingIds:s});return{schemaVersion:n.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:r.policyHash,classification:n.classification,findings:n.findings,blockingFindingIds:s,requiresAcknowledgement:o,acknowledged:a,valid:!o||a}}i(Dn,"analyzePolicyDelta");function Ze(e){let t=e.files.map(y=>{let g=$e(y.path);return{path:g,content:y.content,contentHash:Y(y.content),layer:ue(g,e.contract.config.layers)??null}}).sort((y,g)=>y.path.localeCompare(g.path)),r=new Map(t.map(y=>[y.path,y])),n=[],s=[];for(let y of t){let g=wo(y,r);n.push(...g.edges),s.push(...g.capabilityUses)}let o=Do(n,e.contract.config),a=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(Be(y))]));for(let y of s){let g=r.get(y.file)?.layer;if(!g)continue;let p=a.get(g),m=Ie(y.symbol,p?.forbiddenGlobals??[]);if(m){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${g} must not use module "${y.symbol}" because it is the import form of forbidden global "${m}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(g)?.has(y.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${g} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...El}],f={schemaVersion:mr,policyHash:e.contract.policyHash,compilerOptionsHash:Y(F(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:n,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&o.length===0,ir:f}}i(Ze,"analyzeProject");function xt(e){let t=new Map(e.files.map(r=>[$e(r.path),r]));for(let r of e.changes){let n=$e(r.path);"delete"in r&&r.delete?t.delete(n):"content"in r&&t.set(n,{path:n,content:r.content})}return Ze({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(xt,"analyzeChange");function Mn(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(Mn,"explainViolation");function Cr(e){let t=0,r=new Map,n=new Map,s=new Set,o=[],a=[],l=i(c=>{r.set(c,t),n.set(c,t),t+=1,o.push(c),s.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(r.has(y)?s.has(y)&&n.set(c,Math.min(n.get(c)??0,r.get(y)??0)):(l(y),n.set(c,Math.min(n.get(c)??0,n.get(y)??0))));if(n.get(c)!==r.get(c))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;s.delete(f),u.push(f)}while(f!==c);u.length>1&&a.push(u.sort())},"connect");for(let c of[...e.keys()].sort())r.has(c)||l(c);return a.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(Cr,"detectArchitectureCycles");function He(e){let t=e.contentViolations.map(o=>({...o})),r=(e.warnings??[]).map(o=>({...o})),n=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&n.has(o.from)&&n.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let a=Ne(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,u=!c&&!!(o.typeOnly||o.namedBindingsTypeOnly),f=c?ze(a.peerIsolationReason??"cross-slice",{fromPath:o.from,toPath:o.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?f?`${l.message} (${f})`:l.message:f?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}): ${f}`:`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...c?{peerIsolation:!0}:{},message:u?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...u?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Cr(n);s==="soft"||s==="framework-soft"?r.push(...o.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:r,safety:e.safety}}i(He,"evaluateArchitectureGraph");function Mo(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(Mo,"structureFreezeTarget");var vl=["no-anemic-model"],Ko=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Hn=new RegExp(`\\b(${Ko.join("|")})\\b`),Vo="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",jn=new RegExp(`\\bthis\\.${Vo}\\.push\\s*\\(`),bl=new RegExp(`^this\\.${Vo}\\s*=\\s*\\[\\s*\\]`),Cl=/^this\.[A-Za-z_][A-Za-z0-9_]*\s*=\s*\[\s*\]/,Ol=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,Uo="truncatedUntil";function Kn(){return`${Ko.join(", ")}, or events-array .push(`}i(Kn,"expectedDomainInvariantWordsPhrase");function _l(e){return Hn.test(e)||jn.test(e)}i(_l,"referencesGuardOrPublish");function Vn(e,t,r){let n=e.slice(t);if(bl.test(n))return!0;if(!Cl.test(n))return!1;if(r&&/^pullEvents$/i.test(r))return!0;let s=t>200?t-200:0;return/\bpullEvents\b/.test(e.slice(s,t+200))}i(Vn,"isIdiomaticEventsReset");function xl(e,t){let r=new RegExp(Ol.source,"g"),n;for(;(n=r.exec(t))!==null;)if(!Vn(t,n.index,e))return!0;return!1}i(xl,"methodAssignsThis");function Tl(e,t){return t==null||Object.defineProperty(e,Uo,{value:t,enumerable:!1,configurable:!0}),e}i(Tl,"attachShapeTruncation");function $n(e){let t=Object.getOwnPropertyDescriptor(e,Uo)?.value;return typeof t=="number"?t:void 0}i($n,"shapeTruncatedUntil");function Nl(e){let t=$n(e);return t==null?"":` shape analysed until character ${t}`}i(Nl,"shapeTruncationSuffix");function Fo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Fo,"escapeGlobLiteral");function Ll(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=s}let r="";for(let n=0;n<t.length;n+=1){let s=t[n];s==="\\"&&n+1<t.length?(r+=Fo(t[n+1]),n+=1):s==="*"?t[n+1]==="*"?t[n+2]==="/"?(r+="(?:.*/)?",n+=2):(r+=".*",n+=1):r+="[^/]*":s==="?"?r+="[^/]":r+=Fo(s)}return new RegExp(`^${r}$`)}i(Ll,"globToRegExp");function Qe(e,t){return!t||t.length===0?!0:t.some(r=>Ll(r).test(e))}i(Qe,"matchesAppliesTo");function Pl(e){return vl.includes(e)}i(Pl,"isTier2");function Go(e){return e.mode==="enforced"&&!Pl(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(Go,"severityFor");function Ce(e,t,r,n=1){let{severity:s,failsStrict:o}=Go(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:s,sensor:e.sensor,failsStrict:o}}i(Ce,"baseViolation");function _r(e,t,r){if(!r)return!0;let n=r(e);return n?n===t.provenance.layer:!1}i(_r,"isInRuleLayer");function xr(e,t,r){return t.filter(n=>!(!n.exported||!Qe(n.file,e.appliesTo)||!_r(n.file,e,r)))}i(xr,"shapesForRule");function wl(e,t,r){let n=[];for(let s of xr(e,t,r))(s.hasPublicSetters||s.hasPublicMutableFields)&&n.push(Ce(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return n}i(wl,"evaluateAggregatePrivateState");function Dl(e,t,r){let n=[];for(let s of xr(e,t,r))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;n.push(Ce(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return n}i(Dl,"evaluateAlwaysValidFactory");function Ml(e,t,r){let n=[],s=Kn();for(let o of xr(e,t,r)){let a=Nl(o);$n(o)!=null&&n.push(Ce(e,o.file,`Exported class ${o.className} shape analysed until character ${$n(o)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of o.mutatingMethods)l.referencesGuardOrPublish||n.push(Ce(e,o.file,`Mutating method ${o.className}.${l.name} does not reference ${s} (sensor domain-event-on-mutation).${a}`))}return n}i(Ml,"evaluateDomainEventOnMutation");function Fl(e,t){let r=[];for(let n of t.files)Qe(n,e.appliesTo)&&_r(n,e,t.layerForFile)&&t.fileHints?.[n]?.orchestrationHeavy&&r.push(Ce(e,n,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return r}i(Fl,"evaluateOrchestrationOnly");function $l(e,t){let r=[];for(let n of t.files)Qe(n,e.appliesTo)&&_r(n,e,t.layerForFile)&&t.fileHints?.[n]?.adapterThick&&r.push(Ce(e,n,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return r}i($l,"evaluateThinAdapter");function Hl(e,t){let r=[];for(let n of t.files)Qe(n,e.appliesTo)&&_r(n,e,t.layerForFile)&&t.fileHints?.[n]?.persistenceWrite&&r.push(Ce(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(Hl,"evaluateWritesViaAggregate");function jl(e,t,r){let n=[];for(let s of xr(e,t,r))if(s.dataOnly===!0){let o=Ce(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);n.push({...o,severity:"warning",failsStrict:!1})}return n}i(jl,"evaluateNoAnemicModel");function Tr(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(...wl(r,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Dl(r,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Ml(r,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Fl(r,e));break;case"thin-adapter":t.push(...$l(r,e));break;case"writes-via-aggregate":t.push(...Hl(r,e));break;case"no-anemic-model":t.push(...jl(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(Tr,"evaluateArkRuleSensors");function Nr(e,t){let r=[],n=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||n.some(c=>Qe(c,s.appliesTo)))continue;let{severity:a,failsStrict:l}=Go(s);r.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||n.some(l=>Qe(l,s.appliesTo)))continue;let a=s.mode==="enforced";r.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return r.sort((s,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}i(Nr,"collectEmptyAppliesToFindings");var $o=/\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)/,Ho=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Kl=/\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 Vl(e){return e==="PersistenceAdapters"}i(Vl,"isPersistenceDriverLayer");function Ul(e,t){if($o.test(e)||Ho.test(e))return!0;if(!t)return!1;for(let r of t){if(Vl(r.layer))return!0;let n=r.specifier;if(!n)continue;let s=`from '${n}'`;if($o.test(s)||Ho.test(s))return!0}return!1}i(Ul,"sourceImportsPersistenceDriver");var Gl=/\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*=)/,Bl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,zl=/\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*=/,Wl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Un(e,t,r){if(!t)return null;let n=Ul(t,r),s=n&&Kl.test(t);if(t.length<40)return s?{persistenceWrite:!0}:null;let o=t.match(new RegExp(zl.source,"g"))??[],a=t.match(new RegExp(Wl.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=o.length>=2||o.length>=1&&a.length>=2||a.length>=3&&l+c>=6,f=Gl.test(t)||Bl.test(t),y=o.length>=1||a.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),p=n&&y||f&&y||n&&g&&(l>=4||o.length>=1)||f&&n;return!u&&!p&&!s?null:{...u?{orchestrationHeavy:!0}:{},...p?{adapterThick:!0}:{},...s?{persistenceWrite:!0}:{}}}i(Un,"deriveArkRuleFileHints");function Lr(e,t){let r={};for(let[n,s]of Object.entries(e)){let o=n.replace(/\\/g,"/"),a=Un(n,s,t?.[o]);a&&(r[o]=a)}return r}i(Lr,"buildArkRuleFileHints");var ql=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),Yl=new Set(["if","match","when"]);function Or(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(Or,"skipStringOrComment");function Tt(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=Or(e,r);continue}break}return r}i(Tt,"skipWsAndComments");function jo(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(jo,"readIdent");function Fn(e,t,r,n){if(e[t]!==r)return null;let s=1,o=t+1;for(;o<e.length&&s>0;){let a=Or(e,o);if(a!==o){o=a;continue}let l=e[o];l===r?s+=1:l===n&&(s-=1),o+=1}return s===0?o:null}i(Fn,"skipBalanced");function Jl(e){let t=[],r=0,n;for(;r<e.length&&(r=Tt(e,r),!(r>=e.length));){if(e[r]===";"){r+=1;continue}let s=[],o=r;for(;;){let f=jo(e,o);if(!f||!ql.has(f.ident))break;s.push(f.ident),o=Tt(e,f.end)}let a=jo(e,o);if(!a){r+=1;continue}if(o=Tt(e,a.end),e[o]==="<"){let f=Fn(e,o,"<",">");if(f==null){n=e.length;break}o=Tt(e,f)}if(e[o]==="("){let f=Fn(e,o,"(",")");if(f==null){n=e.length;break}if(o=Tt(e,f),e[o]===":")for(o+=1;o<e.length&&e[o]!=="{"&&e[o]!==";";){let y=Or(e,o);if(y!==o){o=y;continue}o+=1}if(e[o]==="{"){let y=Fn(e,o,"{","}");if(y==null){n=e.length;break}t.push({name:a.ident,modifiers:s,kind:"method",body:e.slice(o+1,y-1)}),r=y;continue}if(e[o]===";"){r=o+1;continue}r=o+1;continue}let l=0,c=0,u=0;for(;o<e.length;){let f=Or(e,o);if(f!==o){o=f;continue}let y=e[o];if(y==="{")l+=1;else if(y==="}"){if(l===0)break;l-=1}else if(y==="(")c+=1;else if(y===")")c-=1;else if(y==="[")u+=1;else if(y==="]")u-=1;else if(y===";"&&l===0&&c===0&&u===0){o+=1;break}o+=1}t.push({name:a.ident,modifiers:s,kind:"field",body:""}),r=o}return{members:t,truncatedAt:n}}i(Jl,"scanClassMembers");function Bo(e,t){let r=[],n=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=n.exec(t))!==null;){let o=s[1],a=s.index+s[0].length,l=1,c=a;for(;c<t.length&&l>0;){let k=t[c];k==="{"?l+=1:k==="}"&&(l-=1),c+=1}let u=t.slice(a,c-1),f=l>0,y=Jl(u),g=f?t.length:y.truncatedAt==null?void 0:a+y.truncatedAt,p=y.members.filter(k=>!(k.kind!=="field"||k.name==="constructor"||k.modifiers.includes("private")||k.modifiers.includes("protected")||k.modifiers.includes("readonly")||k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set"))),m=p.length>0,A=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),I=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),_=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!I,R=/(?:^|[\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),S=[];for(let k of y.members)k.kind==="method"&&k.name!=="constructor"&&(k.modifiers.includes("static")||k.modifiers.includes("get")||k.modifiers.includes("set")||Yl.has(k.name)||xl(k.name,k.body)&&S.push({name:k.name,referencesGuardOrPublish:_l(k.body)}));let w=y.members.filter(k=>k.kind==="method").length<=1&&p.length>=2&&m;r.push(Tl({file:e,className:o,exported:!0,hasPublicMutableFields:m,hasPublicSetters:A,hasPublicConstructor:_,hasStaticFactory:R,mutatingMethods:[...S],dataOnly:w},g))}return r}i(Bo,"extractClassShapesFromSource");var zo=50;function Pr(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(Pr,"normalizeExtraMergeTeethClassification");function fe(e){let t=Pr(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(fe,"extraMergeTeethAllowed");function wr(e){let t=e.length,r=0,n=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(r+=1,n.add(o))}return{governedPercent:t>0?Math.round(r/t*100):0,populatedLayerCount:n.size}}i(wr,"classifyResolvedLayerCoverage");function Dr(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Dr,"isArkRunRuleId");function Gn(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(Gn,"isArkOrderRuleId");function Bn(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(Bn,"isExtraPlaneFinding");function Wo(e,t={}){if(!Array.isArray(e)||fe(t))return e;for(let r of e)Bn(r)&&r.failsStrict!==!1&&(r.failsStrict=!1,r.severity==="error"&&(r.severity="warning"));return e}i(Wo,"demoteExtraPlaneTeethUnderClassificationFloor");var zn="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 ge(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(ge,"countOrZero");function Nt(e={}){let t=Pr(e.classification),r=typeof t.governedPercent=="number"?t.governedPercent:null,n=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=r!=null||n!=null,o=fe(t),a=e.arkRules,l=ge(a?.structureEnforced),c=ge(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?ge(a.structureAdvisory):Math.max(0,c-l),f=ge(a?.invariantEnforced),y=ge(a?.invariantTotal),g=typeof a?.invariantAdvisory=="number"?ge(a.invariantAdvisory):Math.max(0,y-f),p=l>0||f>0,m=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,I=ge(e.arkRun?.residualCount),_=m&&A==="enforced",R=_&&o,S=e.arkOrder?.present===!0,b=e.arkOrder?.mode==="enforced"||e.arkOrder?.mode==="advisory"?e.arkOrder.mode:null,w=ge(e.arkOrder?.residualCount),k=S&&b==="enforced",L=k&&o,X=p||_||k,x=X&&o,z=X&&s&&!o,D;if(x){let J=[];p&&J.push("enforced structure/invariant findings"),_&&J.push("enforced ArkRun skip findings"),k&&J.push("enforced ArkOrder skip findings"),D=`Layer graph failures plus ${J.join(" and ")} (advisory extras never fail merge alone).`}else if(z)D=`Layer graph only \u2014 enforced ${[p?"ArkRules structure/invariant":null,_?"ArkRun":null,k?"ArkOrder":null].filter(Se=>!!Se).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 J=m?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.",Se=S?b==="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."+J+Se}let re={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent extras change nothing here."},structureSensors:{role:"intra-layer-heuristics",total:c,enforced:l,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:y,enforced:f,advisory:g,covered:ge(a?.covered),uncovered:ge(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:m,mode:A,residualCount:I,extraMergeTeeth:R,note:m?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:S,mode:b,residualCount:w,extraMergeTeeth:L,note:S?b==="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:x,dualPlaneStamp:zn,failMergeWhen:D};return s&&(re.classificationGate={governedPercent:r,populatedLayerCount:n,floorPercent:50,allowsTeeth:o}),re}i(Nt,"composeMergePlanesHonesty");var qn=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],Yo=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Xl=new Set(qn),Zl=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"]),Ql=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function et(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(et,"isArkRunKernelModuleSpecifier");var Yn=["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"],Wn=new Set(Yn);function Fr(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Wn.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let r=e.slice(0,t);if(Wn.has(r))return!0;let n=e.indexOf("/",t+1);return n<0?!1:Wn.has(e.slice(0,n))}i(Fr,"isArkRunTransportBypassSpecifier");function Mr(e){if(Xl.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(Mr,"arkRunKernelCallKind");function Pt(e,t){let r=1;for(let n=0;n<t;n+=1)e.charCodeAt(n)===10&&(r+=1);return r}i(Pt,"lineAt");function wt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,r=>" ".repeat(r.length)))}i(wt,"stripCommentsPreservingLines");function ec(e,t){let r=e.slice(t),n=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(r);if(!n)return;let s=n[2]??"";return s.length>0?s:void 0}i(ec,"firstStringLiteralArg");function qo(e,t,r){let n=Math.max(0,t-r.length-8),s=e.slice(n,t);return new RegExp(`\\b${r}\\s+$`).test(s)}i(qo,"keywordBefore");function $r(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($r,"parseValueImportClause");function tc(e,t){$r(wt(e),t)}i(tc,"forEachArkRunValueImportClause");function Hr(e,t){let r=wt(t),n=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,o;for(;(o=s.exec(r))!==null;){let l=o[3]??"";if(!l)continue;let c=o[0]??"";n.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!o[1],line:Pt(t,o.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(o=a.exec(r))!==null;){let l=o[1]??"";if(!l)continue;let c=o[0]?.startsWith("import")?"dynamic-import":"require";n.push({from:e,specifier:l,kind:c,typeOnly:!1,line:Pt(t,o.index),resolution:"resolved-external"})}return n}i(Hr,"extractArkRunValueImportDependenciesFromSource");function jr(e){let t=[];return tc(e,r=>{let n=/\{([^}]*)\}/.exec(r);if(n?.[1])for(let s of n[1].split(",")){let o=s.trim();if(!o||o.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),l=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],c=a?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),Lt(t)}i(jr,"extractArkRunImportedConstructorNamesFromSource");function rc(e){let t=new Map,r=new Set;return $r(e,(n,s)=>{if(!et(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(n);o?.[1]&&r.add(o[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(n.trim());a?.[1]&&t.set(a[1],a[1]);let l=/\{([^}]*)\}/.exec(n);if(l?.[1])for(let c of l[1].split(",")){let u=c.trim();if(!u||u.startsWith("type "))continue;let f=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(f){t.set(f[2],f[1]);continue}let y=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);y?.[1]&&t.set(y[1],y[1])}}),{named:t,namespaces:r}}i(rc,"collectKernelImportBindings");function nc(e,t){let r=new Set(t);return $r(e,(n,s)=>{let o=/\{([^}]*)\}/.exec(n);if(o?.[1])for(let a of o[1].split(",")){let l=a.trim();if(!l||l.startsWith("type "))continue;let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(l),u=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],f=c?.[1]??u;!u||!f||!/^[A-Z]/.test(f)||(et(s)||t.has(f)||t.has(u))&&(r.add(u),r.add(f))}}),r}i(nc,"collectImportedConstructors");function sc(e,t){let r;return $r(e,(n,s)=>{!r&&new RegExp(`\\b${t}\\b`).test(n)&&(r=s)}),r}i(sc,"importedFromForName");function Kr(e,t){let r=wt(t),n=rc(r),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=o.exec(r))!==null;){let l=a[1],c=a.index;if(qo(r,c,"function")||qo(r,c,"class"))continue;let f=r.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],y=n.named.get(l)??l,g=Mr(y)??Mr(l);if(!g)continue;let p=n.named.has(l)||f!==void 0&&n.namespaces.has(f);if(g!=="factory"&&(!p&&f===void 0||f&&Ql.has(f)&&!p))continue;let m=ec(r,c+a[0].length);s.push({file:e,line:Pt(t,c),kind:g,callee:l,viaImport:p,...f?{receiver:f}:{},...m?{nameLiteral:m}:{}})}return s}i(Kr,"extractArkRunKernelCallsFromSource");function Vr(e,t,r){let n=wt(t),s=nc(n,r),o=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=a.exec(n))!==null;){let c=l[1];if(Zl.has(c)||!s.has(c))continue;let u=sc(n,c);o.push({file:e,line:Pt(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return o}i(Vr,"extractArkRunManagedNewsFromSource");function oc(e,t){let r=0,n;for(let s=t;s<e.length;s+=1){let o=e[s];if(n){if(o==="\\"){s+=1;continue}o===n&&(n=void 0);continue}if(o==="'"||o==='"'||o==="`"){n=o;continue}if(o==="[")r+=1;else if(o==="]"&&(r-=1,r===0))return s}return-1}i(oc,"matchingBracketEnd");function ac(e,t,r){let n=e.slice(t+1,r),s=[],o=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=o.exec(n))!==null;){let l=a[2]??"";l.length>0&&s.push(l)}return s}i(ac,"stringLiteralsInList");function Lt(e){return[...new Set(e)].sort((t,r)=>t<r?-1:t>r?1:0)}i(Lt,"uniqueSorted");function Jo(e,t){let r=wt(t),n=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],l=[],c,u;for(;(u=n.exec(r))!==null;){let f=r.slice(u.index+u[0].length),y=/^\s*\[/.exec(f);if(!y)continue;let g=u.index+u[0].length+(y[0].length-1),p=oc(r,g);if(p<0)continue;let m=ac(r,g,p);if(m.length===0)continue;c===void 0&&(c=u.index);let A=u[1];A==="uses"?s.push(...m):A==="reactsTo"?o.push(...m):A==="raises"?a.push(...m):l.push(...m)}return c===void 0?[]:[{file:e,line:Pt(t,c),uses:Lt(s),reactsTo:Lt(o),raises:Lt(a),sends:Lt(l)}]}i(Jo,"extractArkRunDeclarationsFromSource");var Qo=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],ic=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],lc=new Set(ic);function cc(e){return lc.has(e)}i(cc,"isArkRunEditorSensor");var Ur={"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"},Jn="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ea(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 s=n.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(ea,"isDomainRoleLayer");function dc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(dc,"compareFindings");function Ee(e,t,r,n,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Ur[t],sensor:t,message:s,file:r,line:n,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:me({ruleId:Ur[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Ee,"finding");function uc(e,t){let r=[],n=[],s=[],o=[];for(let a of e)a.file===t&&(r.push(...a.uses),n.push(...a.reactsTo),s.push(...a.raises),o.push(...a.sends));return{uses:new Set(r),reactsTo:new Set(n),raises:new Set(s),sends:new Set(o)}}i(uc,"bagForFile");function Xo(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Xo,"emitKinds");function Zo(e){return e==="subscribe"||e==="register-handler"}i(Zo,"handleKinds");function pc(e){return e==="resolve"||e==="resolve-singleton"}i(pc,"dependKinds");function fc(e,t,r){let n=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return n.push(Ee(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,r)),n;let o=new Map;for(let a of t){let l=o.get(a.matchedRoot)??[];l.push(a),o.set(a.matchedRoot,l)}for(let a of s){let l=[...o.get(a)??[]].sort((u,f)=>u.file.localeCompare(f.file));if(l.length===0){n.push(Ee(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(l.some(u=>u.hasKernelFactory))continue;let c=l[0];n.push(Ee(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},r))}return n}i(fc,"evaluateMissingRoot");function mc(e,t,r,n,s){let o=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of r){let c=l.specifier;if(!c||!et(c))continue;let u=n(l.from);u&&ea(u,o.get(u)??[])&&a.push(Ee(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},s))}return a}i(mc,"evaluateKernelInDomain");function gc(e,t,r,n,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(f=>[f.name,f.intentPrefixes??[]])),c=new Set(n.filter(f=>f.hasKernelFactory).map(f=>f.file)),u=[];for(let f of r){if(c.has(f.file))continue;let y=f.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let g=s(f.file);!g||!a.has(g)||ea(g,l.get(g)??[])||u.push(Ee(e,"arkrun-direct-new",f.file,f.line,`${g} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:g,target:f.typeName},o))}return u}i(gc,"evaluateDirectNew");function yc(e,t,r,n,s){let o=[],a=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:o,completenessReasons:a};for(let c of t){if(!Xo(c.kind)&&!Zo(c.kind)&&!pc(c.kind))continue;let u=n(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:Jn,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let f=uc(r,c.file);if(Xo(c.kind)){if(f.raises.has(c.nameLiteral)||f.sends.has(c.nameLiteral))continue;o.push(Ee(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},s));continue}if(Zo(c.kind)){if(f.reactsTo.has(c.nameLiteral))continue;o.push(Ee(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},s));continue}f.uses.has(c.nameLiteral)||o.push(Ee(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},s))}return{findings:o,completenessReasons:a}}i(yc,"evaluateUndeclared");function hc(e,t,r,n){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!Fr(l))continue;let c=r(a.from);!c||!s.has(c)||o.push(Ee(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},n))}return o}i(hc,"evaluateTransportBypass");function Dt(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let r=fe(e.classification),n=yc(t,e.kernelCalls,e.declarations,e.layerForFile,r),s=[...fc(t,e.compositionRootHits,r),...mc(t,e.layers,e.dependencies,e.layerForFile,r),...gc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,r),...n.findings,...hc(t,e.dependencies,e.layerForFile,r)].sort(dc),o=[...n.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:s,completenessReasons:o}}i(Dt,"evaluateArkRunSensors");function Xn(e){return{findings:Dt(e).findings.filter(r=>cc(r.sensor)),completenessReasons:[]}}i(Xn,"evaluateArkRunEditorSensors");function Ac(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(Ac,"fileMatchesCompositionRoot");function Rc(e,t,r){let n=Kr(t,r).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)Ac(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:n});return s}i(Rc,"compositionRootHitsForSource");function ta(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let r=new Set(jr(e.source));return Xn({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Vr(e.file,e.source,r),compositionRootHits:Rc(t,e.file,e.source),declarations:[],dependencies:Hr(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(ta,"evaluateArkRunEditorSensorsFromSource");function ra(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(ra,"isArkOrderModuleSpecifier");var na=new Map;function sa(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(sa,"escapeAppliesToLiteral");function kc(e){let t="";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=n}return t}i(kc,"normalizeAppliesToGlob");function Ec(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(Ec,"appliesToBracesBalanced");function Sc(e){let t=na.get(e);if(t)return t;let r=kc(e),n=Ec(r),s="",o=0;for(let l=0;l<r.length;l+=1){let c=r[l];c==="\\"&&l+1<r.length?(s+=sa(r[l+1]),l+=1):c==="*"?r[l+1]==="*"?r[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&n?(s+="(?:",o+=1):c==="}"&&n&&o>0?(s+=")",o-=1):c===","&&n&&o>0?s+="|":s+=sa(c)}let a=new RegExp(`^${s}$`);return na.set(e,a),a}i(Sc,"globToRegExp");var oa=["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"],Gr={"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 Ic(e,t){return!t||t.length===0?!0:t.some(r=>Sc(r).test(e))}i(Ic,"matchesArkOrderAppliesTo");function vc(e,t=[]){let r=e.trim();return/^domain(?:model)?$/i.test(r)||/^domain(?=[A-Z_\-\s])/i.test(r)?!0:t.some(n=>{let s=n.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(vc,"isDomainRoleLayer");function Oe(e,t,r,n,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Gr[t],sensor:t,message:s,file:r,line:n,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:me({ruleId:Gr[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Oe,"finding");function Br(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let r=fe(e.classification),n=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)n.push(Oe(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,r));else{let c=new Map;for(let u of e.planeRootHits){let f=c.get(u.matchedRoot)??[];f.push(u),c.set(u.matchedRoot,f)}for(let u of s){let f=c.get(u)??[];if(f.length===0){n.push(Oe(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}f.some(y=>y.hasPlaneFactory)||n.push(Oe(t,"arkorder-missing-plane",f[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},r))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!ra(u))continue;let f=e.layerForFile(c.from);f&&vc(f,o.get(f)??[])&&n.push(Oe(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:f,target:u},r))}for(let c of e.genericUpdates)n.push(Oe(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},r));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||n.push(Oe(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},r));for(let c of e.ingestWritesXi??[])n.push(Oe(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,r));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let u=e.layerForFile(c.file);!u||!l.has(u)||Ic(c.file,t.appliesTo)&&n.push(Oe(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:u,target:c.key},r))}return n.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:n,completenessReasons:[]}}i(Br,"evaluateArkOrderSensors");function oe(e,t,r={}){return{ruleId:e,message:t,...r}}i(oe,"configWarning");function Mt(e){let{config:t,rules:r,files:n,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(p=>typeof p!="string"))&&o.push(oe("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)))o.push(oe("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let p of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[p];m!==void 0&&(!Number.isInteger(m)||m<0)&&o.push(oe("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${p} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...a.map(p=>p.name).filter(Boolean),...l.map(p=>p.name).filter(p=>!!p)]);a.length===0&&o.push(oe("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,f=new Set;for(let p of a){if(!p.name){o.push(oe("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(p.name)&&f.add(p.name),u.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(A=>typeof A!="string"))&&o.push(oe("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${p.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:p.name}));let m=Array.isArray(p.patterns)?p.patterns:[];if(m.length===0){o.push(oe("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let A of m){let I;try{I=ye(A)}catch(R){o.push(oe("CONFIG_INVALID_LAYER_PATTERN",`Layer "${p.name}" has an invalid pattern "${A}": ${R instanceof Error?R.message:String(R)}`,{layer:p.name,pattern:A}));continue}let _=p.optional===!0||p.reserved===!0||p.allowEmpty===!0;!n.some(R=>I.test(R))&&!_&&o.push(oe("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${p.name}" pattern "${A}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:p.name,pattern:A,failsStrict:!1,reserved:!1}))}}for(let p of f)o.push(oe("CONFIG_DUPLICATE_LAYER",`Layer "${p}" is configured more than once.`,{layer:p}));if(c.size>0)for(let p of r??[])p.from&&!c.has(p.from)&&o.push(oe("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${p.from}".`,{fromLayer:p.from,toLayer:p.to})),p.to&&!c.has(p.to)&&o.push(oe("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${p.to}".`,{fromLayer:p.from,toLayer:p.to}));let y=new Set;if(a.length>1)for(let p of n){let m=-1,A=[];for(let I of a)for(let _ of I.patterns??[]){if(!ye(_).test(p))continue;let R=yn(_,p);R>m?(m=R,A=[I.name]):R===m&&!A.includes(I.name)&&A.push(I.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&o.push(oe("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let g=n.filter(p=>!ue(p,a));return g.length>0&&o.push(oe("CONFIG_UNCLASSIFIED_FILES",`${g.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:g.length,samples:g.slice(0,5)})),o}i(Mt,"collectAnalysisConfigWarnings");function aa(e,t){let r=e.ruleId==="ARKRULE_STRUCTURE",n=e.ruleId==="ARKRULE_SCOPE_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:Mo({sensor:e.sensor,code:e.code})}:{},...n?{freezable:!1}:{},nextAction:t}}i(aa,"toArkRuleEngineViolation");function bc(e,t){return t.some(r=>{try{return ye(r).test(e)}catch{return!1}})}i(bc,"matchesAny");function Cc(e,t){let r=e.contract.config.safety??{},n=Number.isInteger(r.maxTsSuppressions)?Number(r.maxTsSuppressions):0,s=Number.isInteger(r.maxAnyCasts)?Number(r.maxAnyCasts):0,o=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:I})=>({file:A,line:I})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:I})=>({file:A,line:I})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!bc(A.file,o)).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"})),f=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})),y={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:n,maxAnyCasts:s}},g=[],p=c.filter(A=>A.kind==="import");if(p.length>0){let A=p[0];g.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let m=c.filter(A=>A.kind==="require");if(m.length>0){let A=m[0];g.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>n){let A=a[0];g.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(l.length>s){let A=l[0];g.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(u.length>0){let A=u[0];g.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 f.length>0&&g.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${f.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:g}}i(Cc,"evaluateSafety");function Oc(e,t){return[...t].filter(r=>e===r||e.startsWith(`${r}.`)).sort((r,n)=>n.length-r.length)[0]}i(Oc,"ambientForbiddenGlobal");function ia(e,t){let r=t.config.layers.filter(n=>(n.intentPrefixes??[]).length>0);return Sn(e,r.length>0?r:En.map(n=>({name:n.layer,prefixes:n.prefixes})))}i(ia,"intentLayer");function _c(e,t,r){let n=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let a=r.get(o.file);!a||!Oc(o.symbol,s.get(a)?.forbiddenGlobals??[])||n.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,message:`${a} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let a=r.get(o.file);if(!a)continue;let l=s.get(a),c=l?.forbiddenGlobals??[],u=o.source==="import-based"?t.dependencies.find(f=>f.from===o.file&&f.line===o.line&&f.specifier===o.symbol&&!f.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&dt(o.symbol,c))){if(o.source==="import-based"){let f=Ie(o.symbol,c);if(f){n.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${f}".`});continue}}Be(l).includes(o.capability)&&n.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...u?{edgeKind:u}:{},message:o.source==="import-based"?`${a} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${a} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let a=r.get(o.file);if(!a)continue;for(let c of ut({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))n.push({ruleId:c.ruleId,file:o.file,line:o.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!o.sourceIntent)continue;let l=ia(o.sourceIntent,e.contract);!l||l===a||n.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let o of t.intentReferences){let a=r.get(o.file);if(!a)continue;let l=ia(o.intent,e.contract);if(!l)continue;let c=Ne(e.contract.config.rules,a,l,{fromPath:o.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?ze(c.peerIsolationReason??"cross-slice",{fromPath:o.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,f=`${a} must not reference ${l} intent ${o.intent}.`,y=u&&c.peerIsolationReason!=="cross-slice"?`${f} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:f;n.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:y})}return n}i(_c,"contentViolations");function xc(e){let{facts:t}=e,r=Xe(e.contract.config),n=t.evidenceRequirementsHash===r,s=n?t.completeness:"unavailable",o=n?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,P)=>{let H=`${d.code}\0${d.file??""}\0${d.message}`,le=`${P.code}\0${P.file??""}\0${P.message}`;return H<le?-1:H>le?1:0}),a=t.files.map(d=>({...d,layer:ue(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let P=d.target?l.get(d.target)??ue(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,...P?{toLayer:P}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),u=Mt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),f=Cc(e,t),y=e.contract.arkRules??be(),g=a.map(d=>d.path),m={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Lr(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=[...Tr({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:g,layerForFile:i(d=>l.get(d)??ue(d,e.contract.config.layers),"layerForFile"),fileHints:m}),...Nr(y,g)],I=A.filter(d=>d.failsStrict).map(d=>aa(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.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.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`)),_=A.filter(d=>!d.failsStrict).map(d=>({...aa(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`),failsStrict:!1})),S=(y.invariants?.length??0)>0?Rr({arkRules:y,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},b=S.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),w=S.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${d.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),k=wr(a),L=Dt({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(d=>l.get(d)??ue(d,e.contract.config.layers),"layerForFile"),classification:k}),X=e.contract.config.arkRun?.mode,x=L.findings.filter(()=>X==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),z=L.findings.filter(()=>X!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),D=Br({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(d=>l.get(d)??ue(d,e.contract.config.layers),"layerForFile"),classification:k}),re=e.contract.config.arkOrder?.mode,J=D.findings.filter(()=>re==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Se=D.findings.filter(()=>re!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),st=[...S.partial&&S.coverage.some(d=>d.mode==="enforced"&&d.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...L.completenessReasons,...D.completenessReasons],Te=He({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[..._c(e,t,l),...I,...b,...x,...J],edges:c,warnings:[...u,...f.warnings,..._,...w,...z,...Se],safety:f.report}),Zt=s==="complete"&&st.length>0?"partial":s,sn=Zt==="complete"?o:[...o,...st].sort((d,P)=>{let H=`${d.code}\0${d.file??""}\0${d.message}`,le=`${P.code}\0${P.file??""}\0${P.message}`;return H<le?-1:H>le?1:0}),v=Te.violations.filter(d=>d.failsStrict!==!1),C=Zt==="complete"&&v.length===0,h=C&&Te.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Zt,completenessReasons:sn,valid:C,strictValid:h,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:f.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Te.violations,warnings:Te.warnings}}}i(xc,"analyzeCanonicalResolvedProject");function tt(e){return xc({contract:e.contract,facts:ke(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(tt,"analyzeResolvedProject");function la(e){return Y(F(e.map(({path:t,contentHash:r})=>({path:t,contentHash:r}))))}i(la,"analysisTreeHash");function Zn(e){let t=Ze(e),r=new Map(t.ir.files.map(m=>[m.path,m])),n=[],s=new Set,o=[];for(let m of e.changes){let A=m.path.replace(/\\/g,"/"),I=$e(m.path);if(!I||I===".."||I.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(I)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:I,line:1,message:`The atomic change set contains more than one operation for ${I}.`});continue}s.add(I),"delete"in m&&m.delete&&!r.has(I)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:I,line:1,message:`Cannot delete ${I} because it is not present in the supplied base tree.`}),n.push("delete"in m&&m.delete?{path:I,delete:!0}:{path:I,content:"content"in m?m.content:""})}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=xt({...e,changes:n}),l=new Map(a.ir.files.map(m=>[m.path,m])),c=a.ir.violations.filter(m=>m.ruleId==="CAPABILITY_VIOLATION"||m.ruleId==="FORBIDDEN_GLOBAL").map(m=>{let A=l.get(m.evidence.file)?.layer;return{ruleId:m.ruleId,file:m.evidence.file,line:m.evidence.line,target:m.symbol,...m.capability?{capability:m.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:m.message}}),u=He({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(m=>m.path),contentViolations:c,edges:a.ir.edges.filter(m=>!!m.fromLayer).map(m=>({from:m.from,fromLayer:m.fromLayer,...m.to?{to:m.to}:{},...m.toLayer?{toLayer:m.toLayer}:{},line:m.evidence.line,kind:"import",...m.typeOnly?{typeOnly:!0}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=n.map(m=>{let A=$e(m.path),I=r.get(A),_=l.get(A);return{path:A,operation:"delete"in m&&m.delete?"delete":I?"update":"create",...I?{beforeContentHash:I.contentHash}:{},..._?{candidateContentHash:_.contentHash}:{}}}).sort((m,A)=>m.path.localeCompare(A.path)),y=[...o,...u.violations].map(m=>({...m,nextAction:me(m)})),g=y.filter(m=>m.failsStrict!==!1),p=e.changeMap?Me({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:a.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&g.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:la(t.ir.files),candidateTreeHash:la(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:f,violations:y,warnings:u.warnings}}i(Zn,"preflightChange");function Tc(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let r=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(r.length===0)return;r.pop()}else r.push(s);let n=r.join("/");return n&&n===t?n:void 0}i(Tc,"canonicalChangePath");function Nc(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,s])=>n!==s).map(([n,s,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:n,before:s,candidate:o,message:`Base and candidate facts must use the same ${n}.`}))}i(Nc,"identityViolations");function Lc(e,t,r,n){let s=r.get(t),o=n.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}i(Lc,"preparedChange");function Qn(e){let t=ke(e.baseFacts),r=ke(e.candidateFacts),n=tt({contract:e.contract,facts:t}),s=tt({contract:e.contract,facts:r}),o=new Map(t.files.map(p=>[p.path,p])),a=new Map(r.files.map(p=>[p.path,p])),l=Nc(t,r),c=new Map,u=[];for(let p of e.changes){let m=Tc(p.path);if(!m){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(m)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:m,line:1,message:`The atomic change set contains more than one operation for ${m}.`});continue}c.set(m,p);let A=o.get(m),I=a.get(m);if("delete"in p&&p.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:m,line:1,message:`Cannot delete ${m} because it is not present in the supplied base facts.`}),I&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:m,line:1,message:`Candidate facts still contain deleted file ${m}.`});else{let _="content"in p?p.content:"",R=Y(_);I?I.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:m,line:1,expectedContentHash:R,candidateContentHash:I.contentHash,message:`Candidate facts for ${m} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:m,line:1,message:`Candidate facts do not contain changed file ${m}.`})}u.push(Lc(p,m,o,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...o.keys(),...a.keys()])){if(c.has(p))continue;let m=o.get(p),A=a.get(p);m&&A&&F(m)===F(A)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let f=e.changeMap?Me({changeMap:e.changeMap,changes:u,baseDependencies:n.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:s.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,y=[...l,...s.ir.violations].map(p=>({...p,nextAction:me(p)})),g=y.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:n.completeness==="complete"&&s.strictValid&&g.length===0&&(f?.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:s.completeness,baseCompletenessReasons:n.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:u.sort((p,m)=>p.path<m.path?-1:p.path>m.path?1:0),violations:y,warnings:s.ir.warnings}}i(Qn,"preflightResolvedChange");var es="1.0",Pc=12;function ca(e){return e==="enforced"||e==="advisory"?e:null}i(ca,"closedMode");function wc(e){let t=new Set;if(!Array.isArray(e))return[];for(let r of e){let n=r?.ruleId;typeof n!="string"||!Dr(n)||t.has(n)||t.add(n)}return[...t].sort((r,n)=>r<n?-1:r>n?1:0)}i(wc,"uniqueArkRunRuleIds");function Dc(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:ca(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(Dc,"extraFromConfig");function da(e={}){let t=Dc(e.arkRun),r=t.present?wc(e.findings):[],n=r.slice(0,Pc),s=r.length,o=Nt({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),a=t.present&&t.mode==="enforced"&&fe(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?l="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":l="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":l="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:es,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:n},extraMergeTeeth:a,failMergeWhen:o.failMergeWhen,note:l,mergePlanes:o}}i(da,"summarizeArkRunSection");function zr(e={}){let t=e.present===!0,r=ca(e.mode),n=e.residual,s=null;return typeof n=="number"&&Number.isFinite(n)&&n>=0&&(s=Math.floor(n)),t||(s=s??0),{notAScore:!0,present:t,mode:t?r:null,extraMergeTeeth:t&&r==="enforced"&&e.extraMergeTeeth===!0,residual:s}}i(zr,"projectStatusArkRun");function ua(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=[`mode: ${t} \xB7 extra merge teeth ${r} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),o=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";n.push(`Residual: ${s}${o}`)}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(ua,"formatArkRunDoctorLines");function Wr(e,t){return e.slice(0,t).split(`
13
+ `).length}i(Wr,"lineOf");function pa(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(pa,"normalizeInventoryPath");function ma(e,t){return e.some(r=>{let n=r.trim().replace(/\.+$/,"");return t.some(s=>n===s||n.startsWith(`${s}.`))})}i(ma,"ownsIntent");function fa(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||ma(t,["Domain"])}i(fa,"isDomainLayer");function Mc(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(Mc,"isControllerEligibleLayer");function Fc(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(Fc,"isNonPilotSurface");function ga(e){let t=[],r=0,n=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[pa(c),u])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>fa(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([f],[y])=>f.localeCompare(y))){let f=pa(c);if(Fc(f)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let y=n.has(f),g=n.get(f),p=g?s.get(g)??[]:[],m=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(f)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(f)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(f),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(f),I=/(?:^|\/)actions?(?:\/|\.|$)/i.test(f)||/['"]use server['"]/.test(u),_=/controller|handler|resolver/i.test(c)||A||I||/route\.(?:ts|js|tsx|jsx)$/i.test(f)&&!m||/@(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),R=y?!!(g&&Mc(g,p)&&_):_,S=y?!!(g&&fa(g,p)):/domain|entity|aggregate|model/i.test(c),b=!y||S||R;if(R&&!m){let x=/\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=x.exec(u))!==null;)r+=1,t.push({id:`inv-val-${r}`,kind:"validation-in-controller",file:c,line:Wr(u,z.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${r}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let w=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,k,L=i(x=>/^(?: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(x)||/^(?: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(x)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(x)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(x)||/^(?: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(x)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(x)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(x)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(x)||/_(?:OID|OIDS)$/i.test(x)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(x)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(x),"isInfraMagicName"),X=i((x,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(x)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(x))return!0;let D=z.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(z)&&(/\s/.test(D)||/[.!?…]$/.test(D))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(x))},"isUxMessageConstant");for(;(k=w.exec(u))!==null;){let x=k[2],z=k[3]??"";!b||L(x)||X(x,z)||m&&!S||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(f)&&!S||(r+=1,t.push({id:`inv-magic-${r}`,kind:"magic-business-constant",file:c,line:Wr(u,k.index),message:`Magic business constant ${x} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,invariantId:`INV-${x}`},neverMechanicalSafe:!0}))}if(S){let x=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,z;for(;(z=x.exec(u))!==null;){let D=z[2]??"",re=(D.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(D.match(/:\s*[A-Za-z]/g)??[]).length>=2&&re<=1&&(r+=1,t.push({id:`inv-anemic-${r}`,kind:"anemic-entity",file:c,line:Wr(u,z.index),message:`Class ${z[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(S&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(f)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(f)||/(?:^|\/)errors?(?:\/|$)/i.test(f))){let z=/\bthis\.[A-Za-z_][A-Za-z0-9_]*\s*=(?!=)/g,D;for(;(D=z.exec(u))!==null;){let re=u.lastIndexOf("class ",D.index),J=re>=0?u.indexOf("{",re):-1,Se=re>=0&&J>=re&&J<D.index?u.slice(re,J):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(Se)||Vn(u,D.index))continue;let Ve=u.slice(Math.max(0,D.index-200),D.index+200);if(!Hn.test(Ve)&&!jn.test(Ve)){r+=1,t.push({id:`inv-mut-${r}`,kind:"mutation-without-guard",file:c,line:Wr(u,D.index),message:`Domain field mutation without nearby ${Kn()}.`,confidence:"heuristic",governedLayer:g,suggestedArkRule:{layer:o,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((c,u)=>+(u.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(u.file)||c.line-u.line||c.kind.localeCompare(u.kind)||c.id.localeCompare(u.id));let l=t.filter(c=>c.suggestedArkRule?.invariantId&&a.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&a.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(ga,"buildRulesInventory");function ya(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(ya,"inventoryToExtractionCard");var ha="1.1";var Aa="1.0";var qr="docs/diagnostics.md",Ra="1.0";function E(e,t,r,n,s,o){return{ruleId:e,title:r,why:n,fix:s,docsAnchor:e,category:t,...o?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var Ft=Object.freeze([E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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}),E("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."),E("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."),E("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}),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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."),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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}),E("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."),E("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}),E("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.")]),ts=new Map(Ft.map(e=>[e.ruleId,e])),ka=Object.freeze(Ft.map(e=>e.ruleId));function Ea(e){return typeof e=="string"&&e.length>0&&ts.has(e)}i(Ea,"isKnownDiagnosticCode");function Sa(e){return typeof e!="string"||e.length===0?!1:ts.has(e)?!0:e.startsWith("ARKRULE_")}i(Sa,"isCataloguedOrArkRuleFamily");function $t(e){if(!(typeof e!="string"||e.length===0))return ts.get(e)}i($t,"getDiagnosticCatalogEntry");function rs(e){return`#${$t(e)?.docsAnchor??e}`}i(rs,"diagnosticDocsFragment");function Ia(e){return`${qr}${rs(e)}`}i(Ia,"diagnosticDocsPath");function va(){return{schemaVersion:"1.0",docsPath:qr,codes:Ft}}i(va,"serializeDiagnosticCatalog");function ba(e){return $t(e)?.fix}i(ba,"catalogFixForRuleId");function Ca(e){return $t(e)?.why}i(Ca,"catalogWhyForRuleId");function $c(e){return e==="enforced"||e==="advisory"?e:null}i($c,"closedMode");function Oa(e={}){let t=e.present===!0,r=$c(e.mode),n=e.residual,s=null;return typeof n=="number"&&Number.isFinite(n)&&n>=0&&(s=Math.floor(n)),t||(s=s??0),{notAScore:!0,present:t,mode:t?r:null,extraMergeTeeth:t&&r==="enforced"&&e.extraMergeTeeth===!0,residual:s}}i(Oa,"projectStatusArkOrder");var Yr="1.0",ns="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",ss=["full","subset","unavailable"],os=["doctor-facts","report-snapshot","none"],jt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},_a=/^sha256:[a-f0-9]{64}$/;function as(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"||!_a.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 s=e.expectedRootRelation??"unknown";return s==="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}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:r,expectedProjectId:n,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="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}.`}:s==="exact"||s==="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(as,"evaluateStatusBinding");function is(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(is,"classifyStatusWritePath");function ls(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(ls,"defaultHonestLabel");function cs(e,t,r,n,s){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."}:s.arkRulesLoaded&&(s.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(cs,"resolveStatusNextAction");function xa(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",r=typeof e.projectId=="string"&&_a.test(e.projectId)?e.projectId:null,n=as({resolvedRoot:t,projectId:r,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",o=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,a=is({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():ls(a,o),c={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Ht(e.activeViolations),frozenResidual:Ht(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ht(e.rulesInventoried),underContract:Ht(e.rulesUnderContract),frozenResidual:Ht(e.rulesFrozenResidual)},f={writePath:a,host:o,honestLabel:l},y={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}:{}},g={schemaVersion:Yr,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:f,lastCheck:c,rules:u,nextAction:cs(e,n,f,c,u)},p=ds(e.improvementCompass);return p&&(g.improvementCompass=p),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(g.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(g.arkRun=zr(e.arkRun)),e.arkOrder&&typeof e.arkOrder=="object"&&(g.arkOrder=Oa(e.arkOrder)),g}i(xa,"buildStatusManifest");var Ta=new Set(ss),Hc=new Set(os);function Jr(e){let t=Ta.has(e.mode)?e.mode:"unavailable",r=e.factsSource!=null&&Hc.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:jt.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 s=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],o={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(o.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:jt.FACTS_PARTIAL,o.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&&(o.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(o.reason=e.reason),r&&(o.factsSource=r),n&&(o.contractHash=n),o}i(Jr,"projectStatusImprovementCompass");function Na(e={}){return Jr({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??jt.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(Na,"unavailableStatusImprovementCompass");function ds(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"&&Ta.has(t.mode)?r=t.mode:Array.isArray(t.topResidual)?r="subset":r="unavailable",Jr({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(ds,"normalizeStatusImprovementCompass");function La(e,t){let r=Array.isArray(e)?e:[],n=new Set(Array.isArray(t)?t:[]);for(let s of r)if(!(typeof s!="string"||s.length===0)&&!n.has(s))return!1;return!0}i(La,"statusCompassResidualIsSubsetOfDoctor");function Ht(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ht,"numberOrNull");var Pa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ns,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:Yr},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 Kt="1.0",Vt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Ut=5,_e=["scalability","resilience","security"],rt=new Set(_e),us={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},ps={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},fs={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function ms(e){return ps[e]??e}i(ms,"improvementCompassHumanLabel");function gs(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(gs,"smellIdOf");function ys(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(ys,"violationRuleId");function K(e,t,r,n){if(!r||e.evidence.some(o=>o.source===t&&o.ref===r))return;let s={source:t,ref:r};n&&n.trim()&&(s.detail=n.trim().slice(0,240)),e.evidence.push(s)}i(K,"pushEvidence");function te(e,t,r){rt.has(e.id)||(e.status="residual",e.summary=t,r&&(e.nextAction=r))}i(te,"markResidual");function wa(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`${ps[e]} \u2014 no residual from current sensors.`}}i(wa,"defaultOkSummary");function Da(){return Vt.map(e=>rt.has(e)?{id:e,status:"out-of-scope",summary:fs[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:wa(e),evidence:[]}:{id:e,status:"ok",summary:wa(e),evidence:[]})}i(Da,"createInitialImprovementCompassLenses");function jc(e,t){for(let r of t){let n=gs(r);if(!n)continue;let s=r.outcome||r.message||void 0,a=(Array.isArray(r.evidence)?r.evidence:[])[0],l=i((f,y,g)=>{let p=e.get(f);!p||rt.has(f)||(K(p,"designSmells",n,s),a&&K(p,"designSmells",a,n),te(p,y,g))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(n){case"domain-logic-in-ui":l("soc","Business rules still mix with UI or presentation surfaces.",c),l("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",c);break;case"facade-sql-in-routes":l("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",c),l("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":l("soc","Application/business code reaches I/O directly \u2014 separation is weak.",c),l("dip","I/O is not inverted behind ports/adapters.",u),l("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":l("soc","HTTP/transport handlers live under persistence folders.",c);break;case"god-module":l("cohesion","Large multi-responsibility modules reduce cohesion.",c),l("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":l("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),l("cohesion","Mixed layout styles scatter the same concern across patterns.",c);break;case"soft-contract":l("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),l("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:l("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",c);break}}}i(jc,"mapDesignSmells");function Kc(e){return e.failsStrict===!1||e.typeOnly===!0}i(Kc,"isTypeOnlyPlacementDebt");function Vc(e,t){for(let r of t){let n=ys(r);if(!n)continue;let s=r.message,o=n.toUpperCase(),a=i((c,u,f)=>{let y=e.get(c);!y||rt.has(c)||(K(y,"violations",n,s),r.file&&K(y,"violations",r.file,n),te(y,u,f))},"attach");if(Kc(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 l={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(o==="LAYER_IMPORT_VIOLATION"||o.includes("LAYER_IMPORT")||o==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",l);continue}if(o.includes("CYCLE")||o==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",l);continue}if(o.includes("PEER_ISOLATION")||o==="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(o==="FORBIDDEN_GLOBAL"||o.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(o==="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(o.startsWith("ARKRULE_")||o==="INVARIANT_UNCOVERED"){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(Vc,"mapViolations");function Uc(e,t){let r=Number(t.cycleCount)||0;if(r>0){let p=e.get("coupling");K(p,"cycles",`count:${r}`),te(p,"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 p=e.get("coupling");K(p,"peerIsolation",`count:${n}`),te(p,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let p=e.get("cohesion");K(p,"physicalCohesion",`findings:${s}`),te(p,"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 m=e.get("srp");K(m,"physicalCohesion",`findings:${s}`),te(m,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let o=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(o>0||a>0){let p=e.get("dip");o>0&&K(p,"capability",`residual:${o}`),a>0&&K(p,"forbiddenGlobals",`residual:${a}`),te(p,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let m=e.get("testability");o>0&&K(m,"capability",`residual:${o}`),a>0&&K(m,"forbiddenGlobals",`residual:${a}`),te(m,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let p=e.get("encapsulation");K(p,"arkRules",`structureResidual:${l}`),te(p,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let m=e.get("domain");K(m,"arkRules",`structureResidual:${l}`),te(m,"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 p=e.get("maintainability");K(p,"designFitness","design-weak"),te(p,"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 p=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(p,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(p,"baseline",`stale:${t.baselineStale}`),te(p,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let c=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&c>=10&&e.get("maintainability").status!=="residual"){let p=e.get("maintainability");K(p,"baseline",`frozen:${c}`),te(p,"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,f=Number(t.emptyLayerCount)||0;if(u>0||f>0){let p=e.get("modularity");u>0&&K(p,"coverage",`ungovernedDirs:${u}`),f>0&&K(p,"coverage",`emptyLayers:${f}`),te(p,"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 p=e.get("modularity");K(p,"goldenPattern","absent"),te(p,"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 y=e.get("stack");(t.stackKind??null)==="typescript"?y.status==="ok"&&(y.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(y.status="not-instrumented",y.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",y.evidence=[],y.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Uc,"mapCountsAndFlags");function Ma(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let r=[...t.designSmells].sort((n,s)=>gs(n).localeCompare(gs(s)));jc(e,r)}if(Array.isArray(t.violations)&&t.violations.length>0){let r=[...t.violations].sort((n,s)=>{let o=ys(n).localeCompare(ys(s));return o!==0?o:String(n.file??"").localeCompare(String(s.file??""))});Vc(e,r)}Uc(e,t)}i(Ma,"projectImprovementCompassFacts");function Fa(e){for(let t of _e){let r=e.get(t);r.status="out-of-scope",r.summary=fs[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(Fa,"lockImprovementCompassOutOfScope");function $a(e){for(let t of e)t.evidence.sort((r,n)=>{let s=r.source.localeCompare(n.source);return s!==0?s:r.ref.localeCompare(n.ref)})}i($a,"sortImprovementCompassEvidence");function Ha(e){return e.filter(r=>r.status==="residual"&&!rt.has(r.id)).slice().sort((r,n)=>{let s=us[r.id]??150,o=us[n.id]??150;return s!==o?s-o:r.id.localeCompare(n.id)}).slice(0,5).map(r=>r.id)}i(Ha,"finalizeImprovementCompassTopResidual");function ja(e={}){let t=Da(),r=new Map(t.map(s=>[s.id,s]));Ma(r,e),Fa(r),$a(t);let n=Ha(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let o={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(a=>({...a}))};return s.nextAction&&(o.nextAction={...s.nextAction}),o}),topResidual:n}}i(ja,"buildImprovementCompass");function hs(e){return e.topResidual.map(t=>ms(t))}i(hs,"formatImprovementCompassResidualLabels");function As(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(As,"primaryImprovementCompassNextAction");function Ka(e){let t=hs(e),r=_e.map(o=>ms(o)),n=As(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${r.join(" \xB7 ")}`),n&&s.push(`Next: ${n.ref} \u2014 ${n.summary}`),s}i(Ka,"formatImprovementCompassDoctorLines");var xe="1.0",Rs="<!-- arkgate:agent-projection:begin",Gt="<!-- arkgate:agent-projection:end -->",Bt="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",nt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ks=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]);function je(e){let t=String(e??"").replace(/\r\n/g,`
14
+ `),r=2166136261;for(let n=0;n<t.length;n+=1)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`fnv1a-${(r>>>0).toString(16).padStart(8,"0")}`}i(je,"agentProjectionContentIdentity");function Wt(e){return String(e??"").replace(/\r\n/g,`
15
+ `)}i(Wt,"normalizeNewlines");function Ke(e){let t=Wt(e);return t.endsWith(`
16
16
  `)?t:`${t}
17
- `}i(je,"ensureTrailingNewline");function zt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(zt,"safeVersion");function Ha(e){return e==="compact"?"compact":"full"}i(Ha,"resolveProfile");function Zn(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(Zn,"buildAgentProjectionBeginMarker");function Gt(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 |
17
+ `}i(Ke,"ensureTrailingNewline");function qt(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(qt,"safeVersion");function Va(e){return e==="compact"?"compact":"full"}i(Va,"resolveProfile");function Xr(e){let t=qt(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}i(Xr,"buildAgentProjectionBeginMarker");function zt(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(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],o=n.intentPrefixes??[],a=s.map(c=>`\`${c}\``).join(", ")||"\u2014",l=o.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${a} | ${l} |`}).join(`
20
- `)}`}i(Gt,"formatAgentProjectionLayers");function Qn(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(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let o=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${o}`}).join(`
19
+ ${e.map(r=>{let n=r.name?.trim()||"Unknown",s=r.patterns??[],o=r.intentPrefixes??[],a=s.map(c=>`\`${c}\``).join(", ")||"\u2014",l=o.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${n} | ${a} | ${l} |`}).join(`
20
+ `)}`}i(zt,"formatAgentProjectionLayers");function Zr(e,t){let r=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${r}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let o=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${o}`}).join(`
21
21
  `)}
22
22
 
23
- Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(Qn,"formatAgentProjectionCatalogShortList");function Wt(e){let t=zt(e.arkgateVersion),n=Ha(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",o=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=o&&o!=="unknown"?o:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",Kt,"",`- **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)","",Gt(l),""):u.push("### Contract layers","",Gt(l),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",Qn(c,s),"","### 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)","",nt.map(f=>`- \`${f}\``).join(`
23
+ Full catalog: \`${r}\` (\`#RULE_ID\` anchors).`}i(Zr,"formatAgentProjectionCatalogShortList");function Yt(e){let t=qt(e.arkgateVersion),r=Va(e.profile),n=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",o=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=o&&o!=="unknown"?o:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",Bt,"","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:** \`${r}\`${a?` \xB7 **host:** \`${a}\``:""}`,`- **after edits:** \`${n}\``,""];return r==="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)","",zt(l),""):u.push("### Contract layers","",zt(l),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",Zr(c,s),"","### 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)","",nt.map(f=>`- \`${f}\``).join(`
24
24
  `),""),u.join(`
25
25
  `).replace(/\n{3,}/g,`
26
26
 
27
27
  `).trimEnd()+`
28
- `}i(Wt,"buildAgentProjectionBody");function Rs(e){let t=Wt(e);return`${Zn({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
29
- ${t}${Ut}
30
- `}i(Rs,"buildAgentProjectionBlock");function ks(e){let t=Wt(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:[...nt],contentIdentity:He(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:Ha(e.profile)}}i(ks,"buildAgentProjectionMeta");var Es=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,ja=/<!--\s*arkgate:agent-projection:end\s*-->/i,Mc=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Fc=/\bschema=([A-Za-z0-9._+-]+)/i;function qt(e){let t=Bt(e??""),n=Es.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,o=t.slice(s),a=ja.exec(o);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=a.index,c=l+a[0].length,u=o.slice(0,l);u.startsWith(`
31
- `)&&(u=u.slice(1));let f=t.slice(r,s+c),y=o.slice(c);return{block:f,body:u,before:t.slice(0,r),after:y,beginAttrs:n[1]??""}}i(qt,"extractAgentProjectionBlock");function er(e){let t=String(e??""),r=Es.exec(t)?.[1]??t,s=Mc.exec(r),o=Fc.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}i(er,"parseAgentProjectionStamp");function Is(e,t){let n=er(e).arkgateVersion;return n?n===zt(t):!1}i(Is,"projectionMatchesPackageVersion");function Ss(e){return String(e??"").includes("non-authoritative")}i(Ss,"projectionHasNonEnforcementLabel");function bs(e,t){let n=je(Bt(t)),s=qt(n).body??n.replace(Es,"").replace(ja,"").trim()+`
32
- `,o=He(s);if(e==null||!String(e).trim())return{content:je(`# Ark Enforcement
28
+ `}i(Yt,"buildAgentProjectionBody");function Es(e){let t=Yt(e);return`${Xr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
29
+ ${t}${Gt}
30
+ `}i(Es,"buildAgentProjectionBlock");function Ss(e){let t=Yt(e),r=Array.isArray(e.layers)?e.layers:[],n=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:qt(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...nt],contentIdentity:je(t),layerCount:r.length,catalogCodeCount:n.filter(s=>s?.ruleId).length,profile:Va(e.profile)}}i(Ss,"buildAgentProjectionMeta");var Is=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,Ua=/<!--\s*arkgate:agent-projection:end\s*-->/i,Gc=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Bc=/\bschema=([A-Za-z0-9._+-]+)/i;function Jt(e){let t=Wt(e??""),r=Is.exec(t);if(!r)return{block:null,body:null,before:t,after:"",beginAttrs:null};let n=r.index,s=n+r[0].length,o=t.slice(s),a=Ua.exec(o);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=a.index,c=l+a[0].length,u=o.slice(0,l);u.startsWith(`
31
+ `)&&(u=u.slice(1));let f=t.slice(n,s+c),y=o.slice(c);return{block:f,body:u,before:t.slice(0,n),after:y,beginAttrs:r[1]??""}}i(Jt,"extractAgentProjectionBlock");function Qr(e){let t=String(e??""),n=Is.exec(t)?.[1]??t,s=Gc.exec(n),o=Bc.exec(n),a=/\bnonAuthoritative\s*=\s*true\b/i.test(n);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}i(Qr,"parseAgentProjectionStamp");function vs(e,t){let r=Qr(e).arkgateVersion;return r?r===qt(t):!1}i(vs,"projectionMatchesPackageVersion");function bs(e){return String(e??"").includes("non-authoritative")}i(bs,"projectionHasNonEnforcementLabel");function Cs(e,t){let r=Ke(Wt(t)),s=Jt(r).body??r.replace(Is,"").replace(Ua,"").trim()+`
32
+ `,o=je(s);if(e==null||!String(e).trim())return{content:Ke(`# Ark Enforcement
33
33
 
34
- ${n}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a=Bt(e),l=qt(a);if(l.block!=null){let u=l.body??"";if(He(u)===o)return{content:je(a),action:"unchanged",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0};let f=l.before.replace(/\s*$/,`
34
+ ${r}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a=Wt(e),l=Jt(a);if(l.block!=null){let u=l.body??"";if(je(u)===o)return{content:Ke(a),action:"unchanged",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0};let f=l.before.replace(/\s*$/,`
35
35
 
36
36
  `),y=l.after.replace(/^\s*/,`
37
- `);return{content:je(`${f}${n.trimEnd()}
37
+ `);return{content:Ke(`${f}${r.trimEnd()}
38
38
  ${y}`),action:"block-replaced",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(a);if(c&&c.index!=null){let u=c.index+c[1].length,f=a.slice(0,u).replace(/\s*$/,`
39
39
 
40
40
  `),y=a.slice(u).replace(/^\s*/,`
41
- `);return{content:je(`${f}${n.trimEnd()}
42
- ${y}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:je(`${n.trimEnd()}
41
+ `);return{content:Ke(`${f}${r.trimEnd()}
42
+ ${y}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:Ke(`${r.trimEnd()}
43
43
 
44
- ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(bs,"mergeAgentProjectionDocument");var Va="1.0",vs="templates/agent-skills",Cs="templates/skills",_s="SKILL.md",Yt=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-place","ark-runtime","ark-think","ark-upgrade"]),Os=Yt.length,$c=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xs(e){return typeof e!="string"||e.length<1||e.length>64?!1:$c.test(e)}i(xs,"isValidAgentSkillName");function nr(e){return Yt.includes(e)}i(nr,"isArkSkillName");function Ts(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
44
+ ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(Cs,"mergeAgentProjectionDocument");var Ga="1.0",Os="templates/agent-skills",_s="templates/skills",xs="SKILL.md",Ba=Object.freeze(["Contener","Guiar","Ordenar"]),Ts=Object.freeze(["ark-adopt","ark-autopilot","ark-coverage","ark-explain","ark-explore","ark-order","ark-place","ark-runtime","ark-upgrade"]),en=Object.freeze({"ark-architect":"ark-adopt","ark-contract":"ark-adopt","ark-fix":"ark-autopilot","ark-loop":"ark-autopilot","ark-think":"ark-explore"}),za=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"]}),Xt=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"]),Ns=Xt.length,zc=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Ls(e){return typeof e!="string"||e.length<1||e.length>64?!1:zc.test(e)}i(Ls,"isValidAgentSkillName");function rn(e){return Xt.includes(e)}i(rn,"isArkSkillName");function Wa(e){return Ts.includes(e)}i(Wa,"isFirstClassArkSkillName");function qa(e){return e in en?en[e]:null}i(qa,"arkSkillStubRedirect");function Ps(e){let t=String(e??"").replace(/^\uFEFF/,""),r=t.includes(`\r
45
45
  `)?`\r
46
46
  `:`
47
- `,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let o={};for(let f=1;f<s;f+=1){let y=r[f]??"";if(y.trim()===""||y.trimStart().startsWith("#"))continue;let g=y.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!g)continue;let p=g[1],m=g[2]??"";(m.startsWith('"')&&m.endsWith('"')&&m.length>=2||m.startsWith("'")&&m.endsWith("'")&&m.length>=2)&&(m=m.slice(1,-1)),o[p]=m}let a=r.slice(s+1).join(n),l=typeof o.name=="string"&&o.name.length>0?o.name:null,c=typeof o.description=="string"&&o.description.length>0?o.description:null,u=typeof o.license=="string"&&o.license.length>0?o.license:null;return{hasFrontmatter:!0,frontmatter:{fields:o,name:l,description:c,license:u},body:a}}i(Ts,"parseSkillDocument");function Ns(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),o=Ts(e.content);if(!o.hasFrontmatter||!o.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:a,description:l}=o.frontmatter,c=a??(s||void 0);return!a||!xs(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):a!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${s}".`,skillName:a}):t&&!nr(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:a}),l?l.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${l.length}).`,skillName:c}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:c}),n&&o.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:c}),r}i(Ns,"validateAgentSkillDocument");function Ua(e){let t=[],n=new Set,r=[];for(let s of e){let o=String(s.name??"");if(n.has(o)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${o}".`,skillName:o});continue}n.add(o),r.push(o),t.push(...Ns({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&tr(s.content)!==tr(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${o}" does not match flat template templates/skills/${o}.md.`,skillName:o})}for(let s of Yt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)nr(s)||(t.some(o=>o.code==="UNKNOWN_SKILL_NAME"&&o.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:Os,presentCount:r.length}}i(Ua,"validateAgentSkillsPackage");var rr=/^arkgate@(\S+)\.\s/;function Ps(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(Ps,"skillDescriptionVersionPrefix");function Ls(e){return String(e??"").replace(rr,"")}i(Ls,"stripSkillDescriptionVersion");function Ka(e){return String(e??"").match(rr)?.[1]??null}i(Ka,"parseSkillDescriptionVersion");function Ga(e,t){let n=Ls(e),r=typeof t=="string"?t.trim():"";return r?`${Ps(r)}${n}`:n}i(Ga,"stampSkillDescription");function tr(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
48
- `)}i(tr,"normalizeSkillContent");function ws(e){return`${e}/${_s}`}i(ws,"agentSkillEntryRelativePath");function Ba(e){return`${vs}/${ws(e)}`}i(Ba,"agentSkillPackageFileRelativePath");function za(e){return`${Cs}/${e}.md`}i(za,"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_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_DESCRIPTION_VERSION_PATTERN,ARK_SKILL_NAMES,ARK_SKILL_NAME_COUNT,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,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,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,version});
47
+ `,n=t.split(/\r?\n/);if(n[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=n.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let o={};for(let f=1;f<s;f+=1){let y=n[f]??"";if(y.trim()===""||y.trimStart().startsWith("#"))continue;let g=y.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!g)continue;let p=g[1],m=g[2]??"";(m.startsWith('"')&&m.endsWith('"')&&m.length>=2||m.startsWith("'")&&m.endsWith("'")&&m.length>=2)&&(m=m.slice(1,-1)),o[p]=m}let a=n.slice(s+1).join(r),l=typeof o.name=="string"&&o.name.length>0?o.name:null,c=typeof o.description=="string"&&o.description.length>0?o.description:null,u=typeof o.license=="string"&&o.license.length>0?o.license:null;return{hasFrontmatter:!0,frontmatter:{fields:o,name:l,description:c,license:u},body:a}}i(Ps,"parseSkillDocument");function ws(e){let t=e.requireArkSkillName!==!1,r=e.requireBody!==!1,n=[],s=String(e.directoryName??""),o=Ps(e.content);if(!o.hasFrontmatter||!o.frontmatter)return n.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),n;let{name:a,description:l}=o.frontmatter,c=a??(s||void 0);return!a||!Ls(a)?n.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):a!==s?n.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${s}".`,skillName:a}):t&&!rn(a)&&n.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the closed Ark skill catalog (ARK_SKILL_NAMES).`,skillName:a}),l?l.length>1024&&n.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${l.length}).`,skillName:c}):n.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:c}),r&&o.body.trim().length===0&&n.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:c}),n}i(ws,"validateAgentSkillDocument");function Ya(e){let t=[],r=new Set,n=[];for(let s of e){let o=String(s.name??"");if(r.has(o)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${o}".`,skillName:o});continue}r.add(o),n.push(o),t.push(...ws({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&tn(s.content)!==tn(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${o}" does not match flat template templates/skills/${o}.md.`,skillName:o})}for(let s of Xt)r.has(s)||t.push({code:"MISSING_SKILL",message:`Missing catalog skill "${s}" from Agent Skills package.`,skillName:s});for(let s of n)rn(s)||(t.some(o=>o.code==="UNKNOWN_SKILL_NAME"&&o.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the closed Ark skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the closed Ark skill catalog.`,skillName:s}));return n.sort(),{ok:t.length===0,issues:t,names:n,expectedCount:Ns,presentCount:n.length}}i(Ya,"validateAgentSkillsPackage");var nn=/^arkgate@(\S+)\.\s/;function Ds(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(Ds,"skillDescriptionVersionPrefix");function Ms(e){return String(e??"").replace(nn,"")}i(Ms,"stripSkillDescriptionVersion");function Ja(e){return String(e??"").match(nn)?.[1]??null}i(Ja,"parseSkillDescriptionVersion");function Xa(e,t){let r=Ms(e),n=typeof t=="string"?t.trim():"";return n?`${Ds(n)}${r}`:r}i(Xa,"stampSkillDescription");function tn(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
48
+ `)}i(tn,"normalizeSkillContent");function Fs(e){return`${e}/${xs}`}i(Fs,"agentSkillEntryRelativePath");function Za(e){return`${Os}/${Fs(e)}`}i(Za,"agentSkillPackageFileRelativePath");function Qa(e){return`${_s}/${e}.md`}i(Qa,"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_DESCRIPTION_VERSION_PATTERN,ARK_SKILL_NAMES,ARK_SKILL_NAME_COUNT,ARK_SKILL_NORTH_STAR,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,version});