arkgate 4.8.8 → 4.8.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +64 -3
- package/README.md +9 -6
- package/bin/ark-check-runtime.mjs +22 -0
- package/bin/ark-layer-match.mjs +25 -10
- package/bin/lib/agent-homes.mjs +1 -1
- package/bin/lib/analysis-engine.mjs +8 -8
- package/bin/lib/ark-order-sensors.mjs +103 -3
- package/bin/lib/config-extras.mjs +1 -0
- package/bin/lib/contract-smells.mjs +12 -6
- package/bin/lib/doctor-human.mjs +32 -7
- package/bin/lib/doctor-next-actions.mjs +21 -2
- package/bin/lib/gate-files.mjs +108 -22
- package/bin/lib/managed-upgrade.mjs +9 -1
- package/bin/lib/upgrade-command.mjs +17 -4
- package/dist/{configTypes-0eHpocR3.d.ts → configTypes-j7so8B4O.d.ts} +12 -0
- package/dist/{diagnosticCatalog-DxKCTBbp.d.ts → diagnosticCatalog-BrkOiwCk.d.ts} +3 -3
- package/dist/eslint/index.cjs +5 -5
- package/dist/eslint/index.d.ts +6 -4
- package/dist/eslint/index.js +5 -5
- package/dist/index.cjs +30 -30
- package/dist/index.d.ts +13 -4
- package/dist/index.js +31 -31
- package/dist/nestjs/index.cjs +3 -3
- package/dist/nestjs/index.d.ts +3 -3
- package/dist/nestjs/index.js +2 -2
- package/dist/order/index.cjs +1 -1
- package/dist/order/index.d.ts +6 -2
- package/dist/order/index.js +1 -1
- package/dist/runtime/index.cjs +11 -11
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.js +11 -11
- package/dist/{types-BK47clMl.d.ts → types-Djbs3KjE.d.ts} +1 -1
- package/dist/{types-DxvmJO-D.d.ts → types-tGhZUiGX.d.ts} +1 -1
- package/docs/README.md +4 -3
- package/docs/agent-guide.md +2 -1
- package/docs/arkorder.md +30 -7
- package/docs/configuration.md +47 -13
- package/docs/develop.md +4 -2
- package/docs/package-surface.md +5 -4
- package/package.json +1 -1
- package/schemas/ark.config.schema.json +9 -0
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-contract/SKILL.md +1 -1
- package/templates/agent-skills/ark-explore/SKILL.md +2 -2
- package/templates/skills/ark-contract.md +1 -1
- package/templates/skills/ark-explore.md +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
"use strict";var Mt=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var Ca=Object.getOwnPropertyNames;var Oa=Object.prototype.hasOwnProperty;var i=(e,t)=>Mt(e,"name",{value:t,configurable:!0});var _a=(e,t)=>{for(var n in t)Mt(e,n,{get:t[n],enumerable:!0})},xa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ca(t))!Oa.call(e,s)&&s!==n&&Mt(e,s,{get:()=>t[s],enumerable:!(r=ba(t,s))||r.enumerable});return e};var Ta=e=>xa(Mt({},"__esModule",{value:!0}),e);var Ql={};_a(Ql,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>qn,AGENT_PROJECTION_BEGIN_MARKER:()=>da,AGENT_PROJECTION_END_MARKER:()=>Zr,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Hn,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Qr,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>ss,AGENT_SKILL_ENTRY_FILENAME:()=>as,ANALYSIS_IR_SCHEMA_VERSION:()=>Zt,ARKORDER_RULE_IDS:()=>xn,ARKORDER_TIER1_SENSOR_IDS:()=>_o,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>xr,ARKRUN_KERNEL_FACTORY_CALLEES:()=>Or,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>ko,ARKRUN_RULE_IDS:()=>_n,ARKRUN_TIER1_SENSOR_IDS:()=>So,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>_r,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>ca,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Ra,ARK_ANALYSIS_RESULT_SCHEMA:()=>hs,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Ht,ARK_CONFIG_SCHEMA:()=>qt,ARK_CONFIG_SCHEMA_VERSION:()=>ne,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>jo,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Ho,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>xt,ARK_PROJECT_IDENTITY_SCHEMA:()=>Rs,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>Xn,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>As,ARK_RULES_SCHEMA:()=>en,ARK_RULES_SCHEMA_VERSION:()=>Zs,ARK_RULE_SENSORS:()=>hr,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>Pr,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>Gn,ARK_SKILL_NAMES:()=>Pt,ARK_SKILL_NAME_COUNT:()=>is,ARK_STATUS_MANIFEST_SCHEMA:()=>ea,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Mr,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>wn,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>ua,DIAGNOSTIC_CATALOG:()=>bt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Vo,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Pn,DIAGNOSTIC_RULE_IDS:()=>Uo,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>yo,EffectiveContractError:()=>gt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>os,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>Ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Nt,IMPROVEMENT_LENS_IDS:()=>Tt,MERGE_PLANES_DUAL_STAMP:()=>br,POLICY_DELTA_SCHEMA_VERSION:()=>an,PROJECT_BINDING_SCHEMA:()=>Zn,PROJECT_EXPECTATION_SCHEMA:()=>Jn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Jt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Se,STATUS_COMPASS_FACTS_SOURCES:()=>$r,STATUS_COMPASS_MODES:()=>Fr,STATUS_COMPASS_REASON_CODES:()=>_t,adapterDocsCodePath:()=>Yn,adapterFindingOccurrenceTargetKeys:()=>Ft,adapterFindingRefFromTargetKey:()=>Wn,adapterFindingTargetKey:()=>jt,agentProjectionContentIdentity:()=>Lt,agentSkillEntryRelativePath:()=>fs,agentSkillPackageFileRelativePath:()=>va,analyzeArchitectureConvergence:()=>Le,analyzeChange:()=>Rt,analyzePolicyDelta:()=>Er,analyzeProject:()=>Be,analyzeResolvedProject:()=>We,arkRunKernelCallKind:()=>En,buildAgentProjectionBeginMarker:()=>ts,buildAgentProjectionBlock:()=>ma,buildAgentProjectionBody:()=>Vn,buildAgentProjectionMeta:()=>ga,buildArkRuleFileHints:()=>yn,buildEffectiveArkRules:()=>tn,buildImprovementCompass:()=>ia,buildRulesInventory:()=>Fo,buildStatusManifest:()=>Xo,canPromoteInvariant:()=>sn,catalogFixForRuleId:()=>qo,catalogWhyForRuleId:()=>Wo,classifyArkPolicyDelta:()=>ln,classifyResolvedLayerCoverage:()=>An,classifyStatusWritePath:()=>jr,collectAnalysisConfigWarnings:()=>St,collectEmptyAppliesToFindings:()=>gn,collectForbiddenCapabilityUses:()=>Te,composeMergePlanesHonesty:()=>kn,createAICodeGate:()=>pr,createAdapterResult:()=>ys,createArchitectureProfile:()=>ct,createArchitectureProfileFromArkConfig:()=>mr,createElevenLayerArkConfig:()=>gr,createProjectId:()=>ks,createProjectIdentity:()=>Es,createResolvedCandidateFacts:()=>Xt,defaultHonestLabel:()=>Vr,demoteExtraPlaneTeethUnderClassificationFloor:()=>Ao,deriveArkRuleFileHints:()=>vr,detectArchitectureCycles:()=>un,deterministicHash:()=>X,diagnosticDocsFragment:()=>Dr,diagnosticDocsPath:()=>Bo,effectiveContractPolicyPayload:()=>nn,elevenLayerProfile:()=>lt,emptyEffectiveArkRules:()=>be,evaluateArchitectureGraph:()=>De,evaluateArkOrderSensors:()=>Tn,evaluateArkRuleSensors:()=>mn,evaluateArkRunEditorSensors:()=>Tr,evaluateArkRunEditorSensorsFromSource:()=>Co,evaluateArkRunSensors:()=>vt,evaluateInvariantCoverage:()=>rn,evaluateStatusBinding:()=>Hr,explainViolation:()=>Ir,extraMergeTeethAllowed:()=>me,extractAgentProjectionBlock:()=>$n,extractArkRunDeclarationsFromSource:()=>Eo,extractArkRunImportedConstructorNamesFromSource:()=>bn,extractArkRunKernelCallsFromSource:()=>Cn,extractArkRunManagedNewsFromSource:()=>On,extractArkRunValueImportDependenciesFromSource:()=>Sn,extractClassShapesFromSource:()=>go,extractSemanticDependencies:()=>xe,flatSkillTemplateFileRelativePath:()=>Sa,formatAgentProjectionCatalogShortList:()=>ns,formatAgentProjectionLayers:()=>Fn,formatArkRunDoctorLines:()=>Po,formatImprovementCompassDoctorLines:()=>la,formatImprovementCompassResidualLabels:()=>Xr,getDiagnosticCatalogEntry:()=>Ct,inventoryToExtractionCard:()=>$o,isArkOrderRuleId:()=>ho,isArkRunKernelModuleSpecifier:()=>qe,isArkRunRuleId:()=>Rn,isArkRunTransportBypassSpecifier:()=>In,isArkSkillName:()=>Kn,isCataloguedOrArkRuleFamily:()=>Go,isExtraPlaneFinding:()=>Sr,isKnownDiagnosticCode:()=>Ko,isValidAgentSkillName:()=>ls,loadArkConfigContract:()=>it,loadArkRulesContract:()=>mt,loadContract:()=>At,loadResolvedCandidateFacts:()=>Re,mergeAgentProjectionDocument:()=>Aa,normalizeExtraMergeTeethClassification:()=>hn,normalizeSkillContent:()=>Un,normalizeStatusImprovementCompass:()=>Kr,parseAgentProjectionStamp:()=>rs,parseArkConfigJson:()=>Yt,parseArkRulesJson:()=>Qs,parseSkillDescriptionVersion:()=>Ea,parseSkillDocument:()=>cs,policyDeltaAcknowledgementMatches:()=>cn,preflightChange:()=>Nr,preflightResolvedChange:()=>Lr,primaryImprovementCompassNextAction:()=>Jr,projectStatusArkRun:()=>Nn,projectStatusImprovementCompass:()=>Dn,projectionHasNonEnforcementLabel:()=>ha,projectionMatchesPackageVersion:()=>ya,resolveEffectiveContract:()=>to,resolveStatusNextAction:()=>Ur,resolvedFactsEvidenceRequirementsHash:()=>Ge,serializeDiagnosticCatalog:()=>zo,skillDescriptionVersionPrefix:()=>us,stableSerialize:()=>F,stampSkillDescription:()=>Ia,statusCompassResidualIsSubsetOfDoctor:()=>Qo,stripSkillDescriptionVersion:()=>ps,summarizeArkRunSection:()=>Lo,toAdapterDiagnostic:()=>$t,unavailableStatusImprovementCompass:()=>Zo,validateAgentSkillDocument:()=>ds,validateAgentSkillsPackage:()=>ka,version:()=>ms});module.exports=Ta(Ql);var ms="4.8.8";var Na=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,La=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Pa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function wa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Na.test(n)?"pure-shared":r==="PersistenceAdapters"&&(La.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Pa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(wa,"classifyLayerImportKind");function Da(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=wa(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(Da,"layerImportNextAction");function Ma(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Ma,"arkRunCallSiteName");function Fa(e){let t=Ma(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(Fa,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Da(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 Fa(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(fe,"deterministicNextAction");var Ht="1.5",qn="docs/diagnostics.md";function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function gs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(gs,"positiveInteger");function jt(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(jt,"adapterFindingTargetKey");function Ft(e){let t=new Map;return e.map(n=>{let r=jt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}i(Ft,"adapterFindingOccurrenceTargetKeys");function Wn(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(Wn,"adapterFindingRefFromTargetKey");function Yn(e){return`${qn}#${e}`}i(Yn,"adapterDocsCodePath");function $a(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i($a,"nextActionForDiagnostic");function $t(e,t="error",n){let r=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=n??jt(e),l=Wn(a);return{ruleId:r,severity:s,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:gs(e.line,1),column:gs(e.column,1)},evidence:o,nextAction:O(e.nextAction)??$a(r,o,e),findingRef:l,targetKey:a,docsCodePath:Yn(r)}}i($t,"toAdapterDiagnostic");function ys(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: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(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=Ft(o),c=Ft(a),p=[...o.map((y,m)=>$t(y,"error",l[m])),...a.map((y,m)=>$t(y,"warning",c[m]))],g={schemaVersion:Ht,completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...s};let y={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...y}:{...g,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...s}:{...g,mode:n,valid:!1,completeness:t,...s}}i(ys,"createAdapterResult");var hs={$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:Ht},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}}}}}};var As="1.0",Xn="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Vt="^sha256:[a-f0-9]{64}$",Jn={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:Vt,description:"Project id previously returned by ark_identity or ark_manifest."}}},Zn={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:Vt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Rs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Xn,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:Vt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Vt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Jn,binding:Zn}};function ks(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(ks,"createProjectId");function Es(e){return{schemaVersion:"1.0",...e}}i(Es,"createProjectIdentity");var er=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),nr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),rr=Object.freeze(Object.keys(nr).sort()),Qn=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"}),tr=Object.freeze({process:Object.freeze(["process","node:process"])});function Qe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Qn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Qn[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:Qn[e.slice(0,o)]??null}i(Qe,"capabilityForModuleSpecifier");function ve(e,t){for(let n of t)if(tr[n]?.includes(e))return n;return null}i(ve,"forbiddenGlobalForModuleSpecifier");function Ut(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=nr[r];if(s)return s}return null}i(Ut,"capabilityForAmbientName");function $e(e){if(e?.pure===!0)return[...er].sort();let n=(e?.capabilities?.deny??[]).filter(r=>er.includes(r));return[...new Set(n)].sort()}i($e,"effectiveCapabilityDeny");function et(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(et,"ambientCoveredByForbiddenGlobals");function Kt(e){let t=new Set,n=new Set,r=Object.keys(nr);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 tr[s]??[])t.add(`import-exact:${a}`)}for(let s of $e(e)){if(t.add(`import:${s}`),s==="process")for(let o of tr.process)t.add(`import-exact:${o}`);for(let o of r)Ut(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Kt,"loweredLayerCoverage");var Is=new Map;function vs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(vs,"escapeLiteral");function Gt(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(Gt,"normalizeGlobSeparators");function Ha(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(Ha,"bracesBalanced");function ge(e){let t=Is.get(e);if(t)return t;let n=Gt(e),r=Ha(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=vs(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+=vs(c)}let a=new RegExp(`^${s}$`);return Is.set(e,a),a}i(ge,"globToRegExp");function ja(e){return Gt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(ja,"concreteGlobSegments");function sr(e,t){let n=Gt(String(e)),r=ja(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 p of r){let g=-1;for(let y=l;y<a.length;y+=1)if(a[y]===p){g=y;break}if(g<0)return o;c=g,l=g+1}return(c+1)*1e6+r.length*1e4+s}i(sr,"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=sr(a,n);l>s&&(s=l,r=o.name)}}return r}i(de,"layerForRelativePath");function Ss(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(Ss,"sliceIdForPath");function Va(e){let t=new Set;for(let n of e??[]){let s=Gt(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(Va,"inferSliceFoldersFromPatterns");function Ua(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 Va(r?.patterns)}i(Ua,"resolveSliceFolders");function bs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(bs,"normalizeSegments");function _s(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(_s,"trimTrailingSlashes");var Ka=["src","app"];function Ga(e){let t=_s(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Ga,"isBlanketRoot");function Cs(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||Ga(o))continue;if(o.includes("*")){let c=_s(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=Ka.includes(s[0])&&a[0]!==s[0]?[0,1]:[0];for(let c of l){if(c+a.length>s.length)continue;let p=!0;for(let g=0;g<a.length;g+=1)if(s[c+g]!==a[g]){p=!1;break}if(p)return!0}}return!1}i(Cs,"pathUnderSharedRoot");function Os(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(Os,"sliceMatchesDeclaration");function Ba(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Os(r.from,t)&&Os(r.to,n))}i(Ba,"crossSliceEdgeAllowed");function za(e){if(!e.fromPath||!e.toPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0,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(za,"peerIsolationDecision");function xs(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(xs,"peerIsolationDenyExplanation");function _e(e,t,n,r){return or(e,t,n,r)?.rule}i(_e,"findDeniedEdgeRule");function or(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=Ua(s,t,r?.layers),c=o&&a?Ss(o,l):void 0,p=o&&a?Ss(a,l):void 0,g=za({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p,fromShared:!c&&Cs(o,s.sharedRoots),toShared:!p&&Cs(a,s.sharedRoots),crossSliceAllowed:Ba(s.allowedCrossSlice,c,p)});if(g.denied)return{rule:s,peerIsolationReason:g.reason,fromSlice:c,toSlice:p};continue}if(t!==n)return{rule:s}}}i(or,"findDeniedEdgeDecision");function He(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(He,"literalText");function Ls(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Ls,"lineOf");function Ts(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(Ts,"isTypeOnlyReference");function Ps(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(Ps,"singleFileChecker");function ar(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(ar,"symbolAt");function ir(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):ar(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(ir,"localDeclaration");function xe(e,t){let n,r=[],s=i((a,l,c,p=!1)=>r.push({specifier:c,kind:l,line:Ls(t,a),typeOnly:p,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",He(e,a.moduleSpecifier),Ts(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",He(e,a.moduleSpecifier),Ts(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",He(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!ir(e,n??(n=Ps(e,t)),t,a.expression);(l||p)&&s(a,p?"require":"dynamic-import",He(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i(xe,"extractSemanticDependencies");function qa(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=He(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(qa,"staticAccessPath");function Wa(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(Wa,"runtimeIdentifierReference");function Ns(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(Ns,"bestForbiddenMatch");function Te(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Ps(e,t),o=new Map,a=new Set;for(let m of t.statements)if(e.isVariableStatement(m))for(let u of m.declarationList.declarations)e.isIdentifier(u.name)&&a.add(u.name.text);let l=i(m=>{let u=qa(e,m);if(!u)return;let f=ar(s,u.root),A=f?o.get(f):void 0;return A?[...A,...u.segments.slice(1)]:ir(e,s,t,u.root)||a.has(u.root.text)?void 0:u.segments},"resolvePath");for(let m of t.statements)if(e.isVariableStatement(m))for(let u of m.declarationList.declarations){if(!u.initializer||!e.isIdentifier(u.name))continue;let f=l(u.initializer),A=ar(s,u.name);!f||!A||o.set(A,f)}let c=[],p=new Set,g=i((m,u)=>{let f=Ls(t,u),A=`${m}:${u.getStart(t)}`;p.has(A)||(p.add(A),c.push({name:m,line:f,node:u}))},"flag"),y=i(m=>{let u=m.parent&&(e.isPropertyAccessExpression(m.parent)||e.isElementAccessExpression(m.parent))&&m.parent.expression===m;if((e.isPropertyAccessExpression(m)||e.isElementAccessExpression(m))&&!u){let f=l(m),A=f?Ns(r,f):void 0;A&&g(A,m)}else e.isIdentifier(m)&&r.has(m.text)&&Wa(e,m)&&!ir(e,s,t,m)&&g(m.text,m);if(e.isVariableDeclaration(m)&&e.isObjectBindingPattern(m.name)&&m.initializer){let f=l(m.initializer);if(f)for(let A of m.name.elements){if(!e.isIdentifier(A.name))continue;let v=A.propertyName?He(e,A.propertyName)??A.propertyName.text:A.name.text,_=Ns(r,[...f,v]);_&&g(_,m.initializer)}}e.forEachChild(m,y)},"visit");return y(t),c}i(Te,"collectForbiddenCapabilityUses");function lr(e,t,n){let r=[];for(let s of n?.dependencies??xe(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Qe(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Te(e,t,rr)){let o=Ut(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(lr,"collectCapabilityUses");var cr={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},dr=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 ur(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(ur,"resolveIntentLayer");function Ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ne,"looksLikeArkIntent");function tt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:cr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:cr.PUBLISH_MISSING_SOURCE}),t}i(tt,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function je(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}i(je,"lineOf");function Ya(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}i(Ya,"extractQuotedStrings");function Xa(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(Xa,"extractModuleSpecifiers");function Ja(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(o=>{e.isStringLiteralLike(o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)},"visit");return s(n),r}i(Ja,"extractQuotedStringsAst");function Za(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(Za,"hasInfrastructureToken");function Qa(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(Qa,"isKnownInfrastructurePackage");function ei(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(ei,"layerHasInfrastructureRole");function rt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(rt,"tsStringLiteralText");function ti(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(ti,"tsPropertyName");function ws(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ti(e,r.name)===n)}i(ws,"tsObjectProperty");function st(e,t,n){return ws(e,t,n)!==void 0}i(st,"tsObjectHasProperty");function nt(e,t,n){let r=ws(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(nt,"tsObjectPropertyValue");function ni(e,t){let n=nt(e,t,"metadata");return st(e,n,"source")}i(ni,"tsObjectHasMetadataSource");function Ds(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ds(e,t.name):!1:!1}i(Ds,"tsLooksLikeIntentCreatorExpression");function ri(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(ri,"tsIsPublishCall");function si(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=rt(e,n);return r!==void 0&&Ne(r)||st(e,n,"intent")||Ds(e,n)}i(si,"tsIsArkPublishCandidate");function oi(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return ni(e,n)||st(e,r,"source")||st(e,s,"source")}i(oi,"tsPublishHasSource");function ai(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=nt(e,n,"metadata");return rt(e,nt(e,o,"source"))??rt(e,nt(e,r,"source"))??rt(e,nt(e,s,"source"))}i(ai,"tsPublishSourceLiteral");function ii(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=n,a=o?.filePath,l=o?.layer,c=[],p=i(y=>s.getLineAndCharacterOfPosition(y.getStart(s)).line+1,"lineForNode"),g=i(y=>{if(ri(e,y)){let m=y.arguments[0],u=rt(e,m);for(let A of tt({publishCall:!0,rawIntentName:u,objectHasIntent:st(e,m,"intent"),arkPublishCandidate:si(e,y),hasSource:oi(e,y)}))c.push(W(A.ruleId,A.message,{line:p(y),filePath:a}));let f=ai(e,y);if(r&&l&&f&&Ne(f)){let A=r.resolveLayer(f);A&&A!==l&&c.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${A}, but the target file is classified as ${l}.`,{line:p(y),filePath:a,target:f,fromLayer:l,toLayer:A}))}}e.forEachChild(y,g)},"visit");return g(s),c}i(ii,"analyzePublishAst");function pr(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,p=c?.filePath,g=c?.layer,y=e.typescript,m=y?y.createSourceFile(p??"generated.ts",o,y.ScriptTarget.Latest,!0):void 0,u=m?xe(e.typescript,m):void 0,f=u?u.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(m),kind:R.kind,typeOnly:R.typeOnly})):Xa(o),A=e.typescript?Ja(e.typescript,o):Ya(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let R of u?.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:p}))}let v=g!==void 0&&(r.has(g)||ei(g)),_=g!==void 0?` If "${g}" 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:je(o,I.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+_}))}else o.includes(R)&&l.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:je(o,o.indexOf(R)),filePath:p}));for(let R of f){let I=e.resolveImportTarget?.(R.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,p)}:void 0),C=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,H=I?.layer;if(H&&g){let k=_e(e.architectureProfile?.rules,g,H,{fromPath:C?.relPath,toPath:I?.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 "${g}" must not import across slices into "${H}".`:`Layer "${g}" must not import "${H}".`),{line:je(o,R.index),source:R.value,target:R.value,filePath:p,fromLayer:g,toLayer:H,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}v||R.typeOnly||!Za(R.value)&&!Qa(R.value)||l.push(W("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:je(o,R.index),source:R.value,target:R.value,filePath:p,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 I=R.check({source:o,context:a});if(I!==!0)if(Array.isArray(I))for(let C of I)l.push(W("POLICY_VIOLATION",C.message,{filePath:p,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)Ne(R.value)&&!t.has(R.value)&&l.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:je(o,R.index),filePath:p,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let R of A){if(!Ne(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let C=_e(e.architectureProfile.rules,g,I);C&&l.push(W("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${I}" through "${R.value}".`,{line:je(o,R.index),filePath:p,target:R.value,fromLayer:g,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}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&&m&&g&&e.forbiddenGlobals?.[g]?.length)try{let R=e.forbiddenGlobals[g];l.push(...Te(e.typescript,m,R).map(I=>W("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${I.name}".`,{line:I.line,filePath:p,target:I.name,fromLayer:g,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 u??[]){if(I.typeOnly||!I.specifier)continue;let C=ve(I.specifier,R);C&&l.push(W("FORBIDDEN_GLOBAL",`${g} must not use module "${I.specifier}" because it is the import form of forbidden global "${C}".`,{line:I.line,filePath:p,source:I.specifier,target:I.specifier,fromLayer:g,details:{importKind:I.kind,forbiddenGlobal:C},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&&m&&g&&e.capabilityWalls?.[g]?.length)try{let R=new Set(e.capabilityWalls[g]),I=e.forbiddenGlobals?.[g]??[];for(let C of lr(e.typescript,m))R.has(C.capability)&&(C.source==="ambient-global"&&et(C.symbol,I)||C.source==="import-based"&&ve(C.symbol,I)||l.push(W("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:p,target:C.symbol,capability:C.capability,fromLayer:g,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(...ii(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(pr,"createAICodeGate");var Ve={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ms={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Ve,default:[]},kernelRoots:{...Ve},managedLayers:{...Ve,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Fs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Ve,default:[]},managedLayers:{...Ve,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Ve,default:[]}}};function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ot,"isObject");function $s(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)ot(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i($s,"declaredLayerNames");function Hs(e){if(!ot(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(Hs,"defaultedArkRun");function js(e){if(!ot(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(js,"defaultedArkOrder");function Vs(e,t){let n=e.arkRun;if(n===void 0||!ot(n))return;let r=$s(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(Vs,"validateArkRunExtra");function Us(e,t){let n=e.arkOrder;if(n===void 0||!ot(n))return;let r=$s(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(Us,"validateArkOrderExtra");var ne="1.3",zt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ks=["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 ci(){let e=[];for(let t of Ks)for(let n of Ks)t===n||li.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(ci,"createDefaultRules");var Wt=ci(),fr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:zt,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:zt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ne,default:ne},name:{type:"string",minLength:1},include:{...le,minItems:1,default:["src"]},exclude:{...le,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Wt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...le,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...le,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...le,minItems:1},exclude:le,intentPrefixes:le,description:{type:"string",minLength:1},forbiddenGlobals:le,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...le,minItems:1},sharedRoots:{...le,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; 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:{...le,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...le,minItems:1}}},arkRun:Ms,arkOrder:Fs}},ye=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
1
|
+
"use strict";var Ft=Object.defineProperty;var Oa=Object.getOwnPropertyDescriptor;var _a=Object.getOwnPropertyNames;var xa=Object.prototype.hasOwnProperty;var i=(e,t)=>Ft(e,"name",{value:t,configurable:!0});var Ta=(e,t)=>{for(var n in t)Ft(e,n,{get:t[n],enumerable:!0})},Na=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _a(t))!xa.call(e,s)&&s!==n&&Ft(e,s,{get:()=>t[s],enumerable:!(r=Oa(t,s))||r.enumerable});return e};var La=e=>Na(Ft({},"__esModule",{value:!0}),e);var oc={};Ta(oc,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Yn,AGENT_PROJECTION_BEGIN_MARKER:()=>pa,AGENT_PROJECTION_END_MARKER:()=>Qr,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Vn,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>es,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>os,AGENT_SKILL_ENTRY_FILENAME:()=>is,ANALYSIS_IR_SCHEMA_VERSION:()=>en,ARKORDER_RULE_IDS:()=>Nn,ARKORDER_TIER1_SENSOR_IDS:()=>To,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>Tr,ARKRUN_KERNEL_FACTORY_CALLEES:()=>_r,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>ko,ARKRUN_RULE_IDS:()=>Tn,ARKRUN_TIER1_SENSOR_IDS:()=>So,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>xr,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>ua,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Ea,ARK_ANALYSIS_RESULT_SCHEMA:()=>As,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>jt,ARK_CONFIG_SCHEMA:()=>Yt,ARK_CONFIG_SCHEMA_VERSION:()=>ne,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Uo,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Vo,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Tt,ARK_PROJECT_IDENTITY_SCHEMA:()=>ks,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>Zn,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>Rs,ARK_RULES_SCHEMA:()=>nn,ARK_RULES_SCHEMA_VERSION:()=>Zs,ARK_RULE_SENSORS:()=>Ar,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>wr,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>zn,ARK_SKILL_NAMES:()=>wt,ARK_SKILL_NAME_COUNT:()=>ls,ARK_STATUS_MANIFEST_SCHEMA:()=>na,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Fr,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>Mn,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>fa,DIAGNOSTIC_CATALOG:()=>Ct,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ko,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Dn,DIAGNOSTIC_RULE_IDS:()=>Go,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>yo,EffectiveContractError:()=>yt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>as,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>Ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Lt,IMPROVEMENT_LENS_IDS:()=>Nt,MERGE_PLANES_DUAL_STAMP:()=>Cr,POLICY_DELTA_SCHEMA_VERSION:()=>cn,PROJECT_BINDING_SCHEMA:()=>er,PROJECT_EXPECTATION_SCHEMA:()=>Qn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Qt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>ve,STATUS_COMPASS_FACTS_SOURCES:()=>Hr,STATUS_COMPASS_MODES:()=>$r,STATUS_COMPASS_REASON_CODES:()=>xt,adapterDocsCodePath:()=>Xn,adapterFindingOccurrenceTargetKeys:()=>$t,adapterFindingRefFromTargetKey:()=>Jn,adapterFindingTargetKey:()=>Vt,agentProjectionContentIdentity:()=>Pt,agentSkillEntryRelativePath:()=>ms,agentSkillPackageFileRelativePath:()=>ba,analyzeArchitectureConvergence:()=>Pe,analyzeChange:()=>kt,analyzePolicyDelta:()=>Ir,analyzeProject:()=>ze,analyzeResolvedProject:()=>Ye,arkRunKernelCallKind:()=>vn,buildAgentProjectionBeginMarker:()=>ns,buildAgentProjectionBlock:()=>ya,buildAgentProjectionBody:()=>Kn,buildAgentProjectionMeta:()=>ha,buildArkRuleFileHints:()=>An,buildEffectiveArkRules:()=>rn,buildImprovementCompass:()=>ca,buildRulesInventory:()=>Ho,buildStatusManifest:()=>Zo,canPromoteInvariant:()=>an,catalogFixForRuleId:()=>Yo,catalogWhyForRuleId:()=>Jo,classifyArkPolicyDelta:()=>dn,classifyResolvedLayerCoverage:()=>kn,classifyStatusWritePath:()=>Vr,collectAnalysisConfigWarnings:()=>bt,collectEmptyAppliesToFindings:()=>hn,collectForbiddenCapabilityUses:()=>Te,composeMergePlanesHonesty:()=>In,createAICodeGate:()=>fr,createAdapterResult:()=>hs,createArchitectureProfile:()=>dt,createArchitectureProfileFromArkConfig:()=>gr,createElevenLayerArkConfig:()=>yr,createProjectId:()=>Es,createProjectIdentity:()=>Is,createResolvedCandidateFacts:()=>Zt,defaultHonestLabel:()=>Ur,demoteExtraPlaneTeethUnderClassificationFloor:()=>Ao,deriveArkRuleFileHints:()=>Sr,detectArchitectureCycles:()=>fn,deterministicHash:()=>J,diagnosticDocsFragment:()=>Mr,diagnosticDocsPath:()=>qo,effectiveContractPolicyPayload:()=>sn,elevenLayerProfile:()=>ct,emptyEffectiveArkRules:()=>Se,evaluateArchitectureGraph:()=>Me,evaluateArkOrderSensors:()=>Ln,evaluateArkRuleSensors:()=>yn,evaluateArkRunEditorSensors:()=>Nr,evaluateArkRunEditorSensorsFromSource:()=>Co,evaluateArkRunSensors:()=>St,evaluateInvariantCoverage:()=>on,evaluateStatusBinding:()=>jr,explainViolation:()=>vr,extraMergeTeethAllowed:()=>me,extractAgentProjectionBlock:()=>jn,extractArkRunDeclarationsFromSource:()=>Eo,extractArkRunImportedConstructorNamesFromSource:()=>On,extractArkRunKernelCallsFromSource:()=>_n,extractArkRunManagedNewsFromSource:()=>xn,extractArkRunValueImportDependenciesFromSource:()=>Cn,extractClassShapesFromSource:()=>go,extractSemanticDependencies:()=>xe,flatSkillTemplateFileRelativePath:()=>Ca,formatAgentProjectionCatalogShortList:()=>rs,formatAgentProjectionLayers:()=>Hn,formatArkRunDoctorLines:()=>Do,formatImprovementCompassDoctorLines:()=>da,formatImprovementCompassResidualLabels:()=>Xr,getDiagnosticCatalogEntry:()=>Ot,inventoryToExtractionCard:()=>jo,isArkOrderRuleId:()=>ho,isArkRunKernelModuleSpecifier:()=>We,isArkRunRuleId:()=>En,isArkRunTransportBypassSpecifier:()=>Sn,isArkSkillName:()=>Bn,isCataloguedOrArkRuleFamily:()=>zo,isExtraPlaneFinding:()=>br,isKnownDiagnosticCode:()=>Bo,isValidAgentSkillName:()=>cs,loadArkConfigContract:()=>lt,loadArkRulesContract:()=>gt,loadContract:()=>Rt,loadResolvedCandidateFacts:()=>Re,mergeAgentProjectionDocument:()=>ka,normalizeExtraMergeTeethClassification:()=>Rn,normalizeSkillContent:()=>Gn,normalizeStatusImprovementCompass:()=>Gr,parseAgentProjectionStamp:()=>ss,parseArkConfigJson:()=>Xt,parseArkRulesJson:()=>Qs,parseSkillDescriptionVersion:()=>va,parseSkillDocument:()=>ds,policyDeltaAcknowledgementMatches:()=>un,preflightChange:()=>Lr,preflightResolvedChange:()=>Pr,primaryImprovementCompassNextAction:()=>Zr,projectStatusArkRun:()=>Pn,projectStatusImprovementCompass:()=>Fn,projectionHasNonEnforcementLabel:()=>Ra,projectionMatchesPackageVersion:()=>Aa,resolveEffectiveContract:()=>to,resolveStatusNextAction:()=>Kr,resolvedFactsEvidenceRequirementsHash:()=>Be,serializeDiagnosticCatalog:()=>Wo,skillDescriptionVersionPrefix:()=>ps,stableSerialize:()=>$,stampSkillDescription:()=>Sa,statusCompassResidualIsSubsetOfDoctor:()=>ta,stripSkillDescriptionVersion:()=>fs,summarizeArkRunSection:()=>wo,toAdapterDiagnostic:()=>Ht,unavailableStatusImprovementCompass:()=>ea,validateAgentSkillDocument:()=>us,validateAgentSkillsPackage:()=>Ia,version:()=>gs});module.exports=La(oc);var gs="4.8.9";var Pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,wa=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Da=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ma(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(wa.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Da.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(Ma,"classifyLayerImportKind");function Fa(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=Ma(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(Fa,"layerImportNextAction");function $a(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i($a,"arkRunCallSiteName");function Ha(e){let t=$a(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(Ha,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Fa(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 Ha(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(fe,"deterministicNextAction");var jt="1.5",Yn="docs/diagnostics.md";function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function ys(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(ys,"positiveInteger");function Vt(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(Vt,"adapterFindingTargetKey");function $t(e){let t=new Map;return e.map(n=>{let r=Vt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}i($t,"adapterFindingOccurrenceTargetKeys");function Jn(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(Jn,"adapterFindingRefFromTargetKey");function Xn(e){return`${Yn}#${e}`}i(Xn,"adapterDocsCodePath");function ja(e,t,n){return fe({ruleId:e,target:O(t.target)??O(n.target)??void 0,fromLayer:O(t.fromLayer)??void 0,toLayer:O(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:O(t.edgeKind)??void 0,capability:O(t.capability)??O(n.capability)??void 0,arkruleId:O(t.arkruleId)??void 0,arkruleSource:O(t.arkruleSource)??void 0})}i(ja,"nextActionForDiagnostic");function Ht(e,t="error",n){let r=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=n??Vt(e),l=Jn(a);return{ruleId:r,severity:s,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:ys(e.line,1),column:ys(e.column,1)},evidence:o,nextAction:O(e.nextAction)??ja(r,o,e),findingRef:l,targetKey:a,docsCodePath:Xn(r)}}i(Ht,"toAdapterDiagnostic");function hs(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: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(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=$t(o),c=$t(a),u=[...o.map((y,g)=>Ht(y,"error",l[g])),...a.map((y,g)=>Ht(y,"warning",c[g]))],m={schemaVersion:jt,completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...m,mode:n,valid:!1,completeness:t,...s};let y={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...y}:{...m,mode:n,valid:!1,completeness:t,...y}}return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...s}:{...m,mode:n,valid:!1,completeness:t,...s}}i(hs,"createAdapterResult");var As={$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:jt},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}}}}}};var Rs="1.0",Zn="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Ut="^sha256:[a-f0-9]{64}$",Qn={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:Ut,description:"Project id previously returned by ark_identity or ark_manifest."}}},er={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:Ut},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},ks={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Zn,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:Ut},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Ut},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Qn,binding:er}};function Es(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(Es,"createProjectId");function Is(e){return{schemaVersion:"1.0",...e}}i(Is,"createProjectIdentity");var nr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),sr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),or=Object.freeze(Object.keys(sr).sort()),tr=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),rr=Object.freeze({process:Object.freeze(["process","node:process"])});function et(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=tr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=tr[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:tr[e.slice(0,o)]??null}i(et,"capabilityForModuleSpecifier");function Ie(e,t){for(let n of t)if(rr[n]?.includes(e))return n;return null}i(Ie,"forbiddenGlobalForModuleSpecifier");function Kt(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=sr[r];if(s)return s}return null}i(Kt,"capabilityForAmbientName");function He(e){if(e?.pure===!0)return[...nr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>nr.includes(r));return[...new Set(n)].sort()}i(He,"effectiveCapabilityDeny");function tt(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(tt,"ambientCoveredByForbiddenGlobals");function Gt(e){let t=new Set,n=new Set,r=Object.keys(sr);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 rr[s]??[])t.add(`import-exact:${a}`)}for(let s of He(e)){if(t.add(`import:${s}`),s==="process")for(let o of rr.process)t.add(`import-exact:${o}`);for(let o of r)Kt(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Gt,"loweredLayerCoverage");var vs=new Map;function Ss(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Ss,"escapeLiteral");function Bt(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(Bt,"normalizeGlobSeparators");function Va(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(Va,"bracesBalanced");function ge(e){let t=vs.get(e);if(t)return t;let n=Bt(e),r=Va(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=Ss(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+=Ss(c)}let a=new RegExp(`^${s}$`);return vs.set(e,a),a}i(ge,"globToRegExp");function Ua(e){return Bt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Ua,"concreteGlobSegments");function ar(e,t){let n=Bt(String(e)),r=Ua(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 m=-1;for(let y=l;y<a.length;y+=1)if(a[y]===u){m=y;break}if(m<0)return o;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+s}i(ar,"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=ar(a,n);l>s&&(s=l,r=o.name)}}return r}i(de,"layerForRelativePath");function bs(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(bs,"sliceIdForPath");function Ka(e){let t=new Set;for(let n of e??[]){let s=Bt(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(Ka,"inferSliceFoldersFromPatterns");function Ga(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 Ka(r?.patterns)}i(Ga,"resolveSliceFolders");function Cs(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Cs,"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 Ba=["src","app"];function za(e){let t=xs(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(za,"isBlanketRoot");function Os(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=Cs(n);for(let o of t){if(typeof o!="string"||o.length===0||za(o))continue;if(o.includes("*")){let c=xs(o.toLowerCase());if(ge(c).test(r)||ge(`${c}/**`).test(r))return!0;continue}let a=Cs(o);if(a.length===0)continue;let l=Ba.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 m=0;m<a.length;m+=1)if(s[c+m]!==a[m]){u=!1;break}if(u)return!0}}return!1}i(Os,"pathUnderSharedRoot");function _s(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(_s,"sliceMatchesDeclaration");function qa(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&_s(r.from,t)&&_s(r.to,n))}i(qa,"crossSliceEdgeAllowed");function Wa(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(Wa,"peerIsolationDecision");function je(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(je,"peerIsolationDenyExplanation");function zt(e,t,n,r){return _e(e,t,n,r)?.rule}i(zt,"findDeniedEdgeRule");function _e(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=Ga(s,t,r?.layers),c=o?bs(o,l):void 0,u=a?bs(a,l):void 0,m=Wa({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:u,fromShared:!c&&Os(o,s.sharedRoots),toShared:!u&&Os(a,s.sharedRoots),crossSliceAllowed:qa(s.allowedCrossSlice,c,u)});if(m.denied)return{rule:s,peerIsolationReason:m.reason,fromSlice:c,toSlice:u};continue}if(t!==n)return{rule:s}}}i(_e,"findDeniedEdgeDecision");function Ve(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ve,"literalText");function Ls(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Ls,"lineOf");function Ts(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(Ts,"isTypeOnlyReference");function Ps(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(Ps,"singleFileChecker");function ir(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(ir,"symbolAt");function lr(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):ir(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(lr,"localDeclaration");function xe(e,t){let n,r=[],s=i((a,l,c,u=!1)=>r.push({specifier:c,kind:l,line:Ls(t,a),typeOnly:u,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",Ve(e,a.moduleSpecifier),Ts(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Ve(e,a.moduleSpecifier),Ts(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Ve(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!lr(e,n??(n=Ps(e,t)),t,a.expression);(l||u)&&s(a,u?"require":"dynamic-import",Ve(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i(xe,"extractSemanticDependencies");function Ya(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=Ve(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(Ya,"staticAccessPath");function Ja(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(Ja,"runtimeIdentifierReference");function Ns(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(Ns,"bestForbiddenMatch");function Te(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Ps(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=Ya(e,g);if(!p)return;let f=ir(s,p.root),A=f?o.get(f):void 0;return A?[...A,...p.segments.slice(1)]:lr(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 f=l(p.initializer),A=ir(s,p.name);!f||!A||o.set(A,f)}let c=[],u=new Set,m=i((g,p)=>{let f=Ls(t,p),A=`${g}:${p.getStart(t)}`;u.has(A)||(u.add(A),c.push({name:g,line:f,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 f=l(g),A=f?Ns(r,f):void 0;A&&m(A,g)}else e.isIdentifier(g)&&r.has(g.text)&&Ja(e,g)&&!lr(e,s,t,g)&&m(g.text,g);if(e.isVariableDeclaration(g)&&e.isObjectBindingPattern(g.name)&&g.initializer){let f=l(g.initializer);if(f)for(let A of g.name.elements){if(!e.isIdentifier(A.name))continue;let v=A.propertyName?Ve(e,A.propertyName)??A.propertyName.text:A.name.text,_=Ns(r,[...f,v]);_&&m(_,g.initializer)}}e.forEachChild(g,y)},"visit");return y(t),c}i(Te,"collectForbiddenCapabilityUses");function cr(e,t,n){let r=[];for(let s of n?.dependencies??xe(e,t)){if(s.typeOnly||!s.specifier)continue;let o=et(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Te(e,t,or)){let o=Kt(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(cr,"collectCapabilityUses");var dr={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."},ur=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 pr(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(pr,"resolveIntentLayer");function Ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Ne,"looksLikeArkIntent");function nt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:dr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:dr.PUBLISH_MISSING_SOURCE}),t}i(nt,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function Ue(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}i(Ue,"lineOf");function Xa(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}i(Xa,"extractQuotedStrings");function Za(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(Za,"extractModuleSpecifiers");function Qa(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(o=>{e.isStringLiteralLike(o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)},"visit");return s(n),r}i(Qa,"extractQuotedStringsAst");function ei(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(ei,"hasInfrastructureToken");function ti(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(ti,"isKnownInfrastructurePackage");function ni(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(ni,"layerHasInfrastructureRole");function st(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(st,"tsStringLiteralText");function ri(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(ri,"tsPropertyName");function ws(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ri(e,r.name)===n)}i(ws,"tsObjectProperty");function ot(e,t,n){return ws(e,t,n)!==void 0}i(ot,"tsObjectHasProperty");function rt(e,t,n){let r=ws(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(rt,"tsObjectPropertyValue");function si(e,t){let n=rt(e,t,"metadata");return ot(e,n,"source")}i(si,"tsObjectHasMetadataSource");function Ds(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ds(e,t.name):!1:!1}i(Ds,"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 ai(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=st(e,n);return r!==void 0&&Ne(r)||ot(e,n,"intent")||Ds(e,n)}i(ai,"tsIsArkPublishCandidate");function ii(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return si(e,n)||ot(e,r,"source")||ot(e,s,"source")}i(ii,"tsPublishHasSource");function li(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=rt(e,n,"metadata");return st(e,rt(e,o,"source"))??st(e,rt(e,r,"source"))??st(e,rt(e,s,"source"))}i(li,"tsPublishSourceLiteral");function ci(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"),m=i(y=>{if(oi(e,y)){let g=y.arguments[0],p=st(e,g);for(let A of nt({publishCall:!0,rawIntentName:p,objectHasIntent:ot(e,g,"intent"),arkPublishCandidate:ai(e,y),hasSource:ii(e,y)}))c.push(W(A.ruleId,A.message,{line:u(y),filePath:a}));let f=li(e,y);if(r&&l&&f&&Ne(f)){let A=r.resolveLayer(f);A&&A!==l&&c.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${A}, but the target file is classified as ${l}.`,{line:u(y),filePath:a,target:f,fromLayer:l,toLayer:A}))}}e.forEachChild(y,m)},"visit");return m(s),c}i(ci,"analyzePublishAst");function fr(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,m=c?.layer,y=e.typescript,g=y?y.createSourceFile(u??"generated.ts",o,y.ScriptTarget.Latest,!0):void 0,p=g?xe(e.typescript,g):void 0,f=p?p.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(g),kind:R.kind,typeOnly:R.typeOnly})):Za(o),A=e.typescript?Qa(e.typescript,o):Xa(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 v=m!==void 0&&(r.has(m)||ni(m)),_=m!==void 0?` If "${m}" 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:Ue(o,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+_}))}else o.includes(R)&&l.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:Ue(o,o.indexOf(R)),filePath:u}));for(let R of f){let I=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:m,relPath:void 0}:void 0):void 0,D=I?.layer;if(D&&m){let k=zt(e.architectureProfile?.rules,m,D,{fromPath:b?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(k){if(R.typeOnly&&!k.peerIsolation)continue;let T=!!k.peerIsolation;l.push(W("LAYER_IMPORT_VIOLATION",k.message??(T?`Layer "${m}" must not import across slices into "${D}".`:`Layer "${m}" must not import "${D}".`),{line:Ue(o,R.index),source:R.value,target:R.value,filePath:u,fromLayer:m,toLayer:D,suggestion:T?"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:T,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}v||R.typeOnly||!ei(R.value)&&!ti(R.value)||l.push(W("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:Ue(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 I=R.check({source:o,context:a});if(I!==!0)if(Array.isArray(I))for(let b of I)l.push(W("POLICY_VIOLATION",b.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)Ne(R.value)&&!t.has(R.value)&&l.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:Ue(o,R.index),filePath:u,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let R of A){if(!Ne(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let b=_e(e.architectureProfile.rules,m,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(b){let D=b.rule.peerIsolation?je(b.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:b.fromSlice,toSlice:b.toSlice}):void 0,k=`Layer "${m}" must not reference "${I}" through "${R.value}".`,T=D&&b.peerIsolationReason!=="cross-slice"?`${k} ${D}`:b.rule.message?D?`${b.rule.message} (${D})`:b.rule.message:k;l.push(W("LAYER_REFERENCE_VIOLATION",T,{line:Ue(o,R.index),filePath:u,target:R.value,fromLayer:m,toLayer:I,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 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&&m&&e.forbiddenGlobals?.[m]?.length)try{let R=e.forbiddenGlobals[m];l.push(...Te(e.typescript,g,R).map(I=>W("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:m,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 b=Ie(I.specifier,R);b&&l.push(W("FORBIDDEN_GLOBAL",`${m} must not use module "${I.specifier}" because it is the import form of forbidden global "${b}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:m,details:{importKind:I.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&&m&&e.capabilityWalls?.[m]?.length)try{let R=new Set(e.capabilityWalls[m]),I=e.forbiddenGlobals?.[m]??[];for(let b of cr(e.typescript,g))R.has(b.capability)&&(b.source==="ambient-global"&&tt(b.symbol,I)||b.source==="import-based"&&Ie(b.symbol,I)||l.push(W("CAPABILITY_VIOLATION",b.source==="import-based"?`${m} denies the ${b.capability} capability; found import of "${b.symbol}".`:`${m} denies the ${b.capability} capability; found ambient "${b.symbol}".`,{line:b.line,filePath:u,target:b.symbol,capability:b.capability,fromLayer:m,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(...ci(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(fr,"createAICodeGate");var Le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ms={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Le,default:[]},kernelRoots:{...Le},managedLayers:{...Le,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Fs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Le,default:[]},managedLayers:{...Le,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Le,default:[]},appliesTo:{...Le,default:[]}}};function at(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(at,"isObject");function $s(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)at(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i($s,"declaredLayerNames");function Hs(e){if(!at(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Hs,"defaultedArkRun");function js(e){if(!at(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(js,"defaultedArkOrder");function Vs(e,t){let n=e.arkRun;if(n===void 0||!at(n))return;let r=$s(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(Vs,"validateArkRunExtra");function Us(e,t){let n=e.arkOrder;if(n===void 0||!at(n))return;let r=$s(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(Us,"validateArkOrderExtra");var ne="1.3",Wt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ks=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],di=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function ui(){let e=[];for(let t of Ks)for(let n of Ks)t===n||di.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(ui,"createDefaultRules");var Jt=ui(),mr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Yt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Wt,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:Wt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ne,default:ne},name:{type:"string",minLength:1},include:{...le,minItems:1,default:["src"]},exclude:{...le,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Jt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...le,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...le,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...le,minItems:1},exclude:le,intentPrefixes:le,description:{type:"string",minLength:1},forbiddenGlobals:le,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...le,minItems:1},sharedRoots:{...le,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; 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:{...le,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...le,minItems:1}}},arkRun:Ms,arkOrder:Fs}},ye=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
3
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Gs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Gs,"isObject");function Bt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(Bt,"propertyPath");function Ue(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Ue,"valueType");function di(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(di,"resolveSchemaRef");function at(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}at(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(!Gs(e)){s.push({path:n,message:`must be an object; received ${Ue(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:Bt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:Bt(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||at(e[l],a,Bt(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&at(e[a],l,Bt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ue(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)=>at(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 ${Ue(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 ${Ue(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ue(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(at,"validateNode");function ui(e){let t={...e,$schema:e.$schema===void 0?zt: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?Wt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Hs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=js(e.arkOrder)),t}i(ui,"defaultedConfig");function pi(e){return e===ne?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(pi,"migratedFromOf");function fi(){let e=new Set([ne]);for(let t of fr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(fi,"knownInputVersions");function mi(e,t="ark.config.json"){if(!Gs(e))throw new ye(t,[{path:"$",message:`must be an object; received ${Ue(e)}`}]);let n=fi(),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 ${ne}`}]);if(r!=="unversioned"&&!n.has(r))throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ne}`}]);let s=r,o={...e},a=0;for(;s!==ne&&a<fr.length+1;){a+=1;let l=fr.find(c=>c.from===s);if(!l)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${ne}`}]);s=l.to,o.schemaVersion=s}if(s!==ne)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ne}`}]);return{candidate:ui(o),migratedFrom:pi(r)}}i(mi,"migrateArkConfig");function it(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=mi(e,t),s=[];if(at(n,qt,"$",qt,s),Vs(n,s),Us(n,s),s.length>0)throw new ye(t,s);return{config:n,migratedFrom:r}}i(it,"loadArkConfigContract");function Yt(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 it(n,t)}i(Yt,"parseArkConfigJson");function Bs(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:zt,schemaVersion:ne};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Bs,"withArkConfigMetadata");function gi(e){return e.endsWith(".")?e:`${e}.`}i(gi,"normalizePrefix");function yi(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(yi,"byLongestPrefix");function ct(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(gi)})),n=[...t].sort(yi),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(ct,"createArchitectureProfile");function mr(e,t={}){return ct({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(mr,"createArchitectureProfileFromArkConfig");var hi=[{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}],lt=ct({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:hi,rules:Wt.map(e=>({...e}))}),Ai={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 gr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Bs({include:e.include??[t],layers:lt.layers.map(s=>({name:s.name,patterns:(Ai[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...lt.rules]})}i(gr,"createElevenLayerArkConfig");function X(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(X,"deterministicHash");function 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(n=>`${JSON.stringify(n)}:${F(t[n])}`).join(",")}}`}i(F,"stableSerialize");var Se="1.2";var zs=["network","filesystem","clock","randomness","environment","process","persistence"];function Y(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}i(Y,"compareCanonical");function J(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(J,"sortedUnique");function Ge(e){let t={schemaVersion:"1.2",include:J(e.include??[]),exclude:J(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:J(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:J(n.patterns??[]),exclude:J(n.exclude??[]),forbiddenGlobals:J(n.forbiddenGlobals??[]),intentPrefixes:J(n.intentPrefixes??[]),capabilityDeny:J(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(Y),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:J(e.arkRun.compositionRoots),managedLayers:J(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return X(F(t))}i(Ge,"resolvedFactsEvidenceRequirementsHash");function Ri(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(Y),n=e.files.map(k=>({...k,typeOnlyExportNames:J(k.typeOnlyExportNames)})).sort((k,L)=>k.path<L.path?-1:k.path>L.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:J(k.namedBindings)}:{}})).sort(Y),s=e.capabilityUses.map(k=>({...k})).sort(Y),o=e.ambientUses.map(k=>({...k})).sort(Y),a=e.publishCalls.map(k=>({...k})).sort(Y),l=e.intentReferences.map(k=>({...k})).sort(Y),c=e.safetyUses.map(k=>({...k})).sort(Y),p=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(L=>({...L}))})).sort(Y),g=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(Y),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(Y),m=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(Y),u=(e.arkRunDeclarations??[]).map(k=>({...k,uses:J(k.uses),reactsTo:J(k.reactsTo),raises:J(k.raises),sends:J(k.sends)})).sort(Y),f=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(Y),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(Y),v=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(Y),_=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(Y),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(Y),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(Y),C=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),H=X(F(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:H,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:p,arkRunKernelCalls:g,arkRunManagedNews:y,arkRunCompositionRootHits:m,arkRunDeclarations:u,arkOrderPlaneCalls:f,arkOrderGenericUpdates:A,arkOrderRootHits:v,arkOrderXiFieldWrites:_,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:I}}i(Ri,"canonicalResolvedFactsInput");function qs(e){let t=Ri(e);return{...t,factsHash:X(F(t))}}i(qs,"createCanonicalResolvedCandidateFacts");function Xt(e){return qs(Ys($(e,"$"),!1))}i(Xt,"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 U(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(U,"assertOnlyKeys");function M(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(M,"requiredText");function he(e,t,n){if(e[t]!==void 0)return M(e,t,n)}i(he,"optionalText");function G(e,t,n){let r=M(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(G,"requiredProjectPath");function B(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(B,"requiredBoolean");function Ws(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(Ws,"requiredInteger");function Q(e,t,n){let r=Ws(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Q,"requiredPositiveInteger");function z(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(z,"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 Ke(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(Ke,"parseStringArray");function ki(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(ki,"assertUnique");function Ys(e,t){U(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ae(e,"completeness",["complete","partial","unavailable"],"$"),s=z(e,"completenessReasons","$").map((S,b)=>{let h=`$.completenessReasons[${b}]`,d=$(S,h);U(d,["code","message","file"],h);let P=d.file===void 0?void 0:G(d,"file",h);return{code:M(d,"code",h),message:M(d,"message",h),...P?{file:P}:{}}});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=z(e,"files","$").map((S,b)=>{let h=`$.files[${b}]`,d=$(S,h);return U(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:G(d,"path",h),contentHash:M(d,"contentHash",h),parseStatus:Ae(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Ws(d,"parseDiagnosticCount",h),exportsOnlyTypes:B(d,"exportsOnlyTypes",h),typeOnlyExportNames:Ke(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:B(d,"hasTopLevelSideEffects",h)}}),a=z(e,"dependencies","$").map((S,b)=>{let h=`$.dependencies[${b}]`,d=$(S,h);U(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let P=he(d,"specifier",h),V=he(d,"target",h),ie=Ae(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ie==="resolved-project"&&!V)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ie!=="resolved-project"&&V)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ie!=="dynamic"&&!P)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:G(d,"from",h),...P?{specifier:P}:{},kind:Ae(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:B(d,"typeOnly",h),line:Q(d,"line",h),resolution:ie,...V?{target:G(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Ke(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:B(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:B(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:B(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:B(d,"portProofEligible",h)}:{}}}),l=z(e,"capabilityUses","$").map((S,b)=>{let h=`$.capabilityUses[${b}]`,d=$(S,h);return U(d,["file","line","symbol","capability","source"],h),{file:G(d,"file",h),line:Q(d,"line",h),symbol:M(d,"symbol",h),capability:Ae(d,"capability",zs,h),source:Ae(d,"source",["ambient-global","import-based"],h)}}),c=z(e,"ambientUses","$").map((S,b)=>{let h=`$.ambientUses[${b}]`,d=$(S,h);return U(d,["file","line","symbol"],h),{file:G(d,"file",h),line:Q(d,"line",h),symbol:M(d,"symbol",h)}}),p=z(e,"publishCalls","$").map((S,b)=>{let h=`$.publishCalls[${b}]`,d=$(S,h);U(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let P=he(d,"rawIntentName",h),V=he(d,"sourceIntent",h);return{file:G(d,"file",h),line:Q(d,"line",h),...P?{rawIntentName:P}:{},objectHasIntent:B(d,"objectHasIntent",h),arkPublishCandidate:B(d,"arkPublishCandidate",h),hasSource:B(d,"hasSource",h),...V?{sourceIntent:V}:{}}}),g=z(e,"intentReferences","$").map((S,b)=>{let h=`$.intentReferences[${b}]`,d=$(S,h);return U(d,["file","line","intent"],h),{file:G(d,"file",h),line:Q(d,"line",h),intent:M(d,"intent",h)}}),y=z(e,"safetyUses","$").map((S,b)=>{let h=`$.safetyUses[${b}]`,d=$(S,h);U(d,["file","line","kind","symbol"],h);let P=he(d,"symbol",h),V=Ae(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(V==="in-memory-store"&&!P)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(V!=="in-memory-store"&&P)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:G(d,"file",h),line:Q(d,"line",h),kind:V,...P?{symbol:P}:{}}});ki(o,S=>S.path,"$.files");let m=new Set(o.map(S=>S.path));for(let S of o){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!m.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let f=(e.arkRunKernelCalls===void 0?[]:z(e,"arkRunKernelCalls","$")).map((S,b)=>{let h=`$.arkRunKernelCalls[${b}]`,d=$(S,h);U(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let P=he(d,"receiver",h),V=he(d,"nameLiteral",h);return{file:G(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:M(d,"callee",h),viaImport:B(d,"viaImport",h),...P?{receiver:P}:{},...V?{nameLiteral:V}:{}}}),v=(e.arkRunManagedNews===void 0?[]:z(e,"arkRunManagedNews","$")).map((S,b)=>{let h=`$.arkRunManagedNews[${b}]`,d=$(S,h);U(d,["file","line","typeName","importedFrom"],h);let P=he(d,"importedFrom",h);return{file:G(d,"file",h),line:Q(d,"line",h),typeName:M(d,"typeName",h),...P?{importedFrom:P}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:z(e,"arkRunCompositionRootHits","$")).map((S,b)=>{let h=`$.arkRunCompositionRootHits[${b}]`,d=$(S,h);return U(d,["file","matchedRoot","hasKernelFactory"],h),{file:G(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasKernelFactory:B(d,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:z(e,"arkRunDeclarations","$"),H=(e.arkOrderPlaneCalls===void 0?[]:z(e,"arkOrderPlaneCalls","$")).map((S,b)=>{let h=`$.arkOrderPlaneCalls[${b}]`,d=$(S,h);return U(d,["file","line","callee"],h),{file:G(d,"file",h),line:Q(d,"line",h),callee:M(d,"callee",h)}}),L=(e.arkOrderGenericUpdates===void 0?[]:z(e,"arkOrderGenericUpdates","$")).map((S,b)=>{let h=`$.arkOrderGenericUpdates[${b}]`,d=$(S,h);return U(d,["file","line","method"],h),{file:G(d,"file",h),line:Q(d,"line",h),method:M(d,"method",h)}}),x=(e.arkOrderRootHits===void 0?[]:z(e,"arkOrderRootHits","$")).map((S,b)=>{let h=`$.arkOrderRootHits[${b}]`,d=$(S,h);return U(d,["file","matchedRoot","hasPlaneFactory"],h),{file:G(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasPlaneFactory:B(d,"hasPlaneFactory",h)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:z(e,"arkOrderXiFieldWrites","$")).map((S,b)=>{let h=`$.arkOrderXiFieldWrites[${b}]`,d=$(S,h);return U(d,["file","line","key"],h),{file:G(d,"file",h),line:Q(d,"line",h),key:M(d,"key",h)}}),pe=(e.arkOrderIngestWritesXi===void 0?[]:z(e,"arkOrderIngestWritesXi","$")).map((S,b)=>{let h=`$.arkOrderIngestWritesXi[${b}]`,d=$(S,h);return U(d,["file","line"],h),{file:G(d,"file",h),line:Q(d,"line",h)}}),Je=(e.arkOrderReleaseKeyCounts===void 0?[]:z(e,"arkOrderReleaseKeyCounts","$")).map((S,b)=>{let h=`$.arkOrderReleaseKeyCounts[${b}]`,d=$(S,h);return U(d,["file","line","keyCount"],h),{file:G(d,"file",h),line:Q(d,"line",h),keyCount:Q(d,"keyCount",h)}}),Ze=I.map((S,b)=>{let h=`$.arkRunDeclarations[${b}]`,d=$(S,h);return U(d,["file","line","uses","reactsTo","raises","sends"],h),{file:G(d,"file",h),line:Q(d,"line",h),uses:Ke(d.uses,`${h}.uses`),reactsTo:Ke(d.reactsTo,`${h}.reactsTo`),raises:Ke(d.raises,`${h}.raises`),sends:Ke(d.sends,`${h}.sends`)}});for(let[S,b]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",g],["$.safetyUses",y],["$.arkRunKernelCalls",f],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",Ze],["$.arkOrderPlaneCalls",H],["$.arkOrderGenericUpdates",L],["$.arkOrderRootHits",x],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",pe],["$.arkOrderReleaseKeyCounts",Je]])for(let h of b)if(!m.has(h.file))throw new Error(`${S} references missing file ${h.file}.`);let Oe=he(e,"projectPackageName","$"),Bn=(e.classShapes===void 0?[]:z(e,"classShapes","$")).map((S,b)=>{let h=`$.classShapes[${b}]`,d=$(S,h);U(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let P=z(d,"mutatingMethods",h).map((V,ie)=>{let Dt=`${h}.mutatingMethods[${ie}]`,zn=$(V,Dt);return U(zn,["name","referencesGuardOrPublish"],Dt),{name:M(zn,"name",Dt),referencesGuardOrPublish:B(zn,"referencesGuardOrPublish",Dt)}});return{file:G(d,"file",h),className:M(d,"className",h),exported:B(d,"exported",h),hasPublicMutableFields:B(d,"hasPublicMutableFields",h),hasPublicSetters:B(d,"hasPublicSetters",h),hasPublicConstructor:B(d,"hasPublicConstructor",h),hasStaticFactory:B(d,"hasStaticFactory",h),mutatingMethods:P,...d.dataOnly===void 0?{}:{dataOnly:B(d,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:M(e,"resolverIdentity","$"),compilerIdentity:M(e,"compilerIdentity","$"),compilerOptionsHash:M(e,"compilerOptionsHash","$"),tsconfigHash:M(e,"tsconfigHash","$"),evidenceRequirementsHash:M(e,"evidenceRequirementsHash","$"),...Oe?{projectPackageName:Oe}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:g,safetyUses:y,classShapes:Bn,arkRunKernelCalls:f,arkRunManagedNews:v,arkRunCompositionRootHits:R,arkRunDeclarations:Ze,arkOrderPlaneCalls:H,arkOrderGenericUpdates:L,arkOrderRootHits:x,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:pe,arkOrderReleaseKeyCounts:Je}}i(Ys,"parseResolvedFactsInput");function Re(e){let t=$(e,"$"),n=M(t,"factsHash","$"),r=M(t,"candidateTreeHash","$"),s=qs(Ys(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 Ei=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},re={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Jt={$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:q}}},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:q,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:q,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,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:q,line:re,symbol:T,capability:{enum:Ei},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:re,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:re,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:re,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:q,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:q,line:re,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:T,viaImport:{type:"boolean"},receiver:T,nameLiteral:T}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:q,line:re,typeName:T,importedFrom:T}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:q,matchedRoot:T,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:q,line:re,uses:{type:"array",items:T},reactsTo:{type:"array",items:T},raises:{type:"array",items:T},sends:{type:"array",items:T}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:q,line:re,callee:T}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:q,line:re,method:T}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:q,matchedRoot:T,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:q,line:re,key:T}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:q,line:re}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:q,line:re,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 Zt="1.0";function oe(e){return`${e.from}->${e.to}`}i(oe,"dependencyKey");function dt(e,t,n,r="dependency"){return{id:`${e}:${r}:${oe(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${oe(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${oe(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${oe(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${oe(t)} from the candidate, then preflight again.`}:{}}}i(dt,"dependencyFinding");function Le(e){let t=[],n=new Map(e.changeMap.map.files.map(m=>[m.path,m])),r=new Map(e.changes.map(m=>[m.path,m])),s=new Map(e.changeMap.map.dependencies.map(m=>[oe(m),m])),o=new Map(e.baseDependencies.map(m=>[oe(m),m])),a=new Map(e.candidateDependencies.map(m=>[oe(m),m]));for(let m of[...n.values()].sort((u,f)=>u.path.localeCompare(f.path))){let u=r.get(m.path);u?u.operation!==m.operation?t.push({id:`contradictory:file:${m.path}`,classification:"contradictory",subject:"file",path:m.path,expectedOperation:m.operation,actualOperation:u.operation,message:`${m.path} was planned as ${m.operation} but the actual operation is ${u.operation}.`,nextAction:`Change ${m.path} to the planned ${m.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${m.path}`,classification:"satisfied",subject:"file",path:m.path,expectedOperation:m.operation,actualOperation:u.operation,message:`${m.path} matches the planned ${m.operation} operation.`}):t.push({id:`missing:file:${m.path}`,classification:"missing",subject:"file",path:m.path,expectedOperation:m.operation,message:`${m.path} was planned as ${m.operation} but is absent from the actual change.`,nextAction:`${m.operation[0].toUpperCase()}${m.operation.slice(1)} ${m.path} in the complete change set, then preflight again.`})}for(let m of[...r.values()].sort((u,f)=>u.path.localeCompare(f.path)))n.has(m.path)||t.push({id:`unplanned:file:${m.path}`,classification:"unplanned",subject:"file",path:m.path,actualOperation:m.operation,message:`${m.path} has an unplanned ${m.operation} operation.`,nextAction:`Remove ${m.path} from the change set, then preflight again.`});let l=new Set;for(let m of[...s.values()].sort((u,f)=>oe(u).localeCompare(oe(f)))){if(a.has(oe(m))){t.push(dt("satisfied",m,`${m.from} -> ${m.to} exists in the candidate architecture.`));continue}let u={from:m.to,to:m.from};a.has(oe(u))?(l.add(oe(u)),t.push(dt("contradictory",m,`${m.from} -> ${m.to} was planned, but the candidate contains the reverse edge.`))):t.push(dt("missing",m,`${m.from} -> ${m.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[m,u]of[...a].sort(([f],[A])=>f.localeCompare(A)))o.has(m)||s.has(m)||l.has(m)||!c.has(u.from)&&!c.has(u.to)||t.push({...dt("unplanned",u,`${u.from} -> ${u.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(m=>m.operation==="delete").map(m=>m.path));for(let[m,u]of[...o].sort(([f],[A])=>f.localeCompare(A)))a.has(m)||p.has(u.from)||p.has(u.to)||!c.has(u.from)&&!c.has(u.to)||t.push({...dt("unplanned",u,`${u.from} -> ${u.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((m,u)=>g[m.classification]-g[u.classification]||(m.subject===u.subject?0:m.subject==="file"?-1:1)||m.id.localeCompare(u.id));let y={satisfied:t.filter(m=>m.classification==="satisfied").length,missing:t.filter(m=>m.classification==="missing").length,contradictory:t.filter(m=>m.classification==="contradictory").length,unplanned:t.filter(m=>m.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(Le,"analyzeArchitectureConvergence");var Zs="1.0",yr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",hr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Ii=["no-anemic-model"],Xs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},en={$schema:"https://json-schema.org/draft/2020-12/schema",$id:yr,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:yr},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:[...hr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Xs,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:Xs}}}},Pe=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
4
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Gs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Gs,"isObject");function qt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(qt,"propertyPath");function Ke(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Ke,"valueType");function pi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(pi,"resolveSchemaRef");function it(e,t,n,r,s){if(t.$ref){let o=pi(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}it(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(!Gs(e)){s.push({path:n,message:`must be an object; received ${Ke(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:qt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:qt(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||it(e[l],a,qt(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&it(e[a],l,qt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ke(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)=>it(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 ${Ke(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 ${Ke(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ke(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(it,"validateNode");function fi(e){let t={...e,$schema:e.$schema===void 0?Wt: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?Jt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Hs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=js(e.arkOrder)),t}i(fi,"defaultedConfig");function mi(e){return e===ne?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(mi,"migratedFromOf");function gi(){let e=new Set([ne]);for(let t of mr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(gi,"knownInputVersions");function yi(e,t="ark.config.json"){if(!Gs(e))throw new ye(t,[{path:"$",message:`must be an object; received ${Ke(e)}`}]);let n=gi(),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 ${ne}`}]);if(r!=="unversioned"&&!n.has(r))throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ne}`}]);let s=r,o={...e},a=0;for(;s!==ne&&a<mr.length+1;){a+=1;let l=mr.find(c=>c.from===s);if(!l)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${ne}`}]);s=l.to,o.schemaVersion=s}if(s!==ne)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ne}`}]);return{candidate:fi(o),migratedFrom:mi(r)}}i(yi,"migrateArkConfig");function lt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=yi(e,t),s=[];if(it(n,Yt,"$",Yt,s),Vs(n,s),Us(n,s),s.length>0)throw new ye(t,s);return{config:n,migratedFrom:r}}i(lt,"loadArkConfigContract");function Xt(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 lt(n,t)}i(Xt,"parseArkConfigJson");function Bs(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Wt,schemaVersion:ne};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Bs,"withArkConfigMetadata");function hi(e){return e.endsWith(".")?e:`${e}.`}i(hi,"normalizePrefix");function Ai(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(Ai,"byLongestPrefix");function dt(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(hi)})),n=[...t].sort(Ai),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(dt,"createArchitectureProfile");function gr(e,t={}){return dt({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(gr,"createArchitectureProfileFromArkConfig");var Ri=[{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}],ct=dt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ri,rules:Jt.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 yr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Bs({include:e.include??[t],layers:ct.layers.map(s=>({name:s.name,patterns:(ki[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...ct.rules]})}i(yr,"createElevenLayerArkConfig");function J(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(J,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$(t[n])}`).join(",")}}`}i($,"stableSerialize");var ve="1.2";var zs=["network","filesystem","clock","randomness","environment","process","persistence"];function Y(e,t){let n=$(e),r=$(t);return n<r?-1:n>r?1:0}i(Y,"compareCanonical");function X(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(X,"sortedUnique");function Be(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(Y),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 J($(t))}i(Be,"resolvedFactsEvidenceRequirementsHash");function Ei(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(Y),n=e.files.map(k=>({...k,typeOnlyExportNames:X(k.typeOnlyExportNames)})).sort((k,T)=>k.path<T.path?-1:k.path>T.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:X(k.namedBindings)}:{}})).sort(Y),s=e.capabilityUses.map(k=>({...k})).sort(Y),o=e.ambientUses.map(k=>({...k})).sort(Y),a=e.publishCalls.map(k=>({...k})).sort(Y),l=e.intentReferences.map(k=>({...k})).sort(Y),c=e.safetyUses.map(k=>({...k})).sort(Y),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(T=>({...T}))})).sort(Y),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(Y),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(Y),g=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(Y),p=(e.arkRunDeclarations??[]).map(k=>({...k,uses:X(k.uses),reactsTo:X(k.reactsTo),raises:X(k.raises),sends:X(k.sends)})).sort(Y),f=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(Y),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(Y),v=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(Y),_=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(Y),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(Y),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(Y),b=e.files.map(({path:k,contentHash:T})=>({path:k,contentHash:T})).sort((k,T)=>k.path<T.path?-1:k.path>T.path?1:0),D=J($(b));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:D,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:m,arkRunManagedNews:y,arkRunCompositionRootHits:g,arkRunDeclarations:p,arkOrderPlaneCalls:f,arkOrderGenericUpdates:A,arkOrderRootHits:v,arkOrderXiFieldWrites:_,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:I}}i(Ei,"canonicalResolvedFactsInput");function qs(e){let t=Ei(e);return{...t,factsHash:J($(t))}}i(qs,"createCanonicalResolvedCandidateFacts");function Zt(e){return qs(Ys(H(e,"$"),!1))}i(Zt,"createResolvedCandidateFacts");function H(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(H,"asRecord");function U(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(U,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function he(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(he,"optionalText");function G(e,t,n){let r=F(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(G,"requiredProjectPath");function B(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(B,"requiredBoolean");function Ws(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(Ws,"requiredInteger");function Q(e,t,n){let r=Ws(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Q,"requiredPositiveInteger");function z(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(z,"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 Ge(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(Ge,"parseStringArray");function Ii(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(Ii,"assertUnique");function Ys(e,t){U(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Ae(e,"completeness",["complete","partial","unavailable"],"$"),s=z(e,"completenessReasons","$").map((S,C)=>{let h=`$.completenessReasons[${C}]`,d=H(S,h);U(d,["code","message","file"],h);let P=d.file===void 0?void 0:G(d,"file",h);return{code:F(d,"code",h),message:F(d,"message",h),...P?{file:P}:{}}});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=z(e,"files","$").map((S,C)=>{let h=`$.files[${C}]`,d=H(S,h);return U(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:G(d,"path",h),contentHash:F(d,"contentHash",h),parseStatus:Ae(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Ws(d,"parseDiagnosticCount",h),exportsOnlyTypes:B(d,"exportsOnlyTypes",h),typeOnlyExportNames:Ge(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:B(d,"hasTopLevelSideEffects",h)}}),a=z(e,"dependencies","$").map((S,C)=>{let h=`$.dependencies[${C}]`,d=H(S,h);U(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let P=he(d,"specifier",h),V=he(d,"target",h),ie=Ae(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(ie==="resolved-project"&&!V)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(ie!=="resolved-project"&&V)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(ie!=="dynamic"&&!P)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:G(d,"from",h),...P?{specifier:P}:{},kind:Ae(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:B(d,"typeOnly",h),line:Q(d,"line",h),resolution:ie,...V?{target:G(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Ge(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:B(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:B(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:B(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:B(d,"portProofEligible",h)}:{}}}),l=z(e,"capabilityUses","$").map((S,C)=>{let h=`$.capabilityUses[${C}]`,d=H(S,h);return U(d,["file","line","symbol","capability","source"],h),{file:G(d,"file",h),line:Q(d,"line",h),symbol:F(d,"symbol",h),capability:Ae(d,"capability",zs,h),source:Ae(d,"source",["ambient-global","import-based"],h)}}),c=z(e,"ambientUses","$").map((S,C)=>{let h=`$.ambientUses[${C}]`,d=H(S,h);return U(d,["file","line","symbol"],h),{file:G(d,"file",h),line:Q(d,"line",h),symbol:F(d,"symbol",h)}}),u=z(e,"publishCalls","$").map((S,C)=>{let h=`$.publishCalls[${C}]`,d=H(S,h);U(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let P=he(d,"rawIntentName",h),V=he(d,"sourceIntent",h);return{file:G(d,"file",h),line:Q(d,"line",h),...P?{rawIntentName:P}:{},objectHasIntent:B(d,"objectHasIntent",h),arkPublishCandidate:B(d,"arkPublishCandidate",h),hasSource:B(d,"hasSource",h),...V?{sourceIntent:V}:{}}}),m=z(e,"intentReferences","$").map((S,C)=>{let h=`$.intentReferences[${C}]`,d=H(S,h);return U(d,["file","line","intent"],h),{file:G(d,"file",h),line:Q(d,"line",h),intent:F(d,"intent",h)}}),y=z(e,"safetyUses","$").map((S,C)=>{let h=`$.safetyUses[${C}]`,d=H(S,h);U(d,["file","line","kind","symbol"],h);let P=he(d,"symbol",h),V=Ae(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(V==="in-memory-store"&&!P)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(V!=="in-memory-store"&&P)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:G(d,"file",h),line:Q(d,"line",h),kind:V,...P?{symbol:P}:{}}});Ii(o,S=>S.path,"$.files");let g=new Set(o.map(S=>S.path));for(let S of o){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!g.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let f=(e.arkRunKernelCalls===void 0?[]:z(e,"arkRunKernelCalls","$")).map((S,C)=>{let h=`$.arkRunKernelCalls[${C}]`,d=H(S,h);U(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let P=he(d,"receiver",h),V=he(d,"nameLiteral",h);return{file:G(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:F(d,"callee",h),viaImport:B(d,"viaImport",h),...P?{receiver:P}:{},...V?{nameLiteral:V}:{}}}),v=(e.arkRunManagedNews===void 0?[]:z(e,"arkRunManagedNews","$")).map((S,C)=>{let h=`$.arkRunManagedNews[${C}]`,d=H(S,h);U(d,["file","line","typeName","importedFrom"],h);let P=he(d,"importedFrom",h);return{file:G(d,"file",h),line:Q(d,"line",h),typeName:F(d,"typeName",h),...P?{importedFrom:P}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:z(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let h=`$.arkRunCompositionRootHits[${C}]`,d=H(S,h);return U(d,["file","matchedRoot","hasKernelFactory"],h),{file:G(d,"file",h),matchedRoot:F(d,"matchedRoot",h),hasKernelFactory:B(d,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:z(e,"arkRunDeclarations","$"),D=(e.arkOrderPlaneCalls===void 0?[]:z(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let h=`$.arkOrderPlaneCalls[${C}]`,d=H(S,h);return U(d,["file","line","callee"],h),{file:G(d,"file",h),line:Q(d,"line",h),callee:F(d,"callee",h)}}),T=(e.arkOrderGenericUpdates===void 0?[]:z(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let h=`$.arkOrderGenericUpdates[${C}]`,d=H(S,h);return U(d,["file","line","method"],h),{file:G(d,"file",h),line:Q(d,"line",h),method:F(d,"method",h)}}),x=(e.arkOrderRootHits===void 0?[]:z(e,"arkOrderRootHits","$")).map((S,C)=>{let h=`$.arkOrderRootHits[${C}]`,d=H(S,h);return U(d,["file","matchedRoot","hasPlaneFactory"],h),{file:G(d,"file",h),matchedRoot:F(d,"matchedRoot",h),hasPlaneFactory:B(d,"hasPlaneFactory",h)}}),M=(e.arkOrderXiFieldWrites===void 0?[]:z(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let h=`$.arkOrderXiFieldWrites[${C}]`,d=H(S,h);return U(d,["file","line","key"],h),{file:G(d,"file",h),line:Q(d,"line",h),key:F(d,"key",h)}}),pe=(e.arkOrderIngestWritesXi===void 0?[]:z(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let h=`$.arkOrderIngestWritesXi[${C}]`,d=H(S,h);return U(d,["file","line"],h),{file:G(d,"file",h),line:Q(d,"line",h)}}),Ze=(e.arkOrderReleaseKeyCounts===void 0?[]:z(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let h=`$.arkOrderReleaseKeyCounts[${C}]`,d=H(S,h);return U(d,["file","line","keyCount"],h),{file:G(d,"file",h),line:Q(d,"line",h),keyCount:Q(d,"keyCount",h)}}),Qe=I.map((S,C)=>{let h=`$.arkRunDeclarations[${C}]`,d=H(S,h);return U(d,["file","line","uses","reactsTo","raises","sends"],h),{file:G(d,"file",h),line:Q(d,"line",h),uses:Ge(d.uses,`${h}.uses`),reactsTo:Ge(d.reactsTo,`${h}.reactsTo`),raises:Ge(d.raises,`${h}.raises`),sends:Ge(d.sends,`${h}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",m],["$.safetyUses",y],["$.arkRunKernelCalls",f],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",Qe],["$.arkOrderPlaneCalls",D],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",x],["$.arkOrderXiFieldWrites",M],["$.arkOrderIngestWritesXi",pe],["$.arkOrderReleaseKeyCounts",Ze]])for(let h of C)if(!g.has(h.file))throw new Error(`${S} references missing file ${h.file}.`);let Oe=he(e,"projectPackageName","$"),qn=(e.classShapes===void 0?[]:z(e,"classShapes","$")).map((S,C)=>{let h=`$.classShapes[${C}]`,d=H(S,h);U(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let P=z(d,"mutatingMethods",h).map((V,ie)=>{let Mt=`${h}.mutatingMethods[${ie}]`,Wn=H(V,Mt);return U(Wn,["name","referencesGuardOrPublish"],Mt),{name:F(Wn,"name",Mt),referencesGuardOrPublish:B(Wn,"referencesGuardOrPublish",Mt)}});return{file:G(d,"file",h),className:F(d,"className",h),exported:B(d,"exported",h),hasPublicMutableFields:B(d,"hasPublicMutableFields",h),hasPublicSetters:B(d,"hasPublicSetters",h),hasPublicConstructor:B(d,"hasPublicConstructor",h),hasStaticFactory:B(d,"hasStaticFactory",h),mutatingMethods:P,...d.dataOnly===void 0?{}:{dataOnly:B(d,"dataOnly",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...Oe?{projectPackageName:Oe}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:m,safetyUses:y,classShapes:qn,arkRunKernelCalls:f,arkRunManagedNews:v,arkRunCompositionRootHits:R,arkRunDeclarations:Qe,arkOrderPlaneCalls:D,arkOrderGenericUpdates:T,arkOrderRootHits:x,arkOrderXiFieldWrites:M,arkOrderIngestWritesXi:pe,arkOrderReleaseKeyCounts:Ze}}i(Ys,"parseResolvedFactsInput");function Re(e){let t=H(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),s=qs(Ys(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 vi=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},re={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Qt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:N,message:N,file:q}}},resolverIdentity:N,compilerIdentity:N,compilerOptionsHash:N,tsconfigHash:N,candidateTreeHash:N,evidenceRequirementsHash:N,projectPackageName:N,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:N,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:N},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:q,specifier:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:N},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:q,line:re,symbol:N,capability:{enum:vi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:re,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:re,rawIntentName:N,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:N}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:re,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:N},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:q,className:N,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:N,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:q,line:re,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:N,viaImport:{type:"boolean"},receiver:N,nameLiteral:N}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:q,line:re,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:q,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:q,line:re,uses:{type:"array",items:N},reactsTo:{type:"array",items:N},raises:{type:"array",items:N},sends:{type:"array",items:N}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:q,line:re,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:q,line:re,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:q,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:q,line:re,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:q,line:re}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:q,line:re,keyCount:{type:"integer",minimum:1}}}},factsHash:N},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var en="1.0";function oe(e){return`${e.from}->${e.to}`}i(oe,"dependencyKey");function ut(e,t,n,r="dependency"){return{id:`${e}:${r}:${oe(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${oe(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${oe(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${oe(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${oe(t)} from the candidate, then preflight again.`}:{}}}i(ut,"dependencyFinding");function Pe(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=>[oe(g),g])),o=new Map(e.baseDependencies.map(g=>[oe(g),g])),a=new Map(e.candidateDependencies.map(g=>[oe(g),g]));for(let g of[...n.values()].sort((p,f)=>p.path.localeCompare(f.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,f)=>p.path.localeCompare(f.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,f)=>oe(p).localeCompare(oe(f)))){if(a.has(oe(g))){t.push(ut("satisfied",g,`${g.from} -> ${g.to} exists in the candidate architecture.`));continue}let p={from:g.to,to:g.from};a.has(oe(p))?(l.add(oe(p)),t.push(ut("contradictory",g,`${g.from} -> ${g.to} was planned, but the candidate contains the reverse edge.`))):t.push(ut("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(([f],[A])=>f.localeCompare(A)))o.has(g)||s.has(g)||l.has(g)||!c.has(p.from)&&!c.has(p.to)||t.push({...ut("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(([f],[A])=>f.localeCompare(A)))a.has(g)||u.has(p.from)||u.has(p.to)||!c.has(p.from)&&!c.has(p.to)||t.push({...ut("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let m={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((g,p)=>m[g.classification]-m[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(Pe,"analyzeArchitectureConvergence");var Zs="1.0",hr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ar=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Si=["no-anemic-model"],Js={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},nn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:hr,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:hr},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:[...Ar]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Js,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:Js}}}},we=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
5
5
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
6
|
-
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function
|
|
6
|
+
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function mt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(mt,"isObject");function tn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(tn,"propertyPath");function pt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(pt,"valueType");function bi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(bi,"resolveSchemaRef");function ft(e,t,n,r,s){if(t.$ref){let o=bi(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ft(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(!mt(e)){s.push({path:n,message:`must be an object; received ${pt(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:tn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:tn(n,a),message:"unknown field"});else if(mt(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||ft(e[l],a,tn(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&ft(e[a],l,tn(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${pt(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)=>ft(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 ${pt(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 ${pt(e)}`})}i(ft,"validateNode");function Ci(e){return{...e,$schema:e.$schema===void 0?hr: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(Ci,"defaultedArkRules");function Xs(e){return e==="enforced"?"enforced":"advisory"}i(Xs,"normalizeMode");function Oi(e){return Si.includes(e)}i(Oi,"isTier2Sensor");function _i(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(!mt(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"&&Oi(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(!mt(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(_i,"validateSemantics");function gt(e,t="arkrules.json",n){if(!mt(e))throw new we(t,[{path:"$",message:`must be an object; received ${pt(e)}`}]);let r=Ci(e),s=[];if(ft(r,nn,"$",nn,s),_i(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 we(t,s);return{config:r}}i(gt,"loadArkRulesContract");function Qs(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new we(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return gt(r,t,n)}i(Qs,"parseArkRulesJson");function rn(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:Xs(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}})),l=(o.file.invariants??[]).map(c=>({...c,mode:Xs(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(rn,"buildEffectiveArkRules");function Se(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Se,"emptyEffectiveArkRules");var yt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
|
|
7
7
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
8
|
-
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function eo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(eo,"normalizeRel");function to(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 p=n[c],g=`$.arkRules[${JSON.stringify(c)}]`;if(typeof p!="string"||p.length===0){o.push({path:g,message:"must be a non-empty relative path string"});continue}if(p.startsWith("/")||/^[A-Za-z]:[\\/]/.test(p)){o.push({path:g,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){o.push({path:g,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let y=eo(p);l.add(y);let m=e.fileContents[y]??e.fileContents[p];if(m===void 0){o.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let u=mt(JSON.parse(m),y,c);a.push({layer:c,sourceFile:y,file:u.config})}catch(u){if(u instanceof Pe)for(let f of u.issues)o.push({path:`${g}${f.path==="$"?"":f.path.replace(/^\$/,"")}`,message:`${y}: ${f.message}`});else u instanceof SyntaxError?o.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${u.message}`}):o.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} failed to load: ${u instanceof Error?u.message:String(u)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let p=eo(c);l.has(p)||r.push({path:p,message:`ArkRules file ${JSON.stringify(p)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(o.length>0)throw new gt(t,o);return{config:e.config,arkRules:tn(a),warnings:r}}i(to,"resolveEffectiveContract");function Ar(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}i(Ar,"omitLayerDescriptions");function nn(e){let{stewards:t,...n}=Ar(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(nn,"effectiveContractPolicyPayload");function no(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(no,"formatCoverageDiscards");function Oi(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(Oi,"isUnderCoverageRoot");function _i(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(_i,"titleMatchesInvariant");function xi(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(xi,"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=no(o),l=no(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",p=(e.coverageRoots??[]).filter(f=>typeof f=="string"&&f.length>0),g=p.length>0,y=p.join(", "),m=[],u=[];for(let f of t){let A=[],v=f.coverage?.test!==!1,_=f.coverage?.symbol,R,I;if(!r&&v){let L;for(let w of n){let x=e.fileContents[w];if(!(!x||!_i(x,f.id))){if(!g||Oi(w,p)){R=w,I=g?!1:void 0;break}L??=w}}R===void 0&&L!==void 0&&(R=L,I=!0),R!==void 0&&A.push("test-title")}_&&xi(e.fileContents,_)&&A.push("symbol");let H=(f.coverage?.test===!0||!!_||f.coverage===void 0)&&A.length>0||f.coverage?.test===!1&&!_?!0:A.length>0,k=r&&v&&A.length===0;if(m.push({invariantId:f.id,layer:f.provenance.layer,sourceFile:f.provenance.sourceFile,mode:f.mode,covered:H&&!k,evidence:A,partial:k,description:f.description,...R!==void 0?{testEvidenceFile:R}:{},...I!==void 0?{outsideDeclaredRoots:I}:{}}),I===!0&&R!==void 0&&u.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${f.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:f.id,arkruleSource:f.provenance.sourceFile,fromLayer:f.provenance.layer,severity:"warning",failsStrict:!1}),!H||k){let L=f.mode==="enforced"&&!k,w=r||n.length===0?"never-had-tests":"tests-disappeared";u.push({ruleId:"INVARIANT_UNCOVERED",message:(k?s?`Invariant ${f.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${f.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:w==="tests-disappeared"?`Invariant ${f.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 ${f.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:f.provenance.sourceFile,line:1,arkruleId:f.id,arkruleSource:f.provenance.sourceFile,fromLayer:f.provenance.layer,severity:L?"error":"warning",failsStrict:L,kind:w})}}return{coverage:m,violations:u,partial:m.some(f=>f.partial)}}i(rn,"evaluateInvariantCoverage");function sn(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(sn,"canPromoteInvariant");var an="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),p=a.filter(y=>!l.has(y)),g=o.filter(y=>!c.has(y));p.length===0&&g.length===0||(p.length>0&&N(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),g.length>0&&N(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(ue,"compareStringSets");function yt(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(yt,"compareBoolean");function on(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(on,"keyed");function Ti(e,t,n){let r=on(t,o=>o.name),s=on(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 p=Kt(a),g=Kt(l);ue(e,`${c}.forbiddenGlobals`,p.rawGlobals,g.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`,p.atoms,g.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)}),yt(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."),yt(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(Ti,"compareLayers");function Ni(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=on(t,r),o=on(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),p=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&N(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&N(e,{kind:"deny-removed",path:p,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:`${p}.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 g=l.peerIsolation===!0,y=c.peerIsolation===!0;if(g!==y){let m=l.from===l.to&&c.from===c.to;N(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:m?y?"strengthening":"weakening":"judgment-required",message:m?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:g,after:y})}Z(l.sliceFolders).join("\0")!==Z(c.sliceFolders).join("\0")&&N(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Z(l.sliceFolders),after:Z(c.sliceFolders)}),!(!g&&!y)&&(so(e,`${p}.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."),so(e,`${p}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(ro)),Z((c.allowedCrossSlice??[]).map(ro)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Ni,"compareRules");function ro(e){return JSON.stringify([e.from,e.to])}i(ro,"crossSliceKey");function so(e,t,n,r,s,o,a){if(JSON.stringify(r)===JSON.stringify(s))return;let l=s.filter(g=>!r.includes(g)),c=r.filter(g=>!s.includes(g)),p=l.length>0&&c.length>0;N(e,{kind:p?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:p?"judgment-required":l.length>0?"weakening":"strengthening",message:p?`${o} Entries were added and removed in the same change.`:l.length>0?o:a,before:r,after:s})}i(so,"compareDeclaredExceptions");function Li(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"])yt(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Li,"compareSafety");function Rr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Rr,"arkRunMode");function kr(e){return e.mode==="enforced"?"enforced":"advisory"}i(kr,"arkOrderMode");function Pi(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 (${kr(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=kr(r),l=kr(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(Pi,"compareArkOrder");function wi(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 (${Rr(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=Rr(r),l=Rr(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."}),yt(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(wi,"compareArkRun");function Di(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(Di,"overallClassification");function oo(e,t){return`${e}::${t}`}i(oo,"ruleKey");function ao(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(oo(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(oo(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(ao,"indexEffectiveRules");function Mi(e,t,n,r,s,o){let a=new Map((o??[]).map(m=>[m.invariantId,m])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let m of p){let u=l[m],f=c[m],A=`$.arkRules[${m}]`;if(u===void 0&&f!==void 0){N(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${m} was added.`,after:f});continue}if(u!==void 0&&f===void 0){N(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${m} was removed.`,before:u});continue}u!==f&&N(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${m} changed; verify the effective rules still match intent.`,before:u,after:f})}let g=ao(r),y=ao(s);for(let m of[...new Set([...g.structure.keys(),...y.structure.keys()])].sort()){let u=g.structure.get(m),f=y.structure.get(m),A=`$.arkRules.structure[${m}]`;if(!u&&f){N(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${f.id} was added (${f.mode}).`,after:f});continue}if(u&&!f){N(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${u.id} was removed.`,before:u});continue}if(!(!u||!f)){if(u.mode!==f.mode){let v=u.mode==="advisory"&&f.mode==="enforced";N(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${f.id} was promoted to enforced.`:`Structure ArkRule ${f.id} was demoted to advisory.`,before:u.mode,after:f.mode})}u.sensor!==f.sensor&&N(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${f.id} changed sensor identity.`,before:u.sensor,after:f.sensor})}}for(let m of[...new Set([...g.invariants.keys(),...y.invariants.keys()])].sort()){let u=g.invariants.get(m),f=y.invariants.get(m),A=`$.arkRules.invariants[${m}]`;if(!u&&f){N(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${f.id} was added (${f.mode}).`,after:f});continue}if(u&&!f){N(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${u.id} was removed.`,before:u});continue}if(!(!u||!f)&&u.mode!==f.mode)if(u.mode==="advisory"&&f.mode==="enforced"){let _=a?.get(f.id),R=sn(_);R.ok?N(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${f.id} was promoted to enforced (coverage evidence present).`,before:u.mode,after:f.mode}):N(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${f.id} cannot be promoted to enforced: ${R.reason}`,before:u.mode,after:f.mode})}else N(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${f.id} was demoted to advisory.`,before:u.mode,after:f.mode})}}i(Mi,"compareArkRules");function ln(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."}),yt(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}),Ti(r,e.layers,t.layers),Ni(r,e.rules,t.rules),Li(r,e,t),Mi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),wi(r,e,t),Pi(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:an,classification:Di(r),findings:r}}i(ln,"classifyArkPolicyDelta");function cn(e,t){if(!e||e.schemaVersion!==an||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(cn,"policyDeltaAcknowledgementMatches");function we(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(we,"normalizePath");function io(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(io,"isIdentifierStart");function dn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(dn,"isIdentifierCharacter");function ae(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ae,"skipWhitespace");function ht(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(ht,"readString");function ce(e,t,n){return e.startsWith(t,n)&&!dn(e[n-1])&&!dn(e[n+t.length])}i(ce,"isWordAt");function lo(e,t){let n=ae(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ae(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ce(e,"type",n))return!1;let s=ae(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ce(e,"as",s)||!io(e[s]))return!1;for(n=s;n<e.length&&dn(e[n]);)n+=1;if(n=ae(e,n),ce(e,"as",n)){if(n=ae(e,n+2),!io(e[n]))return!1;for(;n<e.length&&dn(e[n]);)n+=1}r=!0}return!1}i(lo,"bracedNamedBindingsAreTypeOnly");function Fi(e,t){if(t=ae(e,t+6),e[t]==="(")return ht(e,ae(e,t+1));let n=!1;if(ce(e,"type",t)){let s=ae(e,t+4);e[s]!==","&&!ce(e,"from",s)&&(n=!0)}else lo(e,t)&&(n=!0);let r=co(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Fi,"specifierAfterImport");function $i(e,t){t=t+6;let n=ae(e,t),r=!1;if(ce(e,"type",n)){let o=ae(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else lo(e,n)&&(r=!0);let s=co(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i($i,"specifierAfterExport");function co(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ce(e,"from",t))return ht(e,ae(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ht(e,t);if(t>0&&(ce(e,"import",t)||ce(e,"export",t)))return}}i(co,"specifierInStaticStatement");function Hi(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(Hi,"skipTemplateLiteral");function ji(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ae(e,t+7);if(e[r]!=="(")return;r=ae(e,r+1);let s=ht(e,r);return s?{...s,requireCall:!0}:void 0}i(ji,"specifierAfterRequire");function Vi(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=
|
|
10
|
-
`).length;r.push({file:e.path,symbol:o,capability:
|
|
11
|
-
`).length,l={kind:"import",file:e.path,line:a,excerpt:s.excerpt},c=Ui(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(uo,"moduleFactsFor");function Ui(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(Ui,"resolveSpecifier");function po(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=_e(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 Ki={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 Gi(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Gi,"hasActiveArkRules");function Bi(e,t){return Gi(e,t)?X(F(nn({config:e,arkRules:t,warnings:[]}))):X(F(Ar(e)))}i(Bi,"policyHashFor");function At(e,t,n){let r=typeof e=="string"?Yt(e,t):it(e,t),s=n?.arkRules??be();return{...r,arkRules:s,policyHash:Bi(r.config,s)}}i(At,"loadContract");function Er(e){let t=At(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=At(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=ln(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&&cn(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(Er,"analyzePolicyDelta");function Be(e){let t=e.files.map(y=>{let m=we(y.path);return{path:m,content:y.content,contentHash:X(y.content),layer:de(m,e.contract.config.layers)??null}}).sort((y,m)=>y.path.localeCompare(m.path)),n=new Map(t.map(y=>[y.path,y])),r=[],s=[];for(let y of t){let m=uo(y,n);r.push(...m.edges),s.push(...m.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($e(y))]));for(let y of s){let m=n.get(y.file)?.layer;if(!m)continue;let u=a.get(m),f=ve(y.symbol,u?.forbiddenGlobals??[]);if(f){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${m} must not use module "${y.symbol}" because it is the import form of forbidden global "${f}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(m)?.has(y.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${m} 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",p=c==="complete"?[]:[{...Ki}],g={schemaVersion:Zt,policyHash:e.contract.policyHash,compilerOptionsHash:X(F(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:p,valid:c==="complete"&&o.length===0,ir:g}}i(Be,"analyzeProject");function Rt(e){let t=new Map(e.files.map(n=>[we(n.path),n]));for(let n of e.changes){let r=we(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Be({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Rt,"analyzeChange");function Ir(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(Ir,"explainViolation");function un(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 p=[],g;do{if(g=o.pop(),g===void 0)break;s.delete(g),p.push(g)}while(g!==c);p.length>1&&a.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[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(un,"detectArchitectureCycles");function De(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=or(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,p=!c&&!!(o.typeOnly||o.namedBindingsTypeOnly),g=c?xs(a.peerIsolationReason??"cross-slice",{fromPath:o.from,toPath:o.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?g?`${l.message} (${g})`:l.message:g?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}): ${g}`:`${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:p?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...p?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=un(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(De,"evaluateArchitectureGraph");var zi=["no-anemic-model"];function fo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(fo,"escapeGlobLiteral");function qi(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+=fo(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=fo(s)}return new RegExp(`^${n}$`)}i(qi,"globToRegExp");function ze(e,t){return!t||t.length===0?!0:t.some(n=>qi(n).test(e))}i(ze,"matchesAppliesTo");function Wi(e){return zi.includes(e)}i(Wi,"isTier2");function mo(e){return e.mode==="enforced"&&!Wi(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(mo,"severityFor");function Me(e,t,n,r=1){let{severity:s,failsStrict:o}=mo(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(Me,"baseViolation");function pn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(pn,"isInRuleLayer");function fn(e,t,n){return t.filter(r=>!(!r.exported||!ze(r.file,e.appliesTo)||!pn(r.file,e,n)))}i(fn,"shapesForRule");function Yi(e,t,n){let r=[];for(let s of fn(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Me(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Yi,"evaluateAggregatePrivateState");function Xi(e,t,n){let r=[];for(let s of fn(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Me(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Xi,"evaluateAlwaysValidFactory");function Ji(e,t,n){let r=[];for(let s of fn(e,t,n))for(let o of s.mutatingMethods)o.referencesGuardOrPublish||r.push(Me(e,s.file,`Mutating method ${s.className}.${o.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(Ji,"evaluateDomainEventOnMutation");function Zi(e,t){let n=[];for(let r of t.files)ze(r,e.appliesTo)&&pn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Me(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Zi,"evaluateOrchestrationOnly");function Qi(e,t){let n=[];for(let r of t.files)ze(r,e.appliesTo)&&pn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Me(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Qi,"evaluateThinAdapter");function el(e,t){let n=[];for(let r of t.files)ze(r,e.appliesTo)&&pn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Me(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(el,"evaluateWritesViaAggregate");function tl(e,t,n){let r=[];for(let s of fn(e,t,n))if(s.dataOnly===!0){let o=Me(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(tl,"evaluateNoAnemicModel");function mn(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(...Yi(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Xi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Ji(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Zi(n,e));break;case"thin-adapter":t.push(...Qi(n,e));break;case"writes-via-aggregate":t.push(...el(n,e));break;case"no-anemic-model":t.push(...tl(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(mn,"evaluateArkRuleSensors");function gn(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}=mo(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(gn,"collectEmptyAppliesToFindings");var nl=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm|mongoose)/,rl=/\.(?: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,sl=/\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*=)/,ol=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,al=/\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*=/,il=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function vr(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(al.source,"g"))??[],r=t.match(new RegExp(il.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,o=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+o>=6,l=nl.test(t),c=sl.test(t)||ol.test(t),p=n.length>=1||r.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),y=l&&p||c&&p||l&&g&&(s>=4||n.length>=1)||c&&l,m=l&&rl.test(t);return!a&&!y&&!m?null:{...a?{orchestrationHeavy:!0}:{},...y?{adapterThick:!0}:{},...m?{persistenceWrite:!0}:{}}}i(vr,"deriveArkRuleFileHints");function yn(e){let t={};for(let[n,r]of Object.entries(e)){let s=vr(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}i(yn,"buildArkRuleFileHints");function go(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 w=t[c];w==="{"?l+=1:w==="}"&&(l-=1),c+=1}let p=t.slice(a,c-1),g=p.split(`
|
|
8
|
+
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function eo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(eo,"normalizeRel");function to(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:Se(),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],m=`$.arkRules[${JSON.stringify(c)}]`;if(typeof u!="string"||u.length===0){o.push({path:m,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){o.push({path:m,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){o.push({path:m,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:m,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let p=gt(JSON.parse(g),y,c);a.push({layer:c,sourceFile:y,file:p.config})}catch(p){if(p instanceof we)for(let f of p.issues)o.push({path:`${m}${f.path==="$"?"":f.path.replace(/^\$/,"")}`,message:`${y}: ${f.message}`});else p instanceof SyntaxError?o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${p.message}`}):o.push({path:m,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 yt(t,o);return{config:e.config,arkRules:rn(a),warnings:r}}i(to,"resolveEffectiveContract");function Rr(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}i(Rr,"omitLayerDescriptions");function sn(e){let{stewards:t,...n}=Rr(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(sn,"effectiveContractPolicyPayload");function no(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(no,"formatCoverageDiscards");function xi(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(xi,"isUnderCoverageRoot");function Ti(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(Ti,"titleMatchesInvariant");function Ni(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(Ni,"symbolPresent");function on(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=no(o),l=no(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(f=>typeof f=="string"&&f.length>0),m=u.length>0,y=u.join(", "),g=[],p=[];for(let f of t){let A=[],v=f.coverage?.test!==!1,_=f.coverage?.symbol,R,I;if(!r&&v){let T;for(let w of n){let x=e.fileContents[w];if(!(!x||!Ti(x,f.id))){if(!m||xi(w,u)){R=w,I=m?!1:void 0;break}T??=w}}R===void 0&&T!==void 0&&(R=T,I=!0),R!==void 0&&A.push("test-title")}_&&Ni(e.fileContents,_)&&A.push("symbol");let D=(f.coverage?.test===!0||!!_||f.coverage===void 0)&&A.length>0||f.coverage?.test===!1&&!_?!0:A.length>0,k=r&&v&&A.length===0;if(g.push({invariantId:f.id,layer:f.provenance.layer,sourceFile:f.provenance.sourceFile,mode:f.mode,covered:D&&!k,evidence:A,partial:k,description:f.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 ${f.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:f.id,arkruleSource:f.provenance.sourceFile,fromLayer:f.provenance.layer,severity:"warning",failsStrict:!1}),!D||k){let T=f.mode==="enforced"&&!k,w=r||n.length===0?"never-had-tests":"tests-disappeared";p.push({ruleId:"INVARIANT_UNCOVERED",message:(k?s?`Invariant ${f.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${f.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:w==="tests-disappeared"?`Invariant ${f.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 ${f.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:f.provenance.sourceFile,line:1,arkruleId:f.id,arkruleSource:f.provenance.sourceFile,fromLayer:f.provenance.layer,severity:T?"error":"warning",failsStrict:T,kind:w})}}return{coverage:g,violations:p,partial:g.some(f=>f.partial)}}i(on,"evaluateInvariantCoverage");function an(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(an,"canPromoteInvariant");var cn="1.0";function L(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(L,"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)),m=o.filter(y=>!c.has(y));u.length===0&&m.length===0||(u.length>0&&L(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),m.length>0&&L(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(ue,"compareStringSets");function ht(e,t,n,r,s,o,a){if(n===r)return;L(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:a,before:n,after:r})}i(ht,"compareBoolean");function ln(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(ln,"keyed");function Li(e,t,n){let r=ln(t,o=>o.name),s=ln(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&L(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){L(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){L(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=Gt(a),m=Gt(l);ue(e,`${c}.forbiddenGlobals`,u.rawGlobals,m.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,m.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")&&L(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)}),ht(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."),ht(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(Li,"compareLayers");function Pi(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=ln(t,r),o=ln(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&L(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&&L(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&L(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&&L(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 m=l.peerIsolation===!0,y=c.peerIsolation===!0;if(m!==y){let g=l.from===l.to&&c.from===c.to;L(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:m,after:y})}Z(l.sliceFolders).join("\0")!==Z(c.sliceFolders).join("\0")&&L(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)}),!(!m&&!y)&&(so(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."),so(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",Z((l.allowedCrossSlice??[]).map(ro)),Z((c.allowedCrossSlice??[]).map(ro)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Pi,"compareRules");function ro(e){return JSON.stringify([e.from,e.to])}i(ro,"crossSliceKey");function so(e,t,n,r,s,o,a){if(JSON.stringify(r)===JSON.stringify(s))return;let l=s.filter(m=>!r.includes(m)),c=r.filter(m=>!s.includes(m)),u=l.length>0&&c.length>0;L(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(so,"compareDeclaredExceptions");function wi(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&&L(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"])ht(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(wi,"compareSafety");function kr(e){return e.mode==="enforced"?"enforced":"advisory"}i(kr,"arkRunMode");function Er(e){return e.mode==="enforced"?"enforced":"advisory"}i(Er,"arkOrderMode");function Di(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){L(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${Er(s)}).`,after:s});return}if(r&&!s){L(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let a=Er(r),l=Er(s);if(a!==l){let c=a==="advisory"&&l==="enforced";L(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(Di,"compareArkOrder");function Mi(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){L(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${kr(s)}).`,after:s});return}if(r&&!s){L(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=kr(r),l=kr(s);if(a!==l){let c=a==="advisory"&&l==="enforced";L(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."}),ht(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Mi,"compareArkRun");function Fi(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(Fi,"overallClassification");function oo(e,t){return`${e}::${t}`}i(oo,"ruleKey");function ao(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(oo(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(oo(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(ao,"indexEffectiveRules");function $i(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],f=c[g],A=`$.arkRules[${g}]`;if(p===void 0&&f!==void 0){L(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${g} was added.`,after:f});continue}if(p!==void 0&&f===void 0){L(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${g} was removed.`,before:p});continue}p!==f&&L(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:f})}let m=ao(r),y=ao(s);for(let g of[...new Set([...m.structure.keys(),...y.structure.keys()])].sort()){let p=m.structure.get(g),f=y.structure.get(g),A=`$.arkRules.structure[${g}]`;if(!p&&f){L(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${f.id} was added (${f.mode}).`,after:f});continue}if(p&&!f){L(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!f)){if(p.mode!==f.mode){let v=p.mode==="advisory"&&f.mode==="enforced";L(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${f.id} was promoted to enforced.`:`Structure ArkRule ${f.id} was demoted to advisory.`,before:p.mode,after:f.mode})}p.sensor!==f.sensor&&L(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${f.id} changed sensor identity.`,before:p.sensor,after:f.sensor})}}for(let g of[...new Set([...m.invariants.keys(),...y.invariants.keys()])].sort()){let p=m.invariants.get(g),f=y.invariants.get(g),A=`$.arkRules.invariants[${g}]`;if(!p&&f){L(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${f.id} was added (${f.mode}).`,after:f});continue}if(p&&!f){L(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!f)&&p.mode!==f.mode)if(p.mode==="advisory"&&f.mode==="enforced"){let _=a?.get(f.id),R=an(_);R.ok?L(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${f.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:f.mode}):L(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${f.id} cannot be promoted to enforced: ${R.reason}`,before:p.mode,after:f.mode})}else L(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${f.id} was demoted to advisory.`,before:p.mode,after:f.mode})}}i($i,"compareArkRules");function dn(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."}),ht(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";L(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)&&L(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}),Li(r,e.layers,t.layers),Pi(r,e.rules,t.rules),wi(r,e,t),$i(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Mi(r,e,t),Di(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:cn,classification:Fi(r),findings:r}}i(dn,"classifyArkPolicyDelta");function un(e,t){if(!e||e.schemaVersion!==cn||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(un,"policyDeltaAcknowledgementMatches");function De(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(De,"normalizePath");function io(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(io,"isIdentifierStart");function pn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(pn,"isIdentifierCharacter");function ae(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ae,"skipWhitespace");function At(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(At,"readString");function ce(e,t,n){return e.startsWith(t,n)&&!pn(e[n-1])&&!pn(e[n+t.length])}i(ce,"isWordAt");function lo(e,t){let n=ae(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ae(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ce(e,"type",n))return!1;let s=ae(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ce(e,"as",s)||!io(e[s]))return!1;for(n=s;n<e.length&&pn(e[n]);)n+=1;if(n=ae(e,n),ce(e,"as",n)){if(n=ae(e,n+2),!io(e[n]))return!1;for(;n<e.length&&pn(e[n]);)n+=1}r=!0}return!1}i(lo,"bracedNamedBindingsAreTypeOnly");function Hi(e,t){if(t=ae(e,t+6),e[t]==="(")return At(e,ae(e,t+1));let n=!1;if(ce(e,"type",t)){let s=ae(e,t+4);e[s]!==","&&!ce(e,"from",s)&&(n=!0)}else lo(e,t)&&(n=!0);let r=co(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Hi,"specifierAfterImport");function ji(e,t){t=t+6;let n=ae(e,t),r=!1;if(ce(e,"type",n)){let o=ae(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else lo(e,n)&&(r=!0);let s=co(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(ji,"specifierAfterExport");function co(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ce(e,"from",t))return At(e,ae(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return At(e,t);if(t>0&&(ce(e,"import",t)||ce(e,"export",t)))return}}i(co,"specifierInStaticStatement");function Vi(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(Vi,"skipTemplateLiteral");function Ui(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ae(e,t+7);if(e[r]!=="(")return;r=ae(e,r+1);let s=At(e,r);return s?{...s,requireCall:!0}:void 0}i(Ui,"specifierAfterRequire");function Ki(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=Vi(e,n);continue}if(r==="'"||r==='"'){let o=At(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&ce(e,"import",n)?Hi(e,n):r==="e"&&ce(e,"export",n)?ji(e,n):r==="r"&&ce(e,"require",n)?Ui(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(Ki,"moduleSpecifiers");function uo(e,t){let n=[],r=[];for(let s of Ki(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let u=et(o);if(!u)continue;let m=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:m,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=Gi(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(uo,"moduleFactsFor");function Gi(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(Gi,"resolveSpecifier");function po(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=zt(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 Bi={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 zi(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(zi,"hasActiveArkRules");function qi(e,t){return zi(e,t)?J($(sn({config:e,arkRules:t,warnings:[]}))):J($(Rr(e)))}i(qi,"policyHashFor");function Rt(e,t,n){let r=typeof e=="string"?Xt(e,t):lt(e,t),s=n?.arkRules??Se();return{...r,arkRules:s,policyHash:qi(r.config,s)}}i(Rt,"loadContract");function Ir(e){let t=Rt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Rt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=dn(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&&un(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(Ir,"analyzePolicyDelta");function ze(e){let t=e.files.map(y=>{let g=De(y.path);return{path:g,content:y.content,contentHash:J(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=uo(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(He(y))]));for(let y of s){let g=n.get(y.file)?.layer;if(!g)continue;let p=a.get(g),f=Ie(y.symbol,p?.forbiddenGlobals??[]);if(f){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${g} must not use module "${y.symbol}" because it is the import form of forbidden global "${f}".`,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"?[]:[{...Bi}],m={schemaVersion:en,policyHash:e.contract.policyHash,compilerOptionsHash:J($(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:m}}i(ze,"analyzeProject");function kt(e){let t=new Map(e.files.map(n=>[De(n.path),n]));for(let n of e.changes){let r=De(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return ze({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(kt,"analyzeChange");function vr(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(vr,"explainViolation");function fn(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=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),u.push(m)}while(m!==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(fn,"detectArchitectureCycles");function Me(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=_e(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),m=c?je(a.peerIsolationReason??"cross-slice",{fromPath:o.from,toPath:o.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,y=l.message?m?`${l.message} (${m})`:l.message:m?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}): ${m}`:`${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=fn(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(Me,"evaluateArchitectureGraph");var Wi=["no-anemic-model"];function fo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(fo,"escapeGlobLiteral");function Yi(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+=fo(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=fo(s)}return new RegExp(`^${n}$`)}i(Yi,"globToRegExp");function qe(e,t){return!t||t.length===0?!0:t.some(n=>Yi(n).test(e))}i(qe,"matchesAppliesTo");function Ji(e){return Wi.includes(e)}i(Ji,"isTier2");function mo(e){return e.mode==="enforced"&&!Ji(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(mo,"severityFor");function Fe(e,t,n,r=1){let{severity:s,failsStrict:o}=mo(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(Fe,"baseViolation");function mn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(mn,"isInRuleLayer");function gn(e,t,n){return t.filter(r=>!(!r.exported||!qe(r.file,e.appliesTo)||!mn(r.file,e,n)))}i(gn,"shapesForRule");function Xi(e,t,n){let r=[];for(let s of gn(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Fe(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Xi,"evaluateAggregatePrivateState");function Zi(e,t,n){let r=[];for(let s of gn(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Fe(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Zi,"evaluateAlwaysValidFactory");function Qi(e,t,n){let r=[];for(let s of gn(e,t,n))for(let o of s.mutatingMethods)o.referencesGuardOrPublish||r.push(Fe(e,s.file,`Mutating method ${s.className}.${o.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(Qi,"evaluateDomainEventOnMutation");function el(e,t){let n=[];for(let r of t.files)qe(r,e.appliesTo)&&mn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Fe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(el,"evaluateOrchestrationOnly");function tl(e,t){let n=[];for(let r of t.files)qe(r,e.appliesTo)&&mn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Fe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(tl,"evaluateThinAdapter");function nl(e,t){let n=[];for(let r of t.files)qe(r,e.appliesTo)&&mn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Fe(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(nl,"evaluateWritesViaAggregate");function rl(e,t,n){let r=[];for(let s of gn(e,t,n))if(s.dataOnly===!0){let o=Fe(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(rl,"evaluateNoAnemicModel");function yn(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(...Xi(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Zi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Qi(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...el(n,e));break;case"thin-adapter":t.push(...tl(n,e));break;case"writes-via-aggregate":t.push(...nl(n,e));break;case"no-anemic-model":t.push(...rl(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(yn,"evaluateArkRuleSensors");function hn(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=>qe(c,s.appliesTo)))continue;let{severity:a,failsStrict:l}=mo(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=>qe(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(hn,"collectEmptyAppliesToFindings");var sl=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm|mongoose)/,ol=/\.(?: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,al=/\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*=)/,il=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,ll=/\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*=/,cl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Sr(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(ll.source,"g"))??[],r=t.match(new RegExp(cl.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,o=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+o>=6,l=sl.test(t),c=al.test(t)||il.test(t),u=n.length>=1||r.length>=2,m=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),y=l&&u||c&&u||l&&m&&(s>=4||n.length>=1)||c&&l,g=l&&ol.test(t);return!a&&!y&&!g?null:{...a?{orchestrationHeavy:!0}:{},...y?{adapterThick:!0}:{},...g?{persistenceWrite:!0}:{}}}i(Sr,"deriveArkRuleFileHints");function An(e){let t={};for(let[n,r]of Object.entries(e)){let s=Sr(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}i(An,"buildArkRuleFileHints");function go(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 w=t[c];w==="{"?l+=1:w==="}"&&(l-=1),c+=1}let u=t.slice(a,c-1),m=u.split(`
|
|
12
12
|
`).map(w=>/^\s*\/\//.test(w)||/^\s*\/\*|\*\//.test(w)?w:w.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
|
|
13
|
-
`),y=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(
|
|
13
|
+
`),y=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(m.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(m),g=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(m)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(m.split(`
|
|
14
14
|
`).filter(w=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(w)).join(`
|
|
15
|
-
`)),u=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(p),f=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(p),A=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(p)&&!f,v=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(p)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(p),_=[],R=new Set(["if","match","when"]),I=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,C;for(;(C=I.exec(p))!==null;){let w=C[1];if(R.has(w))continue;let x=C.index+C[0].length,j=1,D=x;for(;D<p.length&&j>0;)p[D]==="{"?j+=1:p[D]==="}"&&(j-=1),D+=1;let te=p.slice(x,D-1);if(!/this\.\w+\s*=/.test(te))continue;let Fe=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(te);_.push({name:w,referencesGuardOrPublish:Fe})}let H=(p.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,k=(g.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,L=H<=1&&k>=2&&(m||y);n.push({file:e,className:o,exported:!0,hasPublicMutableFields:m||y,hasPublicSetters:u,hasPublicConstructor:A,hasStaticFactory:v,mutatingMethods:[..._],dataOnly:L})}return n}i(go,"extractClassShapesFromSource");var yo=50;function hn(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(hn,"normalizeExtraMergeTeethClassification");function me(e){let t=hn(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(me,"extraMergeTeethAllowed");function An(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(An,"classifyResolvedLayerCoverage");function Rn(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(Rn,"isArkRunRuleId");function ho(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(ho,"isArkOrderRuleId");function Sr(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(Sr,"isExtraPlaneFinding");function Ao(e,t={}){if(!Array.isArray(e)||me(t))return e;for(let n of e)Sr(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Ao,"demoteExtraPlaneTeethUnderClassificationFloor");var br="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 kn(e={}){let t=hn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=me(t),a=e.arkRules,l=ke(a?.structureEnforced),c=ke(a?.structureTotal),p=typeof a?.structureAdvisory=="number"?ke(a.structureAdvisory):Math.max(0,c-l),g=ke(a?.invariantEnforced),y=ke(a?.invariantTotal),m=typeof a?.invariantAdvisory=="number"?ke(a.invariantAdvisory):Math.max(0,y-g),u=l>0||g>0,f=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,v=ke(e.arkRun?.residualCount),_=f&&A==="enforced",R=_&&o,I=u||_,C=I&&o,H=I&&s&&!o,k;if(C){let w=[];u&&w.push("enforced structure/invariant findings"),_&&w.push("enforced ArkRun skip findings"),k=`Layer graph failures plus ${w.join(" and ")} (advisory extras never fail merge alone).`}else H?k=`Layer graph only \u2014 enforced ${[u?"ArkRules structure/invariant":null,_?"ArkRun":null].filter(x=>!!x).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."+(f?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let L={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:p,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:g,advisory:m,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:f,mode:A,residualCount:v,extraMergeTeeth:R,note:f?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:C,dualPlaneStamp:br,failMergeWhen:k};return s&&(L.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),L}i(kn,"composeMergePlanesHonesty");var Or=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],ko=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],ll=new Set(Or),cl=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"]),dl=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 _r=["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"],Cr=new Set(_r);function In(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Cr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Cr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Cr.has(e.slice(0,r))}i(In,"isArkRunTransportBypassSpecifier");function En(e){if(ll.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(En,"arkRunKernelCallKind");function Et(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(Et,"lineAt");function It(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(It,"stripCommentsPreservingLines");function ul(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(ul,"firstStringLiteralArg");function Ro(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(Ro,"keywordBefore");function vn(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(vn,"parseValueImportClause");function pl(e,t){vn(It(e),t)}i(pl,"forEachArkRunValueImportClause");function Sn(e,t){let n=It(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:Et(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:Et(t,o.index),resolution:"resolved-external"})}return r}i(Sn,"extractArkRunValueImportDependenciesFromSource");function bn(e){let t=[];return pl(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)}}),kt(t)}i(bn,"extractArkRunImportedConstructorNamesFromSource");function fl(e){let t=new Map,n=new Set;return vn(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 p=c.trim();if(!p||p.startsWith("type "))continue;let g=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);if(g){t.set(g[2],g[1]);continue}let y=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);y?.[1]&&t.set(y[1],y[1])}}),{named:t,namespaces:n}}i(fl,"collectKernelImportBindings");function ml(e,t){let n=new Set(t);return vn(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),p=c?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(l)?.[1],g=c?.[1]??p;!p||!g||!/^[A-Z]/.test(g)||(qe(s)||t.has(g)||t.has(p))&&(n.add(p),n.add(g))}}),n}i(ml,"collectImportedConstructors");function gl(e,t){let n;return vn(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(gl,"importedFromForName");function Cn(e,t){let n=It(t),r=fl(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(Ro(n,c,"function")||Ro(n,c,"class"))continue;let g=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],y=r.named.get(l)??l,m=En(y)??En(l);if(!m)continue;let u=r.named.has(l)||g!==void 0&&r.namespaces.has(g);if(m!=="factory"&&(!u&&g===void 0||g&&dl.has(g)&&!u))continue;let f=ul(n,c+a[0].length);s.push({file:e,line:Et(t,c),kind:m,callee:l,viaImport:u,...g?{receiver:g}:{},...f?{nameLiteral:f}:{}})}return s}i(Cn,"extractArkRunKernelCallsFromSource");function On(e,t,n){let r=It(t),s=ml(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(cl.has(c)||!s.has(c))continue;let p=gl(r,c);o.push({file:e,line:Et(t,l.index),typeName:c,...p?{importedFrom:p}:{}})}return o}i(On,"extractArkRunManagedNewsFromSource");function yl(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(yl,"matchingBracketEnd");function hl(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(hl,"stringLiteralsInList");function kt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(kt,"uniqueSorted");function Eo(e,t){let n=It(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],l=[],c,p;for(;(p=r.exec(n))!==null;){let g=n.slice(p.index+p[0].length),y=/^\s*\[/.exec(g);if(!y)continue;let m=p.index+p[0].length+(y[0].length-1),u=yl(n,m);if(u<0)continue;let f=hl(n,m,u);if(f.length===0)continue;c===void 0&&(c=p.index);let A=p[1];A==="uses"?s.push(...f):A==="reactsTo"?o.push(...f):A==="raises"?a.push(...f):l.push(...f)}return c===void 0?[]:[{file:e,line:Et(t,c),uses:kt(s),reactsTo:kt(o),raises:kt(a),sends:kt(l)}]}i(Eo,"extractArkRunDeclarationsFromSource");var So=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Al=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Rl=new Set(Al);function kl(e){return Rl.has(e)}i(kl,"isArkRunEditorSensor");var _n={"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"},xr="ARKRUN_INTERACTION_NAME_INCOMPLETE";function bo(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(bo,"isDomainRoleLayer");function El(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(El,"compareFindings");function Ee(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:_n[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:fe({ruleId:_n[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Ee,"finding");function Il(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(Il,"bagForFile");function Io(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Io,"emitKinds");function vo(e){return e==="subscribe"||e==="register-handler"}i(vo,"handleKinds");function vl(e){return e==="resolve"||e==="resolve-singleton"}i(vl,"dependKinds");function Sl(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((p,g)=>p.file.localeCompare(g.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(p=>p.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(Sl,"evaluateMissingRoot");function bl(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 p=r(l.from);p&&bo(p,o.get(p)??[])&&a.push(Ee(e,"arkrun-kernel-in-domain",l.from,l.line,`${p} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:p,target:c},s))}return a}i(bl,"evaluateKernelInDomain");function Cl(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(g=>[g.name,g.intentPrefixes??[]])),c=new Set(r.filter(g=>g.hasKernelFactory).map(g=>g.file)),p=[];for(let g of n){if(c.has(g.file))continue;let y=g.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let m=s(g.file);!m||!a.has(m)||bo(m,l.get(m)??[])||p.push(Ee(e,"arkrun-direct-new",g.file,g.line,`${m} must not construct ${g.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:m,target:g.typeName},o))}return p}i(Cl,"evaluateDirectNew");function Ol(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(!Io(c.kind)&&!vo(c.kind)&&!vl(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:xr,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let g=Il(n,c.file);if(Io(c.kind)){if(g.raises.has(c.nameLiteral)||g.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:p,target:c.nameLiteral},s));continue}if(vo(c.kind)){if(g.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:p,target:c.nameLiteral},s));continue}g.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:p,target:c.nameLiteral},s))}return{findings:o,completenessReasons:a}}i(Ol,"evaluateUndeclared");function _l(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||!In(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(_l,"evaluateTransportBypass");function vt(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=me(e.classification),r=Ol(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Sl(t,e.compositionRootHits,n),...bl(t,e.layers,e.dependencies,e.layerForFile,n),...Cl(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,..._l(t,e.dependencies,e.layerForFile,n)].sort(El),o=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:s,completenessReasons:o}}i(vt,"evaluateArkRunSensors");function Tr(e){return{findings:vt(e).findings.filter(n=>kl(n.sensor)),completenessReasons:[]}}i(Tr,"evaluateArkRunEditorSensors");function xl(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(xl,"fileMatchesCompositionRoot");function Tl(e,t,n){let r=Cn(t,n).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)xl(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:r});return s}i(Tl,"compositionRootHitsForSource");function Co(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(bn(e.source));return Tr({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:On(e.file,e.source,n),compositionRootHits:Tl(t,e.file,e.source),declarations:[],dependencies:Sn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Co,"evaluateArkRunEditorSensorsFromSource");function Oo(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Oo,"isArkOrderModuleSpecifier");var _o=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write","arkorder-information-budget","arkorder-xi-ttl"],xn={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function Nl(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(Nl,"isDomainRoleLayer");function Ie(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:xn[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:fe({ruleId:xn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Ie,"finding");function Tn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=me(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(Ie(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let p of e.planeRootHits){let g=c.get(p.matchedRoot)??[];g.push(p),c.set(p.matchedRoot,g)}for(let p of s){let g=c.get(p)??[];if(g.length===0){r.push(Ie(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(p)} matched no governed files and has no createOrderPlane factory.`,{target:p},n));continue}g.some(y=>y.hasPlaneFactory)||r.push(Ie(t,"arkorder-missing-plane",g[0].file,1,`ArkOrder plane root ${JSON.stringify(p)} has no createOrderPlane factory.`,{target:p},n))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let p=c.specifier;if(!p||!Oo(p))continue;let g=e.layerForFile(c.from);g&&Nl(g,o.get(g)??[])&&r.push(Ie(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:g,target:p},n))}for(let c of e.genericUpdates)r.push(Ie(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];a.length>t.maxXiKeys&&r.push(Ie(t,"arkorder-too-many-params","ark.config.json",1,`arkOrder.xiKeys has ${a.length} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(a.length)},n));for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Ie(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(Ie(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let p=e.layerForFile(c.file);!p||!l.has(p)||r.push(Ie(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:p,target:c.key},n))}return r.sort((c,p)=>c.file.localeCompare(p.file)||c.ruleId.localeCompare(p.ruleId)||c.line-p.line),{findings:r,completenessReasons:[]}}i(Tn,"evaluateArkOrderSensors");function se(e,t,n={}){return{ruleId:e,message:t,...n}}i(se,"configWarning");function St(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(u=>typeof u!="string"))&&o.push(se("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(se("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let u of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[u];f!==void 0&&(!Number.isInteger(f)||f<0)&&o.push(se("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${u} 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(u=>u.name).filter(Boolean),...l.map(u=>u.name).filter(u=>!!u)]);a.length===0&&o.push(se("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,g=new Set;for(let u of a){if(!u.name){o.push(se("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(u.name)&&g.add(u.name),p.add(u.name),u.forbiddenGlobals!==void 0&&(!Array.isArray(u.forbiddenGlobals)||u.forbiddenGlobals.some(A=>typeof A!="string"))&&o.push(se("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${u.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:u.name}));let f=Array.isArray(u.patterns)?u.patterns:[];if(f.length===0){o.push(se("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${u.name}" has no file patterns and will never classify files.`,{layer:u.name}));continue}for(let A of f){let v;try{v=ge(A)}catch(R){o.push(se("CONFIG_INVALID_LAYER_PATTERN",`Layer "${u.name}" has an invalid pattern "${A}": ${R instanceof Error?R.message:String(R)}`,{layer:u.name,pattern:A}));continue}let _=u.optional===!0||u.reserved===!0||u.allowEmpty===!0;!r.some(R=>v.test(R))&&!_&&o.push(se("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${u.name}" pattern "${A}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:u.name,pattern:A,failsStrict:!1,reserved:!1}))}}for(let u of g)o.push(se("CONFIG_DUPLICATE_LAYER",`Layer "${u}" is configured more than once.`,{layer:u}));if(c.size>0)for(let u of n??[])u.from&&!c.has(u.from)&&o.push(se("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${u.from}".`,{fromLayer:u.from,toLayer:u.to})),u.to&&!c.has(u.to)&&o.push(se("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${u.to}".`,{fromLayer:u.from,toLayer:u.to}));let y=new Set;if(a.length>1)for(let u of r){let f=-1,A=[];for(let v of a)for(let _ of v.patterns??[]){if(!ge(_).test(u))continue;let R=sr(_,u);R>f?(f=R,A=[v.name]):R===f&&!A.includes(v.name)&&A.push(v.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&o.push(se("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 m=r.filter(u=>!de(u,a));return m.length>0&&o.push(se("CONFIG_UNCLASSIFIED_FILES",`${m.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:m.length,samples:m.slice(0,5)})),o}i(St,"collectAnalysisConfigWarnings");function Ll(e,t){return t.some(n=>{try{return ge(n).test(e)}catch{return!1}})}i(Ll,"matchesAny");function Pl(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:v})=>({file:A,line:v})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:v})=>({file:A,line:v})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Ll(A.file,o)).map(A=>({file:A.file,line:A.line,kind:A.kind==="dynamic-require"?"require":"import"})),p=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"})),g=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:p,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},m=[],u=c.filter(A=>A.kind==="import");if(u.length>0){let A=u[0];m.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${u.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let f=c.filter(A=>A.kind==="require");if(f.length>0){let A=f[0];m.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${f.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let A=a[0];m.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];m.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(p.length>0){let A=p[0];m.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:A.file,line:A.line,message:`${p.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 g.length>0&&m.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:y,warnings:m}}i(Pl,"evaluateSafety");function wl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(wl,"ambientForbiddenGlobal");function xo(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return ur(e,n.length>0?n:dr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(xo,"intentLayer");function Dl(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||!wl(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??[],p=o.source==="import-based"?t.dependencies.find(g=>g.from===o.file&&g.line===o.line&&g.specifier===o.symbol&&!g.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&et(o.symbol,c))){if(o.source==="import-based"){let g=ve(o.symbol,c);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...p?{edgeKind:p}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${g}".`});continue}}$e(l).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...p?{edgeKind:p}:{},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 tt({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=xo(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=xo(o.intent,e.contract);if(!l)continue;let c=_e(e.contract.config.rules,a,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:l,target:o.intent,message:c.message??`${a} must not reference ${l} intent ${o.intent}.`})}return r}i(Dl,"contentViolations");function Ml(e){let{facts:t}=e,n=Ge(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,P)=>{let V=`${d.code}\0${d.file??""}\0${d.message}`,ie=`${P.code}\0${P.file??""}\0${P.message}`;return V<ie?-1:V>ie?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 P=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,...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}:{}}}),p=St({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),g=Pl(e,t),y=e.contract.arkRules??be(),m=a.map(d=>d.path),f={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?yn(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=[...mn({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:m,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),fileHints:f}),...gn(y,m)],v=A.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:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),_=A.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==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),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},C=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.`})),H=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=An(a),L=vt({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}),w=e.contract.config.arkRun?.mode,x=L.findings.filter(()=>w==="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=L.findings.filter(()=>w!=="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=Tn({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}),te=e.contract.config.arkOrder?.mode,pe=D.findings.filter(()=>te==="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}:{}})),Fe=D.findings.filter(()=>te!=="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})),Ze=[...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."}]:[],...L.completenessReasons,...D.completenessReasons],Oe=De({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Dl(e,t,l),...v,...C,...x,...pe],edges:c,warnings:[...p,...g.warnings,..._,...H,...j,...Fe],safety:g.report}),wt=s==="complete"&&Ze.length>0?"partial":s,Bn=wt==="complete"?o:[...o,...Ze].sort((d,P)=>{let V=`${d.code}\0${d.file??""}\0${d.message}`,ie=`${P.code}\0${P.file??""}\0${P.message}`;return V<ie?-1:V>ie?1:0}),S=Oe.violations.filter(d=>d.failsStrict!==!1),b=wt==="complete"&&S.length===0,h=b&&Oe.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:wt,completenessReasons:Bn,valid:b,strictValid:h,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.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:Oe.violations,warnings:Oe.warnings}}}i(Ml,"analyzeCanonicalResolvedProject");function We(e){return Ml({contract:e.contract,facts:Re(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(We,"analyzeResolvedProject");function To(e){return X(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(To,"analysisTreeHash");function Nr(e){let t=Be(e),n=new Map(t.ir.files.map(f=>[f.path,f])),r=[],s=new Set,o=[];for(let f of e.changes){let A=f.path.replace(/\\/g,"/"),v=we(f.path);if(!v||v===".."||v.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(v)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}s.add(v),"delete"in f&&f.delete&&!n.has(v)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base tree.`}),r.push("delete"in f&&f.delete?{path:v,delete:!0}:{path:v,content:"content"in f?f.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=Rt({...e,changes:r}),l=new Map(a.ir.files.map(f=>[f.path,f])),c=a.ir.violations.filter(f=>f.ruleId==="CAPABILITY_VIOLATION"||f.ruleId==="FORBIDDEN_GLOBAL").map(f=>{let A=l.get(f.evidence.file)?.layer;return{ruleId:f.ruleId,file:f.evidence.file,line:f.evidence.line,target:f.symbol,...f.capability?{capability:f.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:f.message}}),p=De({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(f=>f.path),contentViolations:c,edges:a.ir.edges.filter(f=>!!f.fromLayer).map(f=>({from:f.from,fromLayer:f.fromLayer,...f.to?{to:f.to}:{},...f.toLayer?{toLayer:f.toLayer}:{},line:f.evidence.line,kind:"import",...f.typeOnly?{typeOnly:!0}:{},...f.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(f=>{let A=we(f.path),v=n.get(A),_=l.get(A);return{path:A,operation:"delete"in f&&f.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},..._?{candidateContentHash:_.contentHash}:{}}}).sort((f,A)=>f.path.localeCompare(A.path)),y=[...o,...p.violations].map(f=>({...f,nextAction:fe(f)})),m=y.filter(f=>f.failsStrict!==!1),u=e.changeMap?Le({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:a.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&m.length===0&&(u?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:To(t.ir.files),candidateTreeHash:To(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...u?{convergence:u}:{},changes:g,violations:y,warnings:p.warnings}}i(Nr,"preflightChange");function Fl(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(Fl,"canonicalChangePath");function $l(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($l,"identityViolations");function Hl(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(Hl,"preparedChange");function Lr(e){let t=Re(e.baseFacts),n=Re(e.candidateFacts),r=We({contract:e.contract,facts:t}),s=We({contract:e.contract,facts:n}),o=new Map(t.files.map(u=>[u.path,u])),a=new Map(n.files.map(u=>[u.path,u])),l=$l(t,n),c=new Map,p=[];for(let u of e.changes){let f=Fl(u.path);if(!f){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(f)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}c.set(f,u);let A=o.get(f),v=a.get(f);if("delete"in u&&u.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base facts.`}),v&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:f,line:1,message:`Candidate facts still contain deleted file ${f}.`});else{let _="content"in u?u.content:"",R=X(_);v?v.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:f,line:1,expectedContentHash:R,candidateContentHash:v.contentHash,message:`Candidate facts for ${f} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:f,line:1,message:`Candidate facts do not contain changed file ${f}.`})}p.push(Hl(u,f,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 u of new Set([...o.keys(),...a.keys()])){if(c.has(u))continue;let f=o.get(u),A=a.get(u);f&&A&&F(f)===F(A)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:u,line:1,message:`Candidate facts change ${u}, but the atomic change set does not declare it.`})}let g=e.changeMap?Le({changeMap:e.changeMap,changes:p,baseDependencies:r.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:s.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0,y=[...l,...s.ir.violations].map(u=>({...u,nextAction:fe(u)})),m=y.filter(u=>u.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&m.length===0&&(g?.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}:{},...g?{convergence:g}:{},changes:p.sort((u,f)=>u.path<f.path?-1:u.path>f.path?1:0),violations:y,warnings:s.ir.warnings}}i(Lr,"preflightResolvedChange");var Pr="1.0",jl=12;function No(e){return e==="enforced"||e==="advisory"?e:null}i(No,"closedMode");function Vl(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!Rn(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(Vl,"uniqueArkRunRuleIds");function Ul(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:No(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(Ul,"extraFromConfig");function Lo(e={}){let t=Ul(e.arkRun),n=t.present?Vl(e.findings):[],r=n.slice(0,jl),s=n.length,o=kn({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"&&me(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:Pr,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(Lo,"summarizeArkRunSection");function Nn(e={}){let t=e.present===!0,n=No(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(Nn,"projectStatusArkRun");function Po(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(Po,"formatArkRunDoctorLines");function Ln(e,t){return e.slice(0,t).split(`
|
|
16
|
-
`).length}i(Ln,"lineOf");function wo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(wo,"normalizeInventoryPath");function Mo(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(Mo,"ownsIntent");function Do(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Mo(t,["Domain"])}i(Do,"isDomainLayer");function Kl(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Mo(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Kl,"isControllerEligibleLayer");function Gl(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(Gl,"isNonPilotSurface");function Fo(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,p])=>[wo(c),p])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>Do(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,p]of Object.entries(e.fileContents).sort(([g],[y])=>g.localeCompare(y))){let g=wo(c);if(Gl(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(p.slice(0,320)))continue;let y=r.has(g),m=r.get(g),u=m?s.get(m)??[]:[],f=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),v=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(p),_=/controller|handler|resolver/i.test(c)||A||v||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!f||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(p)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(p)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(p),R=y?!!(m&&Kl(m,u)&&_):_,I=y?!!(m&&Do(m,u)):/domain|entity|aggregate|model/i.test(c),C=!y||I||R;if(R&&!f){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,j;for(;(j=x.exec(p))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:Ln(p,j.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:m,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let H=/\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"),w=i((x,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(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=j.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(j)&&(/\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=H.exec(p))!==null;){let x=k[2],j=k[3]??"";!C||L(x)||w(x,j)||f&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:Ln(p,k.index),message:`Magic business constant ${x} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:o,invariantId:`INV-${x}`},neverMechanicalSafe:!0}))}if(I){let x=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,j;for(;(j=x.exec(p))!==null;){let D=j[2]??"",te=(D.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(D.match(/:\s*[A-Za-z]/g)??[]).length>=2&&te<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:Ln(p,j.index),message:`Class ${j[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let j=/this\.\w+\s*=/g,D;for(;(D=j.exec(p))!==null;){let te=p.lastIndexOf("class ",D.index),pe=te>=0?p.indexOf("{",te):-1,Fe=te>=0&&pe>=te&&pe<D.index?p.slice(te,pe):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(Fe))continue;let Je=p.slice(Math.max(0,D.index-200),D.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(Je)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:Ln(p,D.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:m,suggestedArkRule:{layer:o,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((c,p)=>+(p.confidence==="direct-evidence")-+(c.confidence==="direct-evidence")||c.file.localeCompare(p.file)||c.line-p.line||c.kind.localeCompare(p.kind)||c.id.localeCompare(p.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(Fo,"buildRulesInventory");function $o(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($o,"inventoryToExtractionCard");var Ho="1.1";var jo="1.0";var Pn="docs/diagnostics.md",Vo="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 bt=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("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.")]),wr=new Map(bt.map(e=>[e.ruleId,e])),Uo=Object.freeze(bt.map(e=>e.ruleId));function Ko(e){return typeof e=="string"&&e.length>0&&wr.has(e)}i(Ko,"isKnownDiagnosticCode");function Go(e){return typeof e!="string"||e.length===0?!1:wr.has(e)?!0:e.startsWith("ARKRULE_")}i(Go,"isCataloguedOrArkRuleFamily");function Ct(e){if(!(typeof e!="string"||e.length===0))return wr.get(e)}i(Ct,"getDiagnosticCatalogEntry");function Dr(e){return`#${Ct(e)?.docsAnchor??e}`}i(Dr,"diagnosticDocsFragment");function Bo(e){return`${Pn}${Dr(e)}`}i(Bo,"diagnosticDocsPath");function zo(){return{schemaVersion:"1.0",docsPath:Pn,codes:bt}}i(zo,"serializeDiagnosticCatalog");function qo(e){return Ct(e)?.fix}i(qo,"catalogFixForRuleId");function Wo(e){return Ct(e)?.why}i(Wo,"catalogWhyForRuleId");var wn="1.0",Mr="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Fr=["full","subset","unavailable"],$r=["doctor-facts","report-snapshot","none"],_t={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Yo=/^sha256:[a-f0-9]{64}$/;function Hr(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"||!Yo.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(Hr,"evaluateStatusBinding");function jr(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(jr,"classifyStatusWritePath");function Vr(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(Vr,"defaultHonestLabel");function Ur(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(Ur,"resolveStatusNextAction");function Xo(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Yo.test(e.projectId)?e.projectId:null,r=Hr({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=jr({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Vr(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:Ot(e.activeViolations),frozenResidual:Ot(e.frozenResidual)},p={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Ot(e.rulesInventoried),underContract:Ot(e.rulesUnderContract),frozenResidual:Ot(e.rulesFrozenResidual)},g={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}:{}},m={schemaVersion:wn,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:g,lastCheck:c,rules:p,nextAction:Ur(e,r,g,c,p)},u=Kr(e.improvementCompass);return u&&(m.improvementCompass=u),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(m.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(m.arkRun=Nn(e.arkRun)),m}i(Xo,"buildStatusManifest");var Jo=new Set(Fr),Bl=new Set($r);function Dn(e){let t=Jo.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Bl.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(Dn,"projectStatusImprovementCompass");function Zo(e={}){return Dn({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(Zo,"unavailableStatusImprovementCompass");function Kr(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"&&Jo.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Dn({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(Kr,"normalizeStatusImprovementCompass");function Qo(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(Qo,"statusCompassResidualIsSubsetOfDoctor");function Ot(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(Ot,"numberOrNull");var ea={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Mr,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:wn},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 xt="1.0",Tt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Nt=5,Ce=["scalability","resilience","security"],Ye=new Set(Ce),Gr={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},Br={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"},zr={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 qr(e){return Br[e]??e}i(qr,"improvementCompassHumanLabel");function Wr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Wr,"smellIdOf");function Yr(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Yr,"violationRuleId");function K(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(K,"pushEvidence");function ee(e,t,n){Ye.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(ee,"markResidual");function ta(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`${Br[e]} \u2014 no residual from current sensors.`}}i(ta,"defaultOkSummary");function na(){return Tt.map(e=>Ye.has(e)?{id:e,status:"out-of-scope",summary:zr[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:ta(e),evidence:[]}:{id:e,status:"ok",summary:ta(e),evidence:[]})}i(na,"createInitialImprovementCompassLenses");function zl(e,t){for(let n of t){let r=Wr(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((g,y,m)=>{let u=e.get(g);!u||Ye.has(g)||(K(u,"designSmells",r,s),a&&K(u,"designSmells",a,r),ee(u,y,m))},"attach"),c={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},p={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.",p);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.",p),l("testability","Direct I/O under application code hurts pure unit testing.",p);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(zl,"mapDesignSmells");function ql(e){return e.failsStrict===!1||e.typeOnly===!0}i(ql,"isTypeOnlyPlacementDebt");function Wl(e,t){for(let n of t){let r=Yr(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=i((c,p,g)=>{let y=e.get(c);!y||Ye.has(c)||(K(y,"violations",r,s),n.file&&K(y,"violations",n.file,r),ee(y,p,g))},"attach");if(ql(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(Wl,"mapViolations");function Yl(e,t){let n=Number(t.cycleCount)||0;if(n>0){let u=e.get("coupling");K(u,"cycles",`count:${n}`),ee(u,"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 u=e.get("coupling");K(u,"peerIsolation",`count:${r}`),ee(u,"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 u=e.get("cohesion");K(u,"physicalCohesion",`findings:${s}`),ee(u,"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 f=e.get("srp");K(f,"physicalCohesion",`findings:${s}`),ee(f,"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 u=e.get("dip");o>0&&K(u,"capability",`residual:${o}`),a>0&&K(u,"forbiddenGlobals",`residual:${a}`),ee(u,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let f=e.get("testability");o>0&&K(f,"capability",`residual:${o}`),a>0&&K(f,"forbiddenGlobals",`residual:${a}`),ee(f,"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 u=e.get("encapsulation");K(u,"arkRules",`structureResidual:${l}`),ee(u,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let f=e.get("domain");K(f,"arkRules",`structureResidual:${l}`),ee(f,"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 u=e.get("maintainability");K(u,"designFitness","design-weak"),ee(u,"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 u=e.get("maintainability");t.dirtyBaselineRisk===!0&&K(u,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(u,"baseline",`stale:${t.baselineStale}`),ee(u,"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 u=e.get("maintainability");K(u,"baseline",`frozen:${c}`),ee(u,"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 p=Number(t.ungovernedDirCount)||0,g=Number(t.emptyLayerCount)||0;if(p>0||g>0){let u=e.get("modularity");p>0&&K(u,"coverage",`ungovernedDirs:${p}`),g>0&&K(u,"coverage",`emptyLayers:${g}`),ee(u,"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 u=e.get("modularity");K(u,"goldenPattern","absent"),ee(u,"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(Yl,"mapCountsAndFlags");function ra(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>Wr(r).localeCompare(Wr(s)));zl(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=Yr(r).localeCompare(Yr(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});Wl(e,n)}Yl(e,t)}i(ra,"projectImprovementCompassFacts");function sa(e){for(let t of Ce){let n=e.get(t);n.status="out-of-scope",n.summary=zr[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(sa,"lockImprovementCompassOutOfScope");function oa(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(oa,"sortImprovementCompassEvidence");function aa(e){return e.filter(n=>n.status==="residual"&&!Ye.has(n.id)).slice().sort((n,r)=>{let s=Gr[n.id]??150,o=Gr[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(aa,"finalizeImprovementCompassTopResidual");function ia(e={}){let t=na(),n=new Map(t.map(s=>[s.id,s]));ra(n,e),sa(n),oa(t);let r=aa(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(ia,"buildImprovementCompass");function Xr(e){return e.topResidual.map(t=>qr(t))}i(Xr,"formatImprovementCompassResidualLabels");function Jr(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(Jr,"primaryImprovementCompassNextAction");function la(e){let t=Xr(e),n=Ce.map(o=>qr(o)),r=Jr(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(la,"formatImprovementCompassDoctorLines");var ca="1.0",da="<!-- arkgate:agent-projection:begin",Zr="<!-- arkgate:agent-projection:end -->",Qr="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",Hn=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),ua=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"]),es=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,pa=/<!--\s*arkgate:agent-projection:end\s*-->/i,Xl=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Jl=/\bschema=([A-Za-z0-9._+-]+)/i;function Lt(e){let t=String(e??"").replace(/\r\n/g,`
|
|
17
|
-
`),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(
|
|
18
|
-
`)}i(
|
|
15
|
+
`)),p=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),f=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),A=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!f,v=/(?:^|[\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),_=[],R=new Set(["if","match","when"]),I=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,b;for(;(b=I.exec(u))!==null;){let w=b[1];if(R.has(w))continue;let x=b.index+b[0].length,j=1,M=x;for(;M<u.length&&j>0;)u[M]==="{"?j+=1:u[M]==="}"&&(j-=1),M+=1;let te=u.slice(x,M-1);if(!/this\.\w+\s*=/.test(te))continue;let $e=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(te);_.push({name:w,referencesGuardOrPublish:$e})}let D=(u.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,k=(m.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,T=D<=1&&k>=2&&(g||y);n.push({file:e,className:o,exported:!0,hasPublicMutableFields:g||y,hasPublicSetters:p,hasPublicConstructor:A,hasStaticFactory:v,mutatingMethods:[..._],dataOnly:T})}return n}i(go,"extractClassShapesFromSource");var yo=50;function Rn(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(Rn,"normalizeExtraMergeTeethClassification");function me(e){let t=Rn(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(me,"extraMergeTeethAllowed");function kn(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(kn,"classifyResolvedLayerCoverage");function En(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(En,"isArkRunRuleId");function ho(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(ho,"isArkOrderRuleId");function br(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(br,"isExtraPlaneFinding");function Ao(e,t={}){if(!Array.isArray(e)||me(t))return e;for(let n of e)br(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(Ao,"demoteExtraPlaneTeethUnderClassificationFloor");var Cr="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 In(e={}){let t=Rn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=me(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),m=ke(a?.invariantEnforced),y=ke(a?.invariantTotal),g=typeof a?.invariantAdvisory=="number"?ke(a.invariantAdvisory):Math.max(0,y-m),p=l>0||m>0,f=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,v=ke(e.arkRun?.residualCount),_=f&&A==="enforced",R=_&&o,I=p||_,b=I&&o,D=I&&s&&!o,k;if(b){let w=[];p&&w.push("enforced structure/invariant findings"),_&&w.push("enforced ArkRun skip findings"),k=`Layer graph failures plus ${w.join(" and ")} (advisory extras never fail merge alone).`}else D?k=`Layer graph only \u2014 enforced ${[p?"ArkRules structure/invariant":null,_?"ArkRun":null].filter(x=>!!x).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."+(f?A==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let T={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:m,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:f,mode:A,residualCount:v,extraMergeTeeth:R,note:f?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:b,dualPlaneStamp:Cr,failMergeWhen:k};return s&&(T.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),T}i(In,"composeMergePlanesHonesty");var _r=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],ko=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],dl=new Set(_r),ul=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"]),pl=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function We(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(We,"isArkRunKernelModuleSpecifier");var xr=["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"],Or=new Set(xr);function Sn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Or.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Or.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Or.has(e.slice(0,r))}i(Sn,"isArkRunTransportBypassSpecifier");function vn(e){if(dl.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(vn,"arkRunKernelCallKind");function It(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(It,"lineAt");function vt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}i(vt,"stripCommentsPreservingLines");function fl(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(fl,"firstStringLiteralArg");function Ro(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(Ro,"keywordBefore");function bn(e,t){let n=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;)r[1]||t(r[2]??"",r[3]??"")}i(bn,"parseValueImportClause");function ml(e,t){bn(vt(e),t)}i(ml,"forEachArkRunValueImportClause");function Cn(e,t){let n=vt(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:It(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:It(t,o.index),resolution:"resolved-external"})}return r}i(Cn,"extractArkRunValueImportDependenciesFromSource");function On(e){let t=[];return ml(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)}}),Et(t)}i(On,"extractArkRunImportedConstructorNamesFromSource");function gl(e){let t=new Map,n=new Set;return bn(e,(r,s)=>{if(!We(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 m=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(m){t.set(m[2],m[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(gl,"collectKernelImportBindings");function yl(e,t){let n=new Set(t);return bn(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],m=c?.[1]??u;!u||!m||!/^[A-Z]/.test(m)||(We(s)||t.has(m)||t.has(u))&&(n.add(u),n.add(m))}}),n}i(yl,"collectImportedConstructors");function hl(e,t){let n;return bn(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(hl,"importedFromForName");function _n(e,t){let n=vt(t),r=gl(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(Ro(n,c,"function")||Ro(n,c,"class"))continue;let m=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],y=r.named.get(l)??l,g=vn(y)??vn(l);if(!g)continue;let p=r.named.has(l)||m!==void 0&&r.namespaces.has(m);if(g!=="factory"&&(!p&&m===void 0||m&&pl.has(m)&&!p))continue;let f=fl(n,c+a[0].length);s.push({file:e,line:It(t,c),kind:g,callee:l,viaImport:p,...m?{receiver:m}:{},...f?{nameLiteral:f}:{}})}return s}i(_n,"extractArkRunKernelCallsFromSource");function xn(e,t,n){let r=vt(t),s=yl(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(ul.has(c)||!s.has(c))continue;let u=hl(r,c);o.push({file:e,line:It(t,l.index),typeName:c,...u?{importedFrom:u}:{}})}return o}i(xn,"extractArkRunManagedNewsFromSource");function Al(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(Al,"matchingBracketEnd");function Rl(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(Rl,"stringLiteralsInList");function Et(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Et,"uniqueSorted");function Eo(e,t){let n=vt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],l=[],c,u;for(;(u=r.exec(n))!==null;){let m=n.slice(u.index+u[0].length),y=/^\s*\[/.exec(m);if(!y)continue;let g=u.index+u[0].length+(y[0].length-1),p=Al(n,g);if(p<0)continue;let f=Rl(n,g,p);if(f.length===0)continue;c===void 0&&(c=u.index);let A=u[1];A==="uses"?s.push(...f):A==="reactsTo"?o.push(...f):A==="raises"?a.push(...f):l.push(...f)}return c===void 0?[]:[{file:e,line:It(t,c),uses:Et(s),reactsTo:Et(o),raises:Et(a),sends:Et(l)}]}i(Eo,"extractArkRunDeclarationsFromSource");var So=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],kl=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],El=new Set(kl);function Il(e){return El.has(e)}i(Il,"isArkRunEditorSensor");var Tn={"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"},Tr="ARKRUN_INTERACTION_NAME_INCOMPLETE";function bo(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(bo,"isDomainRoleLayer");function vl(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(vl,"compareFindings");function Ee(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Tn[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:fe({ruleId:Tn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Ee,"finding");function Sl(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(Sl,"bagForFile");function Io(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Io,"emitKinds");function vo(e){return e==="subscribe"||e==="register-handler"}i(vo,"handleKinds");function bl(e){return e==="resolve"||e==="resolve-singleton"}i(bl,"dependKinds");function Cl(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,m)=>u.file.localeCompare(m.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(Cl,"evaluateMissingRoot");function Ol(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||!We(c))continue;let u=r(l.from);u&&bo(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(Ol,"evaluateKernelInDomain");function _l(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(m=>[m.name,m.intentPrefixes??[]])),c=new Set(r.filter(m=>m.hasKernelFactory).map(m=>m.file)),u=[];for(let m of n){if(c.has(m.file))continue;let y=m.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let g=s(m.file);!g||!a.has(g)||bo(g,l.get(g)??[])||u.push(Ee(e,"arkrun-direct-new",m.file,m.line,`${g} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:g,target:m.typeName},o))}return u}i(_l,"evaluateDirectNew");function xl(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(!Io(c.kind)&&!vo(c.kind)&&!bl(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:Tr,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let m=Sl(n,c.file);if(Io(c.kind)){if(m.raises.has(c.nameLiteral)||m.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(vo(c.kind)){if(m.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}m.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(xl,"evaluateUndeclared");function Tl(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||!Sn(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(Tl,"evaluateTransportBypass");function St(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=me(e.classification),r=xl(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Cl(t,e.compositionRootHits,n),...Ol(t,e.layers,e.dependencies,e.layerForFile,n),..._l(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Tl(t,e.dependencies,e.layerForFile,n)].sort(vl),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(St,"evaluateArkRunSensors");function Nr(e){return{findings:St(e).findings.filter(n=>Il(n.sensor)),completenessReasons:[]}}i(Nr,"evaluateArkRunEditorSensors");function Nl(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(Nl,"fileMatchesCompositionRoot");function Ll(e,t,n){let r=_n(t,n).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)Nl(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:r});return s}i(Ll,"compositionRootHitsForSource");function Co(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(On(e.source));return Nr({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:xn(e.file,e.source,n),compositionRootHits:Ll(t,e.file,e.source),declarations:[],dependencies:Cn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(Co,"evaluateArkRunEditorSensorsFromSource");function Oo(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Oo,"isArkOrderModuleSpecifier");var _o=new Map;function xo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(xo,"escapeAppliesToLiteral");function Pl(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(Pl,"normalizeAppliesToGlob");function wl(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(wl,"appliesToBracesBalanced");function Dl(e){let t=_o.get(e);if(t)return t;let n=Pl(e),r=wl(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=xo(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+=xo(c)}let a=new RegExp(`^${s}$`);return _o.set(e,a),a}i(Dl,"globToRegExp");var To=["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"],Nn={"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 Ml(e,t){return!t||t.length===0?!0:t.some(n=>Dl(n).test(e))}i(Ml,"matchesArkOrderAppliesTo");function Fl(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(Fl,"isDomainRoleLayer");function be(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:Nn[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:fe({ruleId:Nn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(be,"finding");function Ln(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=me(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(be(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 m=c.get(u.matchedRoot)??[];m.push(u),c.set(u.matchedRoot,m)}for(let u of s){let m=c.get(u)??[];if(m.length===0){r.push(be(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}m.some(y=>y.hasPlaneFactory)||r.push(be(t,"arkorder-missing-plane",m[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||!Oo(u))continue;let m=e.layerForFile(c.from);m&&Fl(m,o.get(m)??[])&&r.push(be(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:m,target:u},n))}for(let c of e.genericUpdates)r.push(be(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(be(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(be(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)||Ml(c.file,t.appliesTo)&&r.push(be(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(Ln,"evaluateArkOrderSensors");function se(e,t,n={}){return{ruleId:e,message:t,...n}}i(se,"configWarning");function bt(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(se("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(se("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let p of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[p];f!==void 0&&(!Number.isInteger(f)||f<0)&&o.push(se("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(se("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,m=new Set;for(let p of a){if(!p.name){o.push(se("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(p.name)&&m.add(p.name),u.add(p.name),p.forbiddenGlobals!==void 0&&(!Array.isArray(p.forbiddenGlobals)||p.forbiddenGlobals.some(A=>typeof A!="string"))&&o.push(se("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 f=Array.isArray(p.patterns)?p.patterns:[];if(f.length===0){o.push(se("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${p.name}" has no file patterns and will never classify files.`,{layer:p.name}));continue}for(let A of f){let v;try{v=ge(A)}catch(R){o.push(se("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;!r.some(R=>v.test(R))&&!_&&o.push(se("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 m)o.push(se("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(se("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(se("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 f=-1,A=[];for(let v of a)for(let _ of v.patterns??[]){if(!ge(_).test(p))continue;let R=ar(_,p);R>f?(f=R,A=[v.name]):R===f&&!A.includes(v.name)&&A.push(v.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&o.push(se("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(se("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(bt,"collectAnalysisConfigWarnings");function $l(e,t){return t.some(n=>{try{return ge(n).test(e)}catch{return!1}})}i($l,"matchesAny");function Hl(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:v})=>({file:A,line:v})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:v})=>({file:A,line:v})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!$l(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"})),m=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:m,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 f=c.filter(A=>A.kind==="require");if(f.length>0){let A=f[0];g.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${f.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 m.length>0&&g.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${m.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(Hl,"evaluateSafety");function jl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(jl,"ambientForbiddenGlobal");function No(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return pr(e,n.length>0?n:ur.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(No,"intentLayer");function Vl(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||!jl(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(m=>m.from===o.file&&m.line===o.line&&m.specifier===o.symbol&&!m.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&tt(o.symbol,c))){if(o.source==="import-based"){let m=Ie(o.symbol,c);if(m){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 "${m}".`});continue}}He(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 nt({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=No(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=No(o.intent,e.contract);if(!l)continue;let c=_e(e.contract.config.rules,a,l,{fromPath:o.file,layers:e.contract.config.layers});if(!c)continue;let u=c.rule.peerIsolation?je(c.peerIsolationReason??"cross-slice",{fromPath:o.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,m=`${a} must not reference ${l} intent ${o.intent}.`,y=u&&c.peerIsolationReason!=="cross-slice"?`${m} ${u}`:c.rule.message?u?`${c.rule.message} (${u})`:c.rule.message:m;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(Vl,"contentViolations");function Ul(e){let{facts:t}=e,n=Be(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,P)=>{let V=`${d.code}\0${d.file??""}\0${d.message}`,ie=`${P.code}\0${P.file??""}\0${P.message}`;return V<ie?-1:V>ie?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 P=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,...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=bt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),m=Hl(e,t),y=e.contract.arkRules??Se(),g=a.map(d=>d.path),f={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?An(e.coverageInputs.fileContents):{},...e.fileHints??{}},A=[...yn({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:g,layerForFile:i(d=>l.get(d)??de(d,e.contract.config.layers),"layerForFile"),fileHints:f}),...hn(y,g)],v=A.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:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),_=A.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==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),I=(y.invariants?.length??0)>0?on({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=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.`})),D=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=kn(a),T=St({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}),w=e.contract.config.arkRun?.mode,x=T.findings.filter(()=>w==="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=T.findings.filter(()=>w!=="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})),M=Ln({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}),te=e.contract.config.arkOrder?.mode,pe=M.findings.filter(()=>te==="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}:{}})),$e=M.findings.filter(()=>te!=="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})),Qe=[...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."}]:[],...T.completenessReasons,...M.completenessReasons],Oe=Me({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Vl(e,t,l),...v,...b,...x,...pe],edges:c,warnings:[...u,...m.warnings,..._,...D,...j,...$e],safety:m.report}),Dt=s==="complete"&&Qe.length>0?"partial":s,qn=Dt==="complete"?o:[...o,...Qe].sort((d,P)=>{let V=`${d.code}\0${d.file??""}\0${d.message}`,ie=`${P.code}\0${P.file??""}\0${P.message}`;return V<ie?-1:V>ie?1:0}),S=Oe.violations.filter(d=>d.failsStrict!==!1),C=Dt==="complete"&&S.length===0,h=C&&Oe.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Dt,completenessReasons:qn,valid:C,strictValid:h,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:m.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:Oe.violations,warnings:Oe.warnings}}}i(Ul,"analyzeCanonicalResolvedProject");function Ye(e){return Ul({contract:e.contract,facts:Re(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(Ye,"analyzeResolvedProject");function Lo(e){return J($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Lo,"analysisTreeHash");function Lr(e){let t=ze(e),n=new Map(t.ir.files.map(f=>[f.path,f])),r=[],s=new Set,o=[];for(let f of e.changes){let A=f.path.replace(/\\/g,"/"),v=De(f.path);if(!v||v===".."||v.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(v)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}s.add(v),"delete"in f&&f.delete&&!n.has(v)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base tree.`}),r.push("delete"in f&&f.delete?{path:v,delete:!0}:{path:v,content:"content"in f?f.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=kt({...e,changes:r}),l=new Map(a.ir.files.map(f=>[f.path,f])),c=a.ir.violations.filter(f=>f.ruleId==="CAPABILITY_VIOLATION"||f.ruleId==="FORBIDDEN_GLOBAL").map(f=>{let A=l.get(f.evidence.file)?.layer;return{ruleId:f.ruleId,file:f.evidence.file,line:f.evidence.line,target:f.symbol,...f.capability?{capability:f.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:f.message}}),u=Me({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(f=>f.path),contentViolations:c,edges:a.ir.edges.filter(f=>!!f.fromLayer).map(f=>({from:f.from,fromLayer:f.fromLayer,...f.to?{to:f.to}:{},...f.toLayer?{toLayer:f.toLayer}:{},line:f.evidence.line,kind:"import",...f.typeOnly?{typeOnly:!0}:{},...f.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(f=>{let A=De(f.path),v=n.get(A),_=l.get(A);return{path:A,operation:"delete"in f&&f.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},..._?{candidateContentHash:_.contentHash}:{}}}).sort((f,A)=>f.path.localeCompare(A.path)),y=[...o,...u.violations].map(f=>({...f,nextAction:fe(f)})),g=y.filter(f=>f.failsStrict!==!1),p=e.changeMap?Pe({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:a.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.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:Lo(t.ir.files),candidateTreeHash:Lo(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:m,violations:y,warnings:u.warnings}}i(Lr,"preflightChange");function Kl(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(Kl,"canonicalChangePath");function Gl(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(Gl,"identityViolations");function Bl(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(Bl,"preparedChange");function Pr(e){let t=Re(e.baseFacts),n=Re(e.candidateFacts),r=Ye({contract:e.contract,facts:t}),s=Ye({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=Gl(t,n),c=new Map,u=[];for(let p of e.changes){let f=Kl(p.path);if(!f){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(f)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}c.set(f,p);let A=o.get(f),v=a.get(f);if("delete"in p&&p.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base facts.`}),v&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:f,line:1,message:`Candidate facts still contain deleted file ${f}.`});else{let _="content"in p?p.content:"",R=J(_);v?v.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:f,line:1,expectedContentHash:R,candidateContentHash:v.contentHash,message:`Candidate facts for ${f} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:f,line:1,message:`Candidate facts do not contain changed file ${f}.`})}u.push(Bl(p,f,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 f=o.get(p),A=a.get(p);f&&A&&$(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 m=e.changeMap?Pe({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:fe(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&&(m?.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}:{},...m?{convergence:m}:{},changes:u.sort((p,f)=>p.path<f.path?-1:p.path>f.path?1:0),violations:y,warnings:s.ir.warnings}}i(Pr,"preflightResolvedChange");var wr="1.0",zl=12;function Po(e){return e==="enforced"||e==="advisory"?e:null}i(Po,"closedMode");function ql(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!En(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(ql,"uniqueArkRunRuleIds");function Wl(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Po(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(Wl,"extraFromConfig");function wo(e={}){let t=Wl(e.arkRun),n=t.present?ql(e.findings):[],r=n.slice(0,zl),s=n.length,o=In({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"&&me(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:wr,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(wo,"summarizeArkRunSection");function Pn(e={}){let t=e.present===!0,n=Po(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(Pn,"projectStatusArkRun");function Do(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(Do,"formatArkRunDoctorLines");function wn(e,t){return e.slice(0,t).split(`
|
|
16
|
+
`).length}i(wn,"lineOf");function Mo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Mo,"normalizeInventoryPath");function $o(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i($o,"ownsIntent");function Fo(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||$o(t,["Domain"])}i(Fo,"isDomainLayer");function Yl(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||$o(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(Yl,"isControllerEligibleLayer");function Jl(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(Jl,"isNonPilotSurface");function Ho(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,u])=>[Mo(c),u])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>Fo(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,u]of Object.entries(e.fileContents).sort(([m],[y])=>m.localeCompare(y))){let m=Mo(c);if(Jl(m)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let y=r.has(m),g=r.get(m),p=g?s.get(g)??[]:[],f=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(m)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(m)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(m),A=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(m),v=/(?:^|\/)actions?(?:\/|\.|$)/i.test(m)||/['"]use server['"]/.test(u),_=/controller|handler|resolver/i.test(c)||A||v||/route\.(?:ts|js|tsx|jsx)$/i.test(m)&&!f||/@(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&&Yl(g,p)&&_):_,I=y?!!(g&&Fo(g,p)):/domain|entity|aggregate|model/i.test(c),b=!y||I||R;if(R&&!f){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,j;for(;(j=x.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:wn(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 D=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,k,T=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"),w=i((x,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(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 M=j.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(j)&&(/\s/.test(M)||/[.!?…]$/.test(M))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(x))},"isUxMessageConstant");for(;(k=D.exec(u))!==null;){let x=k[2],j=k[3]??"";!b||T(x)||w(x,j)||f&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(m)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:wn(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(I){let x=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,j;for(;(j=x.exec(u))!==null;){let M=j[2]??"",te=(M.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(M.match(/:\s*[A-Za-z]/g)??[]).length>=2&&te<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:wn(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(m)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(m)||/(?:^|\/)errors?(?:\/|$)/i.test(m))){let j=/this\.\w+\s*=/g,M;for(;(M=j.exec(u))!==null;){let te=u.lastIndexOf("class ",M.index),pe=te>=0?u.indexOf("{",te):-1,$e=te>=0&&pe>=te&&pe<M.index?u.slice(te,pe):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test($e))continue;let Ze=u.slice(Math.max(0,M.index-200),M.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(Ze)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:wn(u,M.index),message:"Domain field mutation without nearby guard/publish call.",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(Ho,"buildRulesInventory");function jo(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(jo,"inventoryToExtractionCard");var Vo="1.1";var Uo="1.0";var Dn="docs/diagnostics.md",Ko="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 Ct=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("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.")]),Dr=new Map(Ct.map(e=>[e.ruleId,e])),Go=Object.freeze(Ct.map(e=>e.ruleId));function Bo(e){return typeof e=="string"&&e.length>0&&Dr.has(e)}i(Bo,"isKnownDiagnosticCode");function zo(e){return typeof e!="string"||e.length===0?!1:Dr.has(e)?!0:e.startsWith("ARKRULE_")}i(zo,"isCataloguedOrArkRuleFamily");function Ot(e){if(!(typeof e!="string"||e.length===0))return Dr.get(e)}i(Ot,"getDiagnosticCatalogEntry");function Mr(e){return`#${Ot(e)?.docsAnchor??e}`}i(Mr,"diagnosticDocsFragment");function qo(e){return`${Dn}${Mr(e)}`}i(qo,"diagnosticDocsPath");function Wo(){return{schemaVersion:"1.0",docsPath:Dn,codes:Ct}}i(Wo,"serializeDiagnosticCatalog");function Yo(e){return Ot(e)?.fix}i(Yo,"catalogFixForRuleId");function Jo(e){return Ot(e)?.why}i(Jo,"catalogWhyForRuleId");var Mn="1.0",Fr="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",$r=["full","subset","unavailable"],Hr=["doctor-facts","report-snapshot","none"],xt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Xo=/^sha256:[a-f0-9]{64}$/;function jr(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"||!Xo.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(jr,"evaluateStatusBinding");function Vr(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(Vr,"classifyStatusWritePath");function Ur(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(Ur,"defaultHonestLabel");function Kr(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(Kr,"resolveStatusNextAction");function Zo(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Xo.test(e.projectId)?e.projectId:null,r=jr({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=Vr({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Ur(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:_t(e.activeViolations),frozenResidual:_t(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:_t(e.rulesInventoried),underContract:_t(e.rulesUnderContract),frozenResidual:_t(e.rulesFrozenResidual)},m={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:Mn,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:m,lastCheck:c,rules:u,nextAction:Kr(e,r,m,c,u)},p=Gr(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=Pn(e.arkRun)),g}i(Zo,"buildStatusManifest");var Qo=new Set($r),Xl=new Set(Hr);function Fn(e){let t=Qo.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Xl.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:xt.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:xt.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(Fn,"projectStatusImprovementCompass");function ea(e={}){return Fn({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??xt.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(ea,"unavailableStatusImprovementCompass");function Gr(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"&&Qo.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Fn({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(Gr,"normalizeStatusImprovementCompass");function ta(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(ta,"statusCompassResidualIsSubsetOfDoctor");function _t(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(_t,"numberOrNull");var na={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Fr,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:Mn},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 Tt="1.0",Nt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Lt=5,Ce=["scalability","resilience","security"],Je=new Set(Ce),Br={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},zr={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"},qr={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 Wr(e){return zr[e]??e}i(Wr,"improvementCompassHumanLabel");function Yr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Yr,"smellIdOf");function Jr(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Jr,"violationRuleId");function K(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(K,"pushEvidence");function ee(e,t,n){Je.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(ee,"markResidual");function ra(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`${zr[e]} \u2014 no residual from current sensors.`}}i(ra,"defaultOkSummary");function sa(){return Nt.map(e=>Je.has(e)?{id:e,status:"out-of-scope",summary:qr[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:ra(e),evidence:[]}:{id:e,status:"ok",summary:ra(e),evidence:[]})}i(sa,"createInitialImprovementCompassLenses");function Zl(e,t){for(let n of t){let r=Yr(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((m,y,g)=>{let p=e.get(m);!p||Je.has(m)||(K(p,"designSmells",r,s),a&&K(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(Zl,"mapDesignSmells");function Ql(e){return e.failsStrict===!1||e.typeOnly===!0}i(Ql,"isTypeOnlyPlacementDebt");function ec(e,t){for(let n of t){let r=Jr(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=i((c,u,m)=>{let y=e.get(c);!y||Je.has(c)||(K(y,"violations",r,s),n.file&&K(y,"violations",n.file,r),ee(y,u,m))},"attach");if(Ql(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(ec,"mapViolations");function tc(e,t){let n=Number(t.cycleCount)||0;if(n>0){let p=e.get("coupling");K(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");K(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");K(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 f=e.get("srp");K(f,"physicalCohesion",`findings:${s}`),ee(f,"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}`),ee(p,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let f=e.get("testability");o>0&&K(f,"capability",`residual:${o}`),a>0&&K(f,"forbiddenGlobals",`residual:${a}`),ee(f,"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}`),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 f=e.get("domain");K(f,"arkRules",`structureResidual:${l}`),ee(f,"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"),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&&K(p,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&K(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");K(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,m=Number(t.emptyLayerCount)||0;if(u>0||m>0){let p=e.get("modularity");u>0&&K(p,"coverage",`ungovernedDirs:${u}`),m>0&&K(p,"coverage",`emptyLayers:${m}`),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");K(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(tc,"mapCountsAndFlags");function oa(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>Yr(r).localeCompare(Yr(s)));Zl(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=Jr(r).localeCompare(Jr(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});ec(e,n)}tc(e,t)}i(oa,"projectImprovementCompassFacts");function aa(e){for(let t of Ce){let n=e.get(t);n.status="out-of-scope",n.summary=qr[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}i(aa,"lockImprovementCompassOutOfScope");function ia(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(ia,"sortImprovementCompassEvidence");function la(e){return e.filter(n=>n.status==="residual"&&!Je.has(n.id)).slice().sort((n,r)=>{let s=Br[n.id]??150,o=Br[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(la,"finalizeImprovementCompassTopResidual");function ca(e={}){let t=sa(),n=new Map(t.map(s=>[s.id,s]));oa(n,e),aa(n),ia(t);let r=la(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(ca,"buildImprovementCompass");function Xr(e){return e.topResidual.map(t=>Wr(t))}i(Xr,"formatImprovementCompassResidualLabels");function Zr(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(Zr,"primaryImprovementCompassNextAction");function da(e){let t=Xr(e),n=Ce.map(o=>Wr(o)),r=Zr(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(da,"formatImprovementCompassDoctorLines");var ua="1.0",pa="<!-- arkgate:agent-projection:begin",Qr="<!-- arkgate:agent-projection:end -->",es="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",Vn=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),fa=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"]),ts=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,ma=/<!--\s*arkgate:agent-projection:end\s*-->/i,nc=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,rc=/\bschema=([A-Za-z0-9._+-]+)/i;function Pt(e){let t=String(e??"").replace(/\r\n/g,`
|
|
17
|
+
`),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(Pt,"agentProjectionContentIdentity");function $n(e){return String(e??"").replace(/\r\n/g,`
|
|
18
|
+
`)}i($n,"normalizeNewlines");function Xe(e){let t=$n(e);return t.endsWith(`
|
|
19
19
|
`)?t:`${t}
|
|
20
|
-
`}i(Xe,"ensureTrailingNewline");function
|
|
20
|
+
`}i(Xe,"ensureTrailingNewline");function Un(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(Un,"safeVersion");function ga(e){return e==="compact"?"compact":"full"}i(ga,"resolveProfile");function ns(e){let t=Un(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(ns,"buildAgentProjectionBeginMarker");function Hn(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 |
|
|
21
21
|
|-------|----------|-----------------|
|
|
22
22
|
${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(`
|
|
23
|
-
`)}`}i(
|
|
23
|
+
`)}`}i(Hn,"formatAgentProjectionLayers");function rs(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(`
|
|
24
24
|
`)}
|
|
25
25
|
|
|
26
|
-
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(
|
|
27
|
-
`),""),
|
|
26
|
+
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(rs,"formatAgentProjectionCatalogShortList");function Kn(e){let t=Un(e.arkgateVersion),n=ga(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","",es,"",`- **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)","",Hn(l),""):u.push("### Contract layers","",Hn(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)","",rs(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)","",Vn.map(m=>`- \`${m}\``).join(`
|
|
27
|
+
`),""),u.join(`
|
|
28
28
|
`).replace(/\n{3,}/g,`
|
|
29
29
|
|
|
30
30
|
`).trimEnd()+`
|
|
31
|
-
`}i(
|
|
32
|
-
${t}${
|
|
33
|
-
`}i(
|
|
34
|
-
`)&&(
|
|
35
|
-
`,o=
|
|
31
|
+
`}i(Kn,"buildAgentProjectionBody");function ya(e){let t=Kn(e);return`${ns({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
|
|
32
|
+
${t}${Qr}
|
|
33
|
+
`}i(ya,"buildAgentProjectionBlock");function ha(e){let t=Kn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Un(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...Vn],contentIdentity:Pt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:ga(e.profile)}}i(ha,"buildAgentProjectionMeta");function jn(e){let t=$n(e??""),n=ts.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=ma.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(`
|
|
34
|
+
`)&&(u=u.slice(1));let m=t.slice(r,s+c),y=o.slice(c);return{block:m,body:u,before:t.slice(0,r),after:y,beginAttrs:n[1]??""}}i(jn,"extractAgentProjectionBlock");function ss(e){let t=String(e??""),r=ts.exec(t)?.[1]??t,s=nc.exec(r),o=rc.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}i(ss,"parseAgentProjectionStamp");function Aa(e,t){let n=ss(e).arkgateVersion;return n?n===Un(t):!1}i(Aa,"projectionMatchesPackageVersion");function Ra(e){return String(e??"").includes("non-authoritative")}i(Ra,"projectionHasNonEnforcementLabel");function ka(e,t){let n=Xe($n(t)),s=jn(n).body??n.replace(ts,"").replace(ma,"").trim()+`
|
|
35
|
+
`,o=Pt(s);if(e==null||!String(e).trim())return{content:Xe(`# Ark Enforcement
|
|
36
36
|
|
|
37
|
-
${n}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a
|
|
37
|
+
${n}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a=$n(e),l=jn(a);if(l.block!=null){let u=l.body??"";if(Pt(u)===o)return{content:Xe(a),action:"unchanged",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0};let m=l.before.replace(/\s*$/,`
|
|
38
38
|
|
|
39
39
|
`),y=l.after.replace(/^\s*/,`
|
|
40
|
-
`);return{content:Xe(`${
|
|
41
|
-
${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
|
|
40
|
+
`);return{content:Xe(`${m}${n.trimEnd()}
|
|
41
|
+
${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,m=a.slice(0,u).replace(/\s*$/,`
|
|
42
42
|
|
|
43
|
-
`),y=a.slice(
|
|
44
|
-
`);return{content:Xe(`${
|
|
43
|
+
`),y=a.slice(u).replace(/^\s*/,`
|
|
44
|
+
`);return{content:Xe(`${m}${n.trimEnd()}
|
|
45
45
|
${y}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:Xe(`${n.trimEnd()}
|
|
46
46
|
|
|
47
|
-
${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(
|
|
47
|
+
${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(ka,"mergeAgentProjectionDocument");var Ea="1.0",os="templates/agent-skills",as="templates/skills",is="SKILL.md",wt=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"]),ls=wt.length,sc=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function cs(e){return typeof e!="string"||e.length<1||e.length>64?!1:sc.test(e)}i(cs,"isValidAgentSkillName");function Bn(e){return wt.includes(e)}i(Bn,"isArkSkillName");function ds(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
|
|
48
48
|
`)?`\r
|
|
49
49
|
`:`
|
|
50
|
-
`,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
|
|
51
|
-
`)}i(
|
|
50
|
+
`,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 m=1;m<s;m+=1){let y=r[m]??"";if(y.trim()===""||y.trimStart().startsWith("#"))continue;let g=y.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!g)continue;let p=g[1],f=g[2]??"";(f.startsWith('"')&&f.endsWith('"')&&f.length>=2||f.startsWith("'")&&f.endsWith("'")&&f.length>=2)&&(f=f.slice(1,-1)),o[p]=f}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(ds,"parseSkillDocument");function us(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),o=ds(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||!cs(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&&!Bn(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(us,"validateAgentSkillDocument");function Ia(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(...us({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&Gn(s.content)!==Gn(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 wt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)Bn(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:ls,presentCount:r.length}}i(Ia,"validateAgentSkillsPackage");var zn=/^arkgate@(\S+)\.\s/;function ps(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(ps,"skillDescriptionVersionPrefix");function fs(e){return String(e??"").replace(zn,"")}i(fs,"stripSkillDescriptionVersion");function va(e){return String(e??"").match(zn)?.[1]??null}i(va,"parseSkillDescriptionVersion");function Sa(e,t){let n=fs(e),r=typeof t=="string"?t.trim():"";return r?`${ps(r)}${n}`:n}i(Sa,"stampSkillDescription");function Gn(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
51
|
+
`)}i(Gn,"normalizeSkillContent");function ms(e){return`${e}/${is}`}i(ms,"agentSkillEntryRelativePath");function ba(e){return`${os}/${ms(e)}`}i(ba,"agentSkillPackageFileRelativePath");function Ca(e){return`${as}/${e}.md`}i(Ca,"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});
|