arkgate 4.8.17 → 4.8.18

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.
@@ -392,7 +392,7 @@ declare function createAdapterResult(input: {
392
392
  }): CurrentAdapterResult;
393
393
 
394
394
  /** ArkGate library version — single source of truth. */
395
- declare const version = "4.8.17";
395
+ declare const version = "4.8.18";
396
396
 
397
397
  /**
398
398
  * AI Code Gate (basic).
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var on=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var vi=Object.getOwnPropertyNames;var Ci=Object.prototype.hasOwnProperty;var i=(e,t)=>on(e,"name",{value:t,configurable:!0});var _i=(e,t)=>{for(var n in t)on(e,n,{get:t[n],enumerable:!0})},Oi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vi(t))!Ci.call(e,o)&&o!==n&&on(e,o,{get:()=>t[o],enumerable:!(r=bi(t,o))||r.enumerable});return e};var xi=e=>Oi(on({},"__esModule",{value:!0}),e);var jd={};_i(jd,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>dt,AGENT_PROJECTION_BEGIN_MARKER:()=>xs,AGENT_PROJECTION_END_MARKER:()=>qt,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>ot,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Yt,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>Fs,AGENT_SKILL_ENTRY_FILENAME:()=>Hs,ANALYSIS_IR_SCHEMA_VERSION:()=>En,ARKORDER_RULE_IDS:()=>Xn,ARKORDER_TIER1_SENSOR_IDS:()=>Ca,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>as,ARKRUN_KERNEL_FACTORY_CALLEES:()=>ss,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>ya,ARKRUN_RULE_IDS:()=>Jn,ARKRUN_TIER1_SENSOR_IDS:()=>ka,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>os,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Pe,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>gi,ARK_ANALYSIS_RESULT_SCHEMA:()=>fr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>ct,ARK_CONFIG_SCHEMA:()=>yn,ARK_CONFIG_SCHEMA_VERSION:()=>ae,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ja,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Ha,ARK_FIRST_CLASS_SKILL_NAMES:()=>dr,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Bt,ARK_PROJECT_IDENTITY_SCHEMA:()=>eo,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>mr,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>Qs,ARK_RULES_SCHEMA:()=>In,ARK_RULES_SCHEMA_VERSION:()=>$o,ARK_RULE_SENSORS:()=>$r,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>ds,ARK_SKILL_CAPACITY:()=>tn,ARK_SKILL_CAPACITY_DEDICATED_DOORS:()=>js,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>pr,ARK_SKILL_NAMES:()=>rn,ARK_SKILL_NAME_COUNT:()=>Ks,ARK_SKILL_NORTH_STAR:()=>yi,ARK_SKILL_REQUIRED_SURFACES:()=>nn,ARK_SKILL_STUB_REDIRECTS:()=>ir,ARK_STATUS_MANIFEST_SCHEMA:()=>ti,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>fs,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>nr,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>Ts,DIAGNOSTIC_CATALOG:()=>Kt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ka,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>Va,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>fa,EffectiveContractError:()=>xt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>$s,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>we,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Wt,IMPROVEMENT_LENS_IDS:()=>zt,MERGE_PLANES_DUAL_STAMP:()=>ns,POLICY_DELTA_SCHEMA_VERSION:()=>xn,PROJECT_BINDING_SCHEMA:()=>yr,PROJECT_EXPECTATION_SCHEMA:()=>gr,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>kn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Oe,STATUS_COMPASS_FACTS_SOURCES:()=>gs,STATUS_COMPASS_MODES:()=>ms,STATUS_COMPASS_REASON_CODES:()=>Gt,adapterDocsCodePath:()=>pt,adapterFindingOccurrenceTargetKeys:()=>ze,adapterFindingRefFromTargetKey:()=>ut,adapterFindingTargetKey:()=>Be,agentProjectionContentIdentity:()=>Ue,agentSkillEntryRelativePath:()=>Ws,agentSkillPackageFileRelativePath:()=>Si,analyzeArchitectureConvergence:()=>He,analyzeChange:()=>Pt,analyzePolicyDelta:()=>Br,analyzeProject:()=>et,analyzeResolvedProject:()=>rt,arkRunKernelCallKind:()=>Un,arkSkillStubRedirect:()=>hi,buildAgentProjectionBeginMarker:()=>sr,buildAgentProjectionBlock:()=>Ns,buildAgentProjectionBody:()=>Qt,buildAgentProjectionMeta:()=>ws,buildArkRuleFileHints:()=>Hn,buildEffectiveArkRules:()=>bn,buildImprovementCompass:()=>li,buildRulesInventory:()=>Fa,buildStatusManifest:()=>Xa,canPromoteInvariant:()=>_n,catalogFixForRuleId:()=>Wa,catalogWhyForRuleId:()=>qa,classifyArkPolicyDelta:()=>Tn,classifyResolvedLayerCoverage:()=>Kn,classifyStatusWritePath:()=>hs,collectAnalysisConfigWarnings:()=>jt,collectEmptyAppliesToFindings:()=>$n,collectForbiddenCapabilityUses:()=>Me,composeMergePlanesHonesty:()=>Dt,createAICodeGate:()=>wr,createAdapterResult:()=>Zs,createArchitectureProfile:()=>It,createArchitectureProfileFromArkConfig:()=>Dr,createElevenLayerArkConfig:()=>Mr,createProjectId:()=>to,createProjectIdentity:()=>no,createResolvedCandidateFacts:()=>Rn,defaultHonestLabel:()=>As,demoteExtraPlaneTeethUnderClassificationFloor:()=>ma,deriveArkRuleFileHints:()=>Qr,detectArchitectureCycles:()=>Pn,deterministicHash:()=>J,diagnosticDocsFragment:()=>ps,diagnosticDocsPath:()=>Ba,effectiveContractPolicyPayload:()=>vn,elevenLayerProfile:()=>St,emptyEffectiveArkRules:()=>xe,evaluateArchitectureGraph:()=>Ve,evaluateArkOrderSensors:()=>Zn,evaluateArkRuleSensors:()=>Fn,evaluateArkRunEditorSensors:()=>is,evaluateArkRunEditorSensorsFromSource:()=>Sa,evaluateArkRunSensors:()=>Ht,evaluateInvariantCoverage:()=>Cn,evaluateStatusBinding:()=>ys,explainViolation:()=>zr,extraMergeTeethAllowed:()=>ge,extractAgentProjectionBlock:()=>en,extractArkRunDeclarationsFromSource:()=>ha,extractArkRunImportedConstructorNamesFromSource:()=>Wn,extractArkRunKernelCallsFromSource:()=>qn,extractArkRunManagedNewsFromSource:()=>Yn,extractArkRunValueImportDependenciesFromSource:()=>zn,extractClassShapesFromSource:()=>pa,extractSemanticDependencies:()=>De,flatSkillTemplateFileRelativePath:()=>Ii,formatAgentProjectionCatalogShortList:()=>or,formatAgentProjectionLayers:()=>Jt,formatArkRunDoctorLines:()=>Pa,formatImprovementCompassDoctorLines:()=>ci,formatImprovementCompassResidualLabels:()=>_s,getDiagnosticCatalogEntry:()=>Vt,inventoryToExtractionCard:()=>$a,isArkOrderRuleId:()=>es,isArkRunKernelModuleSpecifier:()=>nt,isArkRunRuleId:()=>Vn,isArkRunTransportBypassSpecifier:()=>Gn,isArkSkillName:()=>ur,isCataloguedOrArkRuleFamily:()=>Ga,isExtraPlaneFinding:()=>ts,isFirstClassArkSkillName:()=>lr,isKnownDiagnosticCode:()=>Ua,isValidAgentSkillName:()=>Vs,loadArkConfigContract:()=>Et,loadArkRulesContract:()=>Ot,loadContract:()=>wt,loadResolvedCandidateFacts:()=>Ie,mergeAgentProjectionDocument:()=>Ms,normalizeExtraMergeTeethClassification:()=>jn,normalizeSkillContent:()=>cr,normalizeStatusImprovementCompass:()=>ks,parseAgentProjectionStamp:()=>ar,parseArkConfigJson:()=>An,parseArkRulesJson:()=>Ho,parseSkillDescriptionVersion:()=>ki,parseSkillDocument:()=>Us,policyDeltaAcknowledgementMatches:()=>Nn,preflightChange:()=>ls,preflightResolvedChange:()=>cs,primaryImprovementCompassNextAction:()=>Os,projectStatusArkRun:()=>Qn,projectStatusImprovementCompass:()=>rr,projectionHasNonEnforcementLabel:()=>Ds,projectionMatchesPackageVersion:()=>Ls,resolveEffectiveContract:()=>Ko,resolveStatusNextAction:()=>Rs,resolvedFactsEvidenceRequirementsHash:()=>Qe,serializeDiagnosticCatalog:()=>za,skillDescriptionVersionPrefix:()=>Bs,stableSerialize:()=>$,stampSkillDescription:()=>Ei,statusCompassResidualIsSubsetOfDoctor:()=>ei,stripSkillDescriptionVersion:()=>zs,summarizeArkRunSection:()=>wa,toAdapterDiagnostic:()=>an,unavailableStatusImprovementCompass:()=>Qa,validateAgentSkillDocument:()=>Gs,validateAgentSkillsPackage:()=>Ai,validateSkillProductCapacity:()=>Ri,version:()=>Js});module.exports=xi(jd);var Js="4.8.17";var Ti=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ni=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,wi=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Pi(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ti.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ni.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":wi.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Pi,"classifyLayerImportKind");function Li(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Pi(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Li,"layerImportNextAction");function Di(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Di,"arkRunCallSiteName");function Mi(e){let t=Di(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Mi,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Li(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Mi(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ye,"deterministicNextAction");var ct="1.5",dt="docs/diagnostics.md",fr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function Be(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(Be,"adapterFindingTargetKey");function ze(e){let t=new Map;return e.map(n=>{let r=Be(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(ze,"adapterFindingOccurrenceTargetKeys");function ut(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(ut,"adapterFindingRefFromTargetKey");function pt(e){return`${dt}#${e}`}i(pt,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}i(x,"text");function Xs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Xs,"positiveInteger");function Fi(e,t,n){return ye({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}i(Fi,"nextActionForDiagnostic");function an(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=n??Be(e),c=ut(a);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:Xs(e.line,1),column:Xs(e.column,1)},evidence:s,nextAction:x(e.nextAction)??Fi(r,s,e),findingRef:c,targetKey:a,docsCodePath:pt(r)}}i(an,"toAdapterDiagnostic");function Zs(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(g=>({code:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=ze(s),l=ze(a),u=[...s.map((g,f)=>an(g,"error",c[f])),...a.map((g,f)=>an(g,"warning",l[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}i(Zs,"createAdapterResult");var Qs="1.0",mr="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",ln="^sha256:[a-f0-9]{64}$",gr={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:ln,description:"Project id previously returned by ark_identity or ark_manifest."}}},yr={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:ln},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},eo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:mr,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:ln},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:ln},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:gr,binding:yr}};function to(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}i(to,"createProjectId");function no(e){return{schemaVersion:"1.0",...e}}i(no,"createProjectIdentity");var Ar=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),kr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Er=Object.freeze(Object.keys(kr).sort()),hr=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Rr=Object.freeze({process:Object.freeze(["process","node:process"])});function ft(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=hr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=hr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:hr[e.slice(0,s)]??null}i(ft,"capabilityForModuleSpecifier");function _e(e,t){for(let n of t)if(Rr[n]?.includes(e))return n;return null}i(_e,"forbiddenGlobalForModuleSpecifier");function cn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=kr[r];if(o)return o}return null}i(cn,"capabilityForAmbientName");function We(e){if(e?.pure===!0)return[...Ar].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Ar.includes(r));return[...new Set(n)].sort()}i(We,"effectiveCapabilityDeny");function mt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(mt,"ambientCoveredByForbiddenGlobals");function dn(e){let t=new Set,n=new Set,r=Object.keys(kr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Rr[o]??[])t.add(`import-exact:${a}`)}for(let o of We(e)){if(t.add(`import:${o}`),o==="process")for(let s of Rr.process)t.add(`import-exact:${s}`);for(let s of r)cn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(dn,"loweredLayerCoverage");var ro=new Map;function so(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(so,"escapeLiteral");function un(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(un,"normalizeGlobSeparators");function $i(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i($i,"bracesBalanced");function Re(e){let t=ro.get(e);if(t)return t;let n=un(e),r=$i(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=so(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=so(l)}let a=new RegExp(`^${o}$`);return ro.set(e,a),a}i(Re,"globToRegExp");function Hi(e){return un(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Hi,"concreteGlobSegments");function Sr(e,t){let n=un(String(e)),r=Hi(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let u of r){let p=-1;for(let g=c;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;l=p,c=p+1}return(l+1)*1e6+r.length*1e4+o}i(Sr,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Re(a).test(n))){for(let a of s.patterns??[])if(Re(a).test(n)){let c=Sr(a,n);c>o&&(o=c,r=s.name)}}return r}i(fe,"layerForRelativePath");function oo(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(oo,"sliceIdForPath");function ji(e){let t=new Set;for(let n of e??[]){let o=un(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(ji,"inferSliceFoldersFromPatterns");function Ki(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return ji(r?.patterns)}i(Ki,"resolveSliceFolders");function ao(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(ao,"normalizeSegments");function co(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(co,"trimTrailingSlashes");var Vi=["src","app"];function Ui(e){let t=co(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Ui,"isBlanketRoot");function io(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=ao(n);for(let s of t){if(typeof s!="string"||s.length===0||Ui(s))continue;if(s.includes("*")){let l=co(s.toLowerCase());if(Re(l).test(r)||Re(`${l}/**`).test(r))return!0;continue}let a=ao(s);if(a.length===0)continue;let c=Vi.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let l of c){if(l+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[l+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(io,"pathUnderSharedRoot");function lo(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(lo,"sliceMatchesDeclaration");function Gi(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&lo(r.from,t)&&lo(r.to,n))}i(Gi,"crossSliceEdgeAllowed");function Bi(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Bi,"peerIsolationDecision");function qe(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(qe,"peerIsolationDenyExplanation");function pn(e,t,n,r){return Le(e,t,n,r)?.rule}i(pn,"findDeniedEdgeRule");function Le(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=Ki(o,t,r?.layers),l=s?oo(s,c):void 0,u=a?oo(a,c):void 0,p=Bi({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:u,fromShared:!l&&io(s,o.sharedRoots),toShared:!u&&io(a,o.sharedRoots),crossSliceAllowed:Gi(o.allowedCrossSlice,l,u)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:l,toSlice:u};continue}if(t!==n)return{rule:o}}}i(Le,"findDeniedEdgeDecision");function Ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ye,"literalText");function fo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(fo,"lineOf");function uo(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(uo,"isTypeOnlyReference");function mo(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(mo,"singleFileChecker");function Ir(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Ir,"symbolAt");function br(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Ir(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(br,"localDeclaration");function De(e,t){let n,r=[],o=i((a,c,l,u=!1)=>r.push({specifier:l,kind:c,line:fo(t,a),typeOnly:u,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",Ye(e,a.moduleSpecifier),uo(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",Ye(e,a.moduleSpecifier),uo(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",Ye(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!br(e,n??(n=mo(e,t)),t,a.expression);(c||u)&&o(a,u?"require":"dynamic-import",Ye(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(De,"extractSemanticDependencies");function zi(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Ye(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(zi,"staticAccessPath");function Wi(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(Wi,"runtimeIdentifierReference");function po(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(po,"bestForbiddenMatch");function Me(e,t,n){if(n.length===0)return[];let r=new Set(n),o=mo(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let c=i(f=>{let m=zi(e,f);if(!m)return;let d=Ir(o,m.root),A=d?s.get(d):void 0;return A?[...A,...m.segments.slice(1)]:br(e,o,t,m.root)||a.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let d=c(m.initializer),A=Ir(o,m.name);!d||!A||s.set(A,d)}let l=[],u=new Set,p=i((f,m)=>{let d=fo(t,m),A=`${f}:${m.getStart(t)}`;u.has(A)||(u.add(A),l.push({name:f,line:d,node:m}))},"flag"),g=i(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let d=c(f),A=d?po(r,d):void 0;A&&p(A,f)}else e.isIdentifier(f)&&r.has(f.text)&&Wi(e,f)&&!br(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=c(f.initializer);if(d)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?Ye(e,A.propertyName)??A.propertyName.text:A.name.text,O=po(r,[...d,b]);O&&p(O,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),l}i(Me,"collectForbiddenCapabilityUses");function vr(e,t,n){let r=[];for(let o of n?.dependencies??De(e,t)){if(o.typeOnly||!o.specifier)continue;let s=ft(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Me(e,t,Er)){let s=cn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(vr,"collectCapabilityUses");var Cr={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},_r=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Or(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Or,"resolveIntentLayer");function Fe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Fe,"looksLikeArkIntent");function gt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Fe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Cr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Cr.PUBLISH_MISSING_SOURCE}),t}i(gt,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function Je(e,t){return e.slice(0,t).split(`
1
+ "use strict";var on=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var vi=Object.getOwnPropertyNames;var Ci=Object.prototype.hasOwnProperty;var i=(e,t)=>on(e,"name",{value:t,configurable:!0});var _i=(e,t)=>{for(var n in t)on(e,n,{get:t[n],enumerable:!0})},Oi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vi(t))!Ci.call(e,o)&&o!==n&&on(e,o,{get:()=>t[o],enumerable:!(r=bi(t,o))||r.enumerable});return e};var xi=e=>Oi(on({},"__esModule",{value:!0}),e);var jd={};_i(jd,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>dt,AGENT_PROJECTION_BEGIN_MARKER:()=>xs,AGENT_PROJECTION_END_MARKER:()=>qt,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>ot,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Yt,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>Fs,AGENT_SKILL_ENTRY_FILENAME:()=>Hs,ANALYSIS_IR_SCHEMA_VERSION:()=>En,ARKORDER_RULE_IDS:()=>Xn,ARKORDER_TIER1_SENSOR_IDS:()=>Ca,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>as,ARKRUN_KERNEL_FACTORY_CALLEES:()=>ss,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>ya,ARKRUN_RULE_IDS:()=>Jn,ARKRUN_TIER1_SENSOR_IDS:()=>ka,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>os,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Pe,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>gi,ARK_ANALYSIS_RESULT_SCHEMA:()=>fr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>ct,ARK_CONFIG_SCHEMA:()=>yn,ARK_CONFIG_SCHEMA_VERSION:()=>ae,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>ja,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Ha,ARK_FIRST_CLASS_SKILL_NAMES:()=>dr,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>Bt,ARK_PROJECT_IDENTITY_SCHEMA:()=>eo,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>mr,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>Qs,ARK_RULES_SCHEMA:()=>In,ARK_RULES_SCHEMA_VERSION:()=>$o,ARK_RULE_SENSORS:()=>$r,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>ds,ARK_SKILL_CAPACITY:()=>tn,ARK_SKILL_CAPACITY_DEDICATED_DOORS:()=>js,ARK_SKILL_DESCRIPTION_VERSION_PATTERN:()=>pr,ARK_SKILL_NAMES:()=>rn,ARK_SKILL_NAME_COUNT:()=>Ks,ARK_SKILL_NORTH_STAR:()=>yi,ARK_SKILL_REQUIRED_SURFACES:()=>nn,ARK_SKILL_STUB_REDIRECTS:()=>ir,ARK_STATUS_MANIFEST_SCHEMA:()=>ti,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>fs,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>nr,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>Ts,DIAGNOSTIC_CATALOG:()=>Kt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>Ka,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>tr,DIAGNOSTIC_RULE_IDS:()=>Va,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>fa,EffectiveContractError:()=>xt,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>$s,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>we,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>Wt,IMPROVEMENT_LENS_IDS:()=>zt,MERGE_PLANES_DUAL_STAMP:()=>ns,POLICY_DELTA_SCHEMA_VERSION:()=>xn,PROJECT_BINDING_SCHEMA:()=>yr,PROJECT_EXPECTATION_SCHEMA:()=>gr,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>kn,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Oe,STATUS_COMPASS_FACTS_SOURCES:()=>gs,STATUS_COMPASS_MODES:()=>ms,STATUS_COMPASS_REASON_CODES:()=>Gt,adapterDocsCodePath:()=>pt,adapterFindingOccurrenceTargetKeys:()=>ze,adapterFindingRefFromTargetKey:()=>ut,adapterFindingTargetKey:()=>Be,agentProjectionContentIdentity:()=>Ue,agentSkillEntryRelativePath:()=>Ws,agentSkillPackageFileRelativePath:()=>Si,analyzeArchitectureConvergence:()=>He,analyzeChange:()=>Pt,analyzePolicyDelta:()=>Br,analyzeProject:()=>et,analyzeResolvedProject:()=>rt,arkRunKernelCallKind:()=>Un,arkSkillStubRedirect:()=>hi,buildAgentProjectionBeginMarker:()=>sr,buildAgentProjectionBlock:()=>Ns,buildAgentProjectionBody:()=>Qt,buildAgentProjectionMeta:()=>ws,buildArkRuleFileHints:()=>Hn,buildEffectiveArkRules:()=>bn,buildImprovementCompass:()=>li,buildRulesInventory:()=>Fa,buildStatusManifest:()=>Xa,canPromoteInvariant:()=>_n,catalogFixForRuleId:()=>Wa,catalogWhyForRuleId:()=>qa,classifyArkPolicyDelta:()=>Tn,classifyResolvedLayerCoverage:()=>Kn,classifyStatusWritePath:()=>hs,collectAnalysisConfigWarnings:()=>jt,collectEmptyAppliesToFindings:()=>$n,collectForbiddenCapabilityUses:()=>Me,composeMergePlanesHonesty:()=>Dt,createAICodeGate:()=>wr,createAdapterResult:()=>Zs,createArchitectureProfile:()=>It,createArchitectureProfileFromArkConfig:()=>Dr,createElevenLayerArkConfig:()=>Mr,createProjectId:()=>to,createProjectIdentity:()=>no,createResolvedCandidateFacts:()=>Rn,defaultHonestLabel:()=>As,demoteExtraPlaneTeethUnderClassificationFloor:()=>ma,deriveArkRuleFileHints:()=>Qr,detectArchitectureCycles:()=>Pn,deterministicHash:()=>J,diagnosticDocsFragment:()=>ps,diagnosticDocsPath:()=>Ba,effectiveContractPolicyPayload:()=>vn,elevenLayerProfile:()=>St,emptyEffectiveArkRules:()=>xe,evaluateArchitectureGraph:()=>Ve,evaluateArkOrderSensors:()=>Zn,evaluateArkRuleSensors:()=>Fn,evaluateArkRunEditorSensors:()=>is,evaluateArkRunEditorSensorsFromSource:()=>Sa,evaluateArkRunSensors:()=>Ht,evaluateInvariantCoverage:()=>Cn,evaluateStatusBinding:()=>ys,explainViolation:()=>zr,extraMergeTeethAllowed:()=>ge,extractAgentProjectionBlock:()=>en,extractArkRunDeclarationsFromSource:()=>ha,extractArkRunImportedConstructorNamesFromSource:()=>Wn,extractArkRunKernelCallsFromSource:()=>qn,extractArkRunManagedNewsFromSource:()=>Yn,extractArkRunValueImportDependenciesFromSource:()=>zn,extractClassShapesFromSource:()=>pa,extractSemanticDependencies:()=>De,flatSkillTemplateFileRelativePath:()=>Ii,formatAgentProjectionCatalogShortList:()=>or,formatAgentProjectionLayers:()=>Jt,formatArkRunDoctorLines:()=>Pa,formatImprovementCompassDoctorLines:()=>ci,formatImprovementCompassResidualLabels:()=>_s,getDiagnosticCatalogEntry:()=>Vt,inventoryToExtractionCard:()=>$a,isArkOrderRuleId:()=>es,isArkRunKernelModuleSpecifier:()=>nt,isArkRunRuleId:()=>Vn,isArkRunTransportBypassSpecifier:()=>Gn,isArkSkillName:()=>ur,isCataloguedOrArkRuleFamily:()=>Ga,isExtraPlaneFinding:()=>ts,isFirstClassArkSkillName:()=>lr,isKnownDiagnosticCode:()=>Ua,isValidAgentSkillName:()=>Vs,loadArkConfigContract:()=>Et,loadArkRulesContract:()=>Ot,loadContract:()=>wt,loadResolvedCandidateFacts:()=>Ie,mergeAgentProjectionDocument:()=>Ms,normalizeExtraMergeTeethClassification:()=>jn,normalizeSkillContent:()=>cr,normalizeStatusImprovementCompass:()=>ks,parseAgentProjectionStamp:()=>ar,parseArkConfigJson:()=>An,parseArkRulesJson:()=>Ho,parseSkillDescriptionVersion:()=>ki,parseSkillDocument:()=>Us,policyDeltaAcknowledgementMatches:()=>Nn,preflightChange:()=>ls,preflightResolvedChange:()=>cs,primaryImprovementCompassNextAction:()=>Os,projectStatusArkRun:()=>Qn,projectStatusImprovementCompass:()=>rr,projectionHasNonEnforcementLabel:()=>Ds,projectionMatchesPackageVersion:()=>Ls,resolveEffectiveContract:()=>Ko,resolveStatusNextAction:()=>Rs,resolvedFactsEvidenceRequirementsHash:()=>Qe,serializeDiagnosticCatalog:()=>za,skillDescriptionVersionPrefix:()=>Bs,stableSerialize:()=>$,stampSkillDescription:()=>Ei,statusCompassResidualIsSubsetOfDoctor:()=>ei,stripSkillDescriptionVersion:()=>zs,summarizeArkRunSection:()=>wa,toAdapterDiagnostic:()=>an,unavailableStatusImprovementCompass:()=>Qa,validateAgentSkillDocument:()=>Gs,validateAgentSkillsPackage:()=>Ai,validateSkillProductCapacity:()=>Ri,version:()=>Js});module.exports=xi(jd);var Js="4.8.18";var Ti=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ni=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,wi=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Pi(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Ti.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ni.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":wi.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(Pi,"classifyLayerImportKind");function Li(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Pi(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Li,"layerImportNextAction");function Di(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Di,"arkRunCallSiteName");function Mi(e){let t=Di(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Mi,"arkRunNextAction");function ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Li(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Mi(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ye,"deterministicNextAction");var ct="1.5",dt="docs/diagnostics.md",fr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function Be(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(Be,"adapterFindingTargetKey");function ze(e){let t=new Map;return e.map(n=>{let r=Be(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(ze,"adapterFindingOccurrenceTargetKeys");function ut(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(ut,"adapterFindingRefFromTargetKey");function pt(e){return`${dt}#${e}`}i(pt,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}i(x,"text");function Xs(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(Xs,"positiveInteger");function Fi(e,t,n){return ye({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}i(Fi,"nextActionForDiagnostic");function an(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=n??Be(e),c=ut(a);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:Xs(e.line,1),column:Xs(e.column,1)},evidence:s,nextAction:x(e.nextAction)??Fi(r,s,e),findingRef:c,targetKey:a,docsCodePath:pt(r)}}i(an,"toAdapterDiagnostic");function Zs(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(g=>({code:x(g.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(g.message)??`Analysis ${t}: required evidence is incomplete.`,...x(g.file)?{file:x(g.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let g of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[g])throw new Error(`${g} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],c=ze(s),l=ze(a),u=[...s.map((g,f)=>an(g,"error",c[f])),...a.map((g,f)=>an(g,"warning",l[f]))],p={schemaVersion:"1.5",completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...p,mode:n,valid:!1,completeness:t,...o};let g={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...g}:{...p,mode:n,valid:!1,completeness:t,...g}}return t==="complete"?{...p,mode:n,valid:e.valid,completeness:t,...o}:{...p,mode:n,valid:!1,completeness:t,...o}}i(Zs,"createAdapterResult");var Qs="1.0",mr="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",ln="^sha256:[a-f0-9]{64}$",gr={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:ln,description:"Project id previously returned by ark_identity or ark_manifest."}}},yr={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:ln},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},eo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:mr,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:ln},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:ln},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:gr,binding:yr}};function to(e,t,n){if(!e||!t)throw new Error("Project identity requires resolvedRoot and resolvedConfigPath.");let r=n(JSON.stringify({resolvedRoot:e,resolvedConfigPath:t})).toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error("Project identity hash adapter must return 64 hexadecimal SHA-256 characters.");return`sha256:${r}`}i(to,"createProjectId");function no(e){return{schemaVersion:"1.0",...e}}i(no,"createProjectIdentity");var Ar=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),kr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Er=Object.freeze(Object.keys(kr).sort()),hr=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Rr=Object.freeze({process:Object.freeze(["process","node:process"])});function ft(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=hr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=hr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:hr[e.slice(0,s)]??null}i(ft,"capabilityForModuleSpecifier");function _e(e,t){for(let n of t)if(Rr[n]?.includes(e))return n;return null}i(_e,"forbiddenGlobalForModuleSpecifier");function cn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=kr[r];if(o)return o}return null}i(cn,"capabilityForAmbientName");function We(e){if(e?.pure===!0)return[...Ar].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Ar.includes(r));return[...new Set(n)].sort()}i(We,"effectiveCapabilityDeny");function mt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(mt,"ambientCoveredByForbiddenGlobals");function dn(e){let t=new Set,n=new Set,r=Object.keys(kr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Rr[o]??[])t.add(`import-exact:${a}`)}for(let o of We(e)){if(t.add(`import:${o}`),o==="process")for(let s of Rr.process)t.add(`import-exact:${s}`);for(let s of r)cn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(dn,"loweredLayerCoverage");var ro=new Map;function so(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(so,"escapeLiteral");function un(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(un,"normalizeGlobSeparators");function $i(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i($i,"bracesBalanced");function Re(e){let t=ro.get(e);if(t)return t;let n=un(e),r=$i(n),o="",s=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=so(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",s+=1):l==="}"&&r&&s>0?(o+=")",s-=1):l===","&&r&&s>0?o+="|":o+=so(l)}let a=new RegExp(`^${o}$`);return ro.set(e,a),a}i(Re,"globToRegExp");function Hi(e){return un(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(Hi,"concreteGlobSegments");function Sr(e,t){let n=un(String(e)),r=Hi(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let c=0,l=-1;for(let u of r){let p=-1;for(let g=c;g<a.length;g+=1)if(a[g]===u){p=g;break}if(p<0)return s;l=p,c=p+1}return(l+1)*1e6+r.length*1e4+o}i(Sr,"patternSpecificity");function fe(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Re(a).test(n))){for(let a of s.patterns??[])if(Re(a).test(n)){let c=Sr(a,n);c>o&&(o=c,r=s.name)}}return r}i(fe,"layerForRelativePath");function oo(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(oo,"sliceIdForPath");function ji(e){let t=new Set;for(let n of e??[]){let o=un(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let c=o[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}i(ji,"inferSliceFoldersFromPatterns");function Ki(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return ji(r?.patterns)}i(Ki,"resolveSliceFolders");function ao(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(ao,"normalizeSegments");function co(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(co,"trimTrailingSlashes");var Vi=["src","app"];function Ui(e){let t=co(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Ui,"isBlanketRoot");function io(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=ao(n);for(let s of t){if(typeof s!="string"||s.length===0||Ui(s))continue;if(s.includes("*")){let l=co(s.toLowerCase());if(Re(l).test(r)||Re(`${l}/**`).test(r))return!0;continue}let a=ao(s);if(a.length===0)continue;let c=Vi.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let l of c){if(l+a.length>o.length)continue;let u=!0;for(let p=0;p<a.length;p+=1)if(o[l+p]!==a[p]){u=!1;break}if(u)return!0}}return!1}i(io,"pathUnderSharedRoot");function lo(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(lo,"sliceMatchesDeclaration");function Gi(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&lo(r.from,t)&&lo(r.to,n))}i(Gi,"crossSliceEdgeAllowed");function Bi(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Bi,"peerIsolationDecision");function qe(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(qe,"peerIsolationDenyExplanation");function pn(e,t,n,r){return Le(e,t,n,r)?.rule}i(pn,"findDeniedEdgeRule");function Le(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,c=Ki(o,t,r?.layers),l=s?oo(s,c):void 0,u=a?oo(a,c):void 0,p=Bi({fromPath:s,toPath:a,folderCount:c.length,fromSlice:l,toSlice:u,fromShared:!l&&io(s,o.sharedRoots),toShared:!u&&io(a,o.sharedRoots),crossSliceAllowed:Gi(o.allowedCrossSlice,l,u)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:l,toSlice:u};continue}if(t!==n)return{rule:o}}}i(Le,"findDeniedEdgeDecision");function Ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ye,"literalText");function fo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(fo,"lineOf");function uo(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(uo,"isTypeOnlyReference");function mo(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(mo,"singleFileChecker");function Ir(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Ir,"symbolAt");function br(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Ir(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(br,"localDeclaration");function De(e,t){let n,r=[],o=i((a,c,l,u=!1)=>r.push({specifier:l,kind:c,line:fo(t,a),typeOnly:u,unresolved:l===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",Ye(e,a.moduleSpecifier),uo(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",Ye(e,a.moduleSpecifier),uo(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",Ye(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!br(e,n??(n=mo(e,t)),t,a.expression);(c||u)&&o(a,u?"require":"dynamic-import",Ye(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(De,"extractSemanticDependencies");function zi(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Ye(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(zi,"staticAccessPath");function Wi(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(Wi,"runtimeIdentifierReference");function po(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(po,"bestForbiddenMatch");function Me(e,t,n){if(n.length===0)return[];let r=new Set(n),o=mo(e,t),s=new Map,a=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations)e.isIdentifier(m.name)&&a.add(m.name.text);let c=i(f=>{let m=zi(e,f);if(!m)return;let d=Ir(o,m.root),A=d?s.get(d):void 0;return A?[...A,...m.segments.slice(1)]:br(e,o,t,m.root)||a.has(m.root.text)?void 0:m.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let m of f.declarationList.declarations){if(!m.initializer||!e.isIdentifier(m.name))continue;let d=c(m.initializer),A=Ir(o,m.name);!d||!A||s.set(A,d)}let l=[],u=new Set,p=i((f,m)=>{let d=fo(t,m),A=`${f}:${m.getStart(t)}`;u.has(A)||(u.add(A),l.push({name:f,line:d,node:m}))},"flag"),g=i(f=>{let m=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!m){let d=c(f),A=d?po(r,d):void 0;A&&p(A,f)}else e.isIdentifier(f)&&r.has(f.text)&&Wi(e,f)&&!br(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=c(f.initializer);if(d)for(let A of f.name.elements){if(!e.isIdentifier(A.name))continue;let b=A.propertyName?Ye(e,A.propertyName)??A.propertyName.text:A.name.text,O=po(r,[...d,b]);O&&p(O,f.initializer)}}e.forEachChild(f,g)},"visit");return g(t),l}i(Me,"collectForbiddenCapabilityUses");function vr(e,t,n){let r=[];for(let o of n?.dependencies??De(e,t)){if(o.typeOnly||!o.specifier)continue;let s=ft(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Me(e,t,Er)){let s=cn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(vr,"collectCapabilityUses");var Cr={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},_r=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Or(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Or,"resolveIntentLayer");function Fe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Fe,"looksLikeArkIntent");function gt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Fe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Cr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Cr.PUBLISH_MISSING_SOURCE}),t}i(gt,"classifyPublishFacts");function W(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(W,"violation");function Je(e,t){return e.slice(0,t).split(`
2
2
  `).length}i(Je,"lineOf");var qi=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Yi(e,t){return e.index+e[0].indexOf(t)}i(Yi,"captureIndex");function Ji(e){let t=[],n=new Set,r=i((c,l)=>{!c||n.has(l)||(n.add(l),t.push({value:c,index:l}))},"push"),o=i(c=>{c.lastIndex=0;let l;for(;(l=c.exec(e))!==null;){let u=l[1];u&&r(u,Yi(l,u))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let c=a[1]??"",l=a.index+a[0].indexOf(c),u=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,p;for(;(p=u.exec(c))!==null;){let g=p[1];g&&r(g,l+p.index+p[0].indexOf(g))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((c,l)=>c.index-l.index)}i(Ji,"extractQuotedStrings");function Xi(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:c})}}return t.sort((r,o)=>r.index-o.index)}i(Xi,"extractModuleSpecifiers");function Zi(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}i(Zi,"isSyntaxWrapper");function xr(e,t){let n=t;for(;n?.parent&&Zi(e,n.parent);)n=n.parent;return n}i(xr,"unwrapWrappers");function Tr(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}i(Tr,"callCalleeName");function Qi(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=xr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Tr(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Nr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let c=xr(e,s).parent;return!!(c&&e.isCallExpression(c)&&Tr(e,c)==="publish")}return!1}i(Qi,"isPublishMetadataSource");function go(e,t){let n=xr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Tr(e,r);if(o&&qi.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return go(e,r);if(e.isPropertyAssignment(r)){let o=Nr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Qi(e,r))return!0}return!1}i(go,"isDeclaredIntentSite");function el(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&go(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(el,"extractQuotedStringsAst");function tl(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}i(tl,"hasInfrastructureToken");function nl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(nl,"isKnownInfrastructurePackage");function rl(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(rl,"layerHasInfrastructureRole");function ht(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(ht,"tsStringLiteralText");function Nr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Nr,"tsPropertyName");function yo(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Nr(e,r.name)===n)}i(yo,"tsObjectProperty");function At(e,t,n){return yo(e,t,n)!==void 0}i(At,"tsObjectHasProperty");function yt(e,t,n){let r=yo(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(yt,"tsObjectPropertyValue");function sl(e,t){let n=yt(e,t,"metadata");return At(e,n,"source")}i(sl,"tsObjectHasMetadataSource");function ho(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?ho(e,t.name):!1:!1}i(ho,"tsLooksLikeIntentCreatorExpression");function ol(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}i(ol,"tsIsPublishCall");function al(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=ht(e,n);return r!==void 0&&Fe(r)||At(e,n,"intent")||ho(e,n)}i(al,"tsIsArkPublishCandidate");function il(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return sl(e,n)||At(e,r,"source")||At(e,o,"source")}i(il,"tsPublishHasSource");function ll(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=yt(e,n,"metadata");return ht(e,yt(e,s,"source"))??ht(e,yt(e,r,"source"))??ht(e,yt(e,o,"source"))}i(ll,"tsPublishSourceLiteral");function cl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,l=[],u=i(g=>o.getLineAndCharacterOfPosition(g.getStart(o)).line+1,"lineForNode"),p=i(g=>{if(ol(e,g)){let f=g.arguments[0],m=ht(e,f);for(let A of gt({publishCall:!0,rawIntentName:m,objectHasIntent:At(e,f,"intent"),arkPublishCandidate:al(e,g),hasSource:il(e,g)}))l.push(W(A.ruleId,A.message,{line:u(g),filePath:a}));let d=ll(e,g);if(r&&c&&d&&Fe(d)){let A=r.resolveLayer(d);A&&A!==c&&l.push(W("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${A}, but the target file is classified as ${c}.`,{line:u(g),filePath:a,target:d,fromLayer:c,toLayer:A}))}}e.forEachChild(g,p)},"visit");return p(o),l}i(cl,"analyzePublishAst");function wr(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],l=a,u=l?.filePath,p=l?.layer,g=e.typescript,f=g?g.createSourceFile(u??"generated.ts",s,g.ScriptTarget.Latest,!0):void 0,m=f?De(e.typescript,f):void 0,d=m?m.filter(k=>k.specifier!==void 0).map(k=>({value:k.specifier,index:k.node.getStart(f),kind:k.kind,typeOnly:k.typeOnly})):Xi(s),A=e.typescript?el(e.typescript,s):Ji(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let k of m?.filter(({unresolved:I})=>I)??[]){let I=k.kind==="require";c.push(W(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:k.line,filePath:u}))}let b=p!==void 0&&(r.has(p)||rl(p)),O=p!==void 0?` If "${p}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let k of n)if(k instanceof RegExp){k.lastIndex=0;let I=k.exec(s);k.lastIndex=0,I&&c.push(W("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${k}`,{line:I.index===void 0?void 0:Je(s,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+O}))}else s.includes(k)&&c.push(W("FORBIDDEN_SUBSTRING",`Forbidden substring: ${k}`,{line:Je(s,s.indexOf(k)),filePath:u}));for(let k of d){let I=e.resolveImportTarget?.(k.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(k.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:p,relPath:void 0}:void 0):void 0,L=I?.layer;if(L&&p){let E=pn(e.architectureProfile?.rules,p,L,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(E){if(k.typeOnly&&!E.peerIsolation)continue;let P=!!E.peerIsolation;c.push(W("LAYER_IMPORT_VIOLATION",E.message??(P?`Layer "${p}" must not import across slices into "${L}".`:`Layer "${p}" must not import "${L}".`),{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,fromLayer:p,toLayer:L,suggestion:P?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:k.kind,peerIsolation:P,...k.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||k.typeOnly||!tl(k.value)&&!nl(k.value)||c.push(W("FORBIDDEN_IMPORT",`Forbidden ${k.kind} target: "${k.value}".`,{line:Je(s,k.index),source:k.value,target:k.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+O,details:{importKind:k.kind}}))}if(e.policies)for(let k of e.policies){let I=k.check({source:s,context:a});if(I!==!0)if(Array.isArray(I))for(let C of I)c.push(W("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${k.name}".`}));else I===!1?c.push(W("POLICY_VIOLATION",`Policy ${k.name} failed on generated code`)):c.push(W("POLICY_VIOLATION",I.message))}if(o&&t.size>0)for(let k of A)Fe(k.value)&&!t.has(k.value)&&c.push(W("UNKNOWN_INTENT",`Unknown intent reference: "${k.value}"`,{line:Je(s,k.index),filePath:u,target:k.value,suggestion:`Register intent "${k.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&p)for(let k of A){if(!Fe(k.value))continue;let I=e.architectureProfile.resolveLayer(k.value);if(!I)continue;let C=Le(e.architectureProfile.rules,p,I,{fromPath:typeof u=="string"?u:void 0,layers:e.architectureLayers});if(C){let L=C.rule.peerIsolation?qe(C.peerIsolationReason??"cross-slice",{fromPath:typeof u=="string"?u:void 0,fromSlice:C.fromSlice,toSlice:C.toSlice}):void 0,E=`Layer "${p}" must not reference "${I}" through "${k.value}".`,P=L&&C.peerIsolationReason!=="cross-slice"?`${E} ${L}`:C.rule.message?L?`${C.rule.message} (${L})`:C.rule.message:E;c.push(W("LAYER_REFERENCE_VIOLATION",P,{line:Je(s,k.index),filePath:u,target:k.value,fromLayer:p,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C.rule,peerIsolationReason:C.peerIsolationReason}}))}}if(e.extensions)for(let k of e.extensions)try{let I=k.analyze(s,a);c.push(...I)}catch(I){c.push(W("EXTENSION_ERROR",`Extension "${k.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&f&&p&&e.forbiddenGlobals?.[p]?.length)try{let k=e.forbiddenGlobals[p];c.push(...Me(e.typescript,f,k).map(I=>W("FORBIDDEN_GLOBAL",`${p} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:p,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of m??[]){if(I.typeOnly||!I.specifier)continue;let C=_e(I.specifier,k);C&&c.push(W("FORBIDDEN_GLOBAL",`${p} must not use module "${I.specifier}" because it is the import form of forbidden global "${C}".`,{line:I.line,filePath:u,source:I.specifier,target:I.specifier,fromLayer:p,details:{importKind:I.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript&&f&&p&&e.capabilityWalls?.[p]?.length)try{let k=new Set(e.capabilityWalls[p]),I=e.forbiddenGlobals?.[p]??[];for(let C of vr(e.typescript,f))k.has(C.capability)&&(C.source==="ambient-global"&&mt(C.symbol,I)||C.source==="import-based"&&_e(C.symbol,I)||c.push(W("CAPABILITY_VIOLATION",C.source==="import-based"?`${p} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${p} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:p,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}if(e.typescript)try{c.push(...cl(e.typescript,s,a,e.architectureProfile))}catch(k){c.push(W("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${k instanceof Error?k.message:String(k)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}i(wr,"createAICodeGate");var $e={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ao={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...$e,default:[]},kernelRoots:{...$e},managedLayers:{...$e,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ro={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...$e,default:[]},managedLayers:{...$e,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...$e,default:[]},appliesTo:{...$e,default:[]}}};function Rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Rt,"isObject");function ko(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Rt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(ko,"declaredLayerNames");function Eo(e){if(!Rt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Eo,"defaultedArkRun");function So(e){if(!Rt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(So,"defaultedArkOrder");function Io(e,t){let n=e.arkRun;if(n===void 0||!Rt(n))return;let r=ko(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(Io,"validateArkRunExtra");function bo(e,t){let n=e.arkOrder;if(n===void 0||!Rt(n))return;let r=ko(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,a)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(bo,"validateArkOrderExtra");function fn(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(fn,"normalizeStewardId");function vo(e){let t=fn(e);return!t||Pr(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(vo,"isGitHubHandle");function dl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Pr(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(dl,"isGitHubEmail");function ul(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&vo(t[1])?fn(t[1]):null}i(ul,"githubHandleFromEmail");function Co(e){let t=ul(e);if(t)return t;let n=fn(e);return!n||Pr(n)?null:vo(n)||dl(n)?n:null}i(Co,"canonicalStewardId");var pl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Pr(e){let t=fn(e);return!t||pl.test(t)}i(Pr,"isAutomationAuthor");var ae="1.3",fl=["public","auth","admin","internal"];function ml(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(ml,"isFutureHouseLayer");function gl(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}i(gl,"layerOwnersList");function Oo(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!ml(t)&&!gl(t)).map(t=>t.name)}i(Oo,"layersMissingRequiredOwners");function xo(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(xo,"missingLayerOwnersNextAction");var gn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",_o=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],yl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function hl(){let e=[];for(let t of _o)for(let n of _o)t===n||yl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(hl,"createDefaultRules");var hn=hl(),Lr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},yn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:gn,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:gn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ae,default:ae},name:{type:"string",minLength:1},include:{...le,minItems:1,default:["src"]},exclude:{...le,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:hn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...le,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...le,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...le,minItems:1},exclude:le,intentPrefixes:le,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...fl]},owners:{...le,minItems:1},forbiddenGlobals:le,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...le,minItems:1},sharedRoots:{...le,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...le,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...le,minItems:1}}},arkRun:Ao,arkOrder:Ro}},ke=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
4
  `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function To(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(To,"isObject");function mn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(mn,"propertyPath");function Xe(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Xe,"valueType");function Al(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Al,"resolveSchemaRef");function kt(e,t,n,r,o){if(t.$ref){let s=Al(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}kt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!To(e)){o.push({path:n,message:`must be an object; received ${Xe(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:mn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||o.push({path:mn(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in s||kt(e[c],a,mn(n,c),r,o)}for(let[a,c]of Object.entries(s))e[a]!==void 0&&kt(e[a],c,mn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Xe(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>kt(s,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${Xe(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${Xe(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${Xe(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}i(kt,"validateNode");function Rl(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((a,c)=>{typeof a=="string"&&(Co(a)||t.push({path:`$.layers[${o}].owners[${c}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(Rl,"validateLayerOwners");function kl(e){let t={...e,$schema:e.$schema===void 0?gn:e.$schema,schemaVersion:e.schemaVersion===void 0?ae:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?hn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Eo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=So(e.arkOrder)),t}i(kl,"defaultedConfig");function El(e){return e===ae?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(El,"migratedFromOf");function Sl(){let e=new Set([ae]);for(let t of Lr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Sl,"knownInputVersions");function Il(e,t="ark.config.json"){if(!To(e))throw new ke(t,[{path:"$",message:`must be an object; received ${Xe(e)}`}]);let n=Sl(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ae}`}]);if(r!=="unversioned"&&!n.has(r))throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);let o=r,s={...e},a=0;for(;o!==ae&&a<Lr.length+1;){a+=1;let c=Lr.find(l=>l.from===o);if(!c)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ae}`}]);o=c.to,s.schemaVersion=o}if(o!==ae)throw new ke(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ae}`}]);return{candidate:kl(s),migratedFrom:El(r)}}i(Il,"migrateArkConfig");function Et(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Il(e,t),o=[];if(kt(n,yn,"$",yn,o),Io(n,o),bo(n,o),Rl(n,o),o.length>0)throw new ke(t,o);return{config:n,migratedFrom:r}}i(Et,"loadArkConfigContract");function An(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ke(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Et(n,t)}i(An,"parseArkConfigJson");function No(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:gn,schemaVersion:ae};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}i(No,"withArkConfigMetadata");function bl(e){return e.endsWith(".")?e:`${e}.`}i(bl,"normalizePrefix");function vl(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}i(vl,"byLongestPrefix");function It(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(bl)})),n=[...t].sort(vl),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(a=>o.startsWith(a)))?.name}}}i(It,"createArchitectureProfile");function Dr(e,t={}){return It({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:e.rules??[]})}i(Dr,"createArchitectureProfileFromArkConfig");var Cl=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],St=It({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Cl,rules:hn.map(e=>({...e}))}),_l={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Mr(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return No({include:e.include??[t],layers:St.layers.map(o=>({name:o.name,patterns:(_l[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...St.rules]})}i(Mr,"createElevenLayerArkConfig");function J(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(J,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$(t[n])}`).join(",")}}`}i($,"stableSerialize");var Oe="1.2";var wo=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=$(e),r=$(t);return n<r?-1:n>r?1:0}i(q,"compareCanonical");function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(Z,"sortedUnique");function Qe(e){let t={schemaVersion:"1.2",include:Z(e.include??[]),exclude:Z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:Z(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:Z(n.patterns??[]),exclude:Z(n.exclude??[]),forbiddenGlobals:Z(n.forbiddenGlobals??[]),intentPrefixes:Z(n.intentPrefixes??[]),capabilityDeny:Z(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(q),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:Z(e.arkRun.compositionRoots),managedLayers:Z(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return J($(t))}i(Qe,"resolvedFactsEvidenceRequirementsHash");function Ol(e){let t=e.completenessReasons.map(E=>({code:E.code,message:E.message,...E.file?{file:E.file}:{}})).sort(q),n=e.files.map(E=>({...E,typeOnlyExportNames:Z(E.typeOnlyExportNames)})).sort((E,P)=>E.path<P.path?-1:E.path>P.path?1:0),r=e.dependencies.map(E=>({...E,...E.namedBindings?{namedBindings:Z(E.namedBindings)}:{}})).sort(q),o=e.capabilityUses.map(E=>({...E})).sort(q),s=e.ambientUses.map(E=>({...E})).sort(q),a=e.publishCalls.map(E=>({...E})).sort(q),c=e.intentReferences.map(E=>({...E})).sort(q),l=e.safetyUses.map(E=>({...E})).sort(q),u=(e.classShapes??[]).map(E=>({...E,mutatingMethods:[...E.mutatingMethods??[]].map(P=>({...P}))})).sort(q),p=(e.arkRunKernelCalls??[]).map(E=>({...E})).sort(q),g=(e.arkRunManagedNews??[]).map(E=>({...E})).sort(q),f=(e.arkRunCompositionRootHits??[]).map(E=>({...E})).sort(q),m=(e.arkRunDeclarations??[]).map(E=>({...E,uses:Z(E.uses),reactsTo:Z(E.reactsTo),raises:Z(E.raises),sends:Z(E.sends)})).sort(q),d=(e.arkOrderPlaneCalls??[]).map(E=>({...E})).sort(q),A=(e.arkOrderGenericUpdates??[]).map(E=>({...E})).sort(q),b=(e.arkOrderRootHits??[]).map(E=>({...E})).sort(q),O=(e.arkOrderXiFieldWrites??[]).map(E=>({...E})).sort(q),k=(e.arkOrderIngestWritesXi??[]).map(E=>({...E})).sort(q),I=(e.arkOrderReleaseKeyCounts??[]).map(E=>({...E})).sort(q),C=e.files.map(({path:E,contentHash:P})=>({path:E,contentHash:P})).sort((E,P)=>E.path<P.path?-1:E.path>P.path?1:0),L=J($(C));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:L,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:l,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:g,arkRunCompositionRootHits:f,arkRunDeclarations:m,arkOrderPlaneCalls:d,arkOrderGenericUpdates:A,arkOrderRootHits:b,arkOrderXiFieldWrites:O,arkOrderIngestWritesXi:k,arkOrderReleaseKeyCounts:I}}i(Ol,"canonicalResolvedFactsInput");function Po(e){let t=Ol(e);return{...t,factsHash:J($(t))}}i(Po,"createCanonicalResolvedCandidateFacts");function Rn(e){return Po(Do(H(e,"$"),!1))}i(Rn,"createResolvedCandidateFacts");function H(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(H,"asRecord");function j(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(j,"assertOnlyKeys");function F(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(F,"requiredText");function Ee(e,t,n){if(e[t]!==void 0)return F(e,t,n)}i(Ee,"optionalText");function U(e,t,n){let r=F(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let c of o.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(U,"requiredProjectPath");function G(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(G,"requiredBoolean");function Lo(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(Lo,"requiredInteger");function te(e,t,n){let r=Lo(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(te,"requiredPositiveInteger");function B(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(B,"requiredArray");function Se(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Se,"enumValue");function Ze(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(Ze,"parseStringArray");function xl(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(xl,"assertUnique");function Do(e,t){j(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Se(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Se(e,"completeness",["complete","partial","unavailable"],"$"),o=B(e,"completenessReasons","$").map((v,_)=>{let y=`$.completenessReasons[${_}]`,R=H(v,y);j(R,["code","message","file"],y);let M=R.file===void 0?void 0:U(R,"file",y);return{code:F(R,"code",y),message:F(R,"message",y),...M?{file:M}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=B(e,"files","$").map((v,_)=>{let y=`$.files[${_}]`,R=H(v,y);return j(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:U(R,"path",y),contentHash:F(R,"contentHash",y),parseStatus:Se(R,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Lo(R,"parseDiagnosticCount",y),exportsOnlyTypes:G(R,"exportsOnlyTypes",y),typeOnlyExportNames:Ze(R.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:G(R,"hasTopLevelSideEffects",y)}}),a=B(e,"dependencies","$").map((v,_)=>{let y=`$.dependencies[${_}]`,R=H(v,y);j(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let M=Ee(R,"specifier",y),Y=Ee(R,"target",y),Ce=Se(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(Ce==="resolved-project"&&!Y)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(Ce!=="resolved-project"&&Y)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(Ce!=="dynamic"&&!M)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:U(R,"from",y),...M?{specifier:M}:{},kind:Se(R,"kind",["import","export","dynamic-import","require"],y),typeOnly:G(R,"typeOnly",y),line:te(R,"line",y),resolution:Ce,...Y?{target:U(R,"target",y)}:{},...R.namedBindings!==void 0?{namedBindings:Ze(R.namedBindings,`${y}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:G(R,"targetTypeOnlyExports",y)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:G(R,"sourcePureTypeModule",y)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:G(R,"namedBindingsTypeOnly",y)}:{},...R.portProofEligible!==void 0?{portProofEligible:G(R,"portProofEligible",y)}:{}}}),c=B(e,"capabilityUses","$").map((v,_)=>{let y=`$.capabilityUses[${_}]`,R=H(v,y);return j(R,["file","line","symbol","capability","source"],y),{file:U(R,"file",y),line:te(R,"line",y),symbol:F(R,"symbol",y),capability:Se(R,"capability",wo,y),source:Se(R,"source",["ambient-global","import-based"],y)}}),l=B(e,"ambientUses","$").map((v,_)=>{let y=`$.ambientUses[${_}]`,R=H(v,y);return j(R,["file","line","symbol"],y),{file:U(R,"file",y),line:te(R,"line",y),symbol:F(R,"symbol",y)}}),u=B(e,"publishCalls","$").map((v,_)=>{let y=`$.publishCalls[${_}]`,R=H(v,y);j(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let M=Ee(R,"rawIntentName",y),Y=Ee(R,"sourceIntent",y);return{file:U(R,"file",y),line:te(R,"line",y),...M?{rawIntentName:M}:{},objectHasIntent:G(R,"objectHasIntent",y),arkPublishCandidate:G(R,"arkPublishCandidate",y),hasSource:G(R,"hasSource",y),...Y?{sourceIntent:Y}:{}}}),p=B(e,"intentReferences","$").map((v,_)=>{let y=`$.intentReferences[${_}]`,R=H(v,y);return j(R,["file","line","intent"],y),{file:U(R,"file",y),line:te(R,"line",y),intent:F(R,"intent",y)}}),g=B(e,"safetyUses","$").map((v,_)=>{let y=`$.safetyUses[${_}]`,R=H(v,y);j(R,["file","line","kind","symbol"],y);let M=Ee(R,"symbol",y),Y=Se(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(Y==="in-memory-store"&&!M)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(Y!=="in-memory-store"&&M)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:U(R,"file",y),line:te(R,"line",y),kind:Y,...M?{symbol:M}:{}}});xl(s,v=>v.path,"$.files");let f=new Set(s.map(v=>v.path));for(let v of s){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!f.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:B(e,"arkRunKernelCalls","$")).map((v,_)=>{let y=`$.arkRunKernelCalls[${_}]`,R=H(v,y);j(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let M=Ee(R,"receiver",y),Y=Ee(R,"nameLiteral",y);return{file:U(R,"file",y),line:te(R,"line",y),kind:Se(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:F(R,"callee",y),viaImport:G(R,"viaImport",y),...M?{receiver:M}:{},...Y?{nameLiteral:Y}:{}}}),b=(e.arkRunManagedNews===void 0?[]:B(e,"arkRunManagedNews","$")).map((v,_)=>{let y=`$.arkRunManagedNews[${_}]`,R=H(v,y);j(R,["file","line","typeName","importedFrom"],y);let M=Ee(R,"importedFrom",y);return{file:U(R,"file",y),line:te(R,"line",y),typeName:F(R,"typeName",y),...M?{importedFrom:M}:{}}}),k=(e.arkRunCompositionRootHits===void 0?[]:B(e,"arkRunCompositionRootHits","$")).map((v,_)=>{let y=`$.arkRunCompositionRootHits[${_}]`,R=H(v,y);return j(R,["file","matchedRoot","hasKernelFactory"],y),{file:U(R,"file",y),matchedRoot:F(R,"matchedRoot",y),hasKernelFactory:G(R,"hasKernelFactory",y)}}),I=e.arkRunDeclarations===void 0?[]:B(e,"arkRunDeclarations","$"),L=(e.arkOrderPlaneCalls===void 0?[]:B(e,"arkOrderPlaneCalls","$")).map((v,_)=>{let y=`$.arkOrderPlaneCalls[${_}]`,R=H(v,y);return j(R,["file","line","callee"],y),{file:U(R,"file",y),line:te(R,"line",y),callee:F(R,"callee",y)}}),P=(e.arkOrderGenericUpdates===void 0?[]:B(e,"arkOrderGenericUpdates","$")).map((v,_)=>{let y=`$.arkOrderGenericUpdates[${_}]`,R=H(v,y);return j(R,["file","line","method"],y),{file:U(R,"file",y),line:te(R,"line",y),method:F(R,"method",y)}}),T=(e.arkOrderRootHits===void 0?[]:B(e,"arkOrderRootHits","$")).map((v,_)=>{let y=`$.arkOrderRootHits[${_}]`,R=H(v,y);return j(R,["file","matchedRoot","hasPlaneFactory"],y),{file:U(R,"file",y),matchedRoot:F(R,"matchedRoot",y),hasPlaneFactory:G(R,"hasPlaneFactory",y)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:B(e,"arkOrderXiFieldWrites","$")).map((v,_)=>{let y=`$.arkOrderXiFieldWrites[${_}]`,R=H(v,y);return j(R,["file","line","key"],y),{file:U(R,"file",y),line:te(R,"line",y),key:F(R,"key",y)}}),X=(e.arkOrderIngestWritesXi===void 0?[]:B(e,"arkOrderIngestWritesXi","$")).map((v,_)=>{let y=`$.arkOrderIngestWritesXi[${_}]`,R=H(v,y);return j(R,["file","line"],y),{file:U(R,"file",y),line:te(R,"line",y)}}),Ae=(e.arkOrderReleaseKeyCounts===void 0?[]:B(e,"arkOrderReleaseKeyCounts","$")).map((v,_)=>{let y=`$.arkOrderReleaseKeyCounts[${_}]`,R=H(v,y);return j(R,["file","line","keyCount"],y),{file:U(R,"file",y),line:te(R,"line",y),keyCount:te(R,"keyCount",y)}}),at=I.map((v,_)=>{let y=`$.arkRunDeclarations[${_}]`,R=H(v,y);return j(R,["file","line","uses","reactsTo","raises","sends"],y),{file:U(R,"file",y),line:te(R,"line",y),uses:Ze(R.uses,`${y}.uses`),reactsTo:Ze(R.reactsTo,`${y}.reactsTo`),raises:Ze(R.raises,`${y}.raises`),sends:Ze(R.sends,`${y}.sends`)}});for(let[v,_]of[["$.capabilityUses",c],["$.ambientUses",l],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",g],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",k],["$.arkRunDeclarations",at],["$.arkOrderPlaneCalls",L],["$.arkOrderGenericUpdates",P],["$.arkOrderRootHits",T],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",X],["$.arkOrderReleaseKeyCounts",Ae]])for(let y of _)if(!f.has(y.file))throw new Error(`${v} references missing file ${y.file}.`);let sn=Ee(e,"projectPackageName","$"),Ys=(e.classShapes===void 0?[]:B(e,"classShapes","$")).map((v,_)=>{let y=`$.classShapes[${_}]`,R=H(v,y);j(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],y);let M=B(R,"mutatingMethods",y).map((Y,Ce)=>{let h=`${y}.mutatingMethods[${Ce}]`,oe=H(Y,h);return j(oe,["name","referencesGuardOrPublish"],h),{name:F(oe,"name",h),referencesGuardOrPublish:G(oe,"referencesGuardOrPublish",h)}});return{file:U(R,"file",y),className:F(R,"className",y),exported:G(R,"exported",y),hasPublicMutableFields:G(R,"hasPublicMutableFields",y),hasPublicSetters:G(R,"hasPublicSetters",y),hasPublicConstructor:G(R,"hasPublicConstructor",y),hasStaticFactory:G(R,"hasStaticFactory",y),mutatingMethods:M,...R.dataOnly===void 0?{}:{dataOnly:G(R,"dataOnly",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:F(e,"resolverIdentity","$"),compilerIdentity:F(e,"compilerIdentity","$"),compilerOptionsHash:F(e,"compilerOptionsHash","$"),tsconfigHash:F(e,"tsconfigHash","$"),evidenceRequirementsHash:F(e,"evidenceRequirementsHash","$"),...sn?{projectPackageName:sn}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:l,publishCalls:u,intentReferences:p,safetyUses:g,classShapes:Ys,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:k,arkRunDeclarations:at,arkOrderPlaneCalls:L,arkOrderGenericUpdates:P,arkOrderRootHits:T,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:X,arkOrderReleaseKeyCounts:Ae}}i(Do,"parseResolvedFactsInput");function Ie(e){let t=H(e,"$"),n=F(t,"factsHash","$"),r=F(t,"candidateTreeHash","$"),o=Po(Do(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(Ie,"loadResolvedCandidateFacts");var Tl=["network","filesystem","clock","randomness","environment","process","persistence"],N={type:"string",minLength:1},ie={type:"integer",minimum:1},z={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},kn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:N,message:N,file:z}}},resolverIdentity:N,compilerIdentity:N,compilerOptionsHash:N,tsconfigHash:N,candidateTreeHash:N,evidenceRequirementsHash:N,projectPackageName:N,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:z,contentHash:N,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:N},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:z,specifier:N,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ie,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:z,namedBindings:{type:"array",items:N},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:z,line:ie,symbol:N,capability:{enum:Tl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:z,line:ie,symbol:N}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:z,line:ie,rawIntentName:N,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:N}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:z,line:ie,intent:N}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:z,line:ie,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:N},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:z,className:N,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:N,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:z,line:ie,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:N,viaImport:{type:"boolean"},receiver:N,nameLiteral:N}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:z,line:ie,typeName:N,importedFrom:N}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:z,matchedRoot:N,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:z,line:ie,uses:{type:"array",items:N},reactsTo:{type:"array",items:N},raises:{type:"array",items:N},sends:{type:"array",items:N}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:z,line:ie,callee:N}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:z,line:ie,method:N}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:z,matchedRoot:N,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:z,line:ie,key:N}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:z,line:ie}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:z,line:ie,keyCount:{type:"integer",minimum:1}}}},factsHash:N},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var En="1.0";function ce(e){return`${e.from}->${e.to}`}i(ce,"dependencyKey");function bt(e,t,n,r="dependency"){return{id:`${e}:${r}:${ce(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${ce(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${ce(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${ce(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${ce(t)} from the candidate, then preflight again.`}:{}}}i(bt,"dependencyFinding");function He(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[ce(f),f])),s=new Map(e.baseDependencies.map(f=>[ce(f),f])),a=new Map(e.candidateDependencies.map(f=>[ce(f),f]));for(let f of[...n.values()].sort((m,d)=>m.path.localeCompare(d.path))){let m=r.get(f.path);m?m.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${m.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:m.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((m,d)=>m.path.localeCompare(d.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let c=new Set;for(let f of[...o.values()].sort((m,d)=>ce(m).localeCompare(ce(d)))){if(a.has(ce(f))){t.push(bt("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let m={from:f.to,to:f.from};a.has(ce(m))?(c.add(ce(m)),t.push(bt("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(bt("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[f,m]of[...a].sort(([d],[A])=>d.localeCompare(A)))s.has(f)||o.has(f)||c.has(f)||!l.has(m.from)&&!l.has(m.to)||t.push({...bt("unplanned",m,`${m.from} -> ${m.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,m]of[...s].sort(([d],[A])=>d.localeCompare(A)))a.has(f)||u.has(m.from)||u.has(m.to)||!l.has(m.from)&&!l.has(m.to)||t.push({...bt("unplanned",m,`${m.from} -> ${m.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,m)=>p[f.classification]-p[m.classification]||(f.subject===m.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(m.id));let g={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}i(He,"analyzeArchitectureConvergence");var $o="1.0",Fr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",$r=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"],Nl=["no-anemic-model"],Mo={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},In={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Fr,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:Fr},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...$r]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Mo,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Mo}}}},je=class extends Error{static{i(this,"ArkRulesValidationError")}issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AdapterViolationInput, a as ArkRulesFile, E as EffectiveArkRules, R as ResolvedArkRunKernelCallKind, b as ResolvedArkRunDeclarationFact, c as ResolvedArkRunKernelCallFact, d as ResolvedArkRunManagedNewFact, e as ResolvedDependencyFact, f as ResolvedArkRunCompositionRootHitFact, g as ResolvedFactsReason, h as ResolvedArkOrderPlaneCallFact, i as ResolvedArkOrderGenericUpdateFact, j as ResolvedArkOrderRootHitFact, k as ResolvedArkOrderXiFieldWriteFact, l as ResolvedArkOrderIngestWriteFact } from './diagnosticCatalog-DVABouBV.js';
2
- export { m as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH, n as AICodeGate, o as AICodeGateContext, p as AICodeGateOptions, q as AICodeGateResult, r as AICodeGateViolation, s as AIGateExtension, t as ANALYSIS_IR_SCHEMA_VERSION, u as ARK_ANALYSIS_RESULT_SCHEMA, v as ARK_ANALYSIS_RESULT_SCHEMA_VERSION, w as ARK_DESIGN_DELTA_SCHEMA_VERSION, x as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION, y as AdapterCompletenessReason, z as AdapterDiagnostic, B as AdapterResult, C as AdapterSeverity, D as AnalysisCapabilityUse, F as AnalysisCompilerOptions, G as AnalysisCompleteness, H as AnalysisContract, I as AnalysisEvidence, J as AnalysisFile, K as AnalysisFileChange, L as AnalysisFileInput, M as AnalysisImportEdge, N as AnalysisIr, O as AnalysisMode, P as AnalysisResult, Q as AnalysisViolation, S as AnalyzeArchitectureConvergenceInput, T as AnalyzeChangeInput, U as AnalyzePolicyDeltaInput, V as AnalyzeProjectInput, W as AnalyzeResolvedProjectInput, X as ArchitectureActualChange, Y as ArchitectureChangeMap, Z as ArchitectureChangeMapContract, _ as ArchitectureChangeMapDependency, $ as ArchitectureChangeMapFile, a0 as ArchitectureChangeOperation, a1 as ArchitectureConvergenceClassification, a2 as ArchitectureConvergenceFinding, a3 as ArchitectureConvergenceResult, a4 as ArchitectureDependency, a5 as ArchitectureEngineEdge, a6 as ArchitectureEngineResult, a7 as ArchitectureEngineViolation, a8 as ArkDesignDeltaResult, a9 as ArkEnforcementHost, aa as ArkEnforcementState, ab as ArkRuleSensorViolation, ac as ChangePreflightResult, ad as ClassShapeFact, ae as CollectAnalysisConfigWarningsInput, af as DIAGNOSTIC_CATALOG, ag as DIAGNOSTIC_CATALOG_SCHEMA_VERSION, ah as DIAGNOSTIC_DOCS_RELATIVE_PATH, ai as DIAGNOSTIC_RULE_IDS, aj as DesignDeltaChange, ak as DesignDeltaEnforcementScope, al as DesignDeltaIdentity, am as DesignSmellEvidence, an as DesignSmellFinding, ao as DesignSmellId, ap as DiagnosticCatalogEntry, aq as DiagnosticCategory, ar as EnforcementBoundaryState, as as EnforcementEvidence, at as EnforcementEvidenceField, au as EnforcementVerification, av as EvaluateArchitectureGraphInput, aw as ForbiddenCapabilityUse, ax as InvariantCoverageEvidence, ay as POLICY_DELTA_SCHEMA_VERSION, az as PolicyDelta, aA as PolicyDeltaAcknowledgement, aB as PolicyDeltaAnalysis, aC as PolicyDeltaClassification, aD as PolicyDeltaFinding, aE as PreflightResolvedChangeInput, aF as PreparedChangeFile, aG as RESOLVED_CANDIDATE_FACTS_SCHEMA, aH as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION, aI as ResolvedAmbientFact, aJ as ResolvedAnalysisFile, aK as ResolvedAnalysisIr, aL as ResolvedAnalysisResult, aM as ResolvedCandidateFacts, aN as ResolvedCandidateFactsInput, aO as ResolvedCapability, aP as ResolvedCapabilityFact, aQ as ResolvedChangePreflightResult, aR as ResolvedDependencyKind, aS as ResolvedDependencyState, aT as ResolvedFactsCompleteness, aU as ResolvedFileFact, aV as ResolvedIntentReferenceFact, aW as ResolvedPublishFact, aX as ResolvedSafetyFact, aY as ResolvedSafetyKind, aZ as ResolvedSafetyReport, a_ as SemanticDependency, a$ as SemanticDependencyKind, b0 as analyzeArchitectureConvergence, b1 as analyzeChange, b2 as analyzePolicyDelta, b3 as analyzeProject, b4 as analyzeResolvedProject, b5 as buildArkRuleFileHints, b6 as canPromoteInvariant, b7 as catalogFixForRuleId, b8 as catalogWhyForRuleId, b9 as classifyArkPolicyDelta, ba as collectAnalysisConfigWarnings, bb as collectEmptyAppliesToFindings, bc as collectForbiddenCapabilityUses, bd as createAICodeGate, be as createAdapterResult, bf as createArchitectureProfile, bg as createArchitectureProfileFromArkConfig, bh as createElevenLayerArkConfig, bi as createResolvedCandidateFacts, bj as deriveArkRuleFileHints, bk as detectArchitectureCycles, bl as deterministicHash, bm as diagnosticDocsFragment, bn as diagnosticDocsPath, bo as elevenLayerProfile, bp as evaluateArchitectureGraph, bq as evaluateArkRuleSensors, br as evaluateInvariantCoverage, bs as explainViolation, bt as extractClassShapesFromSource, bu as extractSemanticDependencies, bv as getDiagnosticCatalogEntry, bw as isCataloguedOrArkRuleFamily, bx as isKnownDiagnosticCode, by as loadContract, bz as loadResolvedCandidateFacts, bA as policyDeltaAcknowledgementMatches, bB as preflightChange, bC as preflightResolvedChange, bD as resolvedFactsEvidenceRequirementsHash, bE as serializeDiagnosticCatalog, bF as stableSerialize, bG as toAdapterDiagnostic, bH as version } from './diagnosticCatalog-DVABouBV.js';
1
+ import { A as AdapterViolationInput, a as ArkRulesFile, E as EffectiveArkRules, R as ResolvedArkRunKernelCallKind, b as ResolvedArkRunDeclarationFact, c as ResolvedArkRunKernelCallFact, d as ResolvedArkRunManagedNewFact, e as ResolvedDependencyFact, f as ResolvedArkRunCompositionRootHitFact, g as ResolvedFactsReason, h as ResolvedArkOrderPlaneCallFact, i as ResolvedArkOrderGenericUpdateFact, j as ResolvedArkOrderRootHitFact, k as ResolvedArkOrderXiFieldWriteFact, l as ResolvedArkOrderIngestWriteFact } from './diagnosticCatalog-BNxKdcN4.js';
2
+ export { m as ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH, n as AICodeGate, o as AICodeGateContext, p as AICodeGateOptions, q as AICodeGateResult, r as AICodeGateViolation, s as AIGateExtension, t as ANALYSIS_IR_SCHEMA_VERSION, u as ARK_ANALYSIS_RESULT_SCHEMA, v as ARK_ANALYSIS_RESULT_SCHEMA_VERSION, w as ARK_DESIGN_DELTA_SCHEMA_VERSION, x as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION, y as AdapterCompletenessReason, z as AdapterDiagnostic, B as AdapterResult, C as AdapterSeverity, D as AnalysisCapabilityUse, F as AnalysisCompilerOptions, G as AnalysisCompleteness, H as AnalysisContract, I as AnalysisEvidence, J as AnalysisFile, K as AnalysisFileChange, L as AnalysisFileInput, M as AnalysisImportEdge, N as AnalysisIr, O as AnalysisMode, P as AnalysisResult, Q as AnalysisViolation, S as AnalyzeArchitectureConvergenceInput, T as AnalyzeChangeInput, U as AnalyzePolicyDeltaInput, V as AnalyzeProjectInput, W as AnalyzeResolvedProjectInput, X as ArchitectureActualChange, Y as ArchitectureChangeMap, Z as ArchitectureChangeMapContract, _ as ArchitectureChangeMapDependency, $ as ArchitectureChangeMapFile, a0 as ArchitectureChangeOperation, a1 as ArchitectureConvergenceClassification, a2 as ArchitectureConvergenceFinding, a3 as ArchitectureConvergenceResult, a4 as ArchitectureDependency, a5 as ArchitectureEngineEdge, a6 as ArchitectureEngineResult, a7 as ArchitectureEngineViolation, a8 as ArkDesignDeltaResult, a9 as ArkEnforcementHost, aa as ArkEnforcementState, ab as ArkRuleSensorViolation, ac as ChangePreflightResult, ad as ClassShapeFact, ae as CollectAnalysisConfigWarningsInput, af as DIAGNOSTIC_CATALOG, ag as DIAGNOSTIC_CATALOG_SCHEMA_VERSION, ah as DIAGNOSTIC_DOCS_RELATIVE_PATH, ai as DIAGNOSTIC_RULE_IDS, aj as DesignDeltaChange, ak as DesignDeltaEnforcementScope, al as DesignDeltaIdentity, am as DesignSmellEvidence, an as DesignSmellFinding, ao as DesignSmellId, ap as DiagnosticCatalogEntry, aq as DiagnosticCategory, ar as EnforcementBoundaryState, as as EnforcementEvidence, at as EnforcementEvidenceField, au as EnforcementVerification, av as EvaluateArchitectureGraphInput, aw as ForbiddenCapabilityUse, ax as InvariantCoverageEvidence, ay as POLICY_DELTA_SCHEMA_VERSION, az as PolicyDelta, aA as PolicyDeltaAcknowledgement, aB as PolicyDeltaAnalysis, aC as PolicyDeltaClassification, aD as PolicyDeltaFinding, aE as PreflightResolvedChangeInput, aF as PreparedChangeFile, aG as RESOLVED_CANDIDATE_FACTS_SCHEMA, aH as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION, aI as ResolvedAmbientFact, aJ as ResolvedAnalysisFile, aK as ResolvedAnalysisIr, aL as ResolvedAnalysisResult, aM as ResolvedCandidateFacts, aN as ResolvedCandidateFactsInput, aO as ResolvedCapability, aP as ResolvedCapabilityFact, aQ as ResolvedChangePreflightResult, aR as ResolvedDependencyKind, aS as ResolvedDependencyState, aT as ResolvedFactsCompleteness, aU as ResolvedFileFact, aV as ResolvedIntentReferenceFact, aW as ResolvedPublishFact, aX as ResolvedSafetyFact, aY as ResolvedSafetyKind, aZ as ResolvedSafetyReport, a_ as SemanticDependency, a$ as SemanticDependencyKind, b0 as analyzeArchitectureConvergence, b1 as analyzeChange, b2 as analyzePolicyDelta, b3 as analyzeProject, b4 as analyzeResolvedProject, b5 as buildArkRuleFileHints, b6 as canPromoteInvariant, b7 as catalogFixForRuleId, b8 as catalogWhyForRuleId, b9 as classifyArkPolicyDelta, ba as collectAnalysisConfigWarnings, bb as collectEmptyAppliesToFindings, bc as collectForbiddenCapabilityUses, bd as createAICodeGate, be as createAdapterResult, bf as createArchitectureProfile, bg as createArchitectureProfileFromArkConfig, bh as createElevenLayerArkConfig, bi as createResolvedCandidateFacts, bj as deriveArkRuleFileHints, bk as detectArchitectureCycles, bl as deterministicHash, bm as diagnosticDocsFragment, bn as diagnosticDocsPath, bo as elevenLayerProfile, bp as evaluateArchitectureGraph, bq as evaluateArkRuleSensors, br as evaluateInvariantCoverage, bs as explainViolation, bt as extractClassShapesFromSource, bu as extractSemanticDependencies, bv as getDiagnosticCatalogEntry, bw as isCataloguedOrArkRuleFamily, bx as isKnownDiagnosticCode, by as loadContract, bz as loadResolvedCandidateFacts, bA as policyDeltaAcknowledgementMatches, bB as preflightChange, bC as preflightResolvedChange, bD as resolvedFactsEvidenceRequirementsHash, bE as serializeDiagnosticCatalog, bF as stableSerialize, bG as toAdapterDiagnostic, bH as version } from './diagnosticCatalog-BNxKdcN4.js';
3
3
  export { A as ArchitectureLayer, a as ArchitectureLayerConfig, b as ArchitectureProfile, c as ArchitectureRule, d as ArkCheckConfig, C as CreateArchitectureProfileFromArkConfigOptions, e as CreateArchitectureProfileOptions, f as CreateElevenLayerArkConfigOptions } from './types-D5GT5ZT8.js';
4
4
  import { a as ArkConfigRule, b as ArkConfigSchemaVersion, c as ArkConfigLoadResult, A as ArkConfig, d as ArkConfigIssue, e as ArkConfigArkRun, f as ArkConfigLayer, g as ArkConfigArkOrder } from './configTypes-VD0qcubY.js';
5
5