arkgate 4.8.2 → 4.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +15 -3
  2. package/README.md +39 -8
  3. package/bin/lib/analysis-engine.mjs +6 -6
  4. package/bin/lib/ark-order-facts.mjs +59 -0
  5. package/bin/lib/ark-order-sensors.mjs +31 -2
  6. package/bin/lib/arkrule-file-hints.mjs +6 -2
  7. package/bin/lib/arkrules-contract.mjs +1 -0
  8. package/bin/lib/arkrules-sensors.mjs +22 -2
  9. package/bin/lib/config-extras.mjs +2 -0
  10. package/bin/lib/diagnostic-catalog.mjs +2 -1
  11. package/bin/lib/remediation.mjs +9 -1
  12. package/bin/lib/resolved-candidate-facts.mjs +31 -0
  13. package/dist/{configTypes-BdCe_gvv.d.ts → configTypes-dNJ2C0yx.d.ts} +5 -0
  14. package/dist/{diagnosticCatalog-CPzH-MLN.d.ts → diagnosticCatalog-C5GgeyEE.d.ts} +97 -7
  15. package/dist/eslint/index.cjs +6 -6
  16. package/dist/eslint/index.d.ts +1 -1
  17. package/dist/eslint/index.js +6 -6
  18. package/dist/index.cjs +34 -34
  19. package/dist/index.d.ts +24 -7
  20. package/dist/index.js +34 -34
  21. package/dist/nestjs/index.cjs +5 -5
  22. package/dist/nestjs/index.d.ts +3 -3
  23. package/dist/nestjs/index.js +5 -5
  24. package/dist/runtime/index.cjs +15 -15
  25. package/dist/runtime/index.d.ts +6 -6
  26. package/dist/runtime/index.js +15 -15
  27. package/dist/{types-C9KApBzX.d.ts → types-DeK7SYGC.d.ts} +1 -1
  28. package/dist/{types-DCSlrRnV.d.ts → types-dK24fDZa.d.ts} +1 -1
  29. package/docs/README.md +4 -4
  30. package/docs/configuration.md +12 -8
  31. package/docs/develop.md +23 -2
  32. package/docs/diagnostics.md +9 -0
  33. package/docs/enthusiast/README.md +6 -4
  34. package/docs/package-surface.md +4 -2
  35. package/docs/product-voice.md +15 -5
  36. package/docs/use.md +8 -5
  37. package/package.json +1 -1
  38. package/schemas/ark.arkrules.schema.json +1 -0
  39. package/schemas/ark.config.schema.json +9 -0
  40. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  41. package/server.json +2 -2
  42. package/templates/agent-skills/README.md +1 -1
  43. package/templates/agent-skills/ark-adopt/SKILL.md +8 -3
  44. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  45. package/templates/agent-skills/ark-contract/SKILL.md +4 -0
  46. package/templates/agent-skills/ark-place/SKILL.md +6 -2
  47. package/templates/arkrules/ApplicationOrchestration.json +6 -0
  48. package/templates/skills/ark-adopt.md +8 -3
  49. package/templates/skills/ark-autopilot.md +1 -1
  50. package/templates/skills/ark-contract.md +4 -0
  51. package/templates/skills/ark-place.md +6 -2
package/dist/index.cjs CHANGED
@@ -1,51 +1,51 @@
1
- "use strict";var Mt=Object.defineProperty;var fa=Object.getOwnPropertyDescriptor;var ma=Object.getOwnPropertyNames;var ga=Object.prototype.hasOwnProperty;var i=(e,t)=>Mt(e,"name",{value:t,configurable:!0});var ya=(e,t)=>{for(var n in t)Mt(e,n,{get:t[n],enumerable:!0})},ha=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ma(t))!ga.call(e,s)&&s!==n&&Mt(e,s,{get:()=>t[s],enumerable:!(r=fa(t,s))||r.enumerable});return e};var Aa=e=>ha(Mt({},"__esModule",{value:!0}),e);var Dl={};ya(Dl,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Gn,AGENT_PROJECTION_BEGIN_MARKER:()=>Xo,AGENT_PROJECTION_END_MARKER:()=>Yr,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>$n,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Wr,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>es,AGENT_SKILL_ENTRY_FILENAME:()=>ns,ANALYSIS_IR_SCHEMA_VERSION:()=>Xt,ARKORDER_RULE_IDS:()=>On,ARKORDER_TIER1_SENSOR_IDS:()=>yo,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>br,ARKRUN_KERNEL_FACTORY_CALLEES:()=>Ir,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>io,ARKRUN_RULE_IDS:()=>_n,ARKRUN_TIER1_SENSOR_IDS:()=>po,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>vr,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Zo,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>ia,ARK_ANALYSIS_RESULT_SCHEMA:()=>fs,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Ht,ARK_CONFIG_SCHEMA:()=>qt,ARK_CONFIG_SCHEMA_VERSION:()=>te,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Oo,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>_o,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Nt,ARK_PROJECT_IDENTITY_SCHEMA:()=>gs,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>qn,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>ms,ARK_RULES_SCHEMA:()=>en,ARK_RULES_SCHEMA_VERSION:()=>Ks,ARK_RULE_SENSORS:()=>fr,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>xr,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>Kn,ARK_SKILL_NAMES:()=>Dt,ARK_SKILL_NAME_COUNT:()=>rs,ARK_STATUS_MANIFEST_SCHEMA:()=>Uo,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Pr,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>Ln,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>Qo,DIAGNOSTIC_CATALOG:()=>_t,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>xo,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Pn,DIAGNOSTIC_RULE_IDS:()=>To,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>ro,EffectiveContractError:()=>gt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>ts,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>_e,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Lt,IMPROVEMENT_LENS_IDS:()=>Pt,MERGE_PLANES_DUAL_STAMP:()=>Er,POLICY_DELTA_SCHEMA_VERSION:()=>an,PROJECT_BINDING_SCHEMA:()=>Wn,PROJECT_EXPECTATION_SCHEMA:()=>Yn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Zt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>be,STATUS_COMPASS_FACTS_SOURCES:()=>wr,STATUS_COMPASS_MODES:()=>Lr,STATUS_COMPASS_REASON_CODES:()=>Tt,adapterDocsCodePath:()=>zn,adapterFindingOccurrenceTargetKeys:()=>Ft,adapterFindingRefFromTargetKey:()=>Bn,adapterFindingTargetKey:()=>jt,agentProjectionContentIdentity:()=>wt,agentSkillEntryRelativePath:()=>cs,agentSkillPackageFileRelativePath:()=>ua,analyzeArchitectureConvergence:()=>Le,analyzeChange:()=>Rt,analyzePolicyDelta:()=>yr,analyzeProject:()=>Ke,analyzeResolvedProject:()=>ze,arkRunKernelCallKind:()=>kn,buildAgentProjectionBeginMarker:()=>Zr,buildAgentProjectionBlock:()=>na,buildAgentProjectionBody:()=>jn,buildAgentProjectionMeta:()=>ra,buildArkRuleFileHints:()=>gn,buildEffectiveArkRules:()=>tn,buildImprovementCompass:()=>Wo,buildRulesInventory:()=>bo,buildStatusManifest:()=>$o,canPromoteInvariant:()=>sn,catalogFixForRuleId:()=>Do,catalogWhyForRuleId:()=>Mo,classifyArkPolicyDelta:()=>ln,classifyResolvedLayerCoverage:()=>hn,classifyStatusWritePath:()=>Mr,collectAnalysisConfigWarnings:()=>Ct,collectEmptyAppliesToFindings:()=>mn,collectForbiddenCapabilityUses:()=>Ne,composeMergePlanesHonesty:()=>Rn,createAICodeGate:()=>lr,createAdapterResult:()=>ps,createArchitectureProfile:()=>ct,createArchitectureProfileFromArkConfig:()=>dr,createElevenLayerArkConfig:()=>ur,createProjectId:()=>ys,createProjectIdentity:()=>hs,createResolvedCandidateFacts:()=>Jt,defaultHonestLabel:()=>Fr,demoteExtraPlaneTeethUnderClassificationFloor:()=>oo,deriveArkRuleFileHints:()=>Rr,detectArchitectureCycles:()=>un,deterministicHash:()=>K,diagnosticDocsFragment:()=>Nr,diagnosticDocsPath:()=>Lo,effectiveContractPolicyPayload:()=>nn,elevenLayerProfile:()=>lt,emptyEffectiveArkRules:()=>Ce,evaluateArchitectureGraph:()=>Me,evaluateArkOrderSensors:()=>xn,evaluateArkRuleSensors:()=>fn,evaluateArkRunEditorSensors:()=>Cr,evaluateArkRunEditorSensorsFromSource:()=>mo,evaluateArkRunSensors:()=>vt,evaluateInvariantCoverage:()=>rn,evaluateStatusBinding:()=>Dr,explainViolation:()=>hr,extraMergeTeethAllowed:()=>fe,extractAgentProjectionBlock:()=>Fn,extractArkRunDeclarationsFromSource:()=>lo,extractArkRunImportedConstructorNamesFromSource:()=>vn,extractArkRunKernelCallsFromSource:()=>bn,extractArkRunManagedNewsFromSource:()=>Cn,extractArkRunValueImportDependenciesFromSource:()=>In,extractClassShapesFromSource:()=>no,extractSemanticDependencies:()=>Te,flatSkillTemplateFileRelativePath:()=>pa,formatAgentProjectionCatalogShortList:()=>Xr,formatAgentProjectionLayers:()=>Mn,formatArkRunDoctorLines:()=>Eo,formatImprovementCompassDoctorLines:()=>Jo,formatImprovementCompassResidualLabels:()=>zr,getDiagnosticCatalogEntry:()=>Ot,inventoryToExtractionCard:()=>Co,isArkOrderRuleId:()=>so,isArkRunKernelModuleSpecifier:()=>Be,isArkRunRuleId:()=>An,isArkRunTransportBypassSpecifier:()=>En,isArkSkillName:()=>Un,isCataloguedOrArkRuleFamily:()=>Po,isExtraPlaneFinding:()=>kr,isKnownDiagnosticCode:()=>No,isValidAgentSkillName:()=>ss,loadArkConfigContract:()=>it,loadArkRulesContract:()=>mt,loadContract:()=>At,loadResolvedCandidateFacts:()=>ke,mergeAgentProjectionDocument:()=>aa,normalizeExtraMergeTeethClassification:()=>yn,normalizeSkillContent:()=>Vn,normalizeStatusImprovementCompass:()=>Hr,parseAgentProjectionStamp:()=>Qr,parseArkConfigJson:()=>Wt,parseArkRulesJson:()=>Gs,parseSkillDescriptionVersion:()=>ca,parseSkillDocument:()=>os,policyDeltaAcknowledgementMatches:()=>cn,preflightChange:()=>_r,preflightResolvedChange:()=>Or,primaryImprovementCompassNextAction:()=>qr,projectStatusArkRun:()=>Tn,projectStatusImprovementCompass:()=>wn,projectionHasNonEnforcementLabel:()=>oa,projectionMatchesPackageVersion:()=>sa,resolveEffectiveContract:()=>zs,resolveStatusNextAction:()=>$r,resolvedFactsEvidenceRequirementsHash:()=>Ue,serializeDiagnosticCatalog:()=>wo,skillDescriptionVersionPrefix:()=>is,stableSerialize:()=>F,stampSkillDescription:()=>da,statusCompassResidualIsSubsetOfDoctor:()=>Vo,stripSkillDescriptionVersion:()=>ls,summarizeArkRunSection:()=>ko,toAdapterDiagnostic:()=>$t,unavailableStatusImprovementCompass:()=>jo,validateAgentSkillDocument:()=>as,validateAgentSkillsPackage:()=>la,version:()=>ds});module.exports=Aa(Dl);var ds="4.8.2";var Ra=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ka=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ea=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Sa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Ra.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ka.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Ea.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(Sa,"classifyLayerImportKind");function Ia(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=Sa(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(Ia,"layerImportNextAction");function va(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(va,"arkRunCallSiteName");function ba(e){let t=va(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(ba,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ia(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, 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 ba(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() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. 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 only. Change \u03BE with proposeRelease + release. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(pe,"deterministicNextAction");var Ht="1.5",Gn="docs/diagnostics.md";function C(e){return typeof e=="string"&&e.length>0?e:void 0}i(C,"text");function us(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(us,"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 Bn(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(Bn,"adapterFindingRefFromTargetKey");function zn(e){return`${Gn}#${e}`}i(zn,"adapterDocsCodePath");function Ca(e,t,n){return pe({ruleId:e,target:C(t.target)??C(n.target)??void 0,fromLayer:C(t.fromLayer)??void 0,toLayer:C(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:C(t.edgeKind)??void 0,capability:C(t.capability)??C(n.capability)??void 0,arkruleId:C(t.arkruleId)??void 0,arkruleSource:C(t.arkruleSource)??void 0})}i(Ca,"nextActionForDiagnostic");function $t(e,t="error",n){let r=C(e.ruleId)??C(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={...C(e.target)?{target:C(e.target)}:{},...C(e.fromLayer)?{fromLayer:C(e.fromLayer)}:{},...C(e.toLayer)?{toLayer:C(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}:{},...C(e.capability)?{capability:C(e.capability)}:{},...C(e.edgeKind)?{edgeKind:C(e.edgeKind)}:{},...C(e.arkruleId)?{arkruleId:C(e.arkruleId)}:{},...C(e.arkruleSource)?{arkruleSource:C(e.arkruleSource)}:{}},a=n??jt(e),l=Bn(a);return{ruleId:r,severity:s,message:C(e.message)??r,location:{file:C(e.file)??"<unknown>",line:us(e.line,1),column:us(e.column,1)},evidence:o,nextAction:C(e.nextAction)??Ca(r,o,e),findingRef:l,targetKey:a,docsCodePath:zn(r)}}i($t,"toAdapterDiagnostic");function ps(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(g=>({code:C(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:C(g.message)??`Analysis ${t}: required evidence is incomplete.`,...C(g.file)?{file:C(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...C(e.policyHash)?{policyHash:C(e.policyHash)}:{},...C(e.resolverIdentity)?{resolverIdentity:C(e.resolverIdentity)}:{},...C(e.factsHash)?{factsHash:C(e.factsHash)}:{},...C(e.candidateTreeHash)?{candidateTreeHash:C(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],l=Ft(o),c=Ft(a),p=[...o.map((g,u)=>$t(g,"error",l[u])),...a.map((g,u)=>$t(g,"warning",c[u]))],m={schemaVersion:Ht,completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...m,mode:n,valid:!1,completeness:t,...s};let g={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...g}:{...m,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...s}:{...m,mode:n,valid:!1,completeness:t,...s}}i(ps,"createAdapterResult");var fs={$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 ms="1.0",qn="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Vt="^sha256:[a-f0-9]{64}$",Yn={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."}}},Wn={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}}},gs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:qn,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:Yn,binding:Wn}};function ys(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(ys,"createProjectId");function hs(e){return{schemaVersion:"1.0",...e}}i(hs,"createProjectIdentity");var Zn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Qn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),er=Object.freeze(Object.keys(Qn).sort()),Jn=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"}),Xn=Object.freeze({process:Object.freeze(["process","node:process"])});function Xe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Jn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Jn[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:Jn[e.slice(0,o)]??null}i(Xe,"capabilityForModuleSpecifier");function ve(e,t){for(let n of t)if(Xn[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=Qn[r];if(s)return s}return null}i(Ut,"capabilityForAmbientName");function Fe(e){if(e?.pure===!0)return[...Zn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Zn.includes(r));return[...new Set(n)].sort()}i(Fe,"effectiveCapabilityDeny");function Qe(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(Qe,"ambientCoveredByForbiddenGlobals");function Kt(e){let t=new Set,n=new Set,r=Object.keys(Qn);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 Xn[s]??[])t.add(`import-exact:${a}`)}for(let s of Fe(e)){if(t.add(`import:${s}`),s==="process")for(let o of Xn.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 As=new Map;function Rs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Rs,"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 _a(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(_a,"bracesBalanced");function xe(e){let t=As.get(e);if(t)return t;let n=Gt(e),r=_a(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=Rs(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+=Rs(c)}let a=new RegExp(`^${s}$`);return As.set(e,a),a}i(xe,"globToRegExp");function Oa(e){return Gt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Oa,"concreteGlobSegments");function tr(e,t){let n=Gt(String(e)),r=Oa(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 m=-1;for(let g=l;g<a.length;g+=1)if(a[g]===p){m=g;break}if(m<0)return o;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+s}i(tr,"patternSpecificity");function ie(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>xe(a).test(n))){for(let a of o.patterns??[])if(xe(a).test(n)){let l=tr(a,n);l>s&&(s=l,r=o.name)}}return r}i(ie,"layerForRelativePath");function ks(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(ks,"sliceIdForPath");function xa(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(xa,"inferSliceFoldersFromPatterns");function Ta(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 xa(r?.patterns)}i(Ta,"resolveSliceFolders");function Na(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(Na,"peerIsolationMustDeny");function ge(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=Ta(s,t,r?.layers),c=o&&a?ks(o,l):void 0,p=o&&a?ks(a,l):void 0;if(Na({fromPath:o,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p}))return s;continue}if(t!==n)return s}}i(ge,"findDeniedEdgeRule");function $e(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i($e,"literalText");function Is(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Is,"lineOf");function Es(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(Es,"isTypeOnlyReference");function vs(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(vs,"singleFileChecker");function nr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(nr,"symbolAt");function rr(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):nr(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(rr,"localDeclaration");function Te(e,t){let n,r=[],s=i((a,l,c,p=!1)=>r.push({specifier:c,kind:l,line:Is(t,a),typeOnly:p,unresolved:c===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",$e(e,a.moduleSpecifier),Es(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",$e(e,a.moduleSpecifier),Es(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",$e(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"&&!rr(e,n??(n=vs(e,t)),t,a.expression);(l||p)&&s(a,p?"require":"dynamic-import",$e(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i(Te,"extractSemanticDependencies");function Pa(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=$e(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(Pa,"staticAccessPath");function La(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(La,"runtimeIdentifierReference");function Ss(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(Ss,"bestForbiddenMatch");function Ne(e,t,n){if(n.length===0)return[];let r=new Set(n),s=vs(e,t),o=new Map,a=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let d of u.declarationList.declarations)e.isIdentifier(d.name)&&a.add(d.name.text);let l=i(u=>{let d=Pa(e,u);if(!d)return;let f=nr(s,d.root),y=f?o.get(f):void 0;return y?[...y,...d.segments.slice(1)]:rr(e,s,t,d.root)||a.has(d.root.text)?void 0:d.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let d of u.declarationList.declarations){if(!d.initializer||!e.isIdentifier(d.name))continue;let f=l(d.initializer),y=nr(s,d.name);!f||!y||o.set(y,f)}let c=[],p=new Set,m=i((u,d)=>{let f=Is(t,d),y=`${u}:${d.getStart(t)}`;p.has(y)||(p.add(y),c.push({name:u,line:f,node:d}))},"flag"),g=i(u=>{let d=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!d){let f=l(u),y=f?Ss(r,f):void 0;y&&m(y,u)}else e.isIdentifier(u)&&r.has(u.text)&&La(e,u)&&!rr(e,s,t,u)&&m(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let f=l(u.initializer);if(f)for(let y of u.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?$e(e,y.propertyName)??y.propertyName.text:y.name.text,N=Ss(r,[...f,I]);N&&m(N,u.initializer)}}e.forEachChild(u,g)},"visit");return g(t),c}i(Ne,"collectForbiddenCapabilityUses");function sr(e,t,n){let r=[];for(let s of n?.dependencies??Te(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Xe(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Ne(e,t,er)){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(sr,"collectCapabilityUses");var or={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."},ar=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 ir(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(ir,"resolveIntentLayer");function Pe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Pe,"looksLikeArkIntent");function et(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Pe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:or.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:or.PUBLISH_MISSING_SOURCE}),t}i(et,"classifyPublishFacts");function V(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(V,"violation");function He(e,t){return e.slice(0,t).split(`
2
- `).length}i(He,"lineOf");function wa(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(wa,"extractQuotedStrings");function Da(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(Da,"extractModuleSpecifiers");function Ma(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(Ma,"extractQuotedStringsAst");function Fa(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(Fa,"hasInfrastructureToken");function $a(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i($a,"isKnownInfrastructurePackage");function Ha(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Ha,"layerHasInfrastructureRole");function nt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(nt,"tsStringLiteralText");function ja(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(ja,"tsPropertyName");function bs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ja(e,r.name)===n)}i(bs,"tsObjectProperty");function rt(e,t,n){return bs(e,t,n)!==void 0}i(rt,"tsObjectHasProperty");function tt(e,t,n){let r=bs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(tt,"tsObjectPropertyValue");function Va(e,t){let n=tt(e,t,"metadata");return rt(e,n,"source")}i(Va,"tsObjectHasMetadataSource");function Cs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Cs(e,t.name):!1:!1}i(Cs,"tsLooksLikeIntentCreatorExpression");function Ua(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(Ua,"tsIsPublishCall");function Ka(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=nt(e,n);return r!==void 0&&Pe(r)||rt(e,n,"intent")||Cs(e,n)}i(Ka,"tsIsArkPublishCandidate");function Ga(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Va(e,n)||rt(e,r,"source")||rt(e,s,"source")}i(Ga,"tsPublishHasSource");function Ba(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=tt(e,n,"metadata");return nt(e,tt(e,o,"source"))??nt(e,tt(e,r,"source"))??nt(e,tt(e,s,"source"))}i(Ba,"tsPublishSourceLiteral");function za(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(g=>s.getLineAndCharacterOfPosition(g.getStart(s)).line+1,"lineForNode"),m=i(g=>{if(Ua(e,g)){let u=g.arguments[0],d=nt(e,u);for(let y of et({publishCall:!0,rawIntentName:d,objectHasIntent:rt(e,u,"intent"),arkPublishCandidate:Ka(e,g),hasSource:Ga(e,g)}))c.push(V(y.ruleId,y.message,{line:p(g),filePath:a}));let f=Ba(e,g);if(r&&l&&f&&Pe(f)){let y=r.resolveLayer(f);y&&y!==l&&c.push(V("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${y}, but the target file is classified as ${l}.`,{line:p(g),filePath:a,target:f,fromLayer:l,toLayer:y}))}}e.forEachChild(g,m)},"visit");return m(s),c}i(za,"analyzePublishAst");function lr(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,m=c?.layer,g=e.typescript,u=g?g.createSourceFile(p??"generated.ts",o,g.ScriptTarget.Latest,!0):void 0,d=u?Te(e.typescript,u):void 0,f=d?d.filter(E=>E.specifier!==void 0).map(E=>({value:E.specifier,index:E.node.getStart(u),kind:E.kind,typeOnly:E.typeOnly})):Da(o),y=e.typescript?Ma(e.typescript,o):wa(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let E of d?.filter(({unresolved:k})=>k)??[]){let k=E.kind==="require";l.push(V(k?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${k?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:E.line,filePath:p}))}let I=m!==void 0&&(r.has(m)||Ha(m)),N=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 E of n)if(E instanceof RegExp){E.lastIndex=0;let k=E.exec(o);E.lastIndex=0,k&&l.push(V("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${E}`,{line:k.index===void 0?void 0:He(o,k.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+N}))}else o.includes(E)&&l.push(V("FORBIDDEN_SUBSTRING",`Forbidden substring: ${E}`,{line:He(o,o.indexOf(E)),filePath:p}));for(let E of f){let k=e.resolveImportTarget?.(E.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(E.value,p)}:void 0),b=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:m,relPath:void 0}:void 0):void 0,J=k?.layer;if(J&&m){let H=ge(e.architectureProfile?.rules,m,J,{fromPath:b?.relPath,toPath:k?.relPath,layers:e.architectureLayers});if(H){if(E.typeOnly&&!H.peerIsolation)continue;let B=!!H.peerIsolation;l.push(V("LAYER_IMPORT_VIOLATION",H.message??(B?`Layer "${m}" must not import across slices into "${J}".`:`Layer "${m}" must not import "${J}".`),{line:He(o,E.index),source:E.value,target:E.value,filePath:p,fromLayer:m,toLayer:J,suggestion:B?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:E.kind,peerIsolation:B,...E.typeOnly?{typeOnly:!0}:{}}}));continue}continue}I||E.typeOnly||!Fa(E.value)&&!$a(E.value)||l.push(V("FORBIDDEN_IMPORT",`Forbidden ${E.kind} target: "${E.value}".`,{line:He(o,E.index),source:E.value,target:E.value,filePath:p,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+N,details:{importKind:E.kind}}))}if(e.policies)for(let E of e.policies){let k=E.check({source:o,context:a});if(k!==!0)if(Array.isArray(k))for(let b of k)l.push(V("POLICY_VIOLATION",b.message,{filePath:p,suggestion:`Fix violation of policy "${E.name}".`}));else k===!1?l.push(V("POLICY_VIOLATION",`Policy ${E.name} failed on generated code`)):l.push(V("POLICY_VIOLATION",k.message))}if(s&&t.size>0)for(let E of y)Pe(E.value)&&!t.has(E.value)&&l.push(V("UNKNOWN_INTENT",`Unknown intent reference: "${E.value}"`,{line:He(o,E.index),filePath:p,target:E.value,suggestion:`Register intent "${E.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let E of y){if(!Pe(E.value))continue;let k=e.architectureProfile.resolveLayer(E.value);if(!k)continue;let b=ge(e.architectureProfile.rules,m,k);b&&l.push(V("LAYER_REFERENCE_VIOLATION",b.message??`Layer "${m}" must not reference "${k}" through "${E.value}".`,{line:He(o,E.index),filePath:p,target:E.value,fromLayer:m,toLayer:k,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:b}}))}if(e.extensions)for(let E of e.extensions)try{let k=E.analyze(o,a);l.push(...k)}catch(k){l.push(V("EXTENSION_ERROR",`Extension "${E.name}" failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&u&&m&&e.forbiddenGlobals?.[m]?.length)try{let E=e.forbiddenGlobals[m];l.push(...Ne(e.typescript,u,E).map(k=>V("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${k.name}".`,{line:k.line,filePath:p,target:k.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 k of d??[]){if(k.typeOnly||!k.specifier)continue;let b=ve(k.specifier,E);b&&l.push(V("FORBIDDEN_GLOBAL",`${m} must not use module "${k.specifier}" because it is the import form of forbidden global "${b}".`,{line:k.line,filePath:p,source:k.specifier,target:k.specifier,fromLayer:m,details:{importKind:k.kind,forbiddenGlobal:b},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(E){l.push(V("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript&&u&&m&&e.capabilityWalls?.[m]?.length)try{let E=new Set(e.capabilityWalls[m]),k=e.forbiddenGlobals?.[m]??[];for(let b of sr(e.typescript,u))E.has(b.capability)&&(b.source==="ambient-global"&&Qe(b.symbol,k)||b.source==="import-based"&&ve(b.symbol,k)||l.push(V("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:p,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(E){l.push(V("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}if(e.typescript)try{l.push(...za(e.typescript,o,a,e.architectureProfile))}catch(E){l.push(V("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${E instanceof Error?E.message:String(E)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(lr,"createAICodeGate");var st={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},_s={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...st,default:[]},kernelRoots:{...st},managedLayers:{...st,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Os={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...st,default:[]},managedLayers:{...st,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7}}};function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ot,"isObject");function xs(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(xs,"declaredLayerNames");function Ts(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(Ts,"defaultedArkRun");function Ns(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}}i(Ns,"defaultedArkOrder");function Ps(e,t){let n=e.arkRun;if(n===void 0||!ot(n))return;let r=xs(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(Ps,"validateArkRunExtra");function Ls(e,t){let n=e.arkOrder;if(n===void 0||!ot(n))return;let r=xs(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(Ls,"validateArkOrderExtra");var te="1.3",zt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",ws=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],qa=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ya(){let e=[];for(let t of ws)for(let n of ws)t===n||qa.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Ya,"createDefaultRules");var Yt=Ya(),cr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ye={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:te,default:te},name:{type:"string",minLength:1},include:{...ye,minItems:1,default:["src"]},exclude:{...ye,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Yt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ye,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ye,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ye,minItems:1},exclude:ye,intentPrefixes:ye,description:{type:"string",minLength:1},forbiddenGlobals:ye,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:{...ye,minItems: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}}},arkRun:_s,arkOrder:Os}},he=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ "use strict";var Mt=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var yo=Object.getOwnPropertyNames;var ho=Object.prototype.hasOwnProperty;var i=(e,t)=>Mt(e,"name",{value:t,configurable:!0});var Ao=(e,t)=>{for(var n in t)Mt(e,n,{get:t[n],enumerable:!0})},Ro=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yo(t))!ho.call(e,s)&&s!==n&&Mt(e,s,{get:()=>t[s],enumerable:!(r=go(t,s))||r.enumerable});return e};var ko=e=>Ro(Mt({},"__esModule",{value:!0}),e);var Hl={};Ao(Hl,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>qn,AGENT_PROJECTION_BEGIN_MARKER:()=>Qa,AGENT_PROJECTION_END_MARKER:()=>Xr,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Hn,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Jr,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>ns,AGENT_SKILL_ENTRY_FILENAME:()=>ss,ANALYSIS_IR_SCHEMA_VERSION:()=>Zt,ARKORDER_RULE_IDS:()=>xn,ARKORDER_TIER1_SENSOR_IDS:()=>ha,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>Or,ARKRUN_KERNEL_FACTORY_CALLEES:()=>vr,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>ca,ARKRUN_RULE_IDS:()=>_n,ARKRUN_TIER1_SENSOR_IDS:()=>fa,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>Cr,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Za,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>lo,ARK_ANALYSIS_RESULT_SCHEMA:()=>gs,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>Ht,ARK_CONFIG_SCHEMA:()=>qt,ARK_CONFIG_SCHEMA_VERSION:()=>te,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>xa,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>_a,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>xt,ARK_PROJECT_IDENTITY_SCHEMA:()=>hs,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>Xn,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>ys,ARK_RULES_SCHEMA:()=>en,ARK_RULES_SCHEMA_VERSION:()=>Bs,ARK_RULE_SENSORS:()=>yr,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>Nr,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>Gn,ARK_SKILL_NAMES:()=>Lt,ARK_SKILL_NAME_COUNT:()=>as,ARK_STATUS_MANIFEST_SCHEMA:()=>Ua,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>wr,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>wn,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>eo,DIAGNOSTIC_CATALOG:()=>vt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ta,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Ln,DIAGNOSTIC_RULE_IDS:()=>Na,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>aa,EffectiveContractError:()=>gt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>rs,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>Ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Nt,IMPROVEMENT_LENS_IDS:()=>Tt,MERGE_PLANES_DUAL_STAMP:()=>Sr,POLICY_DELTA_SCHEMA_VERSION:()=>on,PROJECT_BINDING_SCHEMA:()=>Zn,PROJECT_EXPECTATION_SCHEMA:()=>Jn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Jt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>be,STATUS_COMPASS_FACTS_SOURCES:()=>Mr,STATUS_COMPASS_MODES:()=>Dr,STATUS_COMPASS_REASON_CODES:()=>_t,adapterDocsCodePath:()=>Yn,adapterFindingOccurrenceTargetKeys:()=>Ft,adapterFindingRefFromTargetKey:()=>Wn,adapterFindingTargetKey:()=>jt,agentProjectionContentIdentity:()=>Pt,agentSkillEntryRelativePath:()=>us,agentSkillPackageFileRelativePath:()=>fo,analyzeArchitectureConvergence:()=>Pe,analyzeChange:()=>Rt,analyzePolicyDelta:()=>Rr,analyzeProject:()=>Be,analyzeResolvedProject:()=>We,arkRunKernelCallKind:()=>En,buildAgentProjectionBeginMarker:()=>Qr,buildAgentProjectionBlock:()=>ro,buildAgentProjectionBody:()=>Vn,buildAgentProjectionMeta:()=>so,buildArkRuleFileHints:()=>yn,buildEffectiveArkRules:()=>tn,buildImprovementCompass:()=>Xa,buildRulesInventory:()=>Ca,buildStatusManifest:()=>Ha,canPromoteInvariant:()=>sn,catalogFixForRuleId:()=>Ma,catalogWhyForRuleId:()=>Fa,classifyArkPolicyDelta:()=>ln,classifyResolvedLayerCoverage:()=>An,classifyStatusWritePath:()=>$r,collectAnalysisConfigWarnings:()=>bt,collectEmptyAppliesToFindings:()=>gn,collectForbiddenCapabilityUses:()=>Te,composeMergePlanesHonesty:()=>kn,createAICodeGate:()=>ur,createAdapterResult:()=>ms,createArchitectureProfile:()=>ct,createArchitectureProfileFromArkConfig:()=>fr,createElevenLayerArkConfig:()=>mr,createProjectId:()=>As,createProjectIdentity:()=>Rs,createResolvedCandidateFacts:()=>Xt,defaultHonestLabel:()=>Hr,demoteExtraPlaneTeethUnderClassificationFloor:()=>ia,deriveArkRuleFileHints:()=>Er,detectArchitectureCycles:()=>un,deterministicHash:()=>X,diagnosticDocsFragment:()=>Lr,diagnosticDocsPath:()=>wa,effectiveContractPolicyPayload:()=>nn,elevenLayerProfile:()=>lt,emptyEffectiveArkRules:()=>ve,evaluateArchitectureGraph:()=>De,evaluateArkOrderSensors:()=>Tn,evaluateArkRuleSensors:()=>mn,evaluateArkRunEditorSensors:()=>_r,evaluateArkRunEditorSensorsFromSource:()=>ga,evaluateArkRunSensors:()=>St,evaluateInvariantCoverage:()=>rn,evaluateStatusBinding:()=>Fr,explainViolation:()=>kr,extraMergeTeethAllowed:()=>fe,extractAgentProjectionBlock:()=>$n,extractArkRunDeclarationsFromSource:()=>da,extractArkRunImportedConstructorNamesFromSource:()=>vn,extractArkRunKernelCallsFromSource:()=>Cn,extractArkRunManagedNewsFromSource:()=>On,extractArkRunValueImportDependenciesFromSource:()=>bn,extractClassShapesFromSource:()=>sa,extractSemanticDependencies:()=>xe,flatSkillTemplateFileRelativePath:()=>mo,formatAgentProjectionCatalogShortList:()=>es,formatAgentProjectionLayers:()=>Fn,formatArkRunDoctorLines:()=>Ia,formatImprovementCompassDoctorLines:()=>Ja,formatImprovementCompassResidualLabels:()=>Wr,getDiagnosticCatalogEntry:()=>Ct,inventoryToExtractionCard:()=>Oa,isArkOrderRuleId:()=>oa,isArkRunKernelModuleSpecifier:()=>qe,isArkRunRuleId:()=>Rn,isArkRunTransportBypassSpecifier:()=>In,isArkSkillName:()=>Un,isCataloguedOrArkRuleFamily:()=>La,isExtraPlaneFinding:()=>Ir,isKnownDiagnosticCode:()=>Pa,isValidAgentSkillName:()=>os,loadArkConfigContract:()=>it,loadArkRulesContract:()=>mt,loadContract:()=>At,loadResolvedCandidateFacts:()=>Re,mergeAgentProjectionDocument:()=>io,normalizeExtraMergeTeethClassification:()=>hn,normalizeSkillContent:()=>Kn,normalizeStatusImprovementCompass:()=>Vr,parseAgentProjectionStamp:()=>ts,parseArkConfigJson:()=>Yt,parseArkRulesJson:()=>zs,parseSkillDescriptionVersion:()=>uo,parseSkillDocument:()=>is,policyDeltaAcknowledgementMatches:()=>cn,preflightChange:()=>xr,preflightResolvedChange:()=>Tr,primaryImprovementCompassNextAction:()=>Yr,projectStatusArkRun:()=>Nn,projectStatusImprovementCompass:()=>Dn,projectionHasNonEnforcementLabel:()=>oo,projectionMatchesPackageVersion:()=>ao,resolveEffectiveContract:()=>Ws,resolveStatusNextAction:()=>jr,resolvedFactsEvidenceRequirementsHash:()=>Ge,serializeDiagnosticCatalog:()=>Da,skillDescriptionVersionPrefix:()=>cs,stableSerialize:()=>F,stampSkillDescription:()=>po,statusCompassResidualIsSubsetOfDoctor:()=>Ka,stripSkillDescriptionVersion:()=>ds,summarizeArkRunSection:()=>Ea,toAdapterDiagnostic:()=>$t,unavailableStatusImprovementCompass:()=>Va,validateAgentSkillDocument:()=>ls,validateAgentSkillsPackage:()=>co,version:()=>ps});module.exports=ko(Hl);var ps="4.8.3";var Eo=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Io=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,So=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function bo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Eo.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Io.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":So.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(bo,"classifyLayerImportKind");function vo(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=bo(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(vo,"layerImportNextAction");function Co(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Co,"arkRunCallSiteName");function Oo(e){let t=Co(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(Oo,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return vo(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"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, 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 Oo(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() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. 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 only. Change \u03BE with proposeRelease + release. 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 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 preflight again. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(pe,"deterministicNextAction");var Ht="1.5",qn="docs/diagnostics.md";function O(e){return typeof e=="string"&&e.length>0?e:void 0}i(O,"text");function fs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(fs,"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,a=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",a??""].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 _o(e,t,n){return pe({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(_o,"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,a={...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)}:{}},o=n??jt(e),l=Wn(o);return{ruleId:r,severity:s,message:O(e.message)??r,location:{file:O(e.file)??"<unknown>",line:fs(e.line,1),column:fs(e.column,1)},evidence:a,nextAction:O(e.nextAction)??_o(r,a,e),findingRef:l,targetKey:o,docsCodePath:Yn(r)}}i($t,"toAdapterDiagnostic");function ms(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 a=e.violations??[],o=e.warnings??[],l=Ft(a),c=Ft(o),p=[...a.map((y,f)=>$t(y,"error",l[f])),...o.map((y,f)=>$t(y,"warning",c[f]))],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(ms,"createAdapterResult");var gs={$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 ys="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}}},hs={$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 As(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(As,"createProjectId");function Rs(e){return{schemaVersion:"1.0",...e}}i(Rs,"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 a=e.indexOf("/",n+1);return a<0?null:Qn[e.slice(0,a)]??null}i(Qe,"capabilityForModuleSpecifier");function Se(e,t){for(let n of t)if(tr[n]?.includes(e))return n;return null}i(Se,"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=nr[r];if(s)return s}return null}i(Kt,"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 Ut(e){let t=new Set,n=new Set,r=Object.keys(nr);for(let s of e?.forbiddenGlobals??[]){let a=r.filter(o=>o===s||o.startsWith(`${s}.`));if(a.length===0)n.add(s);else for(let o of a)t.add(`ambient:${o}`);for(let o of tr[s]??[])t.add(`import-exact:${o}`)}for(let s of $e(e)){if(t.add(`import:${s}`),s==="process")for(let a of tr.process)t.add(`import-exact:${a}`);for(let a of r)Kt(a)===s&&t.add(`ambient:${a}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Ut,"loweredLayerCoverage");var ks=new Map;function Es(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Es,"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 xo(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(xo,"bracesBalanced");function _e(e){let t=ks.get(e);if(t)return t;let n=Gt(e),r=xo(n),s="",a=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=Es(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",a+=1):c==="}"&&r&&a>0?(s+=")",a-=1):c===","&&r&&a>0?s+="|":s+=Es(c)}let o=new RegExp(`^${s}$`);return ks.set(e,o),o}i(_e,"globToRegExp");function To(e){return Gt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(To,"concreteGlobSegments");function sr(e,t){let n=Gt(String(e)),r=To(n),s=n.replace(/\*/g,"").length,a=r.length*1e4+s;if(t==null||t==="")return a;let o=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<o.length;y+=1)if(o[y]===p){g=y;break}if(g<0)return a;c=g,l=g+1}return(c+1)*1e6+r.length*1e4+s}i(sr,"patternSpecificity");function ce(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let a of t??[])if(!(a.exclude??[]).some(o=>_e(o).test(n))){for(let o of a.patterns??[])if(_e(o).test(n)){let l=sr(o,n);l>s&&(s=l,r=a.name)}}return r}i(ce,"layerForRelativePath");function Is(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(Is,"sliceIdForPath");function No(e){let t=new Set;for(let n of e??[]){let s=Gt(String(n)).split("/").filter(Boolean);for(let a=0;a<s.length;a+=1){let o=s[a];if((o==="**"||o==="*")&&a>0){let l=s[a-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(No,"inferSliceFoldersFromPatterns");function Po(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 No(r?.patterns)}i(Po,"resolveSliceFolders");function Lo(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}i(Lo,"peerIsolationMustDeny");function me(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let a=r?.fromPath,o=r?.toPath,l=Po(s,t,r?.layers),c=a&&o?Is(a,l):void 0,p=a&&o?Is(o,l):void 0;if(Lo({fromPath:a,toPath:o,folderCount:l.length,fromSlice:c,toSlice:p}))return s;continue}if(t!==n)return s}}i(me,"findDeniedEdgeRule");function He(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(He,"literalText");function vs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(vs,"lineOf");function Ss(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(a=>a.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(Ss,"isTypeOnlyReference");function Cs(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(Cs,"singleFileChecker");function ar(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(ar,"symbolAt");function or(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=s?t.getShorthandAssignmentValueSymbol(r.parent):ar(t,r)}catch{a=void 0}return!!a?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}i(or,"localDeclaration");function xe(e,t){let n,r=[],s=i((o,l,c,p=!1)=>r.push({specifier:c,kind:l,line:vs(t,o),typeOnly:p,unresolved:c===void 0,node:o}),"add"),a=i(o=>{if(e.isImportDeclaration(o))s(o,"import",He(e,o.moduleSpecifier),Ss(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",He(e,o.moduleSpecifier),Ss(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",He(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let l=o.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!or(e,n??(n=Cs(e,t)),t,o.expression);(l||p)&&s(o,p?"require":"dynamic-import",He(e,o.arguments[0]))}e.forEachChild(o,a)},"visit");return a(t),r}i(xe,"extractSemanticDependencies");function wo(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(wo,"staticAccessPath");function Do(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(Do,"runtimeIdentifierReference");function bs(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(bs,"bestForbiddenMatch");function Te(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Cs(e,t),a=new Map,o=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let u of f.declarationList.declarations)e.isIdentifier(u.name)&&o.add(u.name.text);let l=i(f=>{let u=wo(e,f);if(!u)return;let m=ar(s,u.root),A=m?a.get(m):void 0;return A?[...A,...u.segments.slice(1)]:or(e,s,t,u.root)||o.has(u.root.text)?void 0:u.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let u of f.declarationList.declarations){if(!u.initializer||!e.isIdentifier(u.name))continue;let m=l(u.initializer),A=ar(s,u.name);!m||!A||a.set(A,m)}let c=[],p=new Set,g=i((f,u)=>{let m=vs(t,u),A=`${f}:${u.getStart(t)}`;p.has(A)||(p.add(A),c.push({name:f,line:m,node:u}))},"flag"),y=i(f=>{let u=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!u){let m=l(f),A=m?bs(r,m):void 0;A&&g(A,f)}else e.isIdentifier(f)&&r.has(f.text)&&Do(e,f)&&!or(e,s,t,f)&&g(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let m=l(f.initializer);if(m)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?He(e,A.propertyName)??A.propertyName.text:A.name.text,N=bs(r,[...m,b]);N&&g(N,f.initializer)}}e.forEachChild(f,y)},"visit");return y(t),c}i(Te,"collectForbiddenCapabilityUses");function ir(e,t,n){let r=[];for(let s of n?.dependencies??xe(e,t)){if(s.typeOnly||!s.specifier)continue;let a=Qe(s.specifier);a&&r.push({capability:a,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Te(e,t,rr)){let a=Kt(s.name);a&&r.push({capability:a,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,a)=>s.line-a.line||s.capability.localeCompare(a.capability)||s.symbol.localeCompare(a.symbol))}i(ir,"collectCapabilityUses");var lr={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."},cr=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 dr(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(a=>({layer:r.name,layerIndex:s,prefix:a.endsWith(".")?a:`${a}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}i(dr,"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:lr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:lr.PUBLISH_MISSING_SOURCE}),t}i(tt,"classifyPublishFacts");function q(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(q,"violation");function je(e,t){return e.slice(0,t).split(`
2
+ `).length}i(je,"lineOf");function Mo(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(Mo,"extractQuotedStrings");function Fo(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 a=s.index+s[0].indexOf(s[1]),o=s[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:s[1],index:a,kind:r.kind,typeOnly:l})}}return t.sort((r,s)=>r.index-s.index)}i(Fo,"extractModuleSpecifiers");function $o(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i(a=>{e.isStringLiteralLike(a)&&r.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,s)},"visit");return s(n),r}i($o,"extractQuotedStringsAst");function Ho(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(Ho,"hasInfrastructureToken");function jo(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(jo,"isKnownInfrastructurePackage");function Vo(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(Vo,"layerHasInfrastructureRole");function rt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(rt,"tsStringLiteralText");function Ko(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Ko,"tsPropertyName");function Os(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Ko(e,r.name)===n)}i(Os,"tsObjectProperty");function st(e,t,n){return Os(e,t,n)!==void 0}i(st,"tsObjectHasProperty");function nt(e,t,n){let r=Os(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(nt,"tsObjectPropertyValue");function Uo(e,t){let n=nt(e,t,"metadata");return st(e,n,"source")}i(Uo,"tsObjectHasMetadataSource");function _s(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?_s(e,t.name):!1:!1}i(_s,"tsLooksLikeIntentCreatorExpression");function Go(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(Go,"tsIsPublishCall");function Bo(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")||_s(e,n)}i(Bo,"tsIsArkPublishCandidate");function zo(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Uo(e,n)||st(e,r,"source")||st(e,s,"source")}i(zo,"tsPublishHasSource");function qo(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,a=nt(e,n,"metadata");return rt(e,nt(e,a,"source"))??rt(e,nt(e,r,"source"))??rt(e,nt(e,s,"source"))}i(qo,"tsPublishSourceLiteral");function Wo(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,o=a?.filePath,l=a?.layer,c=[],p=i(y=>s.getLineAndCharacterOfPosition(y.getStart(s)).line+1,"lineForNode"),g=i(y=>{if(Go(e,y)){let f=y.arguments[0],u=rt(e,f);for(let A of tt({publishCall:!0,rawIntentName:u,objectHasIntent:st(e,f,"intent"),arkPublishCandidate:Bo(e,y),hasSource:zo(e,y)}))c.push(q(A.ruleId,A.message,{line:p(y),filePath:o}));let m=qo(e,y);if(r&&l&&m&&Ne(m)){let A=r.resolveLayer(m);A&&A!==l&&c.push(q("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${m}" resolves to ${A}, but the target file is classified as ${l}.`,{line:p(y),filePath:o,target:m,fromLayer:l,toLayer:A}))}}e.forEachChild(y,g)},"visit");return g(s),c}i(Wo,"analyzePublishAst");function ur(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(a,o){let l=[],c=o,p=c?.filePath,g=c?.layer,y=e.typescript,f=y?y.createSourceFile(p??"generated.ts",a,y.ScriptTarget.Latest,!0):void 0,u=f?xe(e.typescript,f):void 0,m=u?u.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(f),kind:R.kind,typeOnly:R.typeOnly})):Fo(a),A=e.typescript?$o(e.typescript,a):Mo(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let R of u?.filter(({unresolved:I})=>I)??[]){let I=R.kind==="require";l.push(q(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 b=g!==void 0&&(r.has(g)||Vo(g)),N=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(a);R.lastIndex=0,I&&l.push(q("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:I.index===void 0?void 0:je(a,I.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+N}))}else a.includes(R)&&l.push(q("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:je(a,a.indexOf(R)),filePath:p}));for(let R of m){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,Y=I?.layer;if(Y&&g){let k=me(e.architectureProfile?.rules,g,Y,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(k){if(R.typeOnly&&!k.peerIsolation)continue;let L=!!k.peerIsolation;l.push(q("LAYER_IMPORT_VIOLATION",k.message??(L?`Layer "${g}" must not import across slices into "${Y}".`:`Layer "${g}" must not import "${Y}".`),{line:je(a,R.index),source:R.value,target:R.value,filePath:p,fromLayer:g,toLayer:Y,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}b||R.typeOnly||!Ho(R.value)&&!jo(R.value)||l.push(q("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:je(a,R.index),source:R.value,target:R.value,filePath:p,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+N,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let I=R.check({source:a,context:o});if(I!==!0)if(Array.isArray(I))for(let C of I)l.push(q("POLICY_VIOLATION",C.message,{filePath:p,suggestion:`Fix violation of policy "${R.name}".`}));else I===!1?l.push(q("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):l.push(q("POLICY_VIOLATION",I.message))}if(s&&t.size>0)for(let R of A)Ne(R.value)&&!t.has(R.value)&&l.push(q("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:je(a,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=me(e.architectureProfile.rules,g,I);C&&l.push(q("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${I}" through "${R.value}".`,{line:je(a,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(a,o);l.push(...I)}catch(I){l.push(q("EXTENSION_ERROR",`Extension "${R.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&g&&e.forbiddenGlobals?.[g]?.length)try{let R=e.forbiddenGlobals[g];l.push(...Te(e.typescript,f,R).map(I=>q("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=Se(I.specifier,R);C&&l.push(q("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(q("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&f&&g&&e.capabilityWalls?.[g]?.length)try{let R=new Set(e.capabilityWalls[g]),I=e.forbiddenGlobals?.[g]??[];for(let C of ir(e.typescript,f))R.has(C.capability)&&(C.source==="ambient-global"&&et(C.symbol,I)||C.source==="import-based"&&Se(C.symbol,I)||l.push(q("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(q("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{l.push(...Wo(e.typescript,a,o,e.architectureProfile))}catch(R){l.push(q("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(ur,"createAICodeGate");var Ve={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},xs={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}}},Ts={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 at(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(at,"isObject");function Ns(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(Ns,"declaredLayerNames");function Ps(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(Ps,"defaultedArkRun");function Ls(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(Ls,"defaultedArkOrder");function ws(e,t){let n=e.arkRun;if(n===void 0||!at(n))return;let r=Ns(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((a,o)=>{typeof a=="string"&&a.length>0&&!r.has(a)&&t.push({path:`$.arkRun.managedLayers[${o}]`,message:`layer ${JSON.stringify(a)} is not declared in layers[]`})}),n.mode==="enforced"){let a=n.kernelRoots??n.compositionRoots;(!Array.isArray(a)||a.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(ws,"validateArkRunExtra");function Ds(e,t){let n=e.arkOrder;if(n===void 0||!at(n))return;let r=Ns(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((a,o)=>{typeof a=="string"&&a.length>0&&!r.has(a)&&t.push({path:`$.arkOrder.managedLayers[${o}]`,message:`layer ${JSON.stringify(a)} is not declared in layers[]`})}),n.mode==="enforced"){let a=n.planeRoots;(!Array.isArray(a)||a.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(Ds,"validateArkOrderExtra");var te="1.3",zt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ms=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Yo=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Xo(){let e=[];for(let t of Ms)for(let n of Ms)t===n||Yo.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(Xo,"createDefaultRules");var Wt=Xo(),pr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ge={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:te,default:te},name:{type:"string",minLength:1},include:{...ge,minItems:1,default:["src"]},exclude:{...ge,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:{...ge,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...ge,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ge,minItems:1},exclude:ge,intentPrefixes:ge,description:{type:"string",minLength:1},forbiddenGlobals:ge,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:{...ge,minItems: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}}},arkRun:xs,arkOrder:Ts}},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 Ds(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Ds,"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 je(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(je,"valueType");function Wa(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Wa,"resolveSchemaRef");function at(e,t,n,r,s){if(t.$ref){let o=Wa(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(!Ds(e)){s.push({path:n,message:`must be an object; received ${je(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 ${je(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 ${je(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 ${je(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${je(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(at,"validateNode");function Ja(e){let t={...e,$schema:e.$schema===void 0?zt:e.$schema,schemaVersion:e.schemaVersion===void 0?te:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Yt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Ts(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ns(e.arkOrder)),t}i(Ja,"defaultedConfig");function Za(e){return e===te?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Za,"migratedFromOf");function Xa(){let e=new Set([te]);for(let t of cr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Xa,"knownInputVersions");function Qa(e,t="ark.config.json"){if(!Ds(e))throw new he(t,[{path:"$",message:`must be an object; received ${je(e)}`}]);let n=Xa(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${te}`}]);if(r!=="unversioned"&&!n.has(r))throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);let s=r,o={...e},a=0;for(;s!==te&&a<cr.length+1;){a+=1;let l=cr.find(c=>c.from===s);if(!l)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${te}`}]);s=l.to,o.schemaVersion=s}if(s!==te)throw new he(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);return{candidate:Ja(o),migratedFrom:Za(r)}}i(Qa,"migrateArkConfig");function it(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Qa(e,t),s=[];if(at(n,qt,"$",qt,s),Ps(n,s),Ls(n,s),s.length>0)throw new he(t,s);return{config:n,migratedFrom:r}}i(it,"loadArkConfigContract");function Wt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new he(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return it(n,t)}i(Wt,"parseArkConfigJson");function Ms(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:zt,schemaVersion:te};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(Ms,"withArkConfigMetadata");function ei(e){return e.endsWith(".")?e:`${e}.`}i(ei,"normalizePrefix");function ti(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(ti,"byLongestPrefix");function ct(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(ei)})),n=[...t].sort(ti),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 dr(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(dr,"createArchitectureProfileFromArkConfig");var ni=[{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:ni,rules:Yt.map(e=>({...e}))}),ri={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 ur(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Ms({include:e.include??[t],layers:lt.layers.map(s=>({name:s.name,patterns:(ri[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...lt.rules]})}i(ur,"createElevenLayerArkConfig");function K(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(K,"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 be="1.2";var Fs=["network","filesystem","clock","randomness","environment","process","persistence"];function Z(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}i(Z,"compareCanonical");function X(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(X,"sortedUnique");function Ue(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(Z),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:X(e.arkRun.compositionRoots),managedLayers:X(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return K(F(t))}i(Ue,"resolvedFactsEvidenceRequirementsHash");function si(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(Z),n=e.files.map(k=>({...k,typeOnlyExportNames:X(k.typeOnlyExportNames)})).sort((k,b)=>k.path<b.path?-1:k.path>b.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:X(k.namedBindings)}:{}})).sort(Z),s=e.capabilityUses.map(k=>({...k})).sort(Z),o=e.ambientUses.map(k=>({...k})).sort(Z),a=e.publishCalls.map(k=>({...k})).sort(Z),l=e.intentReferences.map(k=>({...k})).sort(Z),c=e.safetyUses.map(k=>({...k})).sort(Z),p=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(b=>({...b}))})).sort(Z),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(Z),g=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(Z),u=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(Z),d=(e.arkRunDeclarations??[]).map(k=>({...k,uses:X(k.uses),reactsTo:X(k.reactsTo),raises:X(k.raises),sends:X(k.sends)})).sort(Z),f=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(Z),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(Z),I=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(Z),N=e.files.map(({path:k,contentHash:b})=>({path:k,contentHash:b})).sort((k,b)=>k.path<b.path?-1:k.path>b.path?1:0),E=K(F(N));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:E,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:m,arkRunManagedNews:g,arkRunCompositionRootHits:u,arkRunDeclarations:d,arkOrderPlaneCalls:f,arkOrderGenericUpdates:y,arkOrderRootHits:I}}i(si,"canonicalResolvedFactsInput");function $s(e){let t=si(e);return{...t,factsHash:K(F(t))}}i($s,"createCanonicalResolvedCandidateFacts");function Jt(e){return $s(js(U(e,"$"),!1))}i(Jt,"createResolvedCandidateFacts");function U(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(U,"asRecord");function G(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(G,"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 Ae(e,t,n){if(e[t]!==void 0)return M(e,t,n)}i(Ae,"optionalText");function q(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(q,"requiredProjectPath");function j(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(j,"requiredBoolean");function Hs(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(Hs,"requiredInteger");function le(e,t,n){let r=Hs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(le,"requiredPositiveInteger");function Y(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(Y,"requiredArray");function Re(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(Re,"enumValue");function Ve(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(Ve,"parseStringArray");function oi(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(oi,"assertUnique");function js(e,t){G(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",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Re(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Re(e,"completeness",["complete","partial","unavailable"],"$"),s=Y(e,"completenessReasons","$").map((v,_)=>{let A=`$.completenessReasons[${_}]`,R=U(v,A);G(R,["code","message","file"],A);let L=R.file===void 0?void 0:q(R,"file",A);return{code:M(R,"code",A),message:M(R,"message",A),...L?{file:L}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=Y(e,"files","$").map((v,_)=>{let A=`$.files[${_}]`,R=U(v,A);return G(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],A),{path:q(R,"path",A),contentHash:M(R,"contentHash",A),parseStatus:Re(R,"parseStatus",["parsed","invalid"],A),parseDiagnosticCount:Hs(R,"parseDiagnosticCount",A),exportsOnlyTypes:j(R,"exportsOnlyTypes",A),typeOnlyExportNames:Ve(R.typeOnlyExportNames,`${A}.typeOnlyExportNames`),hasTopLevelSideEffects:j(R,"hasTopLevelSideEffects",A)}}),a=Y(e,"dependencies","$").map((v,_)=>{let A=`$.dependencies[${_}]`,R=U(v,A);G(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],A);let L=Ae(R,"specifier",A),z=Ae(R,"target",A),Ie=Re(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],A);if(Ie==="resolved-project"&&!z)throw new Error(`${A}.target is required for resolved-project dependencies.`);if(Ie!=="resolved-project"&&z)throw new Error(`${A}.target is only allowed for resolved-project dependencies.`);if(Ie!=="dynamic"&&!L)throw new Error(`${A}.specifier is required unless resolution is dynamic.`);return{from:q(R,"from",A),...L?{specifier:L}:{},kind:Re(R,"kind",["import","export","dynamic-import","require"],A),typeOnly:j(R,"typeOnly",A),line:le(R,"line",A),resolution:Ie,...z?{target:q(R,"target",A)}:{},...R.namedBindings!==void 0?{namedBindings:Ve(R.namedBindings,`${A}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:j(R,"targetTypeOnlyExports",A)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:j(R,"sourcePureTypeModule",A)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:j(R,"namedBindingsTypeOnly",A)}:{},...R.portProofEligible!==void 0?{portProofEligible:j(R,"portProofEligible",A)}:{}}}),l=Y(e,"capabilityUses","$").map((v,_)=>{let A=`$.capabilityUses[${_}]`,R=U(v,A);return G(R,["file","line","symbol","capability","source"],A),{file:q(R,"file",A),line:le(R,"line",A),symbol:M(R,"symbol",A),capability:Re(R,"capability",Fs,A),source:Re(R,"source",["ambient-global","import-based"],A)}}),c=Y(e,"ambientUses","$").map((v,_)=>{let A=`$.ambientUses[${_}]`,R=U(v,A);return G(R,["file","line","symbol"],A),{file:q(R,"file",A),line:le(R,"line",A),symbol:M(R,"symbol",A)}}),p=Y(e,"publishCalls","$").map((v,_)=>{let A=`$.publishCalls[${_}]`,R=U(v,A);G(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],A);let L=Ae(R,"rawIntentName",A),z=Ae(R,"sourceIntent",A);return{file:q(R,"file",A),line:le(R,"line",A),...L?{rawIntentName:L}:{},objectHasIntent:j(R,"objectHasIntent",A),arkPublishCandidate:j(R,"arkPublishCandidate",A),hasSource:j(R,"hasSource",A),...z?{sourceIntent:z}:{}}}),m=Y(e,"intentReferences","$").map((v,_)=>{let A=`$.intentReferences[${_}]`,R=U(v,A);return G(R,["file","line","intent"],A),{file:q(R,"file",A),line:le(R,"line",A),intent:M(R,"intent",A)}}),g=Y(e,"safetyUses","$").map((v,_)=>{let A=`$.safetyUses[${_}]`,R=U(v,A);G(R,["file","line","kind","symbol"],A);let L=Ae(R,"symbol",A),z=Re(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],A);if(z==="in-memory-store"&&!L)throw new Error(`${A}.symbol is required for in-memory-store facts.`);if(z!=="in-memory-store"&&L)throw new Error(`${A}.symbol is only allowed for in-memory-store facts.`);return{file:q(R,"file",A),line:le(R,"line",A),kind:z,...L?{symbol:L}:{}}});oi(o,v=>v.path,"$.files");let u=new Set(o.map(v=>v.path));for(let v of o){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!u.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let f=(e.arkRunKernelCalls===void 0?[]:Y(e,"arkRunKernelCalls","$")).map((v,_)=>{let A=`$.arkRunKernelCalls[${_}]`,R=U(v,A);G(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],A);let L=Ae(R,"receiver",A),z=Ae(R,"nameLiteral",A);return{file:q(R,"file",A),line:le(R,"line",A),kind:Re(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],A),callee:M(R,"callee",A),viaImport:j(R,"viaImport",A),...L?{receiver:L}:{},...z?{nameLiteral:z}:{}}}),I=(e.arkRunManagedNews===void 0?[]:Y(e,"arkRunManagedNews","$")).map((v,_)=>{let A=`$.arkRunManagedNews[${_}]`,R=U(v,A);G(R,["file","line","typeName","importedFrom"],A);let L=Ae(R,"importedFrom",A);return{file:q(R,"file",A),line:le(R,"line",A),typeName:M(R,"typeName",A),...L?{importedFrom:L}:{}}}),E=(e.arkRunCompositionRootHits===void 0?[]:Y(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let A=`$.arkRunCompositionRootHits[${_}]`,R=U(v,A);return G(R,["file","matchedRoot","hasKernelFactory"],A),{file:q(R,"file",A),matchedRoot:M(R,"matchedRoot",A),hasKernelFactory:j(R,"hasKernelFactory",A)}}),k=e.arkRunDeclarations===void 0?[]:Y(e,"arkRunDeclarations","$"),J=(e.arkOrderPlaneCalls===void 0?[]:Y(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let A=`$.arkOrderPlaneCalls[${_}]`,R=U(v,A);return G(R,["file","line","callee"],A),{file:q(R,"file",A),line:le(R,"line",A),callee:M(R,"callee",A)}}),B=(e.arkOrderGenericUpdates===void 0?[]:Y(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let A=`$.arkOrderGenericUpdates[${_}]`,R=U(v,A);return G(R,["file","line","method"],A),{file:q(R,"file",A),line:le(R,"line",A),method:M(R,"method",A)}}),O=(e.arkOrderRootHits===void 0?[]:Y(e,"arkOrderRootHits","$")).map((v,_)=>{let A=`$.arkOrderRootHits[${_}]`,R=U(v,A);return G(R,["file","matchedRoot","hasPlaneFactory"],A),{file:q(R,"file",A),matchedRoot:M(R,"matchedRoot",A),hasPlaneFactory:j(R,"hasPlaneFactory",A)}}),D=k.map((v,_)=>{let A=`$.arkRunDeclarations[${_}]`,R=U(v,A);return G(R,["file","line","uses","reactsTo","raises","sends"],A),{file:q(R,"file",A),line:le(R,"line",A),uses:Ve(R.uses,`${A}.uses`),reactsTo:Ve(R.reactsTo,`${A}.reactsTo`),raises:Ve(R.raises,`${A}.raises`),sends:Ve(R.sends,`${A}.sends`)}});for(let[v,_]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",m],["$.safetyUses",g],["$.arkRunKernelCalls",f],["$.arkRunManagedNews",I],["$.arkRunCompositionRootHits",E],["$.arkRunDeclarations",D],["$.arkOrderPlaneCalls",J],["$.arkOrderGenericUpdates",B],["$.arkOrderRootHits",O]])for(let A of _)if(!u.has(A.file))throw new Error(`${v} references missing file ${A.file}.`);let P=Ae(e,"projectPackageName","$"),me=(e.classShapes===void 0?[]:Y(e,"classShapes","$")).map((v,_)=>{let A=`$.classShapes[${_}]`,R=U(v,A);G(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],A);let L=Y(R,"mutatingMethods",A).map((z,Ie)=>{let Oe=`${A}.mutatingMethods[${Ie}]`,We=U(z,Oe);return G(We,["name","referencesGuardOrPublish"],Oe),{name:M(We,"name",Oe),referencesGuardOrPublish:j(We,"referencesGuardOrPublish",Oe)}});return{file:q(R,"file",A),className:M(R,"className",A),exported:j(R,"exported",A),hasPublicMutableFields:j(R,"hasPublicMutableFields",A),hasPublicSetters:j(R,"hasPublicSetters",A),hasPublicConstructor:j(R,"hasPublicConstructor",A),hasStaticFactory:j(R,"hasStaticFactory",A),mutatingMethods:L,...R.dataOnly===void 0?{}:{dataOnly:j(R,"dataOnly",A)}}});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","$"),...P?{projectPackageName:P}:{},files:o,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:m,safetyUses:g,classShapes:me,arkRunKernelCalls:f,arkRunManagedNews:I,arkRunCompositionRootHits:E,arkRunDeclarations:D,arkOrderPlaneCalls:J,arkOrderGenericUpdates:B,arkOrderRootHits:O}}i(js,"parseResolvedFactsInput");function ke(e){let t=U(e,"$"),n=M(t,"factsHash","$"),r=M(t,"candidateTreeHash","$"),s=$s(js(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(ke,"loadResolvedCandidateFacts");var ai=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},ce={type:"integer",minimum:1},W={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Zt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:x,message:x,file:W}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:W,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:W,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ce,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:W,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:W,line:ce,symbol:x,capability:{enum:ai},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:W,line:ce,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:W,line:ce,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:W,line:ce,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:W,line:ce,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:W,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:W,line:ce,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:W,line:ce,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:W,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:W,line:ce,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:W,line:ce,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:W,line:ce,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:W,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},factsHash:x},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Xt="1.0";function re(e){return`${e.from}->${e.to}`}i(re,"dependencyKey");function dt(e,t,n,r="dependency"){return{id:`${e}:${r}:${re(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${re(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${re(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${re(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${re(t)} from the candidate, then preflight again.`}:{}}}i(dt,"dependencyFinding");function Le(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),s=new Map(e.changeMap.map.dependencies.map(u=>[re(u),u])),o=new Map(e.baseDependencies.map(u=>[re(u),u])),a=new Map(e.candidateDependencies.map(u=>[re(u),u]));for(let u of[...n.values()].sort((d,f)=>d.path.localeCompare(f.path))){let d=r.get(u.path);d?d.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:d.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${d.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:d.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((d,f)=>d.path.localeCompare(f.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...s.values()].sort((d,f)=>re(d).localeCompare(re(f)))){if(a.has(re(u))){t.push(dt("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let d={from:u.to,to:u.from};a.has(re(d))?(l.add(re(d)),t.push(dt("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(dt("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,d]of[...a].sort(([f],[y])=>f.localeCompare(y)))o.has(u)||s.has(u)||l.has(u)||!c.has(d.from)&&!c.has(d.to)||t.push({...dt("unplanned",d,`${d.from} -> ${d.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,d]of[...o].sort(([f],[y])=>f.localeCompare(y)))a.has(u)||p.has(d.from)||p.has(d.to)||!c.has(d.from)&&!c.has(d.to)||t.push({...dt("unplanned",d,`${d.from} -> ${d.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let m={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,d)=>m[u.classification]-m[d.classification]||(u.subject===d.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(d.id));let g={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}i(Le,"analyzeArchitectureConvergence");var Ks="1.0",pr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",fr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],ii=["no-anemic-model"],Vs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},en={$schema:"https://json-schema.org/draft/2020-12/schema",$id:pr,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:pr},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:[...fr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Vs,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:Vs}}}},we=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 Fs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Fs,"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 Ke(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Ke,"valueType");function Jo(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Jo,"resolveSchemaRef");function ot(e,t,n,r,s){if(t.$ref){let a=Jo(t.$ref,r);if(!a){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ot(e,a,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(a=>Object.is(a,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Fs(e)){s.push({path:n,message:`must be an object; received ${Ke(e)}`});return}let a=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:Bt(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in a||s.push({path:Bt(n,o),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let o=t.additionalProperties;for(let l of Object.keys(e))l in a||ot(e[l],o,Bt(n,l),r,s)}for(let[o,l]of Object.entries(a))e[o]!==void 0&&ot(e[o],l,Bt(n,o),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 a=e.map(o=>JSON.stringify(o));new Set(a).size!==a.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,o)=>ot(a,t.items,`${n}[${o}]`,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(ot,"validateNode");function Zo(e){let t={...e,$schema:e.$schema===void 0?zt:e.$schema,schemaVersion:e.schemaVersion===void 0?te:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Wt.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Ps(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ls(e.arkOrder)),t}i(Zo,"defaultedConfig");function Qo(e){return e===te?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Qo,"migratedFromOf");function ei(){let e=new Set([te]);for(let t of pr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(ei,"knownInputVersions");function ti(e,t="ark.config.json"){if(!Fs(e))throw new ye(t,[{path:"$",message:`must be an object; received ${Ke(e)}`}]);let n=ei(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${te}`}]);if(r!=="unversioned"&&!n.has(r))throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);let s=r,a={...e},o=0;for(;s!==te&&o<pr.length+1;){o+=1;let l=pr.find(c=>c.from===s);if(!l)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${te}`}]);s=l.to,a.schemaVersion=s}if(s!==te)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);return{candidate:Zo(a),migratedFrom:Qo(r)}}i(ti,"migrateArkConfig");function it(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ti(e,t),s=[];if(ot(n,qt,"$",qt,s),ws(n,s),Ds(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 $s(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:zt,schemaVersion:te};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i($s,"withArkConfigMetadata");function ni(e){return e.endsWith(".")?e:`${e}.`}i(ni,"normalizePrefix");function ri(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(ri,"byLongestPrefix");function ct(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(ni)})),n=[...t].sort(ri),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(a=>a.match?.(s))?.name??n.find(a=>a.prefixes.some(o=>s.startsWith(o)))?.name}}}i(ct,"createArchitectureProfile");function fr(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(fr,"createArchitectureProfileFromArkConfig");var si=[{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:si,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 mr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return $s({include:e.include??[t],layers:lt.layers.map(s=>({name:s.name,patterns:(ai[s.name]??[s.name]).map(a=>`${r}${a}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...lt.rules]})}i(mr,"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 be="1.2";var Hs=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}i(W,"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(W),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 oi(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(W),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(W),s=e.capabilityUses.map(k=>({...k})).sort(W),a=e.ambientUses.map(k=>({...k})).sort(W),o=e.publishCalls.map(k=>({...k})).sort(W),l=e.intentReferences.map(k=>({...k})).sort(W),c=e.safetyUses.map(k=>({...k})).sort(W),p=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(L=>({...L}))})).sort(W),g=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(W),y=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(W),f=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(W),u=(e.arkRunDeclarations??[]).map(k=>({...k,uses:J(k.uses),reactsTo:J(k.reactsTo),raises:J(k.raises),sends:J(k.sends)})).sort(W),m=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(W),A=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(W),b=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(W),N=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(W),R=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(W),I=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(W),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),Y=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:Y,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:a,publishCalls:o,intentReferences:l,safetyUses:c,classShapes:p,arkRunKernelCalls:g,arkRunManagedNews:y,arkRunCompositionRootHits:f,arkRunDeclarations:u,arkOrderPlaneCalls:m,arkOrderGenericUpdates:A,arkOrderRootHits:b,arkOrderXiFieldWrites:N,arkOrderIngestWritesXi:R,arkOrderReleaseKeyCounts:I}}i(oi,"canonicalResolvedFactsInput");function js(e){let t=oi(e);return{...t,factsHash:X(F(t))}}i(js,"createCanonicalResolvedCandidateFacts");function Xt(e){return js(Ks($(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 V(e,t,n){let r=new Set(t),s=Object.keys(e).find(a=>!r.has(a));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}i(V,"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 U(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 a=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(a.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);a.pop()}else a.push(l);let o=a.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}i(U,"requiredProjectPath");function G(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(G,"requiredBoolean");function Vs(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(Vs,"requiredInteger");function Z(e,t,n){let r=Vs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Z,"requiredPositiveInteger");function B(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(B,"requiredArray");function 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 Ue(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(Ue,"parseStringArray");function ii(e,t,n){let r=new Set;for(let s of e){let a=t(s);if(r.has(a))throw new Error(`${n} must not contain duplicate facts (${a}).`);r.add(a)}}i(ii,"assertUnique");function Ks(e,t){V(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=B(e,"completenessReasons","$").map((S,v)=>{let h=`$.completenessReasons[${v}]`,d=$(S,h);V(d,["code","message","file"],h);let P=d.file===void 0?void 0:U(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 a=B(e,"files","$").map((S,v)=>{let h=`$.files[${v}]`,d=$(S,h);return V(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:U(d,"path",h),contentHash:M(d,"contentHash",h),parseStatus:Ae(d,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Vs(d,"parseDiagnosticCount",h),exportsOnlyTypes:G(d,"exportsOnlyTypes",h),typeOnlyExportNames:Ue(d.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:G(d,"hasTopLevelSideEffects",h)}}),o=B(e,"dependencies","$").map((S,v)=>{let h=`$.dependencies[${v}]`,d=$(S,h);V(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let P=he(d,"specifier",h),j=he(d,"target",h),oe=Ae(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(oe==="resolved-project"&&!j)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(oe!=="resolved-project"&&j)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(oe!=="dynamic"&&!P)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:U(d,"from",h),...P?{specifier:P}:{},kind:Ae(d,"kind",["import","export","dynamic-import","require"],h),typeOnly:G(d,"typeOnly",h),line:Z(d,"line",h),resolution:oe,...j?{target:U(d,"target",h)}:{},...d.namedBindings!==void 0?{namedBindings:Ue(d.namedBindings,`${h}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(d,"targetTypeOnlyExports",h)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(d,"sourcePureTypeModule",h)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(d,"namedBindingsTypeOnly",h)}:{},...d.portProofEligible!==void 0?{portProofEligible:G(d,"portProofEligible",h)}:{}}}),l=B(e,"capabilityUses","$").map((S,v)=>{let h=`$.capabilityUses[${v}]`,d=$(S,h);return V(d,["file","line","symbol","capability","source"],h),{file:U(d,"file",h),line:Z(d,"line",h),symbol:M(d,"symbol",h),capability:Ae(d,"capability",Hs,h),source:Ae(d,"source",["ambient-global","import-based"],h)}}),c=B(e,"ambientUses","$").map((S,v)=>{let h=`$.ambientUses[${v}]`,d=$(S,h);return V(d,["file","line","symbol"],h),{file:U(d,"file",h),line:Z(d,"line",h),symbol:M(d,"symbol",h)}}),p=B(e,"publishCalls","$").map((S,v)=>{let h=`$.publishCalls[${v}]`,d=$(S,h);V(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let P=he(d,"rawIntentName",h),j=he(d,"sourceIntent",h);return{file:U(d,"file",h),line:Z(d,"line",h),...P?{rawIntentName:P}:{},objectHasIntent:G(d,"objectHasIntent",h),arkPublishCandidate:G(d,"arkPublishCandidate",h),hasSource:G(d,"hasSource",h),...j?{sourceIntent:j}:{}}}),g=B(e,"intentReferences","$").map((S,v)=>{let h=`$.intentReferences[${v}]`,d=$(S,h);return V(d,["file","line","intent"],h),{file:U(d,"file",h),line:Z(d,"line",h),intent:M(d,"intent",h)}}),y=B(e,"safetyUses","$").map((S,v)=>{let h=`$.safetyUses[${v}]`,d=$(S,h);V(d,["file","line","kind","symbol"],h);let P=he(d,"symbol",h),j=Ae(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(j==="in-memory-store"&&!P)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(j!=="in-memory-store"&&P)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:U(d,"file",h),line:Z(d,"line",h),kind:j,...P?{symbol:P}:{}}});ii(a,S=>S.path,"$.files");let f=new Set(a.map(S=>S.path));for(let S of a){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"&&a.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of o)if(!f.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let m=(e.arkRunKernelCalls===void 0?[]:B(e,"arkRunKernelCalls","$")).map((S,v)=>{let h=`$.arkRunKernelCalls[${v}]`,d=$(S,h);V(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let P=he(d,"receiver",h),j=he(d,"nameLiteral",h);return{file:U(d,"file",h),line:Z(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:G(d,"viaImport",h),...P?{receiver:P}:{},...j?{nameLiteral:j}:{}}}),b=(e.arkRunManagedNews===void 0?[]:B(e,"arkRunManagedNews","$")).map((S,v)=>{let h=`$.arkRunManagedNews[${v}]`,d=$(S,h);V(d,["file","line","typeName","importedFrom"],h);let P=he(d,"importedFrom",h);return{file:U(d,"file",h),line:Z(d,"line",h),typeName:M(d,"typeName",h),...P?{importedFrom:P}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:B(e,"arkRunCompositionRootHits","$")).map((S,v)=>{let h=`$.arkRunCompositionRootHits[${v}]`,d=$(S,h);return V(d,["file","matchedRoot","hasKernelFactory"],h),{file:U(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasKernelFactory:G(d,"hasKernelFactory",h)}}),I=e.arkRunDeclarations===void 0?[]:B(e,"arkRunDeclarations","$"),Y=(e.arkOrderPlaneCalls===void 0?[]:B(e,"arkOrderPlaneCalls","$")).map((S,v)=>{let h=`$.arkOrderPlaneCalls[${v}]`,d=$(S,h);return V(d,["file","line","callee"],h),{file:U(d,"file",h),line:Z(d,"line",h),callee:M(d,"callee",h)}}),L=(e.arkOrderGenericUpdates===void 0?[]:B(e,"arkOrderGenericUpdates","$")).map((S,v)=>{let h=`$.arkOrderGenericUpdates[${v}]`,d=$(S,h);return V(d,["file","line","method"],h),{file:U(d,"file",h),line:Z(d,"line",h),method:M(d,"method",h)}}),x=(e.arkOrderRootHits===void 0?[]:B(e,"arkOrderRootHits","$")).map((S,v)=>{let h=`$.arkOrderRootHits[${v}]`,d=$(S,h);return V(d,["file","matchedRoot","hasPlaneFactory"],h),{file:U(d,"file",h),matchedRoot:M(d,"matchedRoot",h),hasPlaneFactory:G(d,"hasPlaneFactory",h)}}),w=(e.arkOrderXiFieldWrites===void 0?[]:B(e,"arkOrderXiFieldWrites","$")).map((S,v)=>{let h=`$.arkOrderXiFieldWrites[${v}]`,d=$(S,h);return V(d,["file","line","key"],h),{file:U(d,"file",h),line:Z(d,"line",h),key:M(d,"key",h)}}),ue=(e.arkOrderIngestWritesXi===void 0?[]:B(e,"arkOrderIngestWritesXi","$")).map((S,v)=>{let h=`$.arkOrderIngestWritesXi[${v}]`,d=$(S,h);return V(d,["file","line"],h),{file:U(d,"file",h),line:Z(d,"line",h)}}),Je=(e.arkOrderReleaseKeyCounts===void 0?[]:B(e,"arkOrderReleaseKeyCounts","$")).map((S,v)=>{let h=`$.arkOrderReleaseKeyCounts[${v}]`,d=$(S,h);return V(d,["file","line","keyCount"],h),{file:U(d,"file",h),line:Z(d,"line",h),keyCount:Z(d,"keyCount",h)}}),Ze=I.map((S,v)=>{let h=`$.arkRunDeclarations[${v}]`,d=$(S,h);return V(d,["file","line","uses","reactsTo","raises","sends"],h),{file:U(d,"file",h),line:Z(d,"line",h),uses:Ue(d.uses,`${h}.uses`),reactsTo:Ue(d.reactsTo,`${h}.reactsTo`),raises:Ue(d.raises,`${h}.raises`),sends:Ue(d.sends,`${h}.sends`)}});for(let[S,v]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",g],["$.safetyUses",y],["$.arkRunKernelCalls",m],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",Ze],["$.arkOrderPlaneCalls",Y],["$.arkOrderGenericUpdates",L],["$.arkOrderRootHits",x],["$.arkOrderXiFieldWrites",w],["$.arkOrderIngestWritesXi",ue],["$.arkOrderReleaseKeyCounts",Je]])for(let h of v)if(!f.has(h.file))throw new Error(`${S} references missing file ${h.file}.`);let Oe=he(e,"projectPackageName","$"),Bn=(e.classShapes===void 0?[]:B(e,"classShapes","$")).map((S,v)=>{let h=`$.classShapes[${v}]`,d=$(S,h);V(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],h);let P=B(d,"mutatingMethods",h).map((j,oe)=>{let Dt=`${h}.mutatingMethods[${oe}]`,zn=$(j,Dt);return V(zn,["name","referencesGuardOrPublish"],Dt),{name:M(zn,"name",Dt),referencesGuardOrPublish:G(zn,"referencesGuardOrPublish",Dt)}});return{file:U(d,"file",h),className:M(d,"className",h),exported:G(d,"exported",h),hasPublicMutableFields:G(d,"hasPublicMutableFields",h),hasPublicSetters:G(d,"hasPublicSetters",h),hasPublicConstructor:G(d,"hasPublicConstructor",h),hasStaticFactory:G(d,"hasStaticFactory",h),mutatingMethods:P,...d.dataOnly===void 0?{}:{dataOnly:G(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:a,dependencies:o,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:g,safetyUses:y,classShapes:Bn,arkRunKernelCalls:m,arkRunManagedNews:b,arkRunCompositionRootHits:R,arkRunDeclarations:Ze,arkOrderPlaneCalls:Y,arkOrderGenericUpdates:L,arkOrderRootHits:x,arkOrderXiFieldWrites:w,arkOrderIngestWritesXi:ue,arkOrderReleaseKeyCounts:Je}}i(Ks,"parseResolvedFactsInput");function Re(e){let t=$(e,"$"),n=M(t,"factsHash","$"),r=M(t,"candidateTreeHash","$"),s=js(Ks(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 li=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},ne={type:"integer",minimum:1},z={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:_,message:_,file:z}}},resolverIdentity:_,compilerIdentity:_,compilerOptionsHash:_,tsconfigHash:_,candidateTreeHash:_,evidenceRequirementsHash:_,projectPackageName:_,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:z,contentHash:_,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:_},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:z,specifier:_,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ne,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:z,namedBindings:{type:"array",items:_},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:z,line:ne,symbol:_,capability:{enum:li},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:z,line:ne,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:z,line:ne,rawIntentName:_,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:_}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:z,line:ne,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:z,line:ne,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:_},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:z,className:_,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:_,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:z,line:ne,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:_,viaImport:{type:"boolean"},receiver:_,nameLiteral:_}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:z,line:ne,typeName:_,importedFrom:_}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:z,matchedRoot:_,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:z,line:ne,uses:{type:"array",items:_},reactsTo:{type:"array",items:_},raises:{type:"array",items:_},sends:{type:"array",items:_}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:z,line:ne,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:z,line:ne,method:_}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:z,matchedRoot:_,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:z,line:ne,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:z,line:ne}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:z,line:ne,keyCount:{type:"integer",minimum:1}}}},factsHash:_},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 se(e){return`${e.from}->${e.to}`}i(se,"dependencyKey");function dt(e,t,n,r="dependency"){return{id:`${e}:${r}:${se(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${se(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${se(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${se(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${se(t)} from the candidate, then preflight again.`}:{}}}i(dt,"dependencyFinding");function Pe(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),s=new Map(e.changeMap.map.dependencies.map(f=>[se(f),f])),a=new Map(e.baseDependencies.map(f=>[se(f),f])),o=new Map(e.candidateDependencies.map(f=>[se(f),f]));for(let f of[...n.values()].sort((u,m)=>u.path.localeCompare(m.path))){let u=r.get(f.path);u?u.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:u.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${u.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:u.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((u,m)=>u.path.localeCompare(m.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let l=new Set;for(let f of[...s.values()].sort((u,m)=>se(u).localeCompare(se(m)))){if(o.has(se(f))){t.push(dt("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let u={from:f.to,to:f.from};o.has(se(u))?(l.add(se(u)),t.push(dt("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(dt("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,u]of[...o].sort(([m],[A])=>m.localeCompare(A)))a.has(f)||s.has(f)||l.has(f)||!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(f=>f.operation==="delete").map(f=>f.path));for(let[f,u]of[...a].sort(([m],[A])=>m.localeCompare(A)))o.has(f)||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((f,u)=>g[f.classification]-g[u.classification]||(f.subject===u.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(u.id));let y={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}i(Pe,"analyzeArchitectureConvergence");var Bs="1.0",gr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",yr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],ci=["no-anemic-model"],Us={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},en={$schema:"https://json-schema.org/draft/2020-12/schema",$id:gr,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:gr},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:[...yr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Us,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:Us}}}},Le=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 ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ft,"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 ut(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ut,"valueType");function li(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(li,"resolveSchemaRef");function pt(e,t,n,r,s){if(t.$ref){let o=li(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}pt(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(!ft(e)){s.push({path:n,message:`must be an object; received ${ut(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(ft(t.additionalProperties)){let a=t.additionalProperties;for(let l of Object.keys(e))l in o||pt(e[l],a,Qt(n,l),r,s)}for(let[a,l]of Object.entries(o))e[a]!==void 0&&pt(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 ${ut(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)=>pt(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 ${ut(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 ${ut(e)}`})}i(pt,"validateNode");function ci(e){return{...e,$schema:e.$schema===void 0?pr: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 Us(e){return e==="enforced"?"enforced":"advisory"}i(Us,"normalizeMode");function di(e){return ii.includes(e)}i(di,"isTier2Sensor");function ui(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(!ft(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"&&di(o.sensor)&&o.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`sensor ${JSON.stringify(o.sensor)} is Tier-2 advisory-only and cannot be enforced`}),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(!ft(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(ui,"validateSemantics");function mt(e,t="arkrules.json",n){if(!ft(e))throw new we(t,[{path:"$",message:`must be an object; received ${ut(e)}`}]);let r=ci(e),s=[];if(pt(r,en,"$",en,s),ui(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(mt,"loadArkRulesContract");function Gs(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 mt(r,t,n)}i(Gs,"parseArkRulesJson");function tn(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:Us(c.mode),provenance:{sourceFile:o.sourceFile,ruleId:c.id,layer:o.layer}})),l=(o.file.invariants??[]).map(c=>({...c,mode:Us(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(tn,"buildEffectiveArkRules");function Ce(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Ce,"emptyEffectiveArkRules");var gt=class extends Error{static{i(this,"EffectiveContractError")}issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
6
+ `)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(ft,"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 ut(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(ut,"valueType");function di(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(di,"resolveSchemaRef");function pt(e,t,n,r,s){if(t.$ref){let a=di(t.$ref,r);if(!a){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}pt(e,a,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(a=>Object.is(a,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ft(e)){s.push({path:n,message:`must be an object; received ${ut(e)}`});return}let a=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:Qt(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in a||s.push({path:Qt(n,o),message:"unknown field"});else if(ft(t.additionalProperties)){let o=t.additionalProperties;for(let l of Object.keys(e))l in a||pt(e[l],o,Qt(n,l),r,s)}for(let[o,l]of Object.entries(a))e[o]!==void 0&&pt(e[o],l,Qt(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${ut(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 a=e.map(o=>JSON.stringify(o));new Set(a).size!==a.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,o)=>pt(a,t.items,`${n}[${o}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${ut(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 ${ut(e)}`})}i(pt,"validateNode");function ui(e){return{...e,$schema:e.$schema===void 0?gr: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(ui,"defaultedArkRules");function Gs(e){return e==="enforced"?"enforced":"advisory"}i(Gs,"normalizeMode");function pi(e){return ci.includes(e)}i(pi,"isTier2Sensor");function fi(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((a,o)=>{if(!ft(a))return;let l=typeof a.id=="string"?a.id:"";l&&(s.has(l)&&t.push({path:`$.structure[${o}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),typeof a.sensor=="string"&&pi(a.sensor)&&a.mode==="enforced"&&t.push({path:`$.structure[${o}].mode`,message:`sensor ${JSON.stringify(a.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(a.appliesTo)&&a.appliesTo.length===0&&t.push({path:`$.structure[${o}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((a,o)=>{if(!ft(a))return;let l=typeof a.id=="string"?a.id:"";l&&(s.has(l)&&t.push({path:`$.invariants[${o}].id`,message:`duplicate rule id ${JSON.stringify(l)}`}),s.add(l)),Array.isArray(a.appliesTo)&&a.appliesTo.length===0&&t.push({path:`$.invariants[${o}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}i(fi,"validateSemantics");function mt(e,t="arkrules.json",n){if(!ft(e))throw new Le(t,[{path:"$",message:`must be an object; received ${ut(e)}`}]);let r=ui(e),s=[];if(pt(r,en,"$",en,s),fi(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 Le(t,s);return{config:r}}i(mt,"loadArkRulesContract");function zs(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new Le(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return mt(r,t,n)}i(zs,"parseArkRulesJson");function tn(e){let t={},n=[],r=[],s=[...e].sort((a,o)=>a.layer.localeCompare(o.layer));for(let a of s){let o=(a.file.structure??[]).map(c=>({...c,mode:Gs(c.mode),provenance:{sourceFile:a.sourceFile,ruleId:c.id,layer:a.layer}})),l=(a.file.invariants??[]).map(c=>({...c,mode:Gs(c.mode),provenance:{sourceFile:a.sourceFile,ruleId:c.id,layer:a.layer}}));t[a.layer]={sourceFile:a.sourceFile,structure:o,invariants:l},n.push(...o),r.push(...l)}return n.sort((a,o)=>{let l=a.provenance.layer.localeCompare(o.provenance.layer);return l!==0?l:a.id.localeCompare(o.id)}),r.sort((a,o)=>{let l=a.provenance.layer.localeCompare(o.provenance.layer);return l!==0?l:a.id.localeCompare(o.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}i(tn,"buildEffectiveArkRules");function ve(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(ve,"emptyEffectiveArkRules");var gt=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 Bs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Bs,"normalizeRel");function zs(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:Ce(),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],m=`$.arkRules[${JSON.stringify(c)}]`;if(typeof p!="string"||p.length===0){o.push({path:m,message:"must be a non-empty relative path string"});continue}if(p.startsWith("/")||/^[A-Za-z]:[\\/]/.test(p)){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 g=Bs(p);l.add(g);let u=e.fileContents[g]??e.fileContents[p];if(u===void 0){o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(g)} is missing`});continue}try{let d=mt(JSON.parse(u),g,c);a.push({layer:c,sourceFile:g,file:d.config})}catch(d){if(d instanceof we)for(let f of d.issues)o.push({path:`${m}${f.path==="$"?"":f.path.replace(/^\$/,"")}`,message:`${g}: ${f.message}`});else d instanceof SyntaxError?o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(g)} is not valid JSON: ${d.message}`}):o.push({path:m,message:`referenced ArkRules file ${JSON.stringify(g)} failed to load: ${d instanceof Error?d.message:String(d)}`})}}if(e.discoveredArkRulesFiles)for(let c of[...e.discoveredArkRulesFiles].sort()){let p=Bs(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(zs,"resolveEffectiveContract");function nn(e){let{stewards:t,...n}=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 pi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(pi,"titleMatchesInvariant");function fi(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(fi,"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=[],a=[];for(let l of t){let c=[],p=l.coverage?.test!==!1,m=l.coverage?.symbol;if(!r&&p)for(let f of n){let y=e.fileContents[f];if(y&&pi(y,l.id)){c.push("test-title");break}}m&&fi(e.fileContents,m)&&c.push("symbol");let u=(l.coverage?.test===!0||!!m||l.coverage===void 0)&&c.length>0||l.coverage?.test===!1&&!m?!0:c.length>0,d=r&&p&&c.length===0;if(o.push({invariantId:l.id,layer:l.provenance.layer,sourceFile:l.provenance.sourceFile,mode:l.mode,covered:u&&!d,evidence:c,partial:d,description:l.description}),!u||d){let f=l.mode==="enforced"&&!d,y=r||n.length===0?"never-had-tests":"tests-disappeared";a.push({ruleId:"INVARIANT_UNCOVERED",message:d?s?`Invariant ${l.id} coverage cannot be proven (coverage file budget exhausted); reporting partial, not covered.`:`Invariant ${l.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:y==="tests-disappeared"?`Invariant ${l.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${l.id} is not covered by a test title or declared symbol (never-had-tests).`,file:l.provenance.sourceFile,line:1,arkruleId:l.id,arkruleSource:l.provenance.sourceFile,fromLayer:l.provenance.layer,severity:f?"error":"warning",failsStrict:f,kind:y})}}return{coverage:o,violations:a,partial:o.some(l=>l.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?{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 T(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(T,"addFinding");function oe(e){return[...new Set(e??[])].sort()}i(oe,"sortedUnique");function de(e,t,n,r,s){let o=oe(n),a=oe(r),l=new Set(o),c=new Set(a),p=a.filter(g=>!l.has(g)),m=o.filter(g=>!c.has(g));p.length===0&&m.length===0||(p.length>0&&T(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),m.length>0&&T(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(de,"compareStringSets");function yt(e,t,n,r,s,o,a){if(n===r)return;T(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 mi(e,t,n){let r=on(t,o=>o.name),s=on(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&T(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){T(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){T(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;de(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."}),de(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),m=Kt(l);de(e,`${c}.forbiddenGlobals`,p.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."}),de(e,`${c}.capabilities`,p.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)."}),oe(a.intentPrefixes).join("\0")!==oe(l.intentPrefixes).join("\0")&&T(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:oe(a.intentPrefixes),after:oe(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(mi,"compareLayers");function gi(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)&&T(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&&T(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&T(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&&T(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 m=l.peerIsolation===!0,g=c.peerIsolation===!0;if(m!==g){let u=l.from===l.to&&c.from===c.to;T(e,{kind:g?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:u?g?"strengthening":"weakening":"judgment-required",message:u?g?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:m,after:g})}oe(l.sliceFolders).join("\0")!==oe(c.sliceFolders).join("\0")&&T(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:oe(l.sliceFolders),after:oe(c.sliceFolders)})}}i(gi,"compareRules");function yi(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&&T(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(yi,"compareSafety");function mr(e){return e.mode==="enforced"?"enforced":"advisory"}i(mr,"arkRunMode");function gr(e){return e.mode==="enforced"?"enforced":"advisory"}i(gr,"arkOrderMode");function hi(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${gr(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let a=gr(r),l=gr(s);if(a!==l){let c=a==="advisory"&&l==="enforced";T(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})}de(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."}),de(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(hi,"compareArkOrder");function Ai(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${mr(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=mr(r),l=mr(s);if(a!==l){let c=a==="advisory"&&l==="enforced";T(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})}de(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."}),de(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(Ai,"compareArkRun");function Ri(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(Ri,"overallClassification");function qs(e,t){return`${e}::${t}`}i(qs,"ruleKey");function Ys(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(qs(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(qs(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Ys,"indexEffectiveRules");function ki(e,t,n,r,s,o){let a=new Map((o??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of p){let d=l[u],f=c[u],y=`$.arkRules[${u}]`;if(d===void 0&&f!==void 0){T(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:f});continue}if(d!==void 0&&f===void 0){T(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:d});continue}d!==f&&T(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:d,after:f})}let m=Ys(r),g=Ys(s);for(let u of[...new Set([...m.structure.keys(),...g.structure.keys()])].sort()){let d=m.structure.get(u),f=g.structure.get(u),y=`$.arkRules.structure[${u}]`;if(!d&&f){T(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${f.id} was added (${f.mode}).`,after:f});continue}if(d&&!f){T(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${d.id} was removed.`,before:d});continue}if(!(!d||!f)){if(d.mode!==f.mode){let I=d.mode==="advisory"&&f.mode==="enforced";T(e,{kind:I?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:I?"strengthening":"weakening",message:I?`Structure ArkRule ${f.id} was promoted to enforced.`:`Structure ArkRule ${f.id} was demoted to advisory.`,before:d.mode,after:f.mode})}d.sensor!==f.sensor&&T(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${f.id} changed sensor identity.`,before:d.sensor,after:f.sensor})}}for(let u of[...new Set([...m.invariants.keys(),...g.invariants.keys()])].sort()){let d=m.invariants.get(u),f=g.invariants.get(u),y=`$.arkRules.invariants[${u}]`;if(!d&&f){T(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${f.id} was added (${f.mode}).`,after:f});continue}if(d&&!f){T(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${d.id} was removed.`,before:d});continue}if(!(!d||!f)&&d.mode!==f.mode)if(d.mode==="advisory"&&f.mode==="enforced"){let N=a?.get(f.id),E=sn(N);E.ok?T(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${f.id} was promoted to enforced (coverage evidence present).`,before:d.mode,after:f.mode}):T(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${f.id} cannot be promoted to enforced: ${E.reason}`,before:d.mode,after:f.mode})}else T(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${f.id} was demoted to advisory.`,before:d.mode,after:f.mode})}}i(ki,"compareArkRules");function ln(e,t,n){let r=[];de(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),de(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."}),de(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";T(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)&&T(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}),mi(r,e.layers,t.layers),gi(r,e.rules,t.rules),yi(r,e,t),ki(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Ai(r,e,t),hi(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:an,classification:Ri(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=oe(e.findingIds),r=oe(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}i(cn,"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 Ws(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Ws,"isIdentifierStart");function dn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(dn,"isIdentifierCharacter");function se(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(se,"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 ae(e,t,n){return e.startsWith(t,n)&&!dn(e[n-1])&&!dn(e[n+t.length])}i(ae,"isWordAt");function Js(e,t){let n=se(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=se(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ae(e,"type",n))return!1;let s=se(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ae(e,"as",s)||!Ws(e[s]))return!1;for(n=s;n<e.length&&dn(e[n]);)n+=1;if(n=se(e,n),ae(e,"as",n)){if(n=se(e,n+2),!Ws(e[n]))return!1;for(;n<e.length&&dn(e[n]);)n+=1}r=!0}return!1}i(Js,"bracedNamedBindingsAreTypeOnly");function Ei(e,t){if(t=se(e,t+6),e[t]==="(")return ht(e,se(e,t+1));let n=!1;if(ae(e,"type",t)){let s=se(e,t+4);e[s]!==","&&!ae(e,"from",s)&&(n=!0)}else Js(e,t)&&(n=!0);let r=Zs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Ei,"specifierAfterImport");function Si(e,t){t=t+6;let n=se(e,t),r=!1;if(ae(e,"type",n)){let o=se(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else Js(e,n)&&(r=!0);let s=Zs(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(Si,"specifierAfterExport");function Zs(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ae(e,"from",t))return ht(e,se(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ht(e,t);if(t>0&&(ae(e,"import",t)||ae(e,"export",t)))return}}i(Zs,"specifierInStaticStatement");function Ii(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(Ii,"skipTemplateLiteral");function vi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=se(e,t+7);if(e[r]!=="(")return;r=se(e,r+1);let s=ht(e,r);return s?{...s,requireCall:!0}:void 0}i(vi,"specifierAfterRequire");function bi(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=Ii(e,n);continue}if(r==="'"||r==='"'){let o=ht(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&ae(e,"import",n)?Ei(e,n):r==="e"&&ae(e,"export",n)?Si(e,n):r==="r"&&ae(e,"require",n)?vi(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(bi,"moduleSpecifiers");function Xs(e,t){let n=[],r=[];for(let s of bi(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let p=Xe(o);if(!p)continue;let m=e.content.slice(0,s.offset).split(`
10
- `).length;r.push({file:e.path,symbol:o,capability:p,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=Ci(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(Xs,"moduleFactsFor");function Ci(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(Ci,"resolveSpecifier");function Qs(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=ge(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(Qs,"violationsFor");var _i={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 Oi(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Oi,"hasActiveArkRules");function xi(e,t){return Oi(e,t)?K(F(nn({config:e,arkRules:t,warnings:[]}))):K(F(e))}i(xi,"policyHashFor");function At(e,t,n){let r=typeof e=="string"?Wt(e,t):it(e,t),s=n?.arkRules??Ce();return{...r,arkRules:s,policyHash:xi(r.config,s)}}i(At,"loadContract");function yr(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(yr,"analyzePolicyDelta");function Ke(e){let t=e.files.map(g=>{let u=De(g.path);return{path:u,content:g.content,contentHash:K(g.content),layer:ie(u,e.contract.config.layers)??null}}).sort((g,u)=>g.path.localeCompare(u.path)),n=new Map(t.map(g=>[g.path,g])),r=[],s=[];for(let g of t){let u=Xs(g,n);r.push(...u.edges),s.push(...u.capabilityUses)}let o=Qs(r,e.contract.config),a=new Map(e.contract.config.layers.map(g=>[g.name,g])),l=new Map(e.contract.config.layers.map(g=>[g.name,new Set(Fe(g))]));for(let g of s){let u=n.get(g.file)?.layer;if(!u)continue;let d=a.get(u),f=ve(g.symbol,d?.forbiddenGlobals??[]);if(f){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${g.symbol}" because it is the import form of forbidden global "${f}".`,symbol:g.symbol,evidence:g.evidence});continue}l.get(u)?.has(g.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${g.capability} capability; found import of "${g.symbol}".`,capability:g.capability,symbol:g.symbol,evidence:g.evidence})}let c=t.length===0?"complete":"partial",p=c==="complete"?[]:[{..._i}],m={schemaVersion:Xt,policyHash:e.contract.policyHash,compilerOptionsHash:K(F(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(g=>g.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:p,valid:c==="complete"&&o.length===0,ir:m}}i(Ke,"analyzeProject");function Rt(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 Ke({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Rt,"analyzeChange");function hr(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(hr,"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 g of[...e.get(c)??[]].sort())e.has(g)&&(n.has(g)?s.has(g)&&r.set(c,Math.min(r.get(c)??0,n.get(g)??0)):(l(g),r.set(c,Math.min(r.get(c)??0,r.get(g)??0))));if(r.get(c)!==n.get(c))return;let p=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),p.push(m)}while(m!==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 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=ge(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a)continue;let l=!!a.peerIsolation,c=!l&&!!(o.typeOnly||o.namedBindingsTypeOnly),p=a.message??(l?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}). Extract shared code or use events/ports across slices.`:`${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}:{},...!l&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...l?{peerIsolation:!0}:{},message:c?`${p} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:p,...c?{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(Me,"evaluateArchitectureGraph");var Ti=["no-anemic-model"];function eo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(eo,"escapeGlobLiteral");function Ni(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+=eo(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=eo(s)}return new RegExp(`^${n}$`)}i(Ni,"globToRegExp");function kt(e,t){return!t||t.length===0?!0:t.some(n=>Ni(n).test(e))}i(kt,"matchesAppliesTo");function Pi(e){return Ti.includes(e)}i(Pi,"isTier2");function to(e){return e.mode==="enforced"&&!Pi(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(to,"severityFor");function Ge(e,t,n,r=1){let{severity:s,failsStrict:o}=to(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(Ge,"baseViolation");function Ar(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Ar,"isInRuleLayer");function pn(e,t,n){return t.filter(r=>!(!r.exported||!kt(r.file,e.appliesTo)||!Ar(r.file,e,n)))}i(pn,"shapesForRule");function Li(e,t,n){let r=[];for(let s of pn(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Ge(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Li,"evaluateAggregatePrivateState");function wi(e,t,n){let r=[];for(let s of pn(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Ge(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(wi,"evaluateAlwaysValidFactory");function Di(e,t,n){let r=[];for(let s of pn(e,t,n))for(let o of s.mutatingMethods)o.referencesGuardOrPublish||r.push(Ge(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(Di,"evaluateDomainEventOnMutation");function Mi(e,t){let n=[];for(let r of t.files)kt(r,e.appliesTo)&&Ar(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ge(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Mi,"evaluateOrchestrationOnly");function Fi(e,t){let n=[];for(let r of t.files)kt(r,e.appliesTo)&&Ar(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ge(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Fi,"evaluateThinAdapter");function $i(e,t,n){let r=[];for(let s of pn(e,t,n))if(s.dataOnly===!0){let o=Ge(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($i,"evaluateNoAnemicModel");function fn(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Li(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...wi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Di(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Mi(n,e));break;case"thin-adapter":t.push(...Fi(n,e));break;case"no-anemic-model":t.push(...$i(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(fn,"evaluateArkRuleSensors");function mn(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=>kt(c,s.appliesTo)))continue;let{severity:a,failsStrict:l}=to(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=>kt(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(mn,"collectEmptyAppliesToFindings");var Hi=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,ji=/\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*=)/,Vi=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Ui=/\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*=/,Ki=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Rr(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(Ui.source,"g"))??[],r=t.match(new RegExp(Ki.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=Hi.test(t),c=ji.test(t)||Vi.test(t),p=n.length>=1||r.length>=2,m=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),g=l&&p||c&&p||l&&m&&(s>=4||n.length>=1)||c&&l;return!a&&!g?null:{...a?{orchestrationHeavy:!0}:{},...g?{adapterThick:!0}:{}}}i(Rr,"deriveArkRuleFileHints");function gn(e){let t={};for(let[n,r]of Object.entries(e)){let s=Rr(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}i(gn,"buildArkRuleFileHints");function no(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),m=p.split(`
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
- `),g=/(?:^|\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),u=/(?:^|\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
- `).filter(w=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(w)).join(`
15
- `)),d=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(p),f=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(p),y=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(p)&&!f,I=/(?:^|[\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),N=[],E=new Set(["if","match","when"]),k=/(?:^|\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=k.exec(p))!==null;){let w=b[1];if(E.has(w))continue;let O=b.index+b[0].length,D=1,P=O;for(;P<p.length&&D>0;)p[P]==="{"?D+=1:p[P]==="}"&&(D-=1),P+=1;let ee=p.slice(O,P-1);if(!/this\.\w+\s*=/.test(ee))continue;let v=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(ee);N.push({name:w,referencesGuardOrPublish:v})}let J=(p.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,H=(m.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,B=J<=1&&H>=2&&(u||g);n.push({file:e,className:o,exported:!0,hasPublicMutableFields:u||g,hasPublicSetters:d,hasPublicConstructor:y,hasStaticFactory:I,mutatingMethods:[...N],dataOnly:B})}return n}i(no,"extractClassShapesFromSource");var ro=50;function yn(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(yn,"normalizeExtraMergeTeethClassification");function fe(e){let t=yn(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(fe,"extraMergeTeethAllowed");function hn(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(hn,"classifyResolvedLayerCoverage");function An(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}i(An,"isArkRunRuleId");function so(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(so,"isArkOrderRuleId");function kr(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")||t.startsWith("ARKORDER_")}i(kr,"isExtraPlaneFinding");function oo(e,t={}){if(!Array.isArray(e)||fe(t))return e;for(let n of e)kr(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(oo,"demoteExtraPlaneTeethUnderClassificationFloor");var Er="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 Ee(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}i(Ee,"countOrZero");function Rn(e={}){let t=yn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=fe(t),a=e.arkRules,l=Ee(a?.structureEnforced),c=Ee(a?.structureTotal),p=typeof a?.structureAdvisory=="number"?Ee(a.structureAdvisory):Math.max(0,c-l),m=Ee(a?.invariantEnforced),g=Ee(a?.invariantTotal),u=typeof a?.invariantAdvisory=="number"?Ee(a.invariantAdvisory):Math.max(0,g-m),d=l>0||m>0,f=e.arkRun?.present===!0,y=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,I=Ee(e.arkRun?.residualCount),N=f&&y==="enforced",E=N&&o,k=d||N,b=k&&o,J=k&&s&&!o,H;if(b){let w=[];d&&w.push("enforced structure/invariant findings"),N&&w.push("enforced ArkRun skip findings"),H=`Layer graph failures plus ${w.join(" and ")} (advisory extras never fail merge alone).`}else J?H=`Layer graph only \u2014 enforced ${[d?"ArkRules structure/invariant":null,N?"ArkRun":null].filter(O=>!!O).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.`:H="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+(f?y==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let B={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:g,enforced:m,advisory:u,covered:Ee(a?.covered),uncovered:Ee(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:y,residualCount:I,extraMergeTeeth:E,note:f?y==="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:Er,failMergeWhen:H};return s&&(B.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),B}i(Rn,"composeMergePlanesHonesty");var Ir=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],io=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Gi=new Set(Ir),Bi=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"]),zi=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function Be(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Be,"isArkRunKernelModuleSpecifier");var vr=["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"],Sr=new Set(vr);function En(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Sr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Sr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Sr.has(e.slice(0,r))}i(En,"isArkRunTransportBypassSpecifier");function kn(e){if(Gi.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(kn,"arkRunKernelCallKind");function St(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}i(St,"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 qi(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(qi,"firstStringLiteralArg");function ao(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(ao,"keywordBefore");function Sn(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(Sn,"parseValueImportClause");function Yi(e,t){Sn(It(e),t)}i(Yi,"forEachArkRunValueImportClause");function In(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:St(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:St(t,o.index),resolution:"resolved-external"})}return r}i(In,"extractArkRunValueImportDependenciesFromSource");function vn(e){let t=[];return Yi(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(vn,"extractArkRunImportedConstructorNamesFromSource");function Wi(e){let t=new Map,n=new Set;return Sn(e,(r,s)=>{if(!Be(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 m=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);if(m){t.set(m[2],m[1]);continue}let g=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(p);g?.[1]&&t.set(g[1],g[1])}}),{named:t,namespaces:n}}i(Wi,"collectKernelImportBindings");function Ji(e,t){let n=new Set(t);return Sn(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],m=c?.[1]??p;!p||!m||!/^[A-Z]/.test(m)||(Be(s)||t.has(m)||t.has(p))&&(n.add(p),n.add(m))}}),n}i(Ji,"collectImportedConstructors");function Zi(e,t){let n;return Sn(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(Zi,"importedFromForName");function bn(e,t){let n=It(t),r=Wi(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(ao(n,c,"function")||ao(n,c,"class"))continue;let m=n.slice(0,c).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],g=r.named.get(l)??l,u=kn(g)??kn(l);if(!u)continue;let d=r.named.has(l)||m!==void 0&&r.namespaces.has(m);if(u!=="factory"&&(!d&&m===void 0||m&&zi.has(m)&&!d))continue;let f=qi(n,c+a[0].length);s.push({file:e,line:St(t,c),kind:u,callee:l,viaImport:d,...m?{receiver:m}:{},...f?{nameLiteral:f}:{}})}return s}i(bn,"extractArkRunKernelCallsFromSource");function Cn(e,t,n){let r=It(t),s=Ji(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(Bi.has(c)||!s.has(c))continue;let p=Zi(r,c);o.push({file:e,line:St(t,l.index),typeName:c,...p?{importedFrom:p}:{}})}return o}i(Cn,"extractArkRunManagedNewsFromSource");function Xi(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(Xi,"matchingBracketEnd");function Qi(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(Qi,"stringLiteralsInList");function Et(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Et,"uniqueSorted");function lo(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 m=n.slice(p.index+p[0].length),g=/^\s*\[/.exec(m);if(!g)continue;let u=p.index+p[0].length+(g[0].length-1),d=Xi(n,u);if(d<0)continue;let f=Qi(n,u,d);if(f.length===0)continue;c===void 0&&(c=p.index);let y=p[1];y==="uses"?s.push(...f):y==="reactsTo"?o.push(...f):y==="raises"?a.push(...f):l.push(...f)}return c===void 0?[]:[{file:e,line:St(t,c),uses:Et(s),reactsTo:Et(o),raises:Et(a),sends:Et(l)}]}i(lo,"extractArkRunDeclarationsFromSource");var po=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],el=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],tl=new Set(el);function nl(e){return tl.has(e)}i(nl,"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"},br="ARKRUN_INTERACTION_NAME_INCOMPLETE";function fo(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(fo,"isDomainRoleLayer");function rl(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(rl,"compareFindings");function Se(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:pe({ruleId:_n[t],fromLayer:o?.fromLayer,target:o?.target})}}i(Se,"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 co(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(co,"emitKinds");function uo(e){return e==="subscribe"||e==="register-handler"}i(uo,"handleKinds");function ol(e){return e==="resolve"||e==="resolve-singleton"}i(ol,"dependKinds");function al(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(Se(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,m)=>p.file.localeCompare(m.file));if(l.length===0){r.push(Se(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(Se(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(al,"evaluateMissingRoot");function il(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||!Be(c))continue;let p=r(l.from);p&&fo(p,o.get(p)??[])&&a.push(Se(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(il,"evaluateKernelInDomain");function ll(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)),p=[];for(let m of n){if(c.has(m.file))continue;let g=m.typeName;if(e.ignoreDirectNewForErrors!==!1&&(g.endsWith("Error")||g==="Error")||g.endsWith("DTO")||g.endsWith("VO"))continue;let u=s(m.file);!u||!a.has(u)||fo(u,l.get(u)??[])||p.push(Se(e,"arkrun-direct-new",m.file,m.line,`${u} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:m.typeName},o))}return p}i(ll,"evaluateDirectNew");function cl(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(!co(c.kind)&&!uo(c.kind)&&!ol(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:br,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(co(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;o.push(Se(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(uo(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;o.push(Se(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}m.uses.has(c.nameLiteral)||o.push(Se(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(cl,"evaluateUndeclared");function dl(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||!En(l))continue;let c=n(a.from);!c||!s.has(c)||o.push(Se(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(dl,"evaluateTransportBypass");function vt(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=fe(e.classification),r=cl(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...al(t,e.compositionRootHits,n),...il(t,e.layers,e.dependencies,e.layerForFile,n),...ll(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...dl(t,e.dependencies,e.layerForFile,n)].sort(rl),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 Cr(e){return{findings:vt(e).findings.filter(n=>nl(n.sensor)),completenessReasons:[]}}i(Cr,"evaluateArkRunEditorSensors");function ul(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(ul,"fileMatchesCompositionRoot");function pl(e,t,n){let r=bn(t,n).some(a=>a.kind==="factory"),s=[],o=e.kernelRoots??e.compositionRoots;for(let a of o)ul(a,t)&&s.push({file:t,matchedRoot:a,hasKernelFactory:r});return s}i(pl,"compositionRootHitsForSource");function mo(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(vn(e.source));return Cr({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:Cn(e.file,e.source,n),compositionRootHits:pl(t,e.file,e.source),declarations:[],dependencies:In(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(mo,"evaluateArkRunEditorSensorsFromSource");function go(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(go,"isArkOrderModuleSpecifier");var yo=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi"],On={"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"};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 bt(e,t,n,r,s,o,a){let l=e.mode==="enforced"&&a;return{ruleId:On[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:On[t],fromLayer:o?.fromLayer,target:o?.target})}}i(bt,"finding");function xn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=fe(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(bt(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let a=new Map;for(let l of e.planeRootHits){let c=a.get(l.matchedRoot)??[];c.push(l),a.set(l.matchedRoot,c)}for(let l of s){let c=a.get(l)??[];if(c.length===0){r.push(bt(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(l)} matched no governed files and has no createOrderPlane factory.`,{target:l},n));continue}c.some(p=>p.hasPlaneFactory)||r.push(bt(t,"arkorder-missing-plane",c[0].file,1,`ArkOrder plane root ${JSON.stringify(l)} has no createOrderPlane factory.`,{target:l},n))}}let o=new Map(e.layers.map(a=>[a.name,a.intentPrefixes??[]]));for(let a of e.dependencies){let l=a.specifier;if(!l||!go(l))continue;let c=e.layerForFile(a.from);c&&fl(c,o.get(c)??[])&&r.push(bt(t,"arkorder-kernel-in-domain",a.from,a.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:c,target:l},n))}for(let a of e.genericUpdates)r.push(bt(t,"arkorder-generic-update",a.file,a.line,`Generic ${a.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:a.method},n));return r.sort((a,l)=>a.file.localeCompare(l.file)||a.ruleId.localeCompare(l.ruleId)||a.line-l.line),{findings:r,completenessReasons:[]}}i(xn,"evaluateArkOrderSensors");function ne(e,t,n={}){return{ruleId:e,message:t,...n}}i(ne,"configWarning");function Ct(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&o.push(ne("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))o.push(ne("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[d];f!==void 0&&(!Number.isInteger(f)||f<0)&&o.push(ne("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} 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(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);a.length===0&&o.push(ne("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,m=new Set;for(let d of a){if(!d.name){o.push(ne("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(d.name)&&m.add(d.name),p.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(y=>typeof y!="string"))&&o.push(ne("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let f=Array.isArray(d.patterns)?d.patterns:[];if(f.length===0){o.push(ne("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let y of f){let I;try{I=xe(y)}catch(E){o.push(ne("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${y}": ${E instanceof Error?E.message:String(E)}`,{layer:d.name,pattern:y}));continue}let N=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(E=>I.test(E))&&!N&&o.push(ne("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let d of m)o.push(ne("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&o.push(ne("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&o.push(ne("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let g=new Set;if(a.length>1)for(let d of r){let f=-1,y=[];for(let I of a)for(let N of I.patterns??[]){if(!xe(N).test(d))continue;let E=tr(N,d);E>f?(f=E,y=[I.name]):E===f&&!y.includes(I.name)&&y.push(I.name)}y.length>1&&g.add([...y].sort().join(" + "))}g.size>0&&o.push(ne("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...g].join(", ")}.`,{pairs:[...g]}));let u=r.filter(d=>!ie(d,a));return u.length>0&&o.push(ne("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)})),o}i(Ct,"collectAnalysisConfigWarnings");function ml(e,t){return t.some(n=>{try{return xe(n).test(e)}catch{return!1}})}i(ml,"matchesAny");function gl(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(y=>y.kind==="ts-suppression").map(({file:y,line:I})=>({file:y,line:I})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:I})=>({file:y,line:I})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!ml(y.file,o)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),p=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),m=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),g={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:p,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},u=[],d=c.filter(y=>y.kind==="import");if(d.length>0){let y=d[0];u.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${d.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let f=c.filter(y=>y.kind==="require");if(f.length>0){let y=f[0];u.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${f.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];u.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>s){let y=l[0];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(p.length>0){let y=p[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.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 m.length>0&&u.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:g,warnings:u}}i(gl,"evaluateSafety");function yl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(yl,"ambientForbiddenGlobal");function ho(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return ir(e,n.length>0?n:ar.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(ho,"intentLayer");function hl(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||!yl(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(m=>m.from===o.file&&m.line===o.line&&m.specifier===o.symbol&&!m.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&Qe(o.symbol,c))){if(o.source==="import-based"){let m=ve(o.symbol,c);if(m){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 "${m}".`});continue}}Fe(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 et({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=ho(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=ho(o.intent,e.contract);if(!l)continue;let c=ge(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(hl,"contentViolations");function Al(e){let{facts:t}=e,n=Ue(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((h,ue)=>{let Je=`${h.code}\0${h.file??""}\0${h.message}`,Ze=`${ue.code}\0${ue.file??""}\0${ue.message}`;return Je<Ze?-1:Je>Ze?1:0}),a=t.files.map(h=>({...h,layer:ie(h.path,e.contract.config.layers)??null})),l=new Map(a.map(h=>[h.path,h.layer])),c=t.dependencies.map(h=>{let ue=h.target?l.get(h.target)??ie(h.target,e.contract.config.layers):void 0;return{from:h.from,fromLayer:l.get(h.from)??null,...h.resolution==="resolved-project"&&h.target?{to:h.target,...ue?{toLayer:ue}:{}}:{},line:h.line,kind:h.kind,typeOnly:h.typeOnly,...h.targetTypeOnlyExports?{targetTypeOnlyExports:h.targetTypeOnlyExports}:{},...h.sourcePureTypeModule?{sourcePureTypeModule:h.sourcePureTypeModule}:{},...h.namedBindingsTypeOnly?{namedBindingsTypeOnly:h.namedBindingsTypeOnly}:{},...h.portProofEligible?{portProofEligible:h.portProofEligible}:{}}}),p=Ct({config:e.contract.config,rules:e.contract.config.rules,files:a.map(h=>h.path)}),m=gl(e,t),g=e.contract.arkRules??Ce(),u=a.map(h=>h.path),f={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?gn(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...fn({arkRules:g,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:i(h=>l.get(h)??ie(h,e.contract.config.layers),"layerForFile"),fileHints:f}),...mn(g,u)],I=y.filter(h=>h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,nextAction:h.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${h.arkruleId} in ${h.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${h.arkruleId} (declared in ${h.arkruleSource}), then preflight again.`})),N=y.filter(h=>!h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,failsStrict:!1,nextAction:h.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${h.arkruleId} in ${h.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${h.arkruleId} in ${h.arkruleSource} (advisory).`})),k=(g.invariants?.length??0)>0?rn({arkRules:g,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0}):{coverage:[],violations:[],partial:!1},b=k.violations.filter(h=>h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,nextAction:`Add a test title or declared symbol covering ${h.arkruleId} (declared in ${h.arkruleSource}), then preflight again.`})),J=k.violations.filter(h=>!h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${h.arkruleId} in ${h.arkruleSource} (advisory / partial).`})),H=hn(a),B=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(h=>l.get(h)??ie(h,e.contract.config.layers),"layerForFile"),classification:H}),w=e.contract.config.arkRun?.mode,O=B.findings.filter(()=>w==="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:h.failsStrict,...h.severity?{severity:h.severity}:{}})),D=B.findings.filter(()=>w!=="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:!1})),P=xn({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,dependencies:t.dependencies,layerForFile:i(h=>l.get(h)??ie(h,e.contract.config.layers),"layerForFile"),classification:H}),ee=e.contract.config.arkOrder?.mode,me=P.findings.filter(()=>ee==="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:h.failsStrict,...h.severity?{severity:h.severity}:{}})),v=P.findings.filter(()=>ee!=="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:!1})),A=[...k.partial&&k.coverage.some(h=>h.mode==="enforced"&&h.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...B.completenessReasons,...P.completenessReasons],R=Me({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(h=>h.layer).map(h=>h.path),contentViolations:[...hl(e,t,l),...I,...b,...O,...me],edges:c,warnings:[...p,...m.warnings,...N,...J,...D,...v],safety:m.report}),L=s==="complete"&&A.length>0?"partial":s,z=L==="complete"?o:[...o,...A].sort((h,ue)=>{let Je=`${h.code}\0${h.file??""}\0${h.message}`,Ze=`${ue.code}\0${ue.file??""}\0${ue.message}`;return Je<Ze?-1:Je>Ze?1:0}),Ie=R.violations.filter(h=>h.failsStrict!==!1),Oe=L==="complete"&&Ie.length===0,We=Oe&&R.warnings.every(h=>h.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:L,completenessReasons:z,valid:Oe,strictValid:We,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(h=>h.name),edges:c,capabilityUses:t.capabilityUses,violations:R.violations,warnings:R.warnings}}}i(Al,"analyzeCanonicalResolvedProject");function ze(e){return Al({contract:e.contract,facts:ke(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(ze,"analyzeResolvedProject");function Ao(e){return K(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Ao,"analysisTreeHash");function _r(e){let t=Ke(e),n=new Map(t.ir.files.map(f=>[f.path,f])),r=[],s=new Set,o=[];for(let f of e.changes){let y=f.path.replace(/\\/g,"/"),I=De(f.path);if(!I||I===".."||I.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(I)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:I,line:1,message:`The atomic change set contains more than one operation for ${I}.`});continue}s.add(I),"delete"in f&&f.delete&&!n.has(I)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:I,line:1,message:`Cannot delete ${I} because it is not present in the supplied base tree.`}),r.push("delete"in f&&f.delete?{path:I,delete:!0}:{path:I,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 y=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}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:f.message}}),p=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 y=De(f.path),I=n.get(y),N=l.get(y);return{path:y,operation:"delete"in f&&f.delete?"delete":I?"update":"create",...I?{beforeContentHash:I.contentHash}:{},...N?{candidateContentHash:N.contentHash}:{}}}).sort((f,y)=>f.path.localeCompare(y.path)),g=[...o,...p.violations].map(f=>({...f,nextAction:pe(f)})),u=g.filter(f=>f.failsStrict!==!1),d=e.changeMap?Le({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&&u.length===0&&(d?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Ao(t.ir.files),candidateTreeHash:Ao(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...d?{convergence:d}:{},changes:m,violations:g,warnings:p.warnings}}i(_r,"preflightChange");function Rl(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(Rl,"canonicalChangePath");function kl(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(kl,"identityViolations");function El(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(El,"preparedChange");function Or(e){let t=ke(e.baseFacts),n=ke(e.candidateFacts),r=ze({contract:e.contract,facts:t}),s=ze({contract:e.contract,facts:n}),o=new Map(t.files.map(d=>[d.path,d])),a=new Map(n.files.map(d=>[d.path,d])),l=kl(t,n),c=new Map,p=[];for(let d of e.changes){let f=Rl(d.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,d);let y=o.get(f),I=a.get(f);if("delete"in d&&d.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base facts.`}),I&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:f,line:1,message:`Candidate facts still contain deleted file ${f}.`});else{let N="content"in d?d.content:"",E=K(N);I?I.contentHash!==E&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:f,line:1,expectedContentHash:E,candidateContentHash:I.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(El(d,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 d of new Set([...o.keys(),...a.keys()])){if(c.has(d))continue;let f=o.get(d),y=a.get(d);f&&y&&F(f)===F(y)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:d,line:1,message:`Candidate facts change ${d}, but the atomic change set does not declare it.`})}let m=e.changeMap?Le({changeMap:e.changeMap,changes:p,baseDependencies:r.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:s.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0,g=[...l,...s.ir.violations].map(d=>({...d,nextAction:pe(d)})),u=g.filter(d=>d.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&u.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:p.sort((d,f)=>d.path<f.path?-1:d.path>f.path?1:0),violations:g,warnings:s.ir.warnings}}i(Or,"preflightResolvedChange");var xr="1.0",Sl=12;function Ro(e){return e==="enforced"||e==="advisory"?e:null}i(Ro,"closedMode");function Il(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!An(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}i(Il,"uniqueArkRunRuleIds");function vl(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:Ro(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(vl,"extraFromConfig");function ko(e={}){let t=vl(e.arkRun),n=t.present?Il(e.findings):[],r=n.slice(0,Sl),s=n.length,o=Rn({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),a=t.present&&t.mode==="enforced"&&fe(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?l="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":l="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":l="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:xr,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(ko,"summarizeArkRunSection");function Tn(e={}){let t=e.present===!0,n=Ro(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(Tn,"projectStatusArkRun");function Eo(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(Eo,"formatArkRunDoctorLines");function Nn(e,t){return e.slice(0,t).split(`
16
- `).length}i(Nn,"lineOf");function So(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(So,"normalizeInventoryPath");function vo(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(vo,"ownsIntent");function Io(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||vo(t,["Domain"])}i(Io,"isDomainLayer");function bl(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||vo(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(bl,"isControllerEligibleLayer");function Cl(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(Cl,"isNonPilotSurface");function bo(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,p])=>[So(c),p])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),o=(e.layerContexts??[]).find(c=>Io(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,p]of Object.entries(e.fileContents).sort(([m],[g])=>m.localeCompare(g))){let m=So(c);if(Cl(m)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(p.slice(0,320)))continue;let g=r.has(m),u=r.get(m),d=u?s.get(u)??[]:[],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),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(m),I=/(?:^|\/)actions?(?:\/|\.|$)/i.test(m)||/['"]use server['"]/.test(p),N=/controller|handler|resolver/i.test(c)||y||I||/route\.(?:ts|js|tsx|jsx)$/i.test(m)&&!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),E=g?!!(u&&bl(u,d)&&N):N,k=g?!!(u&&Io(u,d)):/domain|entity|aggregate|model/i.test(c),b=!g||k||E;if(E&&!f){let O=/\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,D;for(;(D=O.exec(p))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:Nn(p,D.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:u,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let J=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,H,B=i(O=>/^(?: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(O)||/^(?: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(O)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(O)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(O)||/^(?: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(O)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(O)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(O)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(O)||/_(?:OID|OIDS)$/i.test(O)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(O)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(O),"isInfraMagicName"),w=i((O,D)=>{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(O)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(O))return!0;let P=D.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(D)&&(/\s/.test(P)||/[.!?…]$/.test(P))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(O))},"isUxMessageConstant");for(;(H=J.exec(p))!==null;){let O=H[2],D=H[3]??"";!b||B(O)||w(O,D)||f&&!k||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(m)&&!k||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:c,line:Nn(p,H.index),message:`Magic business constant ${O} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:u,suggestedArkRule:{layer:o,invariantId:`INV-${O}`},neverMechanicalSafe:!0}))}if(k){let O=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,D;for(;(D=O.exec(p))!==null;){let P=D[2]??"",ee=(P.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(P.match(/:\s*[A-Za-z]/g)??[]).length>=2&&ee<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:Nn(p,D.index),message:`Class ${D[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:u,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(k&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(m)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(m)||/(?:^|\/)errors?(?:\/|$)/i.test(m))){let D=/this\.\w+\s*=/g,P;for(;(P=D.exec(p))!==null;){let ee=p.lastIndexOf("class ",P.index),me=ee>=0?p.indexOf("{",ee):-1,v=ee>=0&&me>=ee&&me<P.index?p.slice(ee,me):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(v))continue;let _=p.slice(Math.max(0,P.index-200),P.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(_)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:c,line:Nn(p,P.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:u,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(bo,"buildRulesInventory");function Co(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(Co,"inventoryToExtractionCard");var _o="1.1";var Oo="1.0";var Pn="docs/diagnostics.md",xo="1.0";function S(e,t,n,r,s,o){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...o?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(S,"entry");var _t=Object.freeze([S("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."),S("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),S("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),S("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),S("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),S("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),S("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),S("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),S("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),S("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),S("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),S("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),S("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),S("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),S("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),S("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),S("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),S("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),S("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),S("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."),S("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),S("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),S("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),S("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),S("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),S("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),S("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),S("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),S("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),S("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. Never mechanical-safe."),S("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),S("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. Never mechanical-safe."),S("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),S("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),S("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),S("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),S("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),S("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),S("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),S("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),S("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),S("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),S("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),S("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),S("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","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."),S("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),S("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),S("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),S("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),S("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),S("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),S("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),S("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),S("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),S("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),S("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),S("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),S("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),S("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),S("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),S("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),S("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),S("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),S("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),S("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),S("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),S("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),S("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.")]),Tr=new Map(_t.map(e=>[e.ruleId,e])),To=Object.freeze(_t.map(e=>e.ruleId));function No(e){return typeof e=="string"&&e.length>0&&Tr.has(e)}i(No,"isKnownDiagnosticCode");function Po(e){return typeof e!="string"||e.length===0?!1:Tr.has(e)?!0:e.startsWith("ARKRULE_")}i(Po,"isCataloguedOrArkRuleFamily");function Ot(e){if(!(typeof e!="string"||e.length===0))return Tr.get(e)}i(Ot,"getDiagnosticCatalogEntry");function Nr(e){return`#${Ot(e)?.docsAnchor??e}`}i(Nr,"diagnosticDocsFragment");function Lo(e){return`${Pn}${Nr(e)}`}i(Lo,"diagnosticDocsPath");function wo(){return{schemaVersion:"1.0",docsPath:Pn,codes:_t}}i(wo,"serializeDiagnosticCatalog");function Do(e){return Ot(e)?.fix}i(Do,"catalogFixForRuleId");function Mo(e){return Ot(e)?.why}i(Mo,"catalogWhyForRuleId");var Ln="1.0",Pr="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Lr=["full","subset","unavailable"],wr=["doctor-facts","report-snapshot","none"],Tt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Fo=/^sha256:[a-f0-9]{64}$/;function Dr(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"||!Fo.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(Dr,"evaluateStatusBinding");function Mr(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(Mr,"classifyStatusWritePath");function Fr(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(Fr,"defaultHonestLabel");function $r(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($r,"resolveStatusNextAction");function $o(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Fo.test(e.projectId)?e.projectId:null,r=Dr({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=Mr({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Fr(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:xt(e.activeViolations),frozenResidual:xt(e.frozenResidual)},p={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:xt(e.rulesInventoried),underContract:xt(e.rulesUnderContract),frozenResidual:xt(e.rulesFrozenResidual)},m={writePath:a,host:o,honestLabel:l},g={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},u={schemaVersion:Ln,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:g,activation:m,lastCheck:c,rules:p,nextAction:$r(e,r,m,c,p)},d=Hr(e.improvementCompass);return d&&(u.improvementCompass=d),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(u.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(u.arkRun=Tn(e.arkRun)),u}i($o,"buildStatusManifest");var Ho=new Set(Lr),_l=new Set(wr);function wn(e){let t=Ho.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&_l.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:Tt.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:Tt.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(wn,"projectStatusImprovementCompass");function jo(e={}){return wn({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??Tt.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(jo,"unavailableStatusImprovementCompass");function Hr(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"&&Ho.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",wn({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(Hr,"normalizeStatusImprovementCompass");function Vo(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(Vo,"statusCompassResidualIsSubsetOfDoctor");function xt(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}i(xt,"numberOrNull");var Uo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Pr,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:Ln},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 Nt="1.0",Pt=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],Lt=5,_e=["scalability","resilience","security"],qe=new Set(_e),jr={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},Vr={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"},Ur={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 Kr(e){return Vr[e]??e}i(Kr,"improvementCompassHumanLabel");function Gr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(Gr,"smellIdOf");function Br(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(Br,"violationRuleId");function $(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($,"pushEvidence");function Q(e,t,n){qe.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(Q,"markResidual");function Ko(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`${Vr[e]} \u2014 no residual from current sensors.`}}i(Ko,"defaultOkSummary");function Go(){return Pt.map(e=>qe.has(e)?{id:e,status:"out-of-scope",summary:Ur[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:Ko(e),evidence:[]}:{id:e,status:"ok",summary:Ko(e),evidence:[]})}i(Go,"createInitialImprovementCompassLenses");function Ol(e,t){for(let n of t){let r=Gr(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((m,g,u)=>{let d=e.get(m);!d||qe.has(m)||($(d,"designSmells",r,s),a&&$(d,"designSmells",a,r),Q(d,g,u))},"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(Ol,"mapDesignSmells");function xl(e){return e.failsStrict===!1||e.typeOnly===!0}i(xl,"isTypeOnlyPlacementDebt");function Tl(e,t){for(let n of t){let r=Br(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=i((c,p,m)=>{let g=e.get(c);!g||qe.has(c)||($(g,"violations",r,s),n.file&&$(g,"violations",n.file,r),Q(g,p,m))},"attach");if(xl(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(Tl,"mapViolations");function Nl(e,t){let n=Number(t.cycleCount)||0;if(n>0){let d=e.get("coupling");$(d,"cycles",`count:${n}`),Q(d,"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 d=e.get("coupling");$(d,"peerIsolation",`count:${r}`),Q(d,"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 d=e.get("cohesion");$(d,"physicalCohesion",`findings:${s}`),Q(d,"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");$(f,"physicalCohesion",`findings:${s}`),Q(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 d=e.get("dip");o>0&&$(d,"capability",`residual:${o}`),a>0&&$(d,"forbiddenGlobals",`residual:${a}`),Q(d,"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&&$(f,"capability",`residual:${o}`),a>0&&$(f,"forbiddenGlobals",`residual:${a}`),Q(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 d=e.get("encapsulation");$(d,"arkRules",`structureResidual:${l}`),Q(d,"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");$(f,"arkRules",`structureResidual:${l}`),Q(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 d=e.get("maintainability");$(d,"designFitness","design-weak"),Q(d,"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 d=e.get("maintainability");t.dirtyBaselineRisk===!0&&$(d,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&$(d,"baseline",`stale:${t.baselineStale}`),Q(d,"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 d=e.get("maintainability");$(d,"baseline",`frozen:${c}`),Q(d,"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,m=Number(t.emptyLayerCount)||0;if(p>0||m>0){let d=e.get("modularity");p>0&&$(d,"coverage",`ungovernedDirs:${p}`),m>0&&$(d,"coverage",`emptyLayers:${m}`),Q(d,"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 d=e.get("modularity");$(d,"goldenPattern","absent"),Q(d,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let g=e.get("stack");(t.stackKind??null)==="typescript"?g.status==="ok"&&(g.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(g.status="not-instrumented",g.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",g.evidence=[],g.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}i(Nl,"mapCountsAndFlags");function Bo(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>Gr(r).localeCompare(Gr(s)));Ol(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=Br(r).localeCompare(Br(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});Tl(e,n)}Nl(e,t)}i(Bo,"projectImprovementCompassFacts");function zo(e){for(let t of _e){let n=e.get(t);n.status="out-of-scope",n.summary=Ur[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(zo,"lockImprovementCompassOutOfScope");function qo(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(qo,"sortImprovementCompassEvidence");function Yo(e){return e.filter(n=>n.status==="residual"&&!qe.has(n.id)).slice().sort((n,r)=>{let s=jr[n.id]??150,o=jr[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(Yo,"finalizeImprovementCompassTopResidual");function Wo(e={}){let t=Go(),n=new Map(t.map(s=>[s.id,s]));Bo(n,e),zo(n),qo(t);let r=Yo(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(Wo,"buildImprovementCompass");function zr(e){return e.topResidual.map(t=>Kr(t))}i(zr,"formatImprovementCompassResidualLabels");function qr(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(qr,"primaryImprovementCompassNextAction");function Jo(e){let t=zr(e),n=_e.map(o=>Kr(o)),r=qr(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(Jo,"formatImprovementCompassDoctorLines");var Zo="1.0",Xo="<!-- arkgate:agent-projection:begin",Yr="<!-- arkgate:agent-projection:end -->",Wr="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",$n=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),Qo=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"]),Jr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,ea=/<!--\s*arkgate:agent-projection:end\s*-->/i,Pl=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Ll=/\bschema=([A-Za-z0-9._+-]+)/i;function wt(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(wt,"agentProjectionContentIdentity");function Dn(e){return String(e??"").replace(/\r\n/g,`
18
- `)}i(Dn,"normalizeNewlines");function Ye(e){let t=Dn(e);return t.endsWith(`
8
+ `)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function qs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(qs,"normalizeRel");function Ws(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:ve(),warnings:r}}let s=new Set(e.config.layers.map(c=>c.name)),a=[],o=[],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){a.push({path:g,message:"must be a non-empty relative path string"});continue}if(p.startsWith("/")||/^[A-Za-z]:[\\/]/.test(p)){a.push({path:g,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(c)){a.push({path:g,message:`layer ${JSON.stringify(c)} is not declared in layers[]`});continue}let y=qs(p);l.add(y);let f=e.fileContents[y]??e.fileContents[p];if(f===void 0){a.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} is missing`});continue}try{let u=mt(JSON.parse(f),y,c);o.push({layer:c,sourceFile:y,file:u.config})}catch(u){if(u instanceof Le)for(let m of u.issues)a.push({path:`${g}${m.path==="$"?"":m.path.replace(/^\$/,"")}`,message:`${y}: ${m.message}`});else u instanceof SyntaxError?a.push({path:g,message:`referenced ArkRules file ${JSON.stringify(y)} is not valid JSON: ${u.message}`}):a.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=qs(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(a.length>0)throw new gt(t,a);return{config:e.config,arkRules:tn(o),warnings:r}}i(Ws,"resolveEffectiveContract");function nn(e){let{stewards:t,...n}=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 mi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(mi,"titleMatchesInvariant");function gi(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let a of Object.values(e))if(!(s&&!a.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(a)||a.includes(t)))return!0;return!1}i(gi,"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,a=[],o=[];for(let l of t){let c=[],p=l.coverage?.test!==!1,g=l.coverage?.symbol;if(!r&&p)for(let m of n){let A=e.fileContents[m];if(A&&mi(A,l.id)){c.push("test-title");break}}g&&gi(e.fileContents,g)&&c.push("symbol");let f=(l.coverage?.test===!0||!!g||l.coverage===void 0)&&c.length>0||l.coverage?.test===!1&&!g?!0:c.length>0,u=r&&p&&c.length===0;if(a.push({invariantId:l.id,layer:l.provenance.layer,sourceFile:l.provenance.sourceFile,mode:l.mode,covered:f&&!u,evidence:c,partial:u,description:l.description}),!f||u){let m=l.mode==="enforced"&&!u,A=r||n.length===0?"never-had-tests":"tests-disappeared";o.push({ruleId:"INVARIANT_UNCOVERED",message:u?s?`Invariant ${l.id} coverage cannot be proven (coverage file budget exhausted); reporting partial, not covered.`:`Invariant ${l.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:A==="tests-disappeared"?`Invariant ${l.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${l.id} is not covered by a test title or declared symbol (never-had-tests).`,file:l.provenance.sourceFile,line:1,arkruleId:l.id,arkruleSource:l.provenance.sourceFile,fromLayer:l.provenance.layer,severity:m?"error":"warning",failsStrict:m,kind:A})}}return{coverage:a,violations:o,partial:a.some(l=>l.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?{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 on="1.0";function T(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(T,"addFinding");function ie(e){return[...new Set(e??[])].sort()}i(ie,"sortedUnique");function de(e,t,n,r,s){let a=ie(n),o=ie(r),l=new Set(a),c=new Set(o),p=o.filter(y=>!l.has(y)),g=a.filter(y=>!c.has(y));p.length===0&&g.length===0||(p.length>0&&T(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:a,after:o}),g.length>0&&T(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:a,after:o}))}i(de,"compareStringSets");function yt(e,t,n,r,s,a,o){if(n===r)return;T(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?a:o,before:n,after:r})}i(yt,"compareBoolean");function an(e,t){let n=new Map,r=new Set;for(let s of e){let a=t(s);n.has(a)?r.add(a):n.set(a,s)}return{values:n,duplicates:[...r].sort()}}i(an,"keyed");function yi(e,t,n){let r=an(t,a=>a.name),s=an(n,a=>a.name);(r.duplicates.length>0||s.duplicates.length>0)&&T(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 a of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let o=r.values.get(a),l=s.values.get(a),c=`$.layers[${a}]`;if(!o&&l){T(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(o&&!l){T(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!l)continue;de(e,`${c}.patterns`,o.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."}),de(e,`${c}.exclude`,o.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=Ut(o),g=Ut(l);de(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."}),de(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)."}),ie(o.intentPrefixes).join("\0")!==ie(l.intentPrefixes).join("\0")&&T(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:ie(o.intentPrefixes),after:ie(l.intentPrefixes)}),yt(e,`${c}.mayImportInfrastructure`,o.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`,o.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(yi,"compareLayers");function hi(e,t,n){let r=i(o=>`${o.from}->${o.to}`,"keyOf"),s=an(t,r),a=an(n,r);(s.duplicates.length>0||a.duplicates.length>0)&&T(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:a.duplicates});for(let o of[...new Set([...s.values.keys(),...a.values.keys()])].sort()){let l=s.values.get(o),c=a.values.get(o),p=`$.rules[${o}]`;if(!l&&c){c.allowed===!1&&T(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&T(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&&T(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 f=l.from===l.to&&c.from===c.to;T(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:f?y?"strengthening":"weakening":"judgment-required",message:f?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})}ie(l.sliceFolders).join("\0")!==ie(c.sliceFolders).join("\0")&&T(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:ie(l.sliceFolders),after:ie(c.sliceFolders)})}}i(hi,"compareRules");function Ai(e,t,n){let r=t.safety??{},s=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let o=r[a]??0,l=s[a]??0;o!==l&&T(e,{kind:l>o?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:l>o?"weakening":"strengthening",message:l>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:l})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])yt(e,`$.safety.${a}`,r[a]===!0,s[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Ai,"compareSafety");function hr(e){return e.mode==="enforced"?"enforced":"advisory"}i(hr,"arkRunMode");function Ar(e){return e.mode==="enforced"?"enforced":"advisory"}i(Ar,"arkOrderMode");function Ri(e,t,n){let r=t.arkOrder,s=n.arkOrder,a="$.arkOrder";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkorder-added",path:a,classification:"strengthening",message:`ArkOrder extra was added (${Ar(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkorder-removed",path:a,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let o=Ar(r),l=Ar(s);if(o!==l){let c=o==="advisory"&&l==="enforced";T(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${a}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:o,after:l})}de(e,`${a}.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."}),de(e,`${a}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Ri,"compareArkOrder");function ki(e,t,n){let r=t.arkRun,s=n.arkRun,a="$.arkRun";if(!r&&!s)return;if(!r&&s){T(e,{kind:"arkrun-added",path:a,classification:"strengthening",message:`ArkRun extra was added (${hr(s)}).`,after:s});return}if(r&&!s){T(e,{kind:"arkrun-removed",path:a,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let o=hr(r),l=hr(s);if(o!==l){let c=o==="advisory"&&l==="enforced";T(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${a}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:o,after:l})}de(e,`${a}.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."}),de(e,`${a}.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,`${a}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(ki,"compareArkRun");function Ei(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(Ei,"overallClassification");function Ys(e,t){return`${e}::${t}`}i(Ys,"ruleKey");function Xs(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Ys(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Ys(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Xs,"indexEffectiveRules");function Ii(e,t,n,r,s,a){let o=new Map((a??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let f of p){let u=l[f],m=c[f],A=`$.arkRules[${f}]`;if(u===void 0&&m!==void 0){T(e,{kind:"arkrules-ref-added",path:A,classification:"strengthening",message:`ArkRules reference for layer ${f} was added.`,after:m});continue}if(u!==void 0&&m===void 0){T(e,{kind:"arkrules-ref-removed",path:A,classification:"weakening",message:`ArkRules reference for layer ${f} was removed.`,before:u});continue}u!==m&&T(e,{kind:"arkrules-ref-path-changed",path:A,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:u,after:m})}let g=Xs(r),y=Xs(s);for(let f of[...new Set([...g.structure.keys(),...y.structure.keys()])].sort()){let u=g.structure.get(f),m=y.structure.get(f),A=`$.arkRules.structure[${f}]`;if(!u&&m){T(e,{kind:"arkrule-structure-added",path:A,classification:"strengthening",message:`Structure ArkRule ${m.id} was added (${m.mode}).`,after:m});continue}if(u&&!m){T(e,{kind:"arkrule-structure-removed",path:A,classification:"weakening",message:`Structure ArkRule ${u.id} was removed.`,before:u});continue}if(!(!u||!m)){if(u.mode!==m.mode){let b=u.mode==="advisory"&&m.mode==="enforced";T(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${A}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${m.id} was promoted to enforced.`:`Structure ArkRule ${m.id} was demoted to advisory.`,before:u.mode,after:m.mode})}u.sensor!==m.sensor&&T(e,{kind:"arkrule-sensor-changed",path:`${A}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${m.id} changed sensor identity.`,before:u.sensor,after:m.sensor})}}for(let f of[...new Set([...g.invariants.keys(),...y.invariants.keys()])].sort()){let u=g.invariants.get(f),m=y.invariants.get(f),A=`$.arkRules.invariants[${f}]`;if(!u&&m){T(e,{kind:"arkrule-invariant-added",path:A,classification:"strengthening",message:`Invariant ${m.id} was added (${m.mode}).`,after:m});continue}if(u&&!m){T(e,{kind:"arkrule-invariant-removed",path:A,classification:"weakening",message:`Invariant ${u.id} was removed.`,before:u});continue}if(!(!u||!m)&&u.mode!==m.mode)if(u.mode==="advisory"&&m.mode==="enforced"){let N=o?.get(m.id),R=sn(N);R.ok?T(e,{kind:"arkrule-invariant-promoted",path:`${A}.mode`,classification:"strengthening",message:`Invariant ${m.id} was promoted to enforced (coverage evidence present).`,before:u.mode,after:m.mode}):T(e,{kind:"arkrule-invariant-promote-refused",path:`${A}.mode`,classification:"judgment-required",message:`Invariant ${m.id} cannot be promoted to enforced: ${R.reason}`,before:u.mode,after:m.mode})}else T(e,{kind:"arkrule-invariant-demoted",path:`${A}.mode`,classification:"weakening",message:`Invariant ${m.id} was demoted to advisory.`,before:u.mode,after:m.mode})}}i(Ii,"compareArkRules");function ln(e,t,n){let r=[];de(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),de(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."}),de(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},a=e.cyclePolicy??"strict",o=t.cyclePolicy??"strict";if(a!==o){let l=s[o]===s[a]?"judgment-required":s[o]>s[a]?"strengthening":"weakening";T(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:a,after:o})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&T(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}),yi(r,e.layers,t.layers),hi(r,e.rules,t.rules),Ai(r,e,t),Ii(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),ki(r,e,t),Ri(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:on,classification:Ei(r),findings:r}}i(ln,"classifyArkPolicyDelta");function cn(e,t){if(!e||e.schemaVersion!==on||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=ie(e.findingIds),r=ie(t.findingIds);return n.length===r.length&&n.every((s,a)=>s===r[a])}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 Js(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Js,"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 a=e[t];if(a===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=a}}i(ht,"readString");function le(e,t,n){return e.startsWith(t,n)&&!dn(e[n-1])&&!dn(e[n+t.length])}i(le,"isWordAt");function Zs(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(!le(e,"type",n))return!1;let s=ae(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||le(e,"as",s)||!Js(e[s]))return!1;for(n=s;n<e.length&&dn(e[n]);)n+=1;if(n=ae(e,n),le(e,"as",n)){if(n=ae(e,n+2),!Js(e[n]))return!1;for(;n<e.length&&dn(e[n]);)n+=1}r=!0}return!1}i(Zs,"bracedNamedBindingsAreTypeOnly");function Si(e,t){if(t=ae(e,t+6),e[t]==="(")return ht(e,ae(e,t+1));let n=!1;if(le(e,"type",t)){let s=ae(e,t+4);e[s]!==","&&!le(e,"from",s)&&(n=!0)}else Zs(e,t)&&(n=!0);let r=Qs(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Si,"specifierAfterImport");function bi(e,t){t=t+6;let n=ae(e,t),r=!1;if(le(e,"type",n)){let a=ae(e,n+4);(e[a]==="{"||e[a]==="*")&&(r=!0)}else Zs(e,n)&&(r=!0);let s=Qs(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(bi,"specifierAfterExport");function Qs(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(le(e,"from",t))return ht(e,ae(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ht(e,t);if(t>0&&(le(e,"import",t)||le(e,"export",t)))return}}i(Qs,"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 Ci(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(Ci,"specifierAfterRequire");function Oi(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 a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="`"){n=vi(e,n);continue}if(r==="'"||r==='"'){let a=ht(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let s=r==="i"&&le(e,"import",n)?Si(e,n):r==="e"&&le(e,"export",n)?bi(e,n):r==="r"&&le(e,"require",n)?Ci(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(Oi,"moduleSpecifiers");function ea(e,t){let n=[],r=[];for(let s of Oi(e.content)){let a=s.value;if(!a.startsWith(".")){if(s.typeOnly)continue;let p=Qe(a);if(!p)continue;let g=e.content.slice(0,s.offset).split(`
10
+ `).length;r.push({file:e.path,symbol:a,capability:p,evidence:{kind:"import",file:e.path,line:g,excerpt:s.excerpt}});continue}let o=e.content.slice(0,s.offset).split(`
11
+ `).length,l={kind:"import",file:e.path,line:o,excerpt:s.excerpt},c=_i(e.path,a,t);n.push({from:e.path,specifier:a,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(ea,"moduleFactsFor");function _i(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let s=r.join("/");for(let a of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let o=n.get(a);if(o)return o}}i(_i,"resolveSpecifier");function ta(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=me(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(ta,"violationsFor");var xi={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 Ti(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Ti,"hasActiveArkRules");function Ni(e,t){return Ti(e,t)?X(F(nn({config:e,arkRules:t,warnings:[]}))):X(F(e))}i(Ni,"policyHashFor");function At(e,t,n){let r=typeof e=="string"?Yt(e,t):it(e,t),s=n?.arkRules??ve();return{...r,arkRules:s,policyHash:Ni(r.config,s)}}i(At,"loadContract");function Rr(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(),a=s.length>0,o=a&&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:a,acknowledged:o,valid:!a||o}}i(Rr,"analyzePolicyDelta");function Be(e){let t=e.files.map(y=>{let f=we(y.path);return{path:f,content:y.content,contentHash:X(y.content),layer:ce(f,e.contract.config.layers)??null}}).sort((y,f)=>y.path.localeCompare(f.path)),n=new Map(t.map(y=>[y.path,y])),r=[],s=[];for(let y of t){let f=ea(y,n);r.push(...f.edges),s.push(...f.capabilityUses)}let a=ta(r,e.contract.config),o=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 f=n.get(y.file)?.layer;if(!f)continue;let u=o.get(f),m=Se(y.symbol,u?.forbiddenGlobals??[]);if(m){a.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${y.symbol}" because it is the import form of forbidden global "${m}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(f)?.has(y.capability)&&a.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} 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"?[]:[{...xi}],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:a};return{mode:"lexical-compatibility",completeness:c,completenessReasons:p,valid:c==="complete"&&a.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 kr(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(kr,"explainViolation");function un(e){let t=0,n=new Map,r=new Map,s=new Set,a=[],o=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,a.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=a.pop(),g===void 0)break;s.delete(g),p.push(g)}while(g!==c);p.length>1&&o.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return o.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(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.fromLayer||!a.toLayer)continue;let o=me(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!o)continue;let l=!!o.peerIsolation,c=!l&&!!(a.typeOnly||a.namedBindingsTypeOnly),p=o.message??(l?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...l?{peerIsolation:!0}:{},message:c?`${p} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:p,...c?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let a=un(r);s==="soft"||s==="framework-soft"?n.push(...a.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}i(De,"evaluateArchitectureGraph");var Pi=["no-anemic-model"];function na(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(na,"escapeGlobLiteral");function Li(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let a=e[r+1];if("*?{}[],".includes(a)||a==="\\"){t+="\\"+a,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+=na(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=na(s)}return new RegExp(`^${n}$`)}i(Li,"globToRegExp");function ze(e,t){return!t||t.length===0?!0:t.some(n=>Li(n).test(e))}i(ze,"matchesAppliesTo");function wi(e){return Pi.includes(e)}i(wi,"isTier2");function ra(e){return e.mode==="enforced"&&!wi(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(ra,"severityFor");function Me(e,t,n,r=1){let{severity:s,failsStrict:a}=ra(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:a}}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 Di(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(Di,"evaluateAggregatePrivateState");function Mi(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(Mi,"evaluateAlwaysValidFactory");function Fi(e,t,n){let r=[];for(let s of fn(e,t,n))for(let a of s.mutatingMethods)a.referencesGuardOrPublish||r.push(Me(e,s.file,`Mutating method ${s.className}.${a.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}i(Fi,"evaluateDomainEventOnMutation");function $i(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($i,"evaluateOrchestrationOnly");function Hi(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(Hi,"evaluateThinAdapter");function ji(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(ji,"evaluateWritesViaAggregate");function Vi(e,t,n){let r=[];for(let s of fn(e,t,n))if(s.dataOnly===!0){let a=Me(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...a,severity:"warning",failsStrict:!1})}return r}i(Vi,"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(...Di(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Mi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Fi(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...$i(n,e));break;case"thin-adapter":t.push(...Hi(n,e));break;case"writes-via-aggregate":t.push(...ji(n,e));break;case"no-anemic-model":t.push(...Vi(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:o,failsStrict:l}=ra(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:o,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 o=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:o?"error":"warning",sensor:"invariant-coverage",failsStrict:o})}return n.sort((s,a)=>s.file.localeCompare(a.file)||s.arkruleId.localeCompare(a.arkruleId)||s.message.localeCompare(a.message))}i(gn,"collectEmptyAppliesToFindings");var Ki=/\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)/,Ui=/\.(?: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,Gi=/\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*=)/,Bi=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,zi=/\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*=/,qi=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Er(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(zi.source,"g"))??[],r=t.match(new RegExp(qi.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,a=(t.match(/\bswitch\s*\(/g)??[]).length,o=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+a>=6,l=Ki.test(t),c=Gi.test(t)||Bi.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,f=l&&Ui.test(t);return!o&&!y&&!f?null:{...o?{orchestrationHeavy:!0}:{},...y?{adapterThick:!0}:{},...f?{persistenceWrite:!0}:{}}}i(Er,"deriveArkRuleFileHints");function yn(e){let t={};for(let[n,r]of Object.entries(e)){let s=Er(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}i(yn,"buildArkRuleFileHints");function sa(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 a=s[1],o=s.index+s[0].length,l=1,c=o;for(;c<t.length&&l>0;){let D=t[c];D==="{"?l+=1:D==="}"&&(l-=1),c+=1}let p=t.slice(o,c-1),g=p.split(`
12
+ `).map(D=>/^\s*\/\//.test(D)||/^\s*\/\*|\*\//.test(D)?D:D.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(g.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(g),f=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(g)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(g.split(`
14
+ `).filter(D=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(D)).join(`
15
+ `)),u=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(p),m=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(p),A=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(p)&&!m,b=/(?:^|[\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),N=[],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 D=C[1];if(R.has(D))continue;let x=C.index+C[0].length,H=1,w=x;for(;w<p.length&&H>0;)p[w]==="{"?H+=1:p[w]==="}"&&(H-=1),w+=1;let ee=p.slice(x,w-1);if(!/this\.\w+\s*=/.test(ee))continue;let Fe=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(ee);N.push({name:D,referencesGuardOrPublish:Fe})}let Y=(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=Y<=1&&k>=2&&(f||y);n.push({file:e,className:a,exported:!0,hasPublicMutableFields:f||y,hasPublicSetters:u,hasPublicConstructor:A,hasStaticFactory:b,mutatingMethods:[...N],dataOnly:L})}return n}i(sa,"extractClassShapesFromSource");var aa=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 fe(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(fe,"extraMergeTeethAllowed");function An(e){let t=e.length,n=0,r=new Set;for(let s of e){let a=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;a&&(n+=1,r.add(a))}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 oa(e){return typeof e=="string"&&e.startsWith("ARKORDER_")}i(oa,"isArkOrderRuleId");function Ir(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(Ir,"isExtraPlaneFinding");function ia(e,t={}){if(!Array.isArray(e)||fe(t))return e;for(let n of e)Ir(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}i(ia,"demoteExtraPlaneTeethUnderClassificationFloor");var Sr="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,a=fe(t),o=e.arkRules,l=ke(o?.structureEnforced),c=ke(o?.structureTotal),p=typeof o?.structureAdvisory=="number"?ke(o.structureAdvisory):Math.max(0,c-l),g=ke(o?.invariantEnforced),y=ke(o?.invariantTotal),f=typeof o?.invariantAdvisory=="number"?ke(o.invariantAdvisory):Math.max(0,y-g),u=l>0||g>0,m=e.arkRun?.present===!0,A=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,b=ke(e.arkRun?.residualCount),N=m&&A==="enforced",R=N&&a,I=u||N,C=I&&a,Y=I&&s&&!a,k;if(C){let D=[];u&&D.push("enforced structure/invariant findings"),N&&D.push("enforced ArkRun skip findings"),k=`Layer graph failures plus ${D.join(" and ")} (advisory extras never fail merge alone).`}else Y?k=`Layer graph only \u2014 enforced ${[u?"ArkRules structure/invariant":null,N?"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."+(m?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:f,covered:ke(o?.covered),uncovered:ke(o?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:m,mode:A,residualCount:b,extraMergeTeeth:R,note:m?A==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:C,dualPlaneStamp:Sr,failMergeWhen:k};return s&&(L.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:a}),L}i(kn,"composeMergePlanesHonesty");var vr=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],ca=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Wi=new Set(vr),Yi=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"]),Xi=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 Cr=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],br=new Set(Cr);function In(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(br.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(br.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:br.has(e.slice(0,r))}i(In,"isArkRunTransportBypassSpecifier");function En(e){if(Wi.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 Ji(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(Ji,"firstStringLiteralArg");function la(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(la,"keywordBefore");function Sn(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(Sn,"parseValueImportClause");function Zi(e,t){Sn(It(e),t)}i(Zi,"forEachArkRunValueImportClause");function bn(e,t){let n=It(t),r=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,a;for(;(a=s.exec(n))!==null;){let l=a[3]??"";if(!l)continue;let c=a[0]??"";r.push({from:e,specifier:l,kind:/^\s*export/.test(c)?"export":"import",typeOnly:!!a[1],line:Et(t,a.index),resolution:"resolved-external"})}let o=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(a=o.exec(n))!==null;){let l=a[1]??"";if(!l)continue;let c=a[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:l,kind:c,typeOnly:!1,line:Et(t,a.index),resolution:"resolved-external"})}return r}i(bn,"extractArkRunValueImportDependenciesFromSource");function vn(e){let t=[];return Zi(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let s of r[1].split(",")){let a=s.trim();if(!a||a.startsWith("type "))continue;let o=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(a),l=o?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(a)?.[1],c=o?.[1]??l;l&&c&&/^[A-Z]/.test(c)&&t.push(l,c)}}),kt(t)}i(vn,"extractArkRunImportedConstructorNamesFromSource");function Qi(e){let t=new Map,n=new Set;return Sn(e,(r,s)=>{if(!qe(s))return;let a=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);a?.[1]&&n.add(a[1]);let o=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());o?.[1]&&t.set(o[1],o[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(Qi,"collectKernelImportBindings");function el(e,t){let n=new Set(t);return Sn(e,(r,s)=>{let a=/\{([^}]*)\}/.exec(r);if(a?.[1])for(let o of a[1].split(",")){let l=o.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(el,"collectImportedConstructors");function tl(e,t){let n;return Sn(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}i(tl,"importedFromForName");function Cn(e,t){let n=It(t),r=Qi(n),s=[],a=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,o;for(;(o=a.exec(n))!==null;){let l=o[1],c=o.index;if(la(n,c,"function")||la(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,f=En(y)??En(l);if(!f)continue;let u=r.named.has(l)||g!==void 0&&r.namespaces.has(g);if(f!=="factory"&&(!u&&g===void 0||g&&Xi.has(g)&&!u))continue;let m=Ji(n,c+o[0].length);s.push({file:e,line:Et(t,c),kind:f,callee:l,viaImport:u,...g?{receiver:g}:{},...m?{nameLiteral:m}:{}})}return s}i(Cn,"extractArkRunKernelCallsFromSource");function On(e,t,n){let r=It(t),s=el(r,n),a=[],o=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,l;for(;(l=o.exec(r))!==null;){let c=l[1];if(Yi.has(c)||!s.has(c))continue;let p=tl(r,c);a.push({file:e,line:Et(t,l.index),typeName:c,...p?{importedFrom:p}:{}})}return a}i(On,"extractArkRunManagedNewsFromSource");function nl(e,t){let n=0,r;for(let s=t;s<e.length;s+=1){let a=e[s];if(r){if(a==="\\"){s+=1;continue}a===r&&(r=void 0);continue}if(a==="'"||a==='"'||a==="`"){r=a;continue}if(a==="[")n+=1;else if(a==="]"&&(n-=1,n===0))return s}return-1}i(nl,"matchingBracketEnd");function rl(e,t,n){let r=e.slice(t+1,n),s=[],a=/(['"])((?:\\.|[^\\])*?)\1/g,o;for(;(o=a.exec(r))!==null;){let l=o[2]??"";l.length>0&&s.push(l)}return s}i(rl,"stringLiteralsInList");function kt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(kt,"uniqueSorted");function da(e,t){let n=It(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],a=[],o=[],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 f=p.index+p[0].length+(y[0].length-1),u=nl(n,f);if(u<0)continue;let m=rl(n,f,u);if(m.length===0)continue;c===void 0&&(c=p.index);let A=p[1];A==="uses"?s.push(...m):A==="reactsTo"?a.push(...m):A==="raises"?o.push(...m):l.push(...m)}return c===void 0?[]:[{file:e,line:Et(t,c),uses:kt(s),reactsTo:kt(a),raises:kt(o),sends:kt(l)}]}i(da,"extractArkRunDeclarationsFromSource");var fa=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],sl=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],al=new Set(sl);function ol(e){return al.has(e)}i(ol,"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"},Or="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ma(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(ma,"isDomainRoleLayer");function il(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(il,"compareFindings");function Ee(e,t,n,r,s,a,o){let l=e.mode==="enforced"&&o;return{ruleId:_n[t],sensor:t,message:s,file:n,line:r,...a?.fromLayer?{fromLayer:a.fromLayer}:{},...a?.target?{target:a.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:_n[t],fromLayer:a?.fromLayer,target:a?.target})}}i(Ee,"finding");function ll(e,t){let n=[],r=[],s=[],a=[];for(let o of e)o.file===t&&(n.push(...o.uses),r.push(...o.reactsTo),s.push(...o.raises),a.push(...o.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(a)}}i(ll,"bagForFile");function ua(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(ua,"emitKinds");function pa(e){return e==="subscribe"||e==="register-handler"}i(pa,"handleKinds");function cl(e){return e==="resolve"||e==="resolve-singleton"}i(cl,"dependKinds");function dl(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 a=new Map;for(let o of t){let l=a.get(o.matchedRoot)??[];l.push(o),a.set(o.matchedRoot,l)}for(let o of s){let l=[...a.get(o)??[]].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(o)} matched no governed files and has no createArkKernel factory.`,{target:o},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(o)} has no createArkKernel / createStrictArkKernel factory.`,{target:o},n))}return r}i(dl,"evaluateMissingRoot");function ul(e,t,n,r,s){let a=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),o=[];for(let l of n){let c=l.specifier;if(!c||!qe(c))continue;let p=r(l.from);p&&ma(p,a.get(p)??[])&&o.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 o}i(ul,"evaluateKernelInDomain");function pl(e,t,n,r,s,a){let o=new Set(e.managedLayers);if(o.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 f=s(g.file);!f||!o.has(f)||ma(f,l.get(f)??[])||p.push(Ee(e,"arkrun-direct-new",g.file,g.line,`${f} must not construct ${g.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:g.typeName},a))}return p}i(pl,"evaluateDirectNew");function fl(e,t,n,r,s){let a=[],o=[];if(e.requireDeclarations!==!0)return{findings:a,completenessReasons:o};let l=new Set(e.managedLayers);if(l.size===0)return{findings:a,completenessReasons:o};for(let c of t){if(!ua(c.kind)&&!pa(c.kind)&&!cl(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&o.push({code:Or,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=ll(n,c.file);if(ua(c.kind)){if(g.raises.has(c.nameLiteral)||g.sends.has(c.nameLiteral))continue;a.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(pa(c.kind)){if(g.reactsTo.has(c.nameLiteral))continue;a.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)||a.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:a,completenessReasons:o}}i(fl,"evaluateUndeclared");function ml(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let a=[];for(let o of t){if(o.typeOnly)continue;let l=o.specifier;if(!l||!In(l))continue;let c=n(o.from);!c||!s.has(c)||a.push(Ee(e,"arkrun-transport-bypass",o.from,o.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return a}i(ml,"evaluateTransportBypass");function St(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=fe(e.classification),r=fl(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...dl(t,e.compositionRootHits,n),...ul(t,e.layers,e.dependencies,e.layerForFile,n),...pl(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...ml(t,e.dependencies,e.layerForFile,n)].sort(il),a=[...r.completenessReasons].sort((o,l)=>{let c=`${o.code}\0${o.file??""}\0${o.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:s,completenessReasons:a}}i(St,"evaluateArkRunSensors");function _r(e){return{findings:St(e).findings.filter(n=>ol(n.sensor)),completenessReasons:[]}}i(_r,"evaluateArkRunEditorSensors");function gl(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(gl,"fileMatchesCompositionRoot");function yl(e,t,n){let r=Cn(t,n).some(o=>o.kind==="factory"),s=[],a=e.kernelRoots??e.compositionRoots;for(let o of a)gl(o,t)&&s.push({file:t,matchedRoot:o,hasKernelFactory:r});return s}i(yl,"compositionRootHitsForSource");function ga(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(vn(e.source));return _r({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:On(e.file,e.source,n),compositionRootHits:yl(t,e.file,e.source),declarations:[],dependencies:bn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}i(ga,"evaluateArkRunEditorSensorsFromSource");function ya(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(ya,"isArkOrderModuleSpecifier");var ha=["arkorder-missing-plane","arkorder-kernel-in-domain","arkorder-generic-update","arkorder-too-many-params","arkorder-ingest-writes-xi","arkorder-xi-field-write"],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"};function hl(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(hl,"isDomainRoleLayer");function Ie(e,t,n,r,s,a,o){let l=e.mode==="enforced"&&o;return{ruleId:xn[t],sensor:t,message:s,file:n,line:r,...a?.fromLayer?{fromLayer:a.fromLayer}:{},...a?.target?{target:a.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:xn[t],fromLayer:a?.fromLayer,target:a?.target})}}i(Ie,"finding");function Tn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=fe(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(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 a=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let p=c.specifier;if(!p||!ya(p))continue;let g=e.layerForFile(c.from);g&&hl(g,a.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 o=t.xiKeys??[];o.length>t.maxXiKeys&&r.push(Ie(t,"arkorder-too-many-params","ark.config.json",1,`arkOrder.xiKeys has ${o.length} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(o.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 o.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 re(e,t,n={}){return{ruleId:e,message:t,...n}}i(re,"configWarning");function bt(e){let{config:t,rules:n,files:r,manifest:s}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(u=>typeof u!="string"))&&a.push(re("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(re("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let u of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[u];m!==void 0&&(!Number.isInteger(m)||m<0)&&a.push(re("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${u} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...o.map(u=>u.name).filter(Boolean),...l.map(u=>u.name).filter(u=>!!u)]);o.length===0&&a.push(re("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 o){if(!u.name){a.push(re("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"))&&a.push(re("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 m=Array.isArray(u.patterns)?u.patterns:[];if(m.length===0){a.push(re("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${u.name}" has no file patterns and will never classify files.`,{layer:u.name}));continue}for(let A of m){let b;try{b=_e(A)}catch(R){a.push(re("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 N=u.optional===!0||u.reserved===!0||u.allowEmpty===!0;!r.some(R=>b.test(R))&&!N&&a.push(re("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)a.push(re("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)&&a.push(re("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${u.from}".`,{fromLayer:u.from,toLayer:u.to})),u.to&&!c.has(u.to)&&a.push(re("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${u.to}".`,{fromLayer:u.from,toLayer:u.to}));let y=new Set;if(o.length>1)for(let u of r){let m=-1,A=[];for(let b of o)for(let N of b.patterns??[]){if(!_e(N).test(u))continue;let R=sr(N,u);R>m?(m=R,A=[b.name]):R===m&&!A.includes(b.name)&&A.push(b.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&a.push(re("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let f=r.filter(u=>!ce(u,o));return f.length>0&&a.push(re("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)})),a}i(bt,"collectAnalysisConfigWarnings");function Al(e,t){return t.some(n=>{try{return _e(n).test(e)}catch{return!1}})}i(Al,"matchesAny");function Rl(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,a=e.contract.config.dynamicImportAllowlist??[],o=t.safetyUses.filter(A=>A.kind==="ts-suppression").map(({file:A,line:b})=>({file:A,line:b})),l=t.safetyUses.filter(A=>A.kind==="any-cast").map(({file:A,line:b})=>({file:A,line:b})),c=t.safetyUses.filter(A=>(A.kind==="dynamic-import"||A.kind==="dynamic-require")&&!Al(A.file,a)).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:o,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:p,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},f=[],u=c.filter(A=>A.kind==="import");if(u.length>0){let A=u[0];f.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 m=c.filter(A=>A.kind==="require");if(m.length>0){let A=m[0];f.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:A.file,line:A.line,message:`${m.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>r){let A=o[0];f.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:A.file,line:A.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>s){let A=l[0];f.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];f.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&&f.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:f}}i(Rl,"evaluateSafety");function kl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(kl,"ambientForbiddenGlobal");function Aa(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return dr(e,n.length>0?n:cr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Aa,"intentLayer");function El(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(a=>[a.name,a]));for(let a of t.ambientUses){let o=n.get(a.file);!o||!kl(a.symbol,s.get(o)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:o,target:a.symbol,message:`${o} must not use the ambient global "${a.symbol}".`})}for(let a of t.capabilityUses){let o=n.get(a.file);if(!o)continue;let l=s.get(o),c=l?.forbiddenGlobals??[],p=a.source==="import-based"?t.dependencies.find(g=>g.from===a.file&&g.line===a.line&&g.specifier===a.symbol&&!g.typeOnly)?.kind:void 0;if(!(a.source==="ambient-global"&&et(a.symbol,c))){if(a.source==="import-based"){let g=Se(a.symbol,c);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:a.file,line:a.line,fromLayer:o,target:a.symbol,...p?{edgeKind:p}:{},message:`${o} must not use module "${a.symbol}" because it is the import form of forbidden global "${g}".`});continue}}$e(l).includes(a.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:a.file,line:a.line,fromLayer:o,target:a.symbol,capability:a.capability,...p?{edgeKind:p}:{},message:a.source==="import-based"?`${o} denies the ${a.capability} capability; found import of "${a.symbol}".`:`${o} denies the ${a.capability} capability; found ambient "${a.symbol}".`})}}for(let a of t.publishCalls){let o=n.get(a.file);if(!o)continue;for(let c of tt({publishCall:!0,rawIntentName:a.rawIntentName,objectHasIntent:a.objectHasIntent,arkPublishCandidate:a.arkPublishCandidate,hasSource:a.hasSource}))r.push({ruleId:c.ruleId,file:a.file,line:a.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:c.message});if(!a.sourceIntent)continue;let l=Aa(a.sourceIntent,e.contract);!l||l===o||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:a.file,line:a.line,fromLayer:o,toLayer:l,target:a.sourceIntent,message:`Publish source "${a.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${o}.`})}for(let a of t.intentReferences){let o=n.get(a.file);if(!o)continue;let l=Aa(a.intent,e.contract);if(!l)continue;let c=me(e.contract.config.rules,o,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:a.file,line:a.line,fromLayer:o,toLayer:l,target:a.intent,message:c.message??`${o} must not reference ${l} intent ${a.intent}.`})}return r}i(El,"contentViolations");function Il(e){let{facts:t}=e,n=Ge(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",a=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,P)=>{let j=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${P.code}\0${P.file??""}\0${P.message}`;return j<oe?-1:j>oe?1:0}),o=t.files.map(d=>({...d,layer:ce(d.path,e.contract.config.layers)??null})),l=new Map(o.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let P=d.target?l.get(d.target)??ce(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=bt({config:e.contract.config,rules:e.contract.config.rules,files:o.map(d=>d.path)}),g=Rl(e,t),y=e.contract.arkRules??ve(),f=o.map(d=>d.path),m={...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:f,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),fileHints:m}),...gn(y,f)],b=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.`})),N=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}):{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.`})),Y=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:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),k=An(o),L=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)??ce(d,e.contract.config.layers),"layerForFile"),classification:k}),D=e.contract.config.arkRun?.mode,x=L.findings.filter(()=>D==="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}:{}})),H=L.findings.filter(()=>D!=="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})),w=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)??ce(d,e.contract.config.layers),"layerForFile"),classification:k}),ee=e.contract.config.arkOrder?.mode,ue=w.findings.filter(()=>ee==="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=w.findings.filter(()=>ee!=="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,...w.completenessReasons],Oe=De({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(d=>d.layer).map(d=>d.path),contentViolations:[...El(e,t,l),...b,...C,...x,...ue],edges:c,warnings:[...p,...g.warnings,...N,...Y,...H,...Fe],safety:g.report}),wt=s==="complete"&&Ze.length>0?"partial":s,Bn=wt==="complete"?a:[...a,...Ze].sort((d,P)=>{let j=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${P.code}\0${P.file??""}\0${P.message}`;return j<oe?-1:j>oe?1:0}),S=Oe.violations.filter(d=>d.failsStrict!==!1),v=wt==="complete"&&S.length===0,h=v&&Oe.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:wt,completenessReasons:Bn,valid:v,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:o,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Oe.violations,warnings:Oe.warnings}}}i(Il,"analyzeCanonicalResolvedProject");function We(e){return Il({contract:e.contract,facts:Re(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(We,"analyzeResolvedProject");function Ra(e){return X(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Ra,"analysisTreeHash");function xr(e){let t=Be(e),n=new Map(t.ir.files.map(m=>[m.path,m])),r=[],s=new Set,a=[];for(let m of e.changes){let A=m.path.replace(/\\/g,"/"),b=we(m.path);if(!b||b===".."||b.startsWith("../")||A.startsWith("/")||/^[A-Za-z]:\//.test(A)||A.includes("\0")){a.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(b)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}s.add(b),"delete"in m&&m.delete&&!n.has(b)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in m&&m.delete?{path:b,delete:!0}:{path:b,content:"content"in m?m.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=Rt({...e,changes:r}),l=new Map(o.ir.files.map(m=>[m.path,m])),c=o.ir.violations.filter(m=>m.ruleId==="CAPABILITY_VIOLATION"||m.ruleId==="FORBIDDEN_GLOBAL").map(m=>{let A=l.get(m.evidence.file)?.layer;return{ruleId:m.ruleId,file:m.evidence.file,line:m.evidence.line,target:m.symbol,...m.capability?{capability:m.capability}:{},...A?{fromLayer:A}:{},edgeKind:"import",message:m.message}}),p=De({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(m=>m.path),contentViolations:c,edges:o.ir.edges.filter(m=>!!m.fromLayer).map(m=>({from:m.from,fromLayer:m.fromLayer,...m.to?{to:m.to}:{},...m.toLayer?{toLayer:m.toLayer}:{},line:m.evidence.line,kind:"import",...m.typeOnly?{typeOnly:!0}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(m=>{let A=we(m.path),b=n.get(A),N=l.get(A);return{path:A,operation:"delete"in m&&m.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...N?{candidateContentHash:N.contentHash}:{}}}).sort((m,A)=>m.path.localeCompare(A.path)),y=[...a,...p.violations].map(m=>({...m,nextAction:pe(m)})),f=y.filter(m=>m.failsStrict!==!1),u=e.changeMap?Pe({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:o.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&o.valid&&f.length===0&&(u?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:Ra(t.ir.files),candidateTreeHash:Ra(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...u?{convergence:u}:{},changes:g,violations:y,warnings:p.warnings}}i(xr,"preflightChange");function Sl(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(Sl,"canonicalChangePath");function bl(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,a])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:a,message:`Base and candidate facts must use the same ${r}.`}))}i(bl,"identityViolations");function vl(e,t,n,r){let s=n.get(t),a=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...a?{candidateContentHash:a.contentHash}:{}}}i(vl,"preparedChange");function Tr(e){let t=Re(e.baseFacts),n=Re(e.candidateFacts),r=We({contract:e.contract,facts:t}),s=We({contract:e.contract,facts:n}),a=new Map(t.files.map(u=>[u.path,u])),o=new Map(n.files.map(u=>[u.path,u])),l=bl(t,n),c=new Map,p=[];for(let u of e.changes){let m=Sl(u.path);if(!m){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(m)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:m,line:1,message:`The atomic change set contains more than one operation for ${m}.`});continue}c.set(m,u);let A=a.get(m),b=o.get(m);if("delete"in u&&u.delete)A||l.push({ruleId:"DELETE_TARGET_MISSING",file:m,line:1,message:`Cannot delete ${m} because it is not present in the supplied base facts.`}),b&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:m,line:1,message:`Candidate facts still contain deleted file ${m}.`});else{let N="content"in u?u.content:"",R=X(N);b?b.contentHash!==R&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:m,line:1,expectedContentHash:R,candidateContentHash:b.contentHash,message:`Candidate facts for ${m} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:m,line:1,message:`Candidate facts do not contain changed file ${m}.`})}p.push(vl(u,m,a,o))}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([...a.keys(),...o.keys()])){if(c.has(u))continue;let m=a.get(u),A=o.get(u);m&&A&&F(m)===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?Pe({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:pe(u)})),f=y.filter(u=>u.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&f.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,m)=>u.path<m.path?-1:u.path>m.path?1:0),violations:y,warnings:s.ir.warnings}}i(Tr,"preflightResolvedChange");var Nr="1.0",Cl=12;function ka(e){return e==="enforced"||e==="advisory"?e:null}i(ka,"closedMode");function Ol(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(Ol,"uniqueArkRunRuleIds");function _l(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:ka(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(_l,"extraFromConfig");function Ea(e={}){let t=_l(e.arkRun),n=t.present?Ol(e.findings):[],r=n.slice(0,Cl),s=n.length,a=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}}),o=t.present&&t.mode==="enforced"&&fe(e.classification),l;return t.present?t.mode==="advisory"?l="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":o?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:Nr,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:r},extraMergeTeeth:o,failMergeWhen:a.failMergeWhen,note:l,mergePlanes:a}}i(Ea,"summarizeArkRunSection");function Nn(e={}){let t=e.present===!0,n=ka(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 Ia(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(", "),a=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${a}`)}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(Ia,"formatArkRunDoctorLines");function Pn(e,t){return e.slice(0,t).split(`
16
+ `).length}i(Pn,"lineOf");function Sa(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Sa,"normalizeInventoryPath");function va(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}i(va,"ownsIntent");function ba(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||va(t,["Domain"])}i(ba,"isDomainLayer");function xl(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||va(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}i(xl,"isControllerEligibleLayer");function Tl(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(Tl,"isNonPilotSurface");function Ca(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([c,p])=>[Sa(c),p])),s=new Map((e.layerContexts??[]).map(c=>[c.name,c.intentPrefixes??[]])),a=(e.layerContexts??[]).find(c=>ba(c.name,c.intentPrefixes))?.name??"DomainModel";for(let[c,p]of Object.entries(e.fileContents).sort(([g],[y])=>g.localeCompare(y))){let g=Sa(c);if(Tl(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(p.slice(0,320)))continue;let y=r.has(g),f=r.get(g),u=f?s.get(f)??[]:[],m=/(?:^|\/)(?: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),b=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(p),N=/controller|handler|resolver/i.test(c)||A||b||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!m||/@(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?!!(f&&xl(f,u)&&N):N,I=y?!!(f&&ba(f,u)):/domain|entity|aggregate|model/i.test(c),C=!y||I||R;if(R&&!m){let x=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,H;for(;(H=x.exec(p))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:c,line:Pn(p,H.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:f,suggestedArkRule:{layer:a,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let Y=/\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"),D=i((x,H)=>{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 w=H.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(H)&&(/\s/.test(w)||/[.!?…]$/.test(w))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(x))},"isUxMessageConstant");for(;(k=Y.exec(p))!==null;){let x=k[2],H=k[3]??"";!C||L(x)||D(x,H)||m&&!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:Pn(p,k.index),message:`Magic business constant ${x} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:a,invariantId:`INV-${x}`},neverMechanicalSafe:!0}))}if(I){let x=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,H;for(;(H=x.exec(p))!==null;){let w=H[2]??"",ee=(w.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(w.match(/:\s*[A-Za-z]/g)??[]).length>=2&&ee<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:c,line:Pn(p,H.index),message:`Class ${H[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:a,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 H=/this\.\w+\s*=/g,w;for(;(w=H.exec(p))!==null;){let ee=p.lastIndexOf("class ",w.index),ue=ee>=0?p.indexOf("{",ee):-1,Fe=ee>=0&&ue>=ee&&ue<w.index?p.slice(ee,ue):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(Fe))continue;let Je=p.slice(Math.max(0,w.index-200),w.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:Pn(p,w.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:f,suggestedArkRule:{layer:a,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let o=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&&o.has(c.suggestedArkRule.invariantId)||c.suggestedArkRule?.structureId&&o.has(c.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:l,frozen:(e.frozenKeys??[]).length,notAScore:!0}}i(Ca,"buildRulesInventory");function Oa(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(Oa,"inventoryToExtractionCard");var _a="1.1";var xa="1.0";var Ln="docs/diagnostics.md",Ta="1.0";function E(e,t,n,r,s,a){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...a?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(E,"entry");var vt=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."),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() to freeze \u03BE or proposeRelease() for a pattern change with blast radius, then preflight again. 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 or escalate; it never mints a pattern.","Keep ingest results as absorb/escalate only. Change \u03BE with proposeRelease + release. 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 + release, then preflight again. 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_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("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.")]),Pr=new Map(vt.map(e=>[e.ruleId,e])),Na=Object.freeze(vt.map(e=>e.ruleId));function Pa(e){return typeof e=="string"&&e.length>0&&Pr.has(e)}i(Pa,"isKnownDiagnosticCode");function La(e){return typeof e!="string"||e.length===0?!1:Pr.has(e)?!0:e.startsWith("ARKRULE_")}i(La,"isCataloguedOrArkRuleFamily");function Ct(e){if(!(typeof e!="string"||e.length===0))return Pr.get(e)}i(Ct,"getDiagnosticCatalogEntry");function Lr(e){return`#${Ct(e)?.docsAnchor??e}`}i(Lr,"diagnosticDocsFragment");function wa(e){return`${Ln}${Lr(e)}`}i(wa,"diagnosticDocsPath");function Da(){return{schemaVersion:"1.0",docsPath:Ln,codes:vt}}i(Da,"serializeDiagnosticCatalog");function Ma(e){return Ct(e)?.fix}i(Ma,"catalogFixForRuleId");function Fa(e){return Ct(e)?.why}i(Fa,"catalogWhyForRuleId");var wn="1.0",wr="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Dr=["full","subset","unavailable"],Mr=["doctor-facts","report-snapshot","none"],_t={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},$a=/^sha256:[a-f0-9]{64}$/;function Fr(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"||!$a.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(Fr,"evaluateStatusBinding");function $r(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($r,"classifyStatusWritePath");function Hr(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(Hr,"defaultHonestLabel");function jr(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(jr,"resolveStatusNextAction");function Ha(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&$a.test(e.projectId)?e.projectId:null,r=Fr({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",a=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,o=$r({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:a}),l=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Hr(o,a),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:o,host:a,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}:{}},f={schemaVersion:wn,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:y,activation:g,lastCheck:c,rules:p,nextAction:jr(e,r,g,c,p)},u=Vr(e.improvementCompass);return u&&(f.improvementCompass=u),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(f.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(f.arkRun=Nn(e.arkRun)),f}i(Ha,"buildStatusManifest");var ja=new Set(Dr),Nl=new Set(Mr);function Dn(e){let t=ja.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&Nl.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 o={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&&(o.contractHash=r),o}let s=Array.isArray(e.topResidual)?e.topResidual.filter(o=>typeof o=="string"&&o.length>0).slice(0,15):[],a={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(a.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:_t.FACTS_PARTIAL,a.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&&(a.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(a.reason=e.reason),n&&(a.factsSource=n),r&&(a.contractHash=r),a}i(Dn,"projectStatusImprovementCompass");function Va(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(Va,"unavailableStatusImprovementCompass");function Vr(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"&&ja.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(Vr,"normalizeStatusImprovementCompass");function Ka(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(Ka,"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 Ua={$schema:"https://json-schema.org/draft/2020-12/schema",$id:wr,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),Kr={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},Ur={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"},Gr={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 Br(e){return Ur[e]??e}i(Br,"improvementCompassHumanLabel");function zr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}i(zr,"smellIdOf");function qr(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}i(qr,"violationRuleId");function K(e,t,n,r){if(!n||e.evidence.some(a=>a.source===t&&a.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 Q(e,t,n){Ye.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}i(Q,"markResidual");function Ga(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`${Ur[e]} \u2014 no residual from current sensors.`}}i(Ga,"defaultOkSummary");function Ba(){return Tt.map(e=>Ye.has(e)?{id:e,status:"out-of-scope",summary:Gr[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:Ga(e),evidence:[]}:{id:e,status:"ok",summary:Ga(e),evidence:[]})}i(Ba,"createInitialImprovementCompassLenses");function Pl(e,t){for(let n of t){let r=zr(n);if(!r)continue;let s=n.outcome||n.message||void 0,o=(Array.isArray(n.evidence)?n.evidence:[])[0],l=i((g,y,f)=>{let u=e.get(g);!u||Ye.has(g)||(K(u,"designSmells",r,s),o&&K(u,"designSmells",o,r),Q(u,y,f))},"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(Pl,"mapDesignSmells");function Ll(e){return e.failsStrict===!1||e.typeOnly===!0}i(Ll,"isTypeOnlyPlacementDebt");function wl(e,t){for(let n of t){let r=qr(n);if(!r)continue;let s=n.message,a=r.toUpperCase(),o=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),Q(y,p,g))},"attach");if(Ll(n)){o("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(a==="LAYER_IMPORT_VIOLATION"||a.includes("LAYER_IMPORT")||a==="DYNAMIC_IMPORT_VIOLATION"){o("coupling","Import graph edges violate the layer contract.",l);continue}if(a.includes("CYCLE")||a==="CIRCULAR_DEPENDENCY"){o("coupling","Import cycles couple modules tightly.",l);continue}if(a.includes("PEER_ISOLATION")||a==="PEER_ISOLATION_VIOLATION"){o("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(a==="FORBIDDEN_GLOBAL"||a.startsWith("FORBIDDEN_")){o("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),o("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(a==="CAPABILITY_VIOLATION"){o("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)."}),o("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(a.startsWith("ARKRULE_")||a==="INVARIANT_UNCOVERED"){o("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."}),o("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 Dl(e,t){let n=Number(t.cycleCount)||0;if(n>0){let u=e.get("coupling");K(u,"cycles",`count:${n}`),Q(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}`),Q(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}`),Q(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 m=e.get("srp");K(m,"physicalCohesion",`findings:${s}`),Q(m,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let a=Number(t.pureOrCapabilityResidual)||0,o=Number(t.forbiddenGlobalResidual)||0;if(a>0||o>0){let u=e.get("dip");a>0&&K(u,"capability",`residual:${a}`),o>0&&K(u,"forbiddenGlobals",`residual:${o}`),Q(u,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let m=e.get("testability");a>0&&K(m,"capability",`residual:${a}`),o>0&&K(m,"forbiddenGlobals",`residual:${o}`),Q(m,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let l=Number(t.arkRulesStructureResidual)||0;if(l>0){let u=e.get("encapsulation");K(u,"arkRules",`structureResidual:${l}`),Q(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 m=e.get("domain");K(m,"arkRules",`structureResidual:${l}`),Q(m,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let u=e.get("maintainability");K(u,"designFitness","design-weak"),Q(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}`),Q(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}`),Q(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}`),Q(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"),Q(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(Dl,"mapCountsAndFlags");function za(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>zr(r).localeCompare(zr(s)));Pl(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let a=qr(r).localeCompare(qr(s));return a!==0?a:String(r.file??"").localeCompare(String(s.file??""))});wl(e,n)}Dl(e,t)}i(za,"projectImprovementCompassFacts");function qa(e){for(let t of Ce){let n=e.get(t);n.status="out-of-scope",n.summary=Gr[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(qa,"lockImprovementCompassOutOfScope");function Wa(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(Wa,"sortImprovementCompassEvidence");function Ya(e){return e.filter(n=>n.status==="residual"&&!Ye.has(n.id)).slice().sort((n,r)=>{let s=Kr[n.id]??150,a=Kr[r.id]??150;return s!==a?s-a:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}i(Ya,"finalizeImprovementCompassTopResidual");function Xa(e={}){let t=Ba(),n=new Map(t.map(s=>[s.id,s]));za(n,e),qa(n),Wa(t);let r=Ya(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let a={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(o=>({...o}))};return s.nextAction&&(a.nextAction={...s.nextAction}),a}),topResidual:r}}i(Xa,"buildImprovementCompass");function Wr(e){return e.topResidual.map(t=>Br(t))}i(Wr,"formatImprovementCompassResidualLabels");function Yr(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(Yr,"primaryImprovementCompassNextAction");function Ja(e){let t=Wr(e),n=Ce.map(a=>Br(a)),r=Yr(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(Ja,"formatImprovementCompassDoctorLines");var Za="1.0",Qa="<!-- arkgate:agent-projection:begin",Xr="<!-- arkgate:agent-projection:end -->",Jr="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"]),eo=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"]),Zr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,to=/<!--\s*arkgate:agent-projection:end\s*-->/i,Ml=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Fl=/\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 Mn(e){return String(e??"").replace(/\r\n/g,`
18
+ `)}i(Mn,"normalizeNewlines");function Xe(e){let t=Mn(e);return t.endsWith(`
19
19
  `)?t:`${t}
20
- `}i(Ye,"ensureTrailingNewline");function Hn(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(Hn,"safeVersion");function ta(e){return e==="compact"?"compact":"full"}i(ta,"resolveProfile");function Zr(e){let t=Hn(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(Zr,"buildAgentProjectionBeginMarker");function Mn(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 |
20
+ `}i(Xe,"ensureTrailingNewline");function jn(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}i(jn,"safeVersion");function no(e){return e==="compact"?"compact":"full"}i(no,"resolveProfile");function Qr(e){let t=jn(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(Qr,"buildAgentProjectionBeginMarker");function Fn(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
- ${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(Mn,"formatAgentProjectionLayers");function Xr(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(`
22
+ ${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],a=n.intentPrefixes??[],o=s.map(c=>`\`${c}\``).join(", ")||"\u2014",l=a.map(c=>`\`${c}\``).join(", ")||"\u2014";return`| ${r} | ${o} | ${l} |`}).join(`
23
+ `)}`}i(Fn,"formatAgentProjectionLayers");function es(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 a=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${a}`}).join(`
24
24
  `)}
25
25
 
26
- Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(Xr,"formatAgentProjectionCatalogShortList");function jn(e){let t=Hn(e.arkgateVersion),n=ta(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:[],p=["## ArkGate agent contract projection","",Wr,"",`- **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"?p.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)","",Mn(l),""):p.push("### Contract layers","",Mn(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)","",Xr(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`).",""),p.push("### Enforcement surfaces (authoritative)","",$n.map(m=>`- \`${m}\``).join(`
26
+ Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}i(es,"formatAgentProjectionCatalogShortList");function Vn(e){let t=jn(e.arkgateVersion),n=no(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",a=typeof e.host=="string"?e.host.trim().toLowerCase():"",o=a&&a!=="unknown"?a:null,l=Array.isArray(e.layers)?e.layers:[],c=Array.isArray(e.catalogShortList)?e.catalogShortList:[],p=["## ArkGate agent contract projection","",Jr,"",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,"- **projectionSchema:** `1.0`",`- **profile:** \`${n}\`${o?` \xB7 **host:** \`${o}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?p.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)","",Fn(l),""):p.push("### Contract layers","",Fn(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)","",es(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`).",""),p.push("### Enforcement surfaces (authoritative)","",Hn.map(g=>`- \`${g}\``).join(`
27
27
  `),""),p.join(`
28
28
  `).replace(/\n{3,}/g,`
29
29
 
30
30
  `).trimEnd()+`
31
- `}i(jn,"buildAgentProjectionBody");function na(e){let t=jn(e);return`${Zr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
32
- ${t}${Yr}
33
- `}i(na,"buildAgentProjectionBlock");function ra(e){let t=jn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Hn(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...$n],contentIdentity:wt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:ta(e.profile)}}i(ra,"buildAgentProjectionMeta");function Fn(e){let t=Dn(e??""),n=Jr.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=ea.exec(o);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=a.index,c=l+a[0].length,p=o.slice(0,l);p.startsWith(`
34
- `)&&(p=p.slice(1));let m=t.slice(r,s+c),g=o.slice(c);return{block:m,body:p,before:t.slice(0,r),after:g,beginAttrs:n[1]??""}}i(Fn,"extractAgentProjectionBlock");function Qr(e){let t=String(e??""),r=Jr.exec(t)?.[1]??t,s=Pl.exec(r),o=Ll.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}i(Qr,"parseAgentProjectionStamp");function sa(e,t){let n=Qr(e).arkgateVersion;return n?n===Hn(t):!1}i(sa,"projectionMatchesPackageVersion");function oa(e){return String(e??"").includes("non-authoritative")}i(oa,"projectionHasNonEnforcementLabel");function aa(e,t){let n=Ye(Dn(t)),s=Fn(n).body??n.replace(Jr,"").replace(ea,"").trim()+`
35
- `,o=wt(s);if(e==null||!String(e).trim())return{content:Ye(`# Ark Enforcement
31
+ `}i(Vn,"buildAgentProjectionBody");function ro(e){let t=Vn(e);return`${Qr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
32
+ ${t}${Xr}
33
+ `}i(ro,"buildAgentProjectionBlock");function so(e){let t=Vn(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:jn(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...Hn],contentIdentity:Pt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:no(e.profile)}}i(so,"buildAgentProjectionMeta");function $n(e){let t=Mn(e??""),n=Zr.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,a=t.slice(s),o=to.exec(a);if(!o)return{block:null,body:null,before:t,after:"",beginAttrs:null};let l=o.index,c=l+o[0].length,p=a.slice(0,l);p.startsWith(`
34
+ `)&&(p=p.slice(1));let g=t.slice(r,s+c),y=a.slice(c);return{block:g,body:p,before:t.slice(0,r),after:y,beginAttrs:n[1]??""}}i($n,"extractAgentProjectionBlock");function ts(e){let t=String(e??""),r=Zr.exec(t)?.[1]??t,s=Ml.exec(r),a=Fl.exec(r),o=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:a?.[1]??null,nonAuthoritative:o}}i(ts,"parseAgentProjectionStamp");function ao(e,t){let n=ts(e).arkgateVersion;return n?n===jn(t):!1}i(ao,"projectionMatchesPackageVersion");function oo(e){return String(e??"").includes("non-authoritative")}i(oo,"projectionHasNonEnforcementLabel");function io(e,t){let n=Xe(Mn(t)),s=$n(n).body??n.replace(Zr,"").replace(to,"").trim()+`
35
+ `,a=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=Dn(e),l=Fn(a);if(l.block!=null){let p=l.body??"";if(wt(p)===o)return{content:Ye(a),action:"unchanged",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0};let m=l.before.replace(/\s*$/,`
37
+ ${n}`),action:"created",previousBlock:null,contentIdentity:a,preservedOutsideBlock:!1};let o=Mn(e),l=$n(o);if(l.block!=null){let p=l.body??"";if(Pt(p)===a)return{content:Xe(o),action:"unchanged",previousBlock:l.block,contentIdentity:a,preservedOutsideBlock:!0};let g=l.before.replace(/\s*$/,`
38
38
 
39
- `),g=l.after.replace(/^\s*/,`
40
- `);return{content:Ye(`${m}${n.trimEnd()}
41
- ${g}`),action:"block-replaced",previousBlock:l.block,contentIdentity:o,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(a);if(c&&c.index!=null){let p=c.index+c[1].length,m=a.slice(0,p).replace(/\s*$/,`
39
+ `),y=l.after.replace(/^\s*/,`
40
+ `);return{content:Xe(`${g}${n.trimEnd()}
41
+ ${y}`),action:"block-replaced",previousBlock:l.block,contentIdentity:a,preservedOutsideBlock:!0}}let c=/^(#\s+[^\n]*\n)/m.exec(o);if(c&&c.index!=null){let p=c.index+c[1].length,g=o.slice(0,p).replace(/\s*$/,`
42
42
 
43
- `),g=a.slice(p).replace(/^\s*/,`
44
- `);return{content:Ye(`${m}${n.trimEnd()}
45
- ${g}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:Ye(`${n.trimEnd()}
43
+ `),y=o.slice(p).replace(/^\s*/,`
44
+ `);return{content:Xe(`${g}${n.trimEnd()}
45
+ ${y}`),action:"block-inserted",previousBlock:null,contentIdentity:a,preservedOutsideBlock:!0}}return{content:Xe(`${n.trimEnd()}
46
46
 
47
- ${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}i(aa,"mergeAgentProjectionDocument");var ia="1.0",es="templates/agent-skills",ts="templates/skills",ns="SKILL.md",Dt=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"]),rs=Dt.length,wl=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ss(e){return typeof e!="string"||e.length<1||e.length>64?!1:wl.test(e)}i(ss,"isValidAgentSkillName");function Un(e){return Dt.includes(e)}i(Un,"isArkSkillName");function os(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
47
+ ${o.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:a,preservedOutsideBlock:!0}}i(io,"mergeAgentProjectionDocument");var lo="1.0",ns="templates/agent-skills",rs="templates/skills",ss="SKILL.md",Lt=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"]),as=Lt.length,$l=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function os(e){return typeof e!="string"||e.length<1||e.length>64?!1:$l.test(e)}i(os,"isValidAgentSkillName");function Un(e){return Lt.includes(e)}i(Un,"isArkSkillName");function is(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 m=1;m<s;m+=1){let g=r[m]??"";if(g.trim()===""||g.trimStart().startsWith("#"))continue;let u=g.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!u)continue;let d=u[1],f=u[2]??"";(f.startsWith('"')&&f.endsWith('"')&&f.length>=2||f.startsWith("'")&&f.endsWith("'")&&f.length>=2)&&(f=f.slice(1,-1)),o[d]=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,p=typeof o.license=="string"&&o.license.length>0?o.license:null;return{hasFrontmatter:!0,frontmatter:{fields:o,name:l,description:c,license:p},body:a}}i(os,"parseSkillDocument");function as(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),o=os(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||!ss(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&&!Un(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(as,"validateAgentSkillDocument");function la(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(...as({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&Vn(s.content)!==Vn(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 Dt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)Un(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:rs,presentCount:r.length}}i(la,"validateAgentSkillsPackage");var Kn=/^arkgate@(\S+)\.\s/;function is(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(is,"skillDescriptionVersionPrefix");function ls(e){return String(e??"").replace(Kn,"")}i(ls,"stripSkillDescriptionVersion");function ca(e){return String(e??"").match(Kn)?.[1]??null}i(ca,"parseSkillDescriptionVersion");function da(e,t){let n=ls(e),r=typeof t=="string"?t.trim():"";return r?`${is(r)}${n}`:n}i(da,"stampSkillDescription");function Vn(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
51
- `)}i(Vn,"normalizeSkillContent");function cs(e){return`${e}/${ns}`}i(cs,"agentSkillEntryRelativePath");function ua(e){return`${es}/${cs(e)}`}i(ua,"agentSkillPackageFileRelativePath");function pa(e){return`${ts}/${e}.md`}i(pa,"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});
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 a={};for(let g=1;g<s;g+=1){let y=r[g]??"";if(y.trim()===""||y.trimStart().startsWith("#"))continue;let f=y.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!f)continue;let u=f[1],m=f[2]??"";(m.startsWith('"')&&m.endsWith('"')&&m.length>=2||m.startsWith("'")&&m.endsWith("'")&&m.length>=2)&&(m=m.slice(1,-1)),a[u]=m}let o=r.slice(s+1).join(n),l=typeof a.name=="string"&&a.name.length>0?a.name:null,c=typeof a.description=="string"&&a.description.length>0?a.description:null,p=typeof a.license=="string"&&a.license.length>0?a.license:null;return{hasFrontmatter:!0,frontmatter:{fields:a,name:l,description:c,license:p},body:o}}i(is,"parseSkillDocument");function ls(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),a=is(e.content);if(!a.hasFrontmatter||!a.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:o,description:l}=a.frontmatter,c=o??(s||void 0);return!o||!os(o)?r.push({code:"INVALID_NAME",message:`Skill name "${o??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:c}):o!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${o}" must match directory name "${s}".`,skillName:o}):t&&!Un(o)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${o}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:o}),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&&a.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:c}),r}i(ls,"validateAgentSkillDocument");function co(e){let t=[],n=new Set,r=[];for(let s of e){let a=String(s.name??"");if(n.has(a)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${a}".`,skillName:a});continue}n.add(a),r.push(a),t.push(...ls({directoryName:a,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&Kn(s.content)!==Kn(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${a}" does not match flat template templates/skills/${a}.md.`,skillName:a})}for(let s of Lt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)Un(s)||(t.some(a=>a.code==="UNKNOWN_SKILL_NAME"&&a.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:as,presentCount:r.length}}i(co,"validateAgentSkillsPackage");var Gn=/^arkgate@(\S+)\.\s/;function cs(e){let t=String(e??"").trim();return t?`arkgate@${t}. `:""}i(cs,"skillDescriptionVersionPrefix");function ds(e){return String(e??"").replace(Gn,"")}i(ds,"stripSkillDescriptionVersion");function uo(e){return String(e??"").match(Gn)?.[1]??null}i(uo,"parseSkillDescriptionVersion");function po(e,t){let n=ds(e),r=typeof t=="string"?t.trim():"";return r?`${cs(r)}${n}`:n}i(po,"stampSkillDescription");function Kn(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
51
+ `)}i(Kn,"normalizeSkillContent");function us(e){return`${e}/${ss}`}i(us,"agentSkillEntryRelativePath");function fo(e){return`${ns}/${us(e)}`}i(fo,"agentSkillPackageFileRelativePath");function mo(e){return`${rs}/${e}.md`}i(mo,"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});