arkgate 4.6.7 → 4.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +109 -0
- package/README.md +20 -9
- package/SECURITY.md +1 -1
- package/bin/ark-check-runtime.mjs +13 -1
- package/bin/ark-mcp-runtime.mjs +65 -3
- package/bin/lib/adapter-contract.mjs +17 -36
- package/bin/lib/analysis-engine.mjs +6 -6
- package/bin/lib/ark-run-doctor.mjs +144 -0
- package/bin/lib/ark-run-facts.mjs +472 -0
- package/bin/lib/ark-run-report.mjs +57 -0
- package/bin/lib/ark-run-sensors.mjs +309 -0
- package/bin/lib/config-contract.mjs +86 -11
- package/bin/lib/diagnostic-catalog.mjs +8 -0
- package/bin/lib/doctor-advisories.mjs +45 -8
- package/bin/lib/doctor-human.mjs +10 -0
- package/bin/lib/doctor-plan.mjs +20 -16
- package/bin/lib/extra-merge-teeth.mjs +187 -0
- package/bin/lib/html-report-advisories.mjs +2 -0
- package/bin/lib/html-report-depth.mjs +22 -2
- package/bin/lib/html-report.mjs +16 -0
- package/bin/lib/remediation.mjs +132 -0
- package/bin/lib/resolved-candidate-facts.mjs +67 -2
- package/bin/lib/rules-under-contract.mjs +37 -89
- package/bin/lib/snippet-analysis.mjs +43 -2
- package/bin/lib/status-command.mjs +28 -0
- package/bin/lib/status-manifest.mjs +23 -0
- package/dist/{configTypes-l6XiwiC1.d.ts → configTypes-CgJimx9o.d.ts} +17 -3
- package/dist/eslint/index.cjs +6 -2
- package/dist/eslint/index.d.ts +70 -2
- package/dist/eslint/index.js +6 -2
- package/dist/index.cjs +35 -35
- package/dist/index.d.ts +787 -272
- package/dist/index.js +35 -35
- package/docs/README.md +2 -1
- package/docs/agent-guide.md +21 -15
- package/docs/ai-gates.md +13 -0
- package/docs/configuration.md +24 -11
- package/docs/develop.md +12 -3
- package/docs/diagnostics.md +75 -0
- package/docs/enthusiast/README.md +4 -3
- package/docs/package-surface.md +16 -13
- package/docs/product-voice.md +6 -3
- package/docs/threat-model.md +1 -1
- package/docs/use.md +5 -4
- package/package.json +1 -1
- package/schemas/ark.config.schema.json +41 -2
- package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
- package/schemas/ark.status-manifest.schema.json +47 -0
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +23 -2
- package/templates/agent-skills/ark-place/SKILL.md +26 -2
- package/templates/agent-skills/ark-runtime/SKILL.md +66 -24
- package/templates/skills/ark-adopt.md +23 -2
- package/templates/skills/ark-place.md +26 -2
- package/templates/skills/ark-runtime.md +66 -24
package/dist/index.cjs
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
"use strict";var nn=Object.defineProperty;var qs=Object.getOwnPropertyDescriptor;var Ys=Object.getOwnPropertyNames;var Ws=Object.prototype.hasOwnProperty;var Js=(e,t)=>{for(var n in t)nn(e,n,{get:t[n],enumerable:!0})},Zs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ys(t))!Ws.call(e,s)&&s!==n&&nn(e,s,{get:()=>t[s],enumerable:!(r=qs(t,s))||r.enumerable});return e};var Xs=e=>Zs(nn({},"__esModule",{value:!0}),e);var Do={};Js(Do,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>sn,AGENT_PROJECTION_BEGIN_MARKER:()=>ws,AGENT_PROJECTION_END_MARKER:()=>Qn,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>Zt,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>er,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>ir,AGENT_SKILL_ENTRY_FILENAME:()=>ar,ANALYSIS_IR_SCHEMA_VERSION:()=>_t,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Ns,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Gs,ARK_ANALYSIS_RESULT_SCHEMA:()=>yr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>mt,ARK_CONFIG_SCHEMA:()=>Et,ARK_CONFIG_SCHEMA_VERSION:()=>Pr,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>cs,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>ls,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>ot,ARK_PROJECT_IDENTITY_SCHEMA:()=>Ar,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>ln,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>hr,ARK_RULES_SCHEMA:()=>Tt,ARK_RULES_SCHEMA_VERSION:()=>jr,ARK_RULE_SENSORS:()=>xn,ARK_SKILL_NAMES:()=>dt,ARK_SKILL_NAME_COUNT:()=>lr,ARK_STATUS_MANIFEST_SCHEMA:()=>vs,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Dn,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>As,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>Ms,DIAGNOSTIC_CATALOG:()=>nt,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ds,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>zt,DIAGNOSTIC_RULE_IDS:()=>ps,EffectiveContractError:()=>Je,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>or,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>ce,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>lt,IMPROVEMENT_LENS_IDS:()=>at,POLICY_DELTA_SCHEMA_VERSION:()=>$t,PROJECT_BINDING_SCHEMA:()=>dn,PROJECT_EXPECTATION_SCHEMA:()=>cn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>kt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>oe,STATUS_COMPASS_FACTS_SOURCES:()=>Hn,STATUS_COMPASS_MODES:()=>Fn,STATUS_COMPASS_REASON_CODES:()=>it,adapterDocsCodePath:()=>an,adapterFindingOccurrenceTargetKeys:()=>ut,adapterFindingRefFromTargetKey:()=>on,adapterFindingTargetKey:()=>gt,agentProjectionContentIdentity:()=>ct,agentSkillEntryRelativePath:()=>ur,agentSkillPackageFileRelativePath:()=>Ks,analyzeArchitectureConvergence:()=>ge,analyzeChange:()=>Qe,analyzePolicyDelta:()=>Tn,analyzeProject:()=>xe,analyzeResolvedProject:()=>Oe,buildAgentProjectionBeginMarker:()=>nr,buildAgentProjectionBlock:()=>Fs,buildAgentProjectionBody:()=>Qt,buildAgentProjectionMeta:()=>Hs,buildArkRuleFileHints:()=>Bt,buildEffectiveArkRules:()=>Ot,buildImprovementCompass:()=>Ps,buildRulesInventory:()=>os,buildStatusManifest:()=>bs,canPromoteInvariant:()=>Nt,catalogFixForRuleId:()=>ys,catalogWhyForRuleId:()=>hs,classifyArkPolicyDelta:()=>Dt,classifyStatusWritePath:()=>jn,collectAnalysisConfigWarnings:()=>tt,collectEmptyAppliesToFindings:()=>Gt,collectForbiddenCapabilityUses:()=>fe,createAICodeGate:()=>Rn,createAdapterResult:()=>gr,createArchitectureProfile:()=>Be,createArchitectureProfileFromArkConfig:()=>Cn,createElevenLayerArkConfig:()=>kn,createProjectId:()=>Ir,createProjectIdentity:()=>br,createResolvedCandidateFacts:()=>Ct,defaultHonestLabel:()=>Un,deriveArkRuleFileHints:()=>Ln,detectArchitectureCycles:()=>Vt,deterministicHash:()=>M,diagnosticDocsFragment:()=>$n,diagnosticDocsPath:()=>ms,effectiveContractPolicyPayload:()=>Pt,elevenLayerProfile:()=>Ge,emptyEffectiveArkRules:()=>le,evaluateArchitectureGraph:()=>Ie,evaluateArkRuleSensors:()=>Ut,evaluateInvariantCoverage:()=>Lt,evaluateStatusBinding:()=>Vn,explainViolation:()=>On,extractAgentProjectionBlock:()=>Jt,extractClassShapesFromSource:()=>es,extractSemanticDependencies:()=>ue,flatSkillTemplateFileRelativePath:()=>zs,formatAgentProjectionCatalogShortList:()=>rr,formatAgentProjectionLayers:()=>Wt,formatImprovementCompassDoctorLines:()=>Ls,formatImprovementCompassResidualLabels:()=>Zn,getDiagnosticCatalogEntry:()=>rt,inventoryToExtractionCard:()=>as,isArkSkillName:()=>tn,isCataloguedOrArkRuleFamily:()=>fs,isKnownDiagnosticCode:()=>us,isValidAgentSkillName:()=>cr,loadArkConfigContract:()=>Ue,loadArkRulesContract:()=>We,loadContract:()=>Xe,loadResolvedCandidateFacts:()=>se,mergeAgentProjectionDocument:()=>Us,normalizeSkillContent:()=>en,normalizeStatusImprovementCompass:()=>Bn,parseAgentProjectionStamp:()=>sr,parseArkConfigJson:()=>vt,parseArkRulesJson:()=>Ur,parseSkillDocument:()=>dr,policyDeltaAcknowledgementMatches:()=>Ft,preflightChange:()=>Nn,preflightResolvedChange:()=>wn,primaryImprovementCompassNextAction:()=>Xn,projectStatusImprovementCompass:()=>qt,projectionHasNonEnforcementLabel:()=>js,projectionMatchesPackageVersion:()=>Vs,resolveEffectiveContract:()=>Br,resolveStatusNextAction:()=>Gn,resolvedFactsEvidenceRequirementsHash:()=>ke,serializeDiagnosticCatalog:()=>gs,stableSerialize:()=>x,statusCompassResidualIsSubsetOfDoctor:()=>Rs,toAdapterDiagnostic:()=>ft,unavailableStatusImprovementCompass:()=>Es,validateAgentSkillDocument:()=>pr,validateAgentSkillsPackage:()=>Bs,version:()=>fr});module.exports=Xs(Do);var fr="4.6.7";var Qs=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ei=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,ti=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ni(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Qs.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ei.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":ti.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}function rn(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=ni(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}function pt(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return rn(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;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.`}}var mt="1.5",sn="docs/diagnostics.md";function R(e){return typeof e=="string"&&e.length>0?e:void 0}function mr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function gt(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function ut(e){let t=new Map;return e.map(n=>{let r=gt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function on(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")}`}function an(e){return`${sn}#${e}`}function ri(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return rn({ruleId:e,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:n.targetTypeOnlyExports===!0,namedBindingsTypeOnly:n.namedBindingsTypeOnly===!0,peerIsolation:n.peerIsolation===!0,portProofEligible:n.portProofEligible===!0,fromLayer:R(t.fromLayer)??void 0,toLayer:R(t.toLayer)??void 0,target:R(t.target)??R(n.target)??void 0});if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, test at the public interface, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${R(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ft(e,t="error",n){let r=R(e.ruleId)??R(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...R(e.target)?{target:R(e.target)}:{},...R(e.fromLayer)?{fromLayer:R(e.fromLayer)}:{},...R(e.toLayer)?{toLayer:R(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}:{},...R(e.capability)?{capability:R(e.capability)}:{},...R(e.edgeKind)?{edgeKind:R(e.edgeKind)}:{},...R(e.arkruleId)?{arkruleId:R(e.arkruleId)}:{},...R(e.arkruleSource)?{arkruleSource:R(e.arkruleSource)}:{}},o=n??gt(e),a=on(o);return{ruleId:r,severity:s,message:R(e.message)??r,location:{file:R(e.file)??"<unknown>",line:mr(e.line,1),column:mr(e.column,1)},evidence:i,nextAction:R(e.nextAction)??ri(r,i,e),findingRef:a,targetKey:o,docsCodePath:an(r)}}function gr(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(m=>({code:R(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:R(m.message)??`Analysis ${t}: required evidence is incomplete.`,...R(m.file)?{file:R(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...R(e.policyHash)?{policyHash:R(e.policyHash)}:{},...R(e.resolverIdentity)?{resolverIdentity:R(e.resolverIdentity)}:{},...R(e.factsHash)?{factsHash:R(e.factsHash)}:{},...R(e.candidateTreeHash)?{candidateTreeHash:R(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let i=e.violations??[],o=e.warnings??[],a=ut(i),d=ut(o),f=[...i.map((m,c)=>ft(m,"error",a[c])),...o.map((m,c)=>ft(m,"warning",d[c]))],g={schemaVersion:mt,completenessReasons:r,diagnostics:f};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...m}:{...g,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...s}:{...g,mode:n,valid:!1,completeness:t,...s}}var yr={$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:mt},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var hr="1.0",ln="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",yt="^sha256:[a-f0-9]{64}$",cn={type:"object",additionalProperties:!1,properties:{expectedRoot:{type:"string",minLength:1,description:"Absolute expected workspace/project directory. The initial authoritative handshake requires the exact project root; descendant calls also require expectedProjectId."},expectedProjectId:{type:"string",pattern:yt,description:"Project id previously returned by ark_identity or ark_manifest."}}},dn={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:yt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},Ar={$schema:"https://json-schema.org/draft/2020-12/schema",$id:ln,title:"ArkGate MCP project identity",description:"Stable project binding plus separate runtime and architecture-contract evidence.",type:"object",additionalProperties:!1,required:["schemaVersion","projectId","resolvedRoot","resolvedConfigPath","arkgateVersion","contractHash","contractSource","runtimeId","processStartedAt"],properties:{schemaVersion:{const:"1.0"},projectId:{type:"string",pattern:yt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:yt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:cn,binding:dn}};function Ir(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}`}function br(e){return{schemaVersion:"1.0",...e}}var un=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),mn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),gn=Object.freeze(Object.keys(mn).sort()),pn=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),fn=Object.freeze({process:Object.freeze(["process","node:process"])});function Me(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=pn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=pn[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:pn[e.slice(0,i)]??null}function ie(e,t){for(let n of t)if(fn[n]?.includes(e))return n;return null}function ht(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=mn[r];if(s)return s}return null}function be(e){if(e?.pure===!0)return[...un].sort();let n=(e?.capabilities?.deny??[]).filter(r=>un.includes(r));return[...new Set(n)].sort()}function $e(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function At(e){let t=new Set,n=new Set,r=Object.keys(mn);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(o=>o===s||o.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let o of i)t.add(`ambient:${o}`);for(let o of fn[s]??[])t.add(`import-exact:${o}`)}for(let s of be(e)){if(t.add(`import:${s}`),s==="process")for(let i of fn.process)t.add(`import-exact:${i}`);for(let i of r)ht(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Sr=new Map;function Er(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function It(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function si(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}function pe(e){let t=Sr.get(e);if(t)return t;let n=It(e),r=si(n),s="",i=0;for(let a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Er(n[a+1]),a+=1):d==="*"?n[a+1]==="*"?n[a+2]==="/"?(s+="(?:.*/)?",a+=2):(s+=".*",a+=1):s+="[^/]*":d==="?"?s+="[^/]":d==="{"&&r?(s+="(?:",i+=1):d==="}"&&r&&i>0?(s+=")",i-=1):d===","&&r&&i>0?s+="|":s+=Er(d)}let o=new RegExp(`^${s}$`);return Sr.set(e,o),o}function ii(e){return It(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function yn(e,t){let n=It(String(e)),r=ii(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let o=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let a=0,d=-1;for(let f of r){let g=-1;for(let m=a;m<o.length;m+=1)if(o[m]===f){g=m;break}if(g<0)return i;d=g,a=g+1}return(d+1)*1e6+r.length*1e4+s}function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(o=>pe(o).test(n))){for(let o of i.patterns??[])if(pe(o).test(n)){let a=yn(o,n);a>s&&(s=a,r=i.name)}}return r}function Rr(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function oi(e){let t=new Set;for(let n of e??[]){let s=It(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let o=s[i];if((o==="**"||o==="*")&&i>0){let a=s[i-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}function ai(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return oi(r?.patterns)}function li(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function ee(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,o=r?.toPath,a=ai(s,t,r?.layers),d=i&&o?Rr(i,a):void 0,f=i&&o?Rr(o,a):void 0;if(li({fromPath:i,toPath:o,folderCount:a.length,fromSlice:d,toSlice:f}))return s;continue}if(t!==n)return s}}function Se(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function kr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function vr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(i=>i.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))}function _r(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function hn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function An(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):hn(t,r)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function ue(e,t){let n,r=[],s=(o,a,d,f=!1)=>r.push({specifier:d,kind:a,line:kr(t,o),typeOnly:f,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",Se(e,o.moduleSpecifier),vr(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",Se(e,o.moduleSpecifier),vr(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",Se(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!An(e,n??(n=_r(e,t)),t,o.expression);(a||f)&&s(o,f?"require":"dynamic-import",Se(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),r}function ci(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=Se(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function di(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}function Cr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function fe(e,t,n){if(n.length===0)return[];let r=new Set(n),s=_r(e,t),i=new Map,o=new Set;for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let a=c=>{let l=ci(e,c);if(!l)return;let p=hn(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:An(e,s,t,l.root)||o.has(l.root.text)?void 0:l.segments};for(let c of t.statements)if(e.isVariableStatement(c))for(let l of c.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=a(l.initializer),y=hn(s,l.name);!p||!y||i.set(y,p)}let d=[],f=new Set,g=(c,l)=>{let p=kr(t,l),y=`${c}:${l.getStart(t)}`;f.has(y)||(f.add(y),d.push({name:c,line:p,node:l}))},m=c=>{let l=c.parent&&(e.isPropertyAccessExpression(c.parent)||e.isElementAccessExpression(c.parent))&&c.parent.expression===c;if((e.isPropertyAccessExpression(c)||e.isElementAccessExpression(c))&&!l){let p=a(c),y=p?Cr(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&di(e,c)&&!An(e,s,t,c)&&g(c.text,c);if(e.isVariableDeclaration(c)&&e.isObjectBindingPattern(c.name)&&c.initializer){let p=a(c.initializer);if(p)for(let y of c.name.elements){if(!e.isIdentifier(y.name))continue;let I=y.propertyName?Se(e,y.propertyName)??y.propertyName.text:y.name.text,E=Cr(r,[...p,I]);E&&g(E,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function In(e,t,n){let r=[];for(let s of n?.dependencies??ue(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Me(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??fe(e,t,gn)){let i=ht(s.name);i&&r.push({capability:i,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,i)=>s.line-i.line||s.capability.localeCompare(i.capability)||s.symbol.localeCompare(i.symbol))}var bn={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."},Sn=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 En(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:s,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function De(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&me(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:bn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:bn.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Ee(e,t){return e.slice(0,t).split(`
|
|
2
|
-
`).length}function pi(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function ui(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let i=s.index+s[0].indexOf(s[1]),o=s[0],a=r.kind==="import"&&/\bimport\s+type\b/.test(o)||r.kind==="export"&&/\bexport\s+type\b/.test(o);t.push({value:s[1],index:i,kind:r.kind,typeOnly:a})}}return t.sort((r,s)=>r.index-s.index)}function fi(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=i=>{e.isStringLiteralLike(i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,s)};return s(n),r}function mi(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))}function gi(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function yi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function He(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function hi(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function xr(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:hi(e,r.name)===n)}function Ve(e,t,n){return xr(e,t,n)!==void 0}function Fe(e,t,n){let r=xr(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function Ai(e,t){let n=Fe(e,t,"metadata");return Ve(e,n,"source")}function Tr(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Tr(e,t.name):!1:!1}function Ii(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"}function bi(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=He(e,n);return r!==void 0&&me(r)||Ve(e,n,"intent")||Tr(e,n)}function Si(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Ai(e,n)||Ve(e,r,"source")||Ve(e,s,"source")}function Ei(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=Fe(e,n,"metadata");return He(e,Fe(e,i,"source"))??He(e,Fe(e,r,"source"))??He(e,Fe(e,s,"source"))}function Ri(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,o=i?.filePath,a=i?.layer,d=[],f=m=>s.getLineAndCharacterOfPosition(m.getStart(s)).line+1,g=m=>{if(Ii(e,m)){let c=m.arguments[0],l=He(e,c);for(let y of De({publishCall:!0,rawIntentName:l,objectHasIntent:Ve(e,c,"intent"),arkPublishCandidate:bi(e,m),hasSource:Si(e,m)}))d.push(w(y.ruleId,y.message,{line:f(m),filePath:o}));let p=Ei(e,m);if(r&&a&&p&&me(p)){let y=r.resolveLayer(p);y&&y!==a&&d.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${y}, but the target file is classified as ${a}.`,{line:f(m),filePath:o,target:p,fromLayer:a,toLayer:y}))}}e.forEachChild(m,g)};return g(s),d}function Rn(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(i,o){let a=[],d=o,f=d?.filePath,g=d?.layer,m=e.typescript,c=m?m.createSourceFile(f??"generated.ts",i,m.ScriptTarget.Latest,!0):void 0,l=c?ue(e.typescript,c):void 0,p=l?l.filter(u=>u.specifier!==void 0).map(u=>({value:u.specifier,index:u.node.getStart(c),kind:u.kind,typeOnly:u.typeOnly})):ui(i),y=e.typescript?fi(e.typescript,i):pi(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(f))for(let u of l?.filter(({unresolved:h})=>h)??[]){let h=u.kind==="require";a.push(w(h?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${h?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:u.line,filePath:f}))}let I=g!==void 0&&(r.has(g)||yi(g)),E=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let u of n)if(u instanceof RegExp){u.lastIndex=0;let h=u.exec(i);u.lastIndex=0,h&&a.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${u}`,{line:h.index===void 0?void 0:Ee(i,h.index),filePath:f,suggestion:"Remove infrastructure imports from domain/application layers."+E}))}else i.includes(u)&&a.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${u}`,{line:Ee(i,i.indexOf(u)),filePath:f}));for(let u of p){let h=e.resolveImportTarget?.(u.value,f)??(e.resolveImportLayer?{layer:e.resolveImportLayer(u.value,f)}:void 0),S=typeof f=="string"?e.resolveImportTarget?.(f)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,k=h?.layer;if(k&&g){let N=ee(e.architectureProfile?.rules,g,k,{fromPath:S?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(N){if(u.typeOnly&&!N.peerIsolation)continue;let F=!!N.peerIsolation;a.push(w("LAYER_IMPORT_VIOLATION",N.message??(F?`Layer "${g}" must not import across slices into "${k}".`:`Layer "${g}" must not import "${k}".`),{line:Ee(i,u.index),source:u.value,target:u.value,filePath:f,fromLayer:g,toLayer:k,suggestion:F?"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:u.kind,peerIsolation:F,...u.typeOnly?{typeOnly:!0}:{}}}));continue}continue}I||u.typeOnly||!mi(u.value)&&!gi(u.value)||a.push(w("FORBIDDEN_IMPORT",`Forbidden ${u.kind} target: "${u.value}".`,{line:Ee(i,u.index),source:u.value,target:u.value,filePath:f,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+E,details:{importKind:u.kind}}))}if(e.policies)for(let u of e.policies){let h=u.check({source:i,context:o});if(h!==!0)if(Array.isArray(h))for(let S of h)a.push(w("POLICY_VIOLATION",S.message,{filePath:f,suggestion:`Fix violation of policy "${u.name}".`}));else h===!1?a.push(w("POLICY_VIOLATION",`Policy ${u.name} failed on generated code`)):a.push(w("POLICY_VIOLATION",h.message))}if(s&&t.size>0)for(let u of y)me(u.value)&&!t.has(u.value)&&a.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${u.value}"`,{line:Ee(i,u.index),filePath:f,target:u.value,suggestion:`Register intent "${u.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let u of y){if(!me(u.value))continue;let h=e.architectureProfile.resolveLayer(u.value);if(!h)continue;let S=ee(e.architectureProfile.rules,g,h);S&&a.push(w("LAYER_REFERENCE_VIOLATION",S.message??`Layer "${g}" must not reference "${h}" through "${u.value}".`,{line:Ee(i,u.index),filePath:f,target:u.value,fromLayer:g,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:S}}))}if(e.extensions)for(let u of e.extensions)try{let h=u.analyze(i,o);a.push(...h)}catch(h){a.push(w("EXTENSION_ERROR",`Extension "${u.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&c&&g&&e.forbiddenGlobals?.[g]?.length)try{let u=e.forbiddenGlobals[g];a.push(...fe(e.typescript,c,u).map(h=>w("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${h.name}".`,{line:h.line,filePath:f,target:h.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let h of l??[]){if(h.typeOnly||!h.specifier)continue;let S=ie(h.specifier,u);S&&a.push(w("FORBIDDEN_GLOBAL",`${g} must not use module "${h.specifier}" because it is the import form of forbidden global "${S}".`,{line:h.line,filePath:f,source:h.specifier,target:h.specifier,fromLayer:g,details:{importKind:h.kind,forbiddenGlobal:S},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(u){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${u instanceof Error?u.message:String(u)}`))}if(e.typescript&&c&&g&&e.capabilityWalls?.[g]?.length)try{let u=new Set(e.capabilityWalls[g]),h=e.forbiddenGlobals?.[g]??[];for(let S of In(e.typescript,c))u.has(S.capability)&&(S.source==="ambient-global"&&$e(S.symbol,h)||S.source==="import-based"&&ie(S.symbol,h)||a.push(w("CAPABILITY_VIOLATION",S.source==="import-based"?`${g} denies the ${S.capability} capability; found import of "${S.symbol}".`:`${g} denies the ${S.capability} capability; found ambient "${S.symbol}".`,{line:S.line,filePath:f,target:S.symbol,capability:S.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(u){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${u instanceof Error?u.message:String(u)}`))}if(e.typescript)try{a.push(...Ri(e.typescript,i,o,e.architectureProfile))}catch(u){a.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${u instanceof Error?u.message:String(u)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:a.length===0,violations:a}}}}var Pr="1.1",St="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Or=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],vi=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ci(){let e=[];for(let t of Or)for(let n of Or)t===n||vi.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Rt=Ci(),vn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],te={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Et={$schema:"https://json-schema.org/draft/2020-12/schema",$id:St,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:St,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...te,minItems:1,default:["src"]},exclude:{...te,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Rt,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...te,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},stewards:{...te,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...te,minItems:1},exclude:te,intentPrefixes:te,description:{type:"string",minLength:1},forbiddenGlobals:te,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:{...te,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ne=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
1
|
+
"use strict";var Nn=Object.defineProperty;var Vo=Object.getOwnPropertyDescriptor;var Uo=Object.getOwnPropertyNames;var Ko=Object.prototype.hasOwnProperty;var Go=(e,t)=>{for(var n in t)Nn(e,n,{get:t[n],enumerable:!0})},Bo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Uo(t))!Ko.call(e,s)&&s!==n&&Nn(e,s,{get:()=>t[s],enumerable:!(r=Vo(t,s))||r.enumerable});return e};var zo=e=>Bo(Nn({},"__esModule",{value:!0}),e);var cl={};Go(cl,{ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>On,AGENT_PROJECTION_BEGIN_MARKER:()=>_o,AGENT_PROJECTION_END_MARKER:()=>wr,AGENT_PROJECTION_ENFORCEMENT_SURFACES:()=>vn,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL:()=>Mr,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT:()=>jr,AGENT_SKILL_ENTRY_FILENAME:()=>Ur,ANALYSIS_IR_SCHEMA_VERSION:()=>Vt,ARKRUN_INTERACTION_NAME_INCOMPLETE:()=>ur,ARKRUN_KERNEL_FACTORY_CALLEES:()=>cr,ARKRUN_KERNEL_INTERACTION_CALLEES:()=>$s,ARKRUN_RULE_IDS:()=>yn,ARKRUN_TIER1_SENSOR_IDS:()=>Us,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS:()=>dr,ARK_AGENT_PROJECTION_SCHEMA_VERSION:()=>Co,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION:()=>Do,ARK_ANALYSIS_RESULT_SCHEMA:()=>Xr,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>xt,ARK_CONFIG_SCHEMA:()=>Dt,ARK_CONFIG_SCHEMA_VERSION:()=>fs,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>no,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>to,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION:()=>St,ARK_PROJECT_IDENTITY_SCHEMA:()=>es,ARK_PROJECT_IDENTITY_SCHEMA_URL:()=>wn,ARK_PROJECT_IDENTITY_SCHEMA_VERSION:()=>Qr,ARK_RULES_SCHEMA:()=>Kt,ARK_RULES_SCHEMA_VERSION:()=>Ss,ARK_RULE_SENSORS:()=>er,ARK_RUN_DOCTOR_SCHEMA_VERSION:()=>gr,ARK_SKILL_NAMES:()=>vt,ARK_SKILL_NAME_COUNT:()=>Kr,ARK_STATUS_MANIFEST_SCHEMA:()=>ho,ARK_STATUS_MANIFEST_SCHEMA_URL:()=>Ar,ARK_STATUS_MANIFEST_SCHEMA_VERSION:()=>kn,DEFAULT_AGENT_PROJECTION_RULE_IDS:()=>xo,DIAGNOSTIC_CATALOG:()=>ht,DIAGNOSTIC_CATALOG_SCHEMA_VERSION:()=>ro,DIAGNOSTIC_DOCS_RELATIVE_PATH:()=>Rn,DIAGNOSTIC_RULE_IDS:()=>so,EXTRA_MERGE_TEETH_GOVERNED_FLOOR:()=>Ms,EffectiveContractError:()=>at,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT:()=>Vr,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES:()=>ke,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP:()=>It,IMPROVEMENT_LENS_IDS:()=>Et,MERGE_PLANES_DUAL_STAMP:()=>ir,POLICY_DELTA_SCHEMA_VERSION:()=>Wt,PROJECT_BINDING_SCHEMA:()=>Dn,PROJECT_EXPECTATION_SCHEMA:()=>Mn,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>jt,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>he,STATUS_COMPASS_FACTS_SOURCES:()=>kr,STATUS_COMPASS_MODES:()=>Rr,STATUS_COMPASS_REASON_CODES:()=>kt,adapterDocsCodePath:()=>Pn,adapterFindingOccurrenceTargetKeys:()=>Ct,adapterFindingRefFromTargetKey:()=>Ln,adapterFindingTargetKey:()=>Tt,agentProjectionContentIdentity:()=>bt,agentSkillEntryRelativePath:()=>qr,agentSkillPackageFileRelativePath:()=>$o,analyzeArchitectureConvergence:()=>ve,analyzeChange:()=>dt,analyzePolicyDelta:()=>nr,analyzeProject:()=>Me,analyzeResolvedProject:()=>$e,arkRunKernelCallKind:()=>cn,buildAgentProjectionBeginMarker:()=>Fr,buildAgentProjectionBlock:()=>Oo,buildAgentProjectionBody:()=>_n,buildAgentProjectionMeta:()=>Lo,buildArkRuleFileHints:()=>rn,buildEffectiveArkRules:()=>Gt,buildImprovementCompass:()=>bo,buildRulesInventory:()=>Qs,buildStatusManifest:()=>fo,canPromoteInvariant:()=>qt,catalogFixForRuleId:()=>co,catalogWhyForRuleId:()=>uo,classifyArkPolicyDelta:()=>Jt,classifyResolvedLayerCoverage:()=>on,classifyStatusWritePath:()=>Er,collectAnalysisConfigWarnings:()=>yt,collectEmptyAppliesToFindings:()=>nn,collectForbiddenCapabilityUses:()=>Ie,composeMergePlanesHonesty:()=>ln,createAICodeGate:()=>Wn,createAdapterResult:()=>Zr,createArchitectureProfile:()=>et,createArchitectureProfileFromArkConfig:()=>Zn,createElevenLayerArkConfig:()=>Xn,createProjectId:()=>ts,createProjectIdentity:()=>ns,createResolvedCandidateFacts:()=>Ht,defaultHonestLabel:()=>Ir,demoteExtraPlaneTeethUnderClassificationFloor:()=>Ds,deriveArkRuleFileHints:()=>or,detectArchitectureCycles:()=>Qt,deterministicHash:()=>$,diagnosticDocsFragment:()=>hr,diagnosticDocsPath:()=>io,effectiveContractPolicyPayload:()=>Bt,elevenLayerProfile:()=>Qe,emptyEffectiveArkRules:()=>Ae,evaluateArchitectureGraph:()=>xe,evaluateArkRuleSensors:()=>tn,evaluateArkRunEditorSensors:()=>pr,evaluateArkRunEditorSensorsFromSource:()=>Gs,evaluateArkRunSensors:()=>gt,evaluateInvariantCoverage:()=>zt,evaluateStatusBinding:()=>Sr,explainViolation:()=>rr,extraMergeTeethAllowed:()=>Re,extractAgentProjectionBlock:()=>bn,extractArkRunDeclarationsFromSource:()=>Hs,extractArkRunImportedConstructorNamesFromSource:()=>fn,extractArkRunKernelCallsFromSource:()=>mn,extractArkRunManagedNewsFromSource:()=>gn,extractArkRunValueImportDependenciesFromSource:()=>pn,extractClassShapesFromSource:()=>ws,extractSemanticDependencies:()=>Ee,flatSkillTemplateFileRelativePath:()=>Ho,formatAgentProjectionCatalogShortList:()=>$r,formatAgentProjectionLayers:()=>In,formatArkRunDoctorLines:()=>Ws,formatImprovementCompassDoctorLines:()=>vo,formatImprovementCompassResidualLabels:()=>Lr,getDiagnosticCatalogEntry:()=>At,inventoryToExtractionCard:()=>eo,isArkRunKernelModuleSpecifier:()=>Fe,isArkRunRuleId:()=>an,isArkRunTransportBypassSpecifier:()=>dn,isArkSkillName:()=>Tn,isCataloguedOrArkRuleFamily:()=>ao,isExtraPlaneFinding:()=>ar,isKnownDiagnosticCode:()=>oo,isValidAgentSkillName:()=>Gr,loadArkConfigContract:()=>Xe,loadArkRulesContract:()=>ot,loadContract:()=>ct,loadResolvedCandidateFacts:()=>ce,mergeAgentProjectionDocument:()=>Mo,normalizeExtraMergeTeethClassification:()=>sn,normalizeSkillContent:()=>xn,normalizeStatusImprovementCompass:()=>vr,parseAgentProjectionStamp:()=>Hr,parseArkConfigJson:()=>$t,parseArkRulesJson:()=>Es,parseSkillDocument:()=>Br,policyDeltaAcknowledgementMatches:()=>Zt,preflightChange:()=>fr,preflightResolvedChange:()=>mr,primaryImprovementCompassNextAction:()=>Pr,projectStatusArkRun:()=>hn,projectStatusImprovementCompass:()=>Sn,projectionHasNonEnforcementLabel:()=>wo,projectionMatchesPackageVersion:()=>Po,resolveEffectiveContract:()=>bs,resolveStatusNextAction:()=>br,resolvedFactsEvidenceRequirementsHash:()=>we,serializeDiagnosticCatalog:()=>lo,stableSerialize:()=>L,statusCompassResidualIsSubsetOfDoctor:()=>yo,summarizeArkRunSection:()=>Ys,toAdapterDiagnostic:()=>_t,unavailableStatusImprovementCompass:()=>go,validateAgentSkillDocument:()=>zr,validateAgentSkillsPackage:()=>Fo,version:()=>Wr});module.exports=zo(cl);var Wr="4.7.0";var qo=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Yo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Wo=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Jo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return qo.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Yo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Wo.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}function Zo(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=Jo(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."}function Xo(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}function Qo(e){let t=Xo(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 (never a removed arkgate/runtime shim) 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, never a removed arkgate/runtime shim, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from @arkgate/runtime, never a removed arkgate/runtime shim, 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.`}}function ge(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Zo(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Qo(e);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.`}}var xt="1.5",On="docs/diagnostics.md";function _(e){return typeof e=="string"&&e.length>0?e:void 0}function Jr(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Tt(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,o=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",o??""].join("|")}function Ct(e){let t=new Map;return e.map(n=>{let r=Tt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function Ln(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")}`}function Pn(e){return`${On}#${e}`}function ea(e,t,n){return ge({ruleId:e,target:_(t.target)??_(n.target)??void 0,fromLayer:_(t.fromLayer)??void 0,toLayer:_(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:_(t.edgeKind)??void 0,capability:_(t.capability)??_(n.capability)??void 0,arkruleId:_(t.arkruleId)??void 0,arkruleSource:_(t.arkruleSource)??void 0})}function _t(e,t="error",n){let r=_(e.ruleId)??_(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,o={..._(e.target)?{target:_(e.target)}:{},..._(e.fromLayer)?{fromLayer:_(e.fromLayer)}:{},..._(e.toLayer)?{toLayer:_(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},..._(e.capability)?{capability:_(e.capability)}:{},..._(e.edgeKind)?{edgeKind:_(e.edgeKind)}:{},..._(e.arkruleId)?{arkruleId:_(e.arkruleId)}:{},..._(e.arkruleSource)?{arkruleSource:_(e.arkruleSource)}:{}},a=n??Tt(e),i=Ln(a);return{ruleId:r,severity:s,message:_(e.message)??r,location:{file:_(e.file)??"<unknown>",line:Jr(e.line,1),column:Jr(e.column,1)},evidence:o,nextAction:_(e.nextAction)??ea(r,o,e),findingRef:i,targetKey:a,docsCodePath:Pn(r)}}function Zr(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(m=>({code:_(m.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:_(m.message)??`Analysis ${t}: required evidence is incomplete.`,..._(m.file)?{file:_(m.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={..._(e.policyHash)?{policyHash:_(e.policyHash)}:{},..._(e.resolverIdentity)?{resolverIdentity:_(e.resolverIdentity)}:{},..._(e.factsHash)?{factsHash:_(e.factsHash)}:{},..._(e.candidateTreeHash)?{candidateTreeHash:_(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let m of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[m])throw new Error(`${m} is required for resolved ${t} adapter evidence.`)}let o=e.violations??[],a=e.warnings??[],i=Ct(o),l=Ct(a),u=[...o.map((m,d)=>_t(m,"error",i[d])),...a.map((m,d)=>_t(m,"warning",l[d]))],f={schemaVersion:xt,completenessReasons:r,diagnostics:u};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...f,mode:n,valid:!1,completeness:t,...s};let m={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...m}:{...f,mode:n,valid:!1,completeness:t,...m}}return t==="complete"?{...f,mode:n,valid:e.valid,completeness:t,...s}:{...f,mode:n,valid:!1,completeness:t,...s}}var Xr={$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:xt},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var Qr="1.0",wn="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Nt="^sha256:[a-f0-9]{64}$",Mn={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:Nt,description:"Project id previously returned by ark_identity or ark_manifest."}}},Dn={type:"object",additionalProperties:!1,required:["status","authoritative"],properties:{status:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},expectedRoot:{type:"string",minLength:1},expectedProjectId:{type:"string",pattern:Nt},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},es={$schema:"https://json-schema.org/draft/2020-12/schema",$id:wn,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:Nt},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Nt},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Mn,binding:Dn}};function ts(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}`}function ns(e){return{schemaVersion:"1.0",...e}}var $n=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),jn=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Vn=Object.freeze(Object.keys(jn).sort()),Fn=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"}),Hn=Object.freeze({process:Object.freeze(["process","node:process"])});function Ge(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Fn[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Fn[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:Fn[e.slice(0,o)]??null}function ye(e,t){for(let n of t)if(Hn[n]?.includes(e))return n;return null}function Ot(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=jn[r];if(s)return s}return null}function Te(e){if(e?.pure===!0)return[...$n].sort();let n=(e?.capabilities?.deny??[]).filter(r=>$n.includes(r));return[...new Set(n)].sort()}function Be(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}function Lt(e){let t=new Set,n=new Set,r=Object.keys(jn);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of Hn[s]??[])t.add(`import-exact:${a}`)}for(let s of Te(e)){if(t.add(`import:${s}`),s==="process")for(let o of Hn.process)t.add(`import-exact:${o}`);for(let o of r)Ot(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var rs=new Map;function ss(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Pt(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function ta(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}function Se(e){let t=rs.get(e);if(t)return t;let n=Pt(e),r=ta(n),s="",o=0;for(let i=0;i<n.length;i+=1){let l=n[i];l==="\\"&&i+1<n.length?(s+=ss(n[i+1]),i+=1):l==="*"?n[i+1]==="*"?n[i+2]==="/"?(s+="(?:.*/)?",i+=2):(s+=".*",i+=1):s+="[^/]*":l==="?"?s+="[^/]":l==="{"&&r?(s+="(?:",o+=1):l==="}"&&r&&o>0?(s+=")",o-=1):l===","&&r&&o>0?s+="|":s+=ss(l)}let a=new RegExp(`^${s}$`);return rs.set(e,a),a}function na(e){return Pt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Un(e,t){let n=Pt(String(e)),r=na(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let i=0,l=-1;for(let u of r){let f=-1;for(let m=i;m<a.length;m+=1)if(a[m]===u){f=m;break}if(f<0)return o;l=f,i=f+1}return(l+1)*1e6+r.length*1e4+s}function re(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>Se(a).test(n))){for(let a of o.patterns??[])if(Se(a).test(n)){let i=Un(a,n);i>s&&(s=i,r=o.name)}}return r}function os(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function ra(e){let t=new Set;for(let n of e??[]){let s=Pt(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let i=s[o-1];i&&!i.includes("*")&&!i.includes("{")&&!i.includes("}")&&t.add(i)}}}return[...t]}function sa(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return ra(r?.patterns)}function oa(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function se(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,i=sa(s,t,r?.layers),l=o&&a?os(o,i):void 0,u=o&&a?os(a,i):void 0;if(oa({fromPath:o,toPath:a,folderCount:i.length,fromSlice:l,toSlice:u}))return s;continue}if(t!==n)return s}}function Ne(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function ls(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function as(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}function cs(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Kn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Gn(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):Kn(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function Ee(e,t){let n,r=[],s=(a,i,l,u=!1)=>r.push({specifier:l,kind:i,line:ls(t,a),typeOnly:u,unresolved:l===void 0,node:a}),o=a=>{if(e.isImportDeclaration(a))s(a,"import",Ne(e,a.moduleSpecifier),as(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Ne(e,a.moduleSpecifier),as(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Ne(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let i=a.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Gn(e,n??(n=cs(e,t)),t,a.expression);(i||u)&&s(a,u?"require":"dynamic-import",Ne(e,a.arguments[0]))}e.forEachChild(a,o)};return o(t),r}function aa(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=Ne(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ia(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}function is(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}function Ie(e,t,n){if(n.length===0)return[];let r=new Set(n),s=cs(e,t),o=new Map,a=new Set;for(let d of t.statements)if(e.isVariableStatement(d))for(let c of d.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let i=d=>{let c=aa(e,d);if(!c)return;let p=Kn(s,c.root),g=p?o.get(p):void 0;return g?[...g,...c.segments.slice(1)]:Gn(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let d of t.statements)if(e.isVariableStatement(d))for(let c of d.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let p=i(c.initializer),g=Kn(s,c.name);!p||!g||o.set(g,p)}let l=[],u=new Set,f=(d,c)=>{let p=ls(t,c),g=`${d}:${c.getStart(t)}`;u.has(g)||(u.add(g),l.push({name:d,line:p,node:c}))},m=d=>{let c=d.parent&&(e.isPropertyAccessExpression(d.parent)||e.isElementAccessExpression(d.parent))&&d.parent.expression===d;if((e.isPropertyAccessExpression(d)||e.isElementAccessExpression(d))&&!c){let p=i(d),g=p?is(r,p):void 0;g&&f(g,d)}else e.isIdentifier(d)&&r.has(d.text)&&ia(e,d)&&!Gn(e,s,t,d)&&f(d.text,d);if(e.isVariableDeclaration(d)&&e.isObjectBindingPattern(d.name)&&d.initializer){let p=i(d.initializer);if(p)for(let g of d.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?Ne(e,g.propertyName)??g.propertyName.text:g.name.text,v=is(r,[...p,k]);v&&f(v,d.initializer)}}e.forEachChild(d,m)};return m(t),l}function Bn(e,t,n){let r=[];for(let s of n?.dependencies??Ee(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Ge(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Ie(e,t,Vn)){let o=Ot(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}var zn={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."},qn=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 Yn(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}function be(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ze(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&be(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:zn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:zn.PUBLISH_MISSING_SOURCE}),t}function D(e,t,n){return{ruleId:e,code:e,message:t,...n}}function Oe(e,t){return e.slice(0,t).split(`
|
|
2
|
+
`).length}function la(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function ca(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let s;for(;(s=r.re.exec(e))!==null;){let o=s.index+s[0].indexOf(s[1]),a=s[0],i=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:o,kind:r.kind,typeOnly:i})}}return t.sort((r,s)=>r.index-s.index)}function da(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],s=o=>{e.isStringLiteralLike(o)&&r.push({value:o.text,index:o.getStart(n)}),e.forEachChild(o,s)};return s(n),r}function ua(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))}function pa(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function fa(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function ma(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function ds(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:ma(e,r.name)===n)}function We(e,t,n){return ds(e,t,n)!==void 0}function qe(e,t,n){let r=ds(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function ga(e,t){let n=qe(e,t,"metadata");return We(e,n,"source")}function us(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?us(e,t.name):!1:!1}function ya(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"}function ha(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Ye(e,n);return r!==void 0&&be(r)||We(e,n,"intent")||us(e,n)}function Aa(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return ga(e,n)||We(e,r,"source")||We(e,s,"source")}function Ra(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,o=qe(e,n,"metadata");return Ye(e,qe(e,o,"source"))??Ye(e,qe(e,r,"source"))??Ye(e,qe(e,s,"source"))}function ka(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),o=n,a=o?.filePath,i=o?.layer,l=[],u=m=>s.getLineAndCharacterOfPosition(m.getStart(s)).line+1,f=m=>{if(ya(e,m)){let d=m.arguments[0],c=Ye(e,d);for(let g of ze({publishCall:!0,rawIntentName:c,objectHasIntent:We(e,d,"intent"),arkPublishCandidate:ha(e,m),hasSource:Aa(e,m)}))l.push(D(g.ruleId,g.message,{line:u(m),filePath:a}));let p=Ra(e,m);if(r&&i&&p&&be(p)){let g=r.resolveLayer(p);g&&g!==i&&l.push(D("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${g}, but the target file is classified as ${i}.`,{line:u(m),filePath:a,target:p,fromLayer:i,toLayer:g}))}}e.forEachChild(m,f)};return f(s),l}function Wn(e={}){let t=new Set((e.intents||[]).map(o=>typeof o=="string"?o:o.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),s=e.enforceIntentAllowlist??t.size>0;return{validate(o,a){let i=[],l=a,u=l?.filePath,f=l?.layer,m=e.typescript,d=m?m.createSourceFile(u??"generated.ts",o,m.ScriptTarget.Latest,!0):void 0,c=d?Ee(e.typescript,d):void 0,p=c?c.filter(R=>R.specifier!==void 0).map(R=>({value:R.specifier,index:R.node.getStart(d),kind:R.kind,typeOnly:R.typeOnly})):ca(o),g=e.typescript?da(e.typescript,o):la(o);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let R of c?.filter(({unresolved:I})=>I)??[]){let I=R.kind==="require";i.push(D(I?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${I?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:R.line,filePath:u}))}let k=f!==void 0&&(r.has(f)||fa(f)),v=f!==void 0?` If "${f}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let R of n)if(R instanceof RegExp){R.lastIndex=0;let I=R.exec(o);R.lastIndex=0,I&&i.push(D("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${R}`,{line:I.index===void 0?void 0:Oe(o,I.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+v}))}else o.includes(R)&&i.push(D("FORBIDDEN_SUBSTRING",`Forbidden substring: ${R}`,{line:Oe(o,o.indexOf(R)),filePath:u}));for(let R of p){let I=e.resolveImportTarget?.(R.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(R.value,u)}:void 0),C=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:f,relPath:void 0}:void 0):void 0,H=I?.layer;if(H&&f){let M=se(e.architectureProfile?.rules,f,H,{fromPath:C?.relPath,toPath:I?.relPath,layers:e.architectureLayers});if(M){if(R.typeOnly&&!M.peerIsolation)continue;let j=!!M.peerIsolation;i.push(D("LAYER_IMPORT_VIOLATION",M.message??(j?`Layer "${f}" must not import across slices into "${H}".`:`Layer "${f}" must not import "${H}".`),{line:Oe(o,R.index),source:R.value,target:R.value,filePath:u,fromLayer:f,toLayer:H,suggestion:j?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:R.kind,peerIsolation:j,...R.typeOnly?{typeOnly:!0}:{}}}));continue}continue}k||R.typeOnly||!ua(R.value)&&!pa(R.value)||i.push(D("FORBIDDEN_IMPORT",`Forbidden ${R.kind} target: "${R.value}".`,{line:Oe(o,R.index),source:R.value,target:R.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+v,details:{importKind:R.kind}}))}if(e.policies)for(let R of e.policies){let I=R.check({source:o,context:a});if(I!==!0)if(Array.isArray(I))for(let C of I)i.push(D("POLICY_VIOLATION",C.message,{filePath:u,suggestion:`Fix violation of policy "${R.name}".`}));else I===!1?i.push(D("POLICY_VIOLATION",`Policy ${R.name} failed on generated code`)):i.push(D("POLICY_VIOLATION",I.message))}if(s&&t.size>0)for(let R of g)be(R.value)&&!t.has(R.value)&&i.push(D("UNKNOWN_INTENT",`Unknown intent reference: "${R.value}"`,{line:Oe(o,R.index),filePath:u,target:R.value,suggestion:`Register intent "${R.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&f)for(let R of g){if(!be(R.value))continue;let I=e.architectureProfile.resolveLayer(R.value);if(!I)continue;let C=se(e.architectureProfile.rules,f,I);C&&i.push(D("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${f}" must not reference "${I}" through "${R.value}".`,{line:Oe(o,R.index),filePath:u,target:R.value,fromLayer:f,toLayer:I,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let R of e.extensions)try{let I=R.analyze(o,a);i.push(...I)}catch(I){i.push(D("EXTENSION_ERROR",`Extension "${R.name}" failed: ${I instanceof Error?I.message:String(I)}`))}if(e.typescript&&d&&f&&e.forbiddenGlobals?.[f]?.length)try{let R=e.forbiddenGlobals[f];i.push(...Ie(e.typescript,d,R).map(I=>D("FORBIDDEN_GLOBAL",`${f} must not use the ambient global "${I.name}".`,{line:I.line,filePath:u,target:I.name,fromLayer:f,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let I of c??[]){if(I.typeOnly||!I.specifier)continue;let C=ye(I.specifier,R);C&&i.push(D("FORBIDDEN_GLOBAL",`${f} 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:f,details:{importKind:I.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(R){i.push(D("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript&&d&&f&&e.capabilityWalls?.[f]?.length)try{let R=new Set(e.capabilityWalls[f]),I=e.forbiddenGlobals?.[f]??[];for(let C of Bn(e.typescript,d))R.has(C.capability)&&(C.source==="ambient-global"&&Be(C.symbol,I)||C.source==="import-based"&&ye(C.symbol,I)||i.push(D("CAPABILITY_VIOLATION",C.source==="import-based"?`${f} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${f} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:u,target:C.symbol,capability:C.capability,fromLayer:f,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(R){i.push(D("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}if(e.typescript)try{i.push(...ka(e.typescript,o,a,e.architectureProfile))}catch(R){i.push(D("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${R instanceof Error?R.message:String(R)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:i.length===0,violations:i}}}}var fs="1.2",Mt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",ps=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Sa=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ea(){let e=[];for(let t of ps)for(let n of ps)t===n||Sa.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var Ft=Ea(),Jn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"}],te={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Dt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Mt,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:Mt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.2",default:"1.2"},name:{type:"string",minLength:1},include:{...te,minItems:1,default:["src"]},exclude:{...te,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Ft,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...te,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},stewards:{...te,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...te,minItems:1},exclude:te,intentPrefixes:te,description:{type:"string",minLength:1},forbiddenGlobals:te,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:{...te,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},arkRun:{type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...te,default:[]},managedLayers:{...te,default:[]},requireDeclarations:{type:"boolean",default:!0}}}}},oe=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
3
3
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Lr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Re(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function ki(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function je(e,t,n,r,s){if(t.$ref){let i=ki(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}je(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Lr(e)){s.push({path:n,message:`must be an object; received ${Re(e)}`});return}let i=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:bt(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||s.push({path:bt(n,o),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let o=t.additionalProperties;for(let a of Object.keys(e))a in i||je(e[a],o,bt(n,a),r,s)}for(let[o,a]of Object.entries(i))e[o]!==void 0&&je(e[o],a,bt(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Re(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(o=>JSON.stringify(o));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,o)=>je(i,t.items,`${n}[${o}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Re(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${Re(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Re(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function _i(e){return{...e,$schema:e.$schema===void 0?St:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Rt.map(t=>({...t})):e.rules}}function xi(){let e=new Set(["1.1"]);for(let t of vn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function Ti(e,t="ark.config.json"){if(!Lr(e))throw new ne(t,[{path:"$",message:`must be an object; received ${Re(e)}`}]);let n=xi(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},o=0;for(;s!=="1.1"&&o<vn.length+1;){o+=1;let d=vn.find(f=>f.from===s);if(!d)throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=d.to,i.schemaVersion=s}if(s!=="1.1")throw new ne(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let a=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:_i(i),migratedFrom:a}}function Ue(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ti(e,t),s=[];if(je(n,Et,"$",Et,s),s.length>0)throw new ne(t,s);return{config:n,migratedFrom:r}}function vt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ne(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ue(n,t)}function Nr(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:St,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Oi(e){return e.endsWith(".")?e:`${e}.`}function Pi(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}function Be(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Oi)})),n=[...t].sort(Pi),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(i=>i.match?.(s))?.name??n.find(i=>i.prefixes.some(o=>s.startsWith(o)))?.name}}}function Cn(e,t={}){return Be({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Li=[{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}],Ge=Be({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Li,rules:Rt.map(e=>({...e}))}),Ni={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 kn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return Nr({include:e.include??[t],layers:Ge.layers.map(s=>({name:s.name,patterns:(Ni[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ge.rules]})}function M(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")}`}function x(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(x).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${x(t[n])}`).join(",")}}`}var oe="1.1";var wr=["network","filesystem","clock","randomness","environment","process","persistence"];function re(e,t){let n=x(e),r=x(t);return n<r?-1:n>r?1:0}function Z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ke(e){let t={schemaVersion:"1.1",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(re),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return M(x(t))}function wi(e){let t=e.completenessReasons.map(c=>({code:c.code,message:c.message,...c.file?{file:c.file}:{}})).sort(re),n=e.files.map(c=>({...c,typeOnlyExportNames:Z(c.typeOnlyExportNames)})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),r=e.dependencies.map(c=>({...c,...c.namedBindings?{namedBindings:Z(c.namedBindings)}:{}})).sort(re),s=e.capabilityUses.map(c=>({...c})).sort(re),i=e.ambientUses.map(c=>({...c})).sort(re),o=e.publishCalls.map(c=>({...c})).sort(re),a=e.intentReferences.map(c=>({...c})).sort(re),d=e.safetyUses.map(c=>({...c})).sort(re),f=(e.classShapes??[]).map(c=>({...c,mutatingMethods:[...c.mutatingMethods??[]].map(l=>({...l}))})).sort(re),g=e.files.map(({path:c,contentHash:l})=>({path:c,contentHash:l})).sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),m=M(x(g));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:m,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:o,intentReferences:a,safetyUses:d,classShapes:f}}function $r(e){let t=wi(e);return{...t,factsHash:M(x(t))}}function Ct(e){return $r(Fr(K(e,"$"),!1))}function K(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function Y(e,t,n){let r=new Set(t),s=Object.keys(e).find(i=>!r.has(i));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.1"}.`)}function D(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}function ve(e,t,n){if(e[t]!==void 0)return D(e,t,n)}function W(e,t,n){let r=D(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let a of s.split("/"))if(!(!a||a==="."))if(a===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(a);let o=i.join("/");if(!o||o!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Dr(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)}function Ce(e,t,n){let r=Dr(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function J(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function ae(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function Mr(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]}function Mi(e,t,n){let r=new Set;for(let s of e){let i=t(s);if(r.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);r.add(i)}}function Fr(e,t){Y(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ae(e,"schemaVersion",["1.0","1.1"],"$"),r=ae(e,"completeness",["complete","partial","unavailable"],"$"),s=J(e,"completenessReasons","$").map((I,E)=>{let u=`$.completenessReasons[${E}]`,h=K(I,u);Y(h,["code","message","file"],u);let S=h.file===void 0?void 0:W(h,"file",u);return{code:D(h,"code",u),message:D(h,"message",u),...S?{file:S}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=J(e,"files","$").map((I,E)=>{let u=`$.files[${E}]`,h=K(I,u);return Y(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:W(h,"path",u),contentHash:D(h,"contentHash",u),parseStatus:ae(h,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:Dr(h,"parseDiagnosticCount",u),exportsOnlyTypes:$(h,"exportsOnlyTypes",u),typeOnlyExportNames:Mr(h.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:$(h,"hasTopLevelSideEffects",u)}}),o=J(e,"dependencies","$").map((I,E)=>{let u=`$.dependencies[${E}]`,h=K(I,u);Y(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let S=ve(h,"specifier",u),k=ve(h,"target",u),N=ae(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(N==="resolved-project"&&!k)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(N!=="resolved-project"&&k)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(N!=="dynamic"&&!S)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:W(h,"from",u),...S?{specifier:S}:{},kind:ae(h,"kind",["import","export","dynamic-import","require"],u),typeOnly:$(h,"typeOnly",u),line:Ce(h,"line",u),resolution:N,...k?{target:W(h,"target",u)}:{},...h.namedBindings!==void 0?{namedBindings:Mr(h.namedBindings,`${u}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(h,"targetTypeOnlyExports",u)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(h,"sourcePureTypeModule",u)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(h,"namedBindingsTypeOnly",u)}:{},...h.portProofEligible!==void 0?{portProofEligible:$(h,"portProofEligible",u)}:{}}}),a=J(e,"capabilityUses","$").map((I,E)=>{let u=`$.capabilityUses[${E}]`,h=K(I,u);return Y(h,["file","line","symbol","capability","source"],u),{file:W(h,"file",u),line:Ce(h,"line",u),symbol:D(h,"symbol",u),capability:ae(h,"capability",wr,u),source:ae(h,"source",["ambient-global","import-based"],u)}}),d=J(e,"ambientUses","$").map((I,E)=>{let u=`$.ambientUses[${E}]`,h=K(I,u);return Y(h,["file","line","symbol"],u),{file:W(h,"file",u),line:Ce(h,"line",u),symbol:D(h,"symbol",u)}}),f=J(e,"publishCalls","$").map((I,E)=>{let u=`$.publishCalls[${E}]`,h=K(I,u);Y(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let S=ve(h,"rawIntentName",u),k=ve(h,"sourceIntent",u);return{file:W(h,"file",u),line:Ce(h,"line",u),...S?{rawIntentName:S}:{},objectHasIntent:$(h,"objectHasIntent",u),arkPublishCandidate:$(h,"arkPublishCandidate",u),hasSource:$(h,"hasSource",u),...k?{sourceIntent:k}:{}}}),g=J(e,"intentReferences","$").map((I,E)=>{let u=`$.intentReferences[${E}]`,h=K(I,u);return Y(h,["file","line","intent"],u),{file:W(h,"file",u),line:Ce(h,"line",u),intent:D(h,"intent",u)}}),m=J(e,"safetyUses","$").map((I,E)=>{let u=`$.safetyUses[${E}]`,h=K(I,u);Y(h,["file","line","kind","symbol"],u);let S=ve(h,"symbol",u),k=ae(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(k==="in-memory-store"&&!S)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(k!=="in-memory-store"&&S)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:W(h,"file",u),line:Ce(h,"line",u),kind:k,...S?{symbol:S}:{}}});Mi(i,I=>I.path,"$.files");let c=new Set(i.map(I=>I.path));for(let I of i){if(I.parseStatus==="parsed"&&I.parseDiagnosticCount!==0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(I.parseStatus==="invalid"&&I.parseDiagnosticCount===0)throw new Error(`$.files[${I.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(I=>I.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let I of o)if(!c.has(I.from))throw new Error(`$.dependencies references missing source file ${I.from}.`);for(let[I,E]of[["$.capabilityUses",a],["$.ambientUses",d],["$.publishCalls",f],["$.intentReferences",g],["$.safetyUses",m]])for(let u of E)if(!c.has(u.file))throw new Error(`${I} references missing file ${u.file}.`);let l=ve(e,"projectPackageName","$"),y=(e.classShapes===void 0?[]:J(e,"classShapes","$")).map((I,E)=>{let u=`$.classShapes[${E}]`,h=K(I,u);Y(h,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],u);let S=J(h,"mutatingMethods",u).map((k,N)=>{let F=`${u}.mutatingMethods[${N}]`,_=K(k,F);return Y(_,["name","referencesGuardOrPublish"],F),{name:D(_,"name",F),referencesGuardOrPublish:$(_,"referencesGuardOrPublish",F)}});return{file:W(h,"file",u),className:D(h,"className",u),exported:$(h,"exported",u),hasPublicMutableFields:$(h,"hasPublicMutableFields",u),hasPublicSetters:$(h,"hasPublicSetters",u),hasPublicConstructor:$(h,"hasPublicConstructor",u),hasStaticFactory:$(h,"hasStaticFactory",u),mutatingMethods:S,...h.dataOnly===void 0?{}:{dataOnly:$(h,"dataOnly",u)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:D(e,"resolverIdentity","$"),compilerIdentity:D(e,"compilerIdentity","$"),compilerOptionsHash:D(e,"compilerOptionsHash","$"),tsconfigHash:D(e,"tsconfigHash","$"),evidenceRequirementsHash:D(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:o,capabilityUses:a,ambientUses:d,publishCalls:f,intentReferences:g,safetyUses:m,classShapes:y}}function se(e){let t=K(e,"$"),n=D(t,"factsHash","$"),r=D(t,"candidateTreeHash","$"),s=$r(Fr(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var $i=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},_e={type:"integer",minimum:1},X={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},kt={$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"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:T,message:T,file:X}}},resolverIdentity:T,compilerIdentity:T,compilerOptionsHash:T,tsconfigHash:T,candidateTreeHash:T,evidenceRequirementsHash:T,projectPackageName:T,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:X,contentHash:T,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:T},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:X,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:_e,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:X,namedBindings:{type:"array",items:T},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:X,line:_e,symbol:T,capability:{enum:$i},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:X,line:_e,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:X,line:_e,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:X,line:_e,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:X,line:_e,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:X,className:T,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:T,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:T},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var _t="1.0";function U(e){return`${e.from}->${e.to}`}function Ke(e,t,n,r="dependency"){return{id:`${e}:${r}:${U(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${U(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${U(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${U(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${U(t)} from the candidate, then preflight again.`}:{}}}function ge(e){let t=[],n=new Map(e.changeMap.map.files.map(c=>[c.path,c])),r=new Map(e.changes.map(c=>[c.path,c])),s=new Map(e.changeMap.map.dependencies.map(c=>[U(c),c])),i=new Map(e.baseDependencies.map(c=>[U(c),c])),o=new Map(e.candidateDependencies.map(c=>[U(c),c]));for(let c of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=r.get(c.path);l?l.operation!==c.operation?t.push({id:`contradictory:file:${c.path}`,classification:"contradictory",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} was planned as ${c.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${c.path} to the planned ${c.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${c.path}`,classification:"satisfied",subject:"file",path:c.path,expectedOperation:c.operation,actualOperation:l.operation,message:`${c.path} matches the planned ${c.operation} operation.`}):t.push({id:`missing:file:${c.path}`,classification:"missing",subject:"file",path:c.path,expectedOperation:c.operation,message:`${c.path} was planned as ${c.operation} but is absent from the actual change.`,nextAction:`${c.operation[0].toUpperCase()}${c.operation.slice(1)} ${c.path} in the complete change set, then preflight again.`})}for(let c of[...r.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(c.path)||t.push({id:`unplanned:file:${c.path}`,classification:"unplanned",subject:"file",path:c.path,actualOperation:c.operation,message:`${c.path} has an unplanned ${c.operation} operation.`,nextAction:`Remove ${c.path} from the change set, then preflight again.`});let a=new Set;for(let c of[...s.values()].sort((l,p)=>U(l).localeCompare(U(p)))){if(o.has(U(c))){t.push(Ke("satisfied",c,`${c.from} -> ${c.to} exists in the candidate architecture.`));continue}let l={from:c.to,to:c.from};o.has(U(l))?(a.add(U(l)),t.push(Ke("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ke("missing",c,`${c.from} -> ${c.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[c,l]of[...o].sort(([p],[y])=>p.localeCompare(y)))i.has(c)||s.has(c)||a.has(c)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(c=>c.operation==="delete").map(c=>c.path));for(let[c,l]of[...i].sort(([p],[y])=>p.localeCompare(y)))o.has(c)||f.has(l.from)||f.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...Ke("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((c,l)=>g[c.classification]-g[l.classification]||(c.subject===l.subject?0:c.subject==="file"?-1:1)||c.id.localeCompare(l.id));let m={satisfied:t.filter(c=>c.classification==="satisfied").length,missing:t.filter(c=>c.classification==="missing").length,contradictory:t.filter(c=>c.classification==="contradictory").length,unplanned:t.filter(c=>c.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var jr="1.0",_n="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",xn=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Di=["no-anemic-model"],Hr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Tt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:_n,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:_n},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:[...xn]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Hr,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:Hr}}}},ye=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
4
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ze(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Le(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ia(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Je(e,t,n,r,s){if(t.$ref){let o=Ia(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Je(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ze(e)){s.push({path:n,message:`must be an object; received ${Le(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:wt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:wt(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let i of Object.keys(e))i in o||Je(e[i],a,wt(n,i),r,s)}for(let[a,i]of Object.entries(o))e[a]!==void 0&&Je(e[a],i,wt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Le(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>Je(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Le(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${Le(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Le(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function ba(e){return Ze(e)?{...e,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}:e}function va(e){let t={...e,$schema:e.$schema===void 0?Mt:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.2":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Ft.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=ba(e.arkRun)),t}function Ca(e,t){let n=e.arkRun;if(n===void 0||!Ze(n))return;let r=new Set;if(Array.isArray(e.layers))for(let o of e.layers)Ze(o)&&typeof o.name=="string"&&o.name.length>0&&r.add(o.name);let s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one composition root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}function _a(e){return e==="1.2"?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"?e:null}function xa(){let e=new Set(["1.2"]);for(let t of Jn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function Ta(e,t="ark.config.json"){if(!Ze(e))throw new oe(t,[{path:"$",message:`must be an object; received ${Le(e)}`}]);let n=xa(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.2`}]);if(r!=="unversioned"&&!n.has(r))throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.2`}]);let s=r,o={...e},a=0;for(;s!=="1.2"&&a<Jn.length+1;){a+=1;let i=Jn.find(l=>l.from===s);if(!i)throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.2`}]);s=i.to,o.schemaVersion=s}if(s!=="1.2")throw new oe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.2`}]);return{candidate:va(o),migratedFrom:_a(r)}}function Xe(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ta(e,t),s=[];if(Je(n,Dt,"$",Dt,s),Ca(n,s),s.length>0)throw new oe(t,s);return{config:n,migratedFrom:r}}function $t(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new oe(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Xe(n,t)}function ms(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:Mt,schemaVersion:"1.2"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Na(e){return e.endsWith(".")?e:`${e}.`}function Oa(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(s=>s.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(s=>s.length)):0)-n}function et(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Na)})),n=[...t].sort(Oa),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(s){return t.find(o=>o.match?.(s))?.name??n.find(o=>o.prefixes.some(a=>s.startsWith(a)))?.name}}}function Zn(e,t={}){return et({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var La=[{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}],Qe=et({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:La,rules:Ft.map(e=>({...e}))}),Pa={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Xn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ms({include:e.include??[t],layers:Qe.layers.map(s=>({name:s.name,patterns:(Pa[s.name]??[s.name]).map(o=>`${r}${o}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Qe.rules]})}function $(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")}`}function L(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(L).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${L(t[n])}`).join(",")}}`}var he="1.2";var gs=["network","filesystem","clock","randomness","environment","process","persistence"];function J(e,t){let n=L(e),r=L(t);return n<r?-1:n>r?1:0}function U(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function we(e){let t={schemaVersion:"1.2",include:U(e.include??[]),exclude:U(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:U(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:U(n.patterns??[]),exclude:U(n.exclude??[]),forbiddenGlobals:U(n.forbiddenGlobals??[]),intentPrefixes:U(n.intentPrefixes??[]),capabilityDeny:U(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(J),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:U(e.arkRun.compositionRoots),managedLayers:U(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return $(L(t))}function wa(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(J),n=e.files.map(k=>({...k,typeOnlyExportNames:U(k.typeOnlyExportNames)})).sort((k,v)=>k.path<v.path?-1:k.path>v.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:U(k.namedBindings)}:{}})).sort(J),s=e.capabilityUses.map(k=>({...k})).sort(J),o=e.ambientUses.map(k=>({...k})).sort(J),a=e.publishCalls.map(k=>({...k})).sort(J),i=e.intentReferences.map(k=>({...k})).sort(J),l=e.safetyUses.map(k=>({...k})).sort(J),u=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(v=>({...v}))})).sort(J),f=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(J),m=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(J),d=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(J),c=(e.arkRunDeclarations??[]).map(k=>({...k,uses:U(k.uses),reactsTo:U(k.reactsTo),raises:U(k.raises),sends:U(k.sends)})).sort(J),p=e.files.map(({path:k,contentHash:v})=>({path:k,contentHash:v})).sort((k,v)=>k.path<v.path?-1:k.path>v.path?1:0),g=$(L(p));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:i,safetyUses:l,classShapes:u,arkRunKernelCalls:f,arkRunManagedNews:m,arkRunCompositionRootHits:d,arkRunDeclarations:c}}function ys(e){let t=wa(e);return{...t,factsHash:$(L(t))}}function Ht(e){return ys(As(V(e,"$"),!1))}function V(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function K(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}function w(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}function ae(e,t,n){if(e[t]!==void 0)return w(e,t,n)}function z(e,t,n){let r=w(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let o=[];for(let i of s.split("/"))if(!(!i||i==="."))if(i===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(i);let a=o.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function F(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function hs(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}function ie(e,t,n){let r=hs(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function q(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function le(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}function Pe(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]}function Ma(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}function As(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=le(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=le(e,"completeness",["complete","partial","unavailable"],"$"),s=q(e,"completenessReasons","$").map((S,b)=>{let y=`$.completenessReasons[${b}]`,A=V(S,y);K(A,["code","message","file"],y);let x=A.file===void 0?void 0:z(A,"file",y);return{code:w(A,"code",y),message:w(A,"message",y),...x?{file:x}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=q(e,"files","$").map((S,b)=>{let y=`$.files[${b}]`,A=V(S,y);return K(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:z(A,"path",y),contentHash:w(A,"contentHash",y),parseStatus:le(A,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:hs(A,"parseDiagnosticCount",y),exportsOnlyTypes:F(A,"exportsOnlyTypes",y),typeOnlyExportNames:Pe(A.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:F(A,"hasTopLevelSideEffects",y)}}),a=q(e,"dependencies","$").map((S,b)=>{let y=`$.dependencies[${b}]`,A=V(S,y);K(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let x=ae(A,"specifier",y),O=ae(A,"target",y),B=le(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(B==="resolved-project"&&!O)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(B!=="resolved-project"&&O)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(B!=="dynamic"&&!x)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:z(A,"from",y),...x?{specifier:x}:{},kind:le(A,"kind",["import","export","dynamic-import","require"],y),typeOnly:F(A,"typeOnly",y),line:ie(A,"line",y),resolution:B,...O?{target:z(A,"target",y)}:{},...A.namedBindings!==void 0?{namedBindings:Pe(A.namedBindings,`${y}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:F(A,"targetTypeOnlyExports",y)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:F(A,"sourcePureTypeModule",y)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:F(A,"namedBindingsTypeOnly",y)}:{},...A.portProofEligible!==void 0?{portProofEligible:F(A,"portProofEligible",y)}:{}}}),i=q(e,"capabilityUses","$").map((S,b)=>{let y=`$.capabilityUses[${b}]`,A=V(S,y);return K(A,["file","line","symbol","capability","source"],y),{file:z(A,"file",y),line:ie(A,"line",y),symbol:w(A,"symbol",y),capability:le(A,"capability",gs,y),source:le(A,"source",["ambient-global","import-based"],y)}}),l=q(e,"ambientUses","$").map((S,b)=>{let y=`$.ambientUses[${b}]`,A=V(S,y);return K(A,["file","line","symbol"],y),{file:z(A,"file",y),line:ie(A,"line",y),symbol:w(A,"symbol",y)}}),u=q(e,"publishCalls","$").map((S,b)=>{let y=`$.publishCalls[${b}]`,A=V(S,y);K(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let x=ae(A,"rawIntentName",y),O=ae(A,"sourceIntent",y);return{file:z(A,"file",y),line:ie(A,"line",y),...x?{rawIntentName:x}:{},objectHasIntent:F(A,"objectHasIntent",y),arkPublishCandidate:F(A,"arkPublishCandidate",y),hasSource:F(A,"hasSource",y),...O?{sourceIntent:O}:{}}}),f=q(e,"intentReferences","$").map((S,b)=>{let y=`$.intentReferences[${b}]`,A=V(S,y);return K(A,["file","line","intent"],y),{file:z(A,"file",y),line:ie(A,"line",y),intent:w(A,"intent",y)}}),m=q(e,"safetyUses","$").map((S,b)=>{let y=`$.safetyUses[${b}]`,A=V(S,y);K(A,["file","line","kind","symbol"],y);let x=ae(A,"symbol",y),O=le(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(O==="in-memory-store"&&!x)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(O!=="in-memory-store"&&x)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:z(A,"file",y),line:ie(A,"line",y),kind:O,...x?{symbol:x}:{}}});Ma(o,S=>S.path,"$.files");let d=new Set(o.map(S=>S.path));for(let S of o){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!d.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let p=(e.arkRunKernelCalls===void 0?[]:q(e,"arkRunKernelCalls","$")).map((S,b)=>{let y=`$.arkRunKernelCalls[${b}]`,A=V(S,y);K(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],y);let x=ae(A,"receiver",y),O=ae(A,"nameLiteral",y);return{file:z(A,"file",y),line:ie(A,"line",y),kind:le(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],y),callee:w(A,"callee",y),viaImport:F(A,"viaImport",y),...x?{receiver:x}:{},...O?{nameLiteral:O}:{}}}),k=(e.arkRunManagedNews===void 0?[]:q(e,"arkRunManagedNews","$")).map((S,b)=>{let y=`$.arkRunManagedNews[${b}]`,A=V(S,y);K(A,["file","line","typeName","importedFrom"],y);let x=ae(A,"importedFrom",y);return{file:z(A,"file",y),line:ie(A,"line",y),typeName:w(A,"typeName",y),...x?{importedFrom:x}:{}}}),R=(e.arkRunCompositionRootHits===void 0?[]:q(e,"arkRunCompositionRootHits","$")).map((S,b)=>{let y=`$.arkRunCompositionRootHits[${b}]`,A=V(S,y);return K(A,["file","matchedRoot","hasKernelFactory"],y),{file:z(A,"file",y),matchedRoot:w(A,"matchedRoot",y),hasKernelFactory:F(A,"hasKernelFactory",y)}}),C=(e.arkRunDeclarations===void 0?[]:q(e,"arkRunDeclarations","$")).map((S,b)=>{let y=`$.arkRunDeclarations[${b}]`,A=V(S,y);return K(A,["file","line","uses","reactsTo","raises","sends"],y),{file:z(A,"file",y),line:ie(A,"line",y),uses:Pe(A.uses,`${y}.uses`),reactsTo:Pe(A.reactsTo,`${y}.reactsTo`),raises:Pe(A.raises,`${y}.raises`),sends:Pe(A.sends,`${y}.sends`)}});for(let[S,b]of[["$.capabilityUses",i],["$.ambientUses",l],["$.publishCalls",u],["$.intentReferences",f],["$.safetyUses",m],["$.arkRunKernelCalls",p],["$.arkRunManagedNews",k],["$.arkRunCompositionRootHits",R],["$.arkRunDeclarations",C]])for(let y of b)if(!d.has(y.file))throw new Error(`${S} references missing file ${y.file}.`);let H=ae(e,"projectPackageName","$"),j=(e.classShapes===void 0?[]:q(e,"classShapes","$")).map((S,b)=>{let y=`$.classShapes[${b}]`,A=V(S,y);K(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],y);let x=q(A,"mutatingMethods",y).map((O,B)=>{let me=`${y}.mutatingMethods[${B}]`,Ve=V(O,me);return K(Ve,["name","referencesGuardOrPublish"],me),{name:w(Ve,"name",me),referencesGuardOrPublish:F(Ve,"referencesGuardOrPublish",me)}});return{file:z(A,"file",y),className:w(A,"className",y),exported:F(A,"exported",y),hasPublicMutableFields:F(A,"hasPublicMutableFields",y),hasPublicSetters:F(A,"hasPublicSetters",y),hasPublicConstructor:F(A,"hasPublicConstructor",y),hasStaticFactory:F(A,"hasStaticFactory",y),mutatingMethods:x,...A.dataOnly===void 0?{}:{dataOnly:F(A,"dataOnly",y)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:w(e,"resolverIdentity","$"),compilerIdentity:w(e,"compilerIdentity","$"),compilerOptionsHash:w(e,"compilerOptionsHash","$"),tsconfigHash:w(e,"tsconfigHash","$"),evidenceRequirementsHash:w(e,"evidenceRequirementsHash","$"),...H?{projectPackageName:H}:{},files:o,dependencies:a,capabilityUses:i,ambientUses:l,publishCalls:u,intentReferences:f,safetyUses:m,classShapes:j,arkRunKernelCalls:p,arkRunManagedNews:k,arkRunCompositionRootHits:R,arkRunDeclarations:C}}function ce(e){let t=V(e,"$"),n=w(t,"factsHash","$"),r=w(t,"candidateTreeHash","$"),s=ys(As(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}var Da=["network","filesystem","clock","randomness","environment","process","persistence"],T={type:"string",minLength:1},de={type:"integer",minimum:1},Y={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},jt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:T,message:T,file:Y}}},resolverIdentity:T,compilerIdentity:T,compilerOptionsHash:T,tsconfigHash:T,candidateTreeHash:T,evidenceRequirementsHash:T,projectPackageName:T,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:Y,contentHash:T,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:T},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:Y,specifier:T,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:de,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:Y,namedBindings:{type:"array",items:T},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:Y,line:de,symbol:T,capability:{enum:Da},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:Y,line:de,symbol:T}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:Y,line:de,rawIntentName:T,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:T}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:Y,line:de,intent:T}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:Y,line:de,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:T},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:Y,className:T,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:T,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:Y,line:de,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:T,viaImport:{type:"boolean"},receiver:T,nameLiteral:T}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:Y,line:de,typeName:T,importedFrom:T}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:Y,matchedRoot:T,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:Y,line:de,uses:{type:"array",items:T},reactsTo:{type:"array",items:T},raises:{type:"array",items:T},sends:{type:"array",items:T}}}},factsHash:T},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Vt="1.0";function Z(e){return`${e.from}->${e.to}`}function tt(e,t,n,r="dependency"){return{id:`${e}:${r}:${Z(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Z(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Z(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Z(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Z(t)} from the candidate, then preflight again.`}:{}}}function ve(e){let t=[],n=new Map(e.changeMap.map.files.map(d=>[d.path,d])),r=new Map(e.changes.map(d=>[d.path,d])),s=new Map(e.changeMap.map.dependencies.map(d=>[Z(d),d])),o=new Map(e.baseDependencies.map(d=>[Z(d),d])),a=new Map(e.candidateDependencies.map(d=>[Z(d),d]));for(let d of[...n.values()].sort((c,p)=>c.path.localeCompare(p.path))){let c=r.get(d.path);c?c.operation!==d.operation?t.push({id:`contradictory:file:${d.path}`,classification:"contradictory",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:c.operation,message:`${d.path} was planned as ${d.operation} but the actual operation is ${c.operation}.`,nextAction:`Change ${d.path} to the planned ${d.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${d.path}`,classification:"satisfied",subject:"file",path:d.path,expectedOperation:d.operation,actualOperation:c.operation,message:`${d.path} matches the planned ${d.operation} operation.`}):t.push({id:`missing:file:${d.path}`,classification:"missing",subject:"file",path:d.path,expectedOperation:d.operation,message:`${d.path} was planned as ${d.operation} but is absent from the actual change.`,nextAction:`${d.operation[0].toUpperCase()}${d.operation.slice(1)} ${d.path} in the complete change set, then preflight again.`})}for(let d of[...r.values()].sort((c,p)=>c.path.localeCompare(p.path)))n.has(d.path)||t.push({id:`unplanned:file:${d.path}`,classification:"unplanned",subject:"file",path:d.path,actualOperation:d.operation,message:`${d.path} has an unplanned ${d.operation} operation.`,nextAction:`Remove ${d.path} from the change set, then preflight again.`});let i=new Set;for(let d of[...s.values()].sort((c,p)=>Z(c).localeCompare(Z(p)))){if(a.has(Z(d))){t.push(tt("satisfied",d,`${d.from} -> ${d.to} exists in the candidate architecture.`));continue}let c={from:d.to,to:d.from};a.has(Z(c))?(i.add(Z(c)),t.push(tt("contradictory",d,`${d.from} -> ${d.to} was planned, but the candidate contains the reverse edge.`))):t.push(tt("missing",d,`${d.from} -> ${d.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[d,c]of[...a].sort(([p],[g])=>p.localeCompare(g)))o.has(d)||s.has(d)||i.has(d)||!l.has(c.from)&&!l.has(c.to)||t.push({...tt("unplanned",c,`${c.from} -> ${c.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(d=>d.operation==="delete").map(d=>d.path));for(let[d,c]of[...o].sort(([p],[g])=>p.localeCompare(g)))a.has(d)||u.has(c.from)||u.has(c.to)||!l.has(c.from)&&!l.has(c.to)||t.push({...tt("unplanned",c,`${c.from} -> ${c.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let f={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((d,c)=>f[d.classification]-f[c.classification]||(d.subject===c.subject?0:d.subject==="file"?-1:1)||d.id.localeCompare(c.id));let m={satisfied:t.filter(d=>d.classification==="satisfied").length,missing:t.filter(d=>d.classification==="missing").length,contradictory:t.filter(d=>d.classification==="contradictory").length,unplanned:t.filter(d=>d.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var Ss="1.0",Qn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",er=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Fa=["no-anemic-model"],Rs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Kt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Qn,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:Qn},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:[...er]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Rs,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:Rs}}}},Ce=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
|
5
5
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
6
|
-
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function
|
|
6
|
+
`)}`),this.name="ArkRulesValidationError",this.source=t,this.issues=n}};function st(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ut(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function nt(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function $a(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function rt(e,t,n,r,s){if(t.$ref){let o=$a(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}rt(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!st(e)){s.push({path:n,message:`must be an object; received ${nt(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:Ut(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:Ut(n,a),message:"unknown field"});else if(st(t.additionalProperties)){let a=t.additionalProperties;for(let i of Object.keys(e))i in o||rt(e[i],a,Ut(n,i),r,s)}for(let[a,i]of Object.entries(o))e[a]!==void 0&&rt(e[a],i,Ut(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${nt(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>rt(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${nt(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}t.type==="boolean"&&typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${nt(e)}`})}function Ha(e){return{...e,$schema:e.$schema===void 0?Qn:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,structure:e.structure===void 0?[]:e.structure,invariants:e.invariants===void 0?[]:e.invariants}}function ks(e){return e==="enforced"?"enforced":"advisory"}function ja(e){return Fa.includes(e)}function Va(e,t){let n=Array.isArray(e.structure)?e.structure:[],r=Array.isArray(e.invariants)?e.invariants:[],s=new Set;n.forEach((o,a)=>{if(!st(o))return;let i=typeof o.id=="string"?o.id:"";i&&(s.has(i)&&t.push({path:`$.structure[${a}].id`,message:`duplicate rule id ${JSON.stringify(i)}`}),s.add(i)),typeof o.sensor=="string"&&ja(o.sensor)&&o.mode==="enforced"&&t.push({path:`$.structure[${a}].mode`,message:`sensor ${JSON.stringify(o.sensor)} is Tier-2 advisory-only and cannot be enforced`}),Array.isArray(o.appliesTo)&&o.appliesTo.length===0&&t.push({path:`$.structure[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})}),r.forEach((o,a)=>{if(!st(o))return;let i=typeof o.id=="string"?o.id:"";i&&(s.has(i)&&t.push({path:`$.invariants[${a}].id`,message:`duplicate rule id ${JSON.stringify(i)}`}),s.add(i)),Array.isArray(o.appliesTo)&&o.appliesTo.length===0&&t.push({path:`$.invariants[${a}].appliesTo`,message:"must not be an empty array (omit the field to apply to the whole layer)"})})}function ot(e,t="arkrules.json",n){if(!st(e))throw new Ce(t,[{path:"$",message:`must be an object; received ${nt(e)}`}]);let r=Ha(e),s=[];if(rt(r,Kt,"$",Kt,s),Va(r,s),n!==void 0&&typeof r.layer=="string"&&r.layer!==n&&s.push({path:"$.layer",message:`must match referencing key ${JSON.stringify(n)}; received ${JSON.stringify(r.layer)}`}),s.length>0)throw new Ce(t,s);return{config:r}}function Es(e,t="arkrules.json",n){let r;try{r=JSON.parse(e)}catch(s){throw new Ce(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return ot(r,t,n)}function Gt(e){let t={},n=[],r=[],s=[...e].sort((o,a)=>o.layer.localeCompare(a.layer));for(let o of s){let a=(o.file.structure??[]).map(l=>({...l,mode:ks(l.mode),provenance:{sourceFile:o.sourceFile,ruleId:l.id,layer:o.layer}})),i=(o.file.invariants??[]).map(l=>({...l,mode:ks(l.mode),provenance:{sourceFile:o.sourceFile,ruleId:l.id,layer:o.layer}}));t[o.layer]={sourceFile:o.sourceFile,structure:a,invariants:i},n.push(...a),r.push(...i)}return n.sort((o,a)=>{let i=o.provenance.layer.localeCompare(a.provenance.layer);return i!==0?i:o.id.localeCompare(a.id)}),r.sort((o,a)=>{let i=o.provenance.layer.localeCompare(a.provenance.layer);return i!==0?i:o.id.localeCompare(a.id)}),{schemaVersion:"1.0",byLayer:t,structure:n,invariants:r}}function Ae(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}var at=class extends Error{issues;source;constructor(t,n){super(`Invalid Effective Contract (${t}):
|
|
7
7
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
8
|
-
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Gr(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Br(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let d of[...e.discoveredArkRulesFiles].sort())r.push({path:d,message:`ArkRules file ${JSON.stringify(d)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:le(),warnings:r}}let s=new Set(e.config.layers.map(d=>d.name)),i=[],o=[],a=new Set;for(let d of Object.keys(n).sort()){let f=n[d],g=`$.arkRules[${JSON.stringify(d)}]`;if(typeof f!="string"||f.length===0){i.push({path:g,message:"must be a non-empty relative path string"});continue}if(f.startsWith("/")||/^[A-Za-z]:[\\/]/.test(f)){i.push({path:g,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(d)){i.push({path:g,message:`layer ${JSON.stringify(d)} is not declared in layers[]`});continue}let m=Gr(f);a.add(m);let c=e.fileContents[m]??e.fileContents[f];if(c===void 0){i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} is missing`});continue}try{let l=We(JSON.parse(c),m,d);o.push({layer:d,sourceFile:m,file:l.config})}catch(l){if(l instanceof ye)for(let p of l.issues)i.push({path:`${g}${p.path==="$"?"":p.path.replace(/^\$/,"")}`,message:`${m}: ${p.message}`});else l instanceof SyntaxError?i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} is not valid JSON: ${l.message}`}):i.push({path:g,message:`referenced ArkRules file ${JSON.stringify(m)} failed to load: ${l instanceof Error?l.message:String(l)}`})}}if(e.discoveredArkRulesFiles)for(let d of[...e.discoveredArkRulesFiles].sort()){let f=Gr(d);a.has(f)||r.push({path:f,message:`ArkRules file ${JSON.stringify(f)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(i.length>0)throw new Je(t,i);return{config:e.config,arkRules:Ot(o),warnings:r}}function Pt(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}function Ui(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function Gi(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let i of Object.values(e))if(!(s&&!i.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(i)||i.includes(t)))return!0;return!1}function Lt(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],i=[];for(let o of t){let a=[],d=o.coverage?.test!==!1,f=o.coverage?.symbol;if(!r&&d)for(let l of n){let p=e.fileContents[l];if(p&&Ui(p,o.id)){a.push("test-title");break}}f&&Gi(e.fileContents,f)&&a.push("symbol");let m=(o.coverage?.test===!0||!!f||o.coverage===void 0)&&a.length>0||o.coverage?.test===!1&&!f?!0:a.length>0,c=r&&d&&a.length===0;if(s.push({invariantId:o.id,layer:o.provenance.layer,sourceFile:o.provenance.sourceFile,mode:o.mode,covered:m&&!c,evidence:a,partial:c,description:o.description}),!m||c){let l=o.mode==="enforced"&&!c,p=r||n.length===0?"never-had-tests":"tests-disappeared";i.push({ruleId:"INVARIANT_UNCOVERED",message:c?`Invariant ${o.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:p==="tests-disappeared"?`Invariant ${o.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${o.id} is not covered by a test title or declared symbol (never-had-tests).`,file:o.provenance.sourceFile,line:1,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,fromLayer:o.provenance.layer,severity:l?"error":"warning",failsStrict:l,kind:p})}}return{coverage:s,violations:i,partial:s.some(o=>o.partial)}}function Nt(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}var $t="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function z(e){return[...new Set(e??[])].sort()}function he(e,t,n,r,s){let i=z(n),o=z(r),a=new Set(i),d=new Set(o),f=o.filter(m=>!a.has(m)),g=i.filter(m=>!d.has(m));f.length===0&&g.length===0||(f.length>0&&C(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:i,after:o}),g.length>0&&C(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:i,after:o}))}function wt(e,t,n,r,s,i,o){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?i:o,before:n,after:r})}function Mt(e,t){let n=new Map,r=new Set;for(let s of e){let i=t(s);n.has(i)?r.add(i):n.set(i,s)}return{values:n,duplicates:[...r].sort()}}function Bi(e,t,n){let r=Mt(t,i=>i.name),s=Mt(n,i=>i.name);(r.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let i of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let o=r.values.get(i),a=s.values.get(i),d=`$.layers[${i}]`;if(!o&&a){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:a});continue}if(o&&!a){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!a)continue;he(e,`${d}.patterns`,o.patterns,a.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),he(e,`${d}.exclude`,o.exclude,a.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=At(o),g=At(a);he(e,`${d}.forbiddenGlobals`,f.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),he(e,`${d}.capabilities`,f.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),z(o.intentPrefixes).join("\0")!==z(a.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:z(o.intentPrefixes),after:z(a.intentPrefixes)}),wt(e,`${d}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,a.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),wt(e,`${d}.optional`,o.optional===!0,a.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Ki(e,t,n){let r=o=>`${o.from}->${o.to}`,s=Mt(t,r),i=Mt(n,r);(s.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:i.duplicates});for(let o of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let a=s.values.get(o),d=i.values.get(o),f=`$.rules[${o}]`;if(!a&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(a&&!d){a.allowed===!1&&C(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:a});continue}if(!a||!d)continue;a.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:a.allowed,after:d.allowed});let g=a.peerIsolation===!0,m=d.peerIsolation===!0;if(g!==m){let c=a.from===a.to&&d.from===d.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.peerIsolation`,classification:c?m?"strengthening":"weakening":"judgment-required",message:c?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:m})}z(a.sliceFolders).join("\0")!==z(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:z(a.sliceFolders),after:z(d.sliceFolders)})}}function zi(e,t,n){let r=t.safety??{},s=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let o=r[i]??0,a=s[i]??0;o!==a&&C(e,{kind:a>o?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:a>o?"weakening":"strengthening",message:a>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:a})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])wt(e,`$.safety.${i}`,r[i]===!0,s[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function qi(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function Kr(e,t){return`${e}::${t}`}function zr(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Kr(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Kr(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Yi(e,t,n,r,s,i){let o=new Map((i??[]).map(c=>[c.invariantId,c])),a=t.arkRules??{},d=n.arkRules??{},f=[...new Set([...Object.keys(a),...Object.keys(d)])].sort();for(let c of f){let l=a[c],p=d[c],y=`$.arkRules[${c}]`;if(l===void 0&&p!==void 0){C(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${c} was added.`,after:p});continue}if(l!==void 0&&p===void 0){C(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${c} was removed.`,before:l});continue}l!==p&&C(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${c} changed; verify the effective rules still match intent.`,before:l,after:p})}let g=zr(r),m=zr(s);for(let c of[...new Set([...g.structure.keys(),...m.structure.keys()])].sort()){let l=g.structure.get(c),p=m.structure.get(c),y=`$.arkRules.structure[${c}]`;if(!l&&p){C(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${p.id} was added (${p.mode}).`,after:p});continue}if(l&&!p){C(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${l.id} was removed.`,before:l});continue}if(!(!l||!p)){if(l.mode!==p.mode){let I=l.mode==="advisory"&&p.mode==="enforced";C(e,{kind:I?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:I?"strengthening":"weakening",message:I?`Structure ArkRule ${p.id} was promoted to enforced.`:`Structure ArkRule ${p.id} was demoted to advisory.`,before:l.mode,after:p.mode})}l.sensor!==p.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${p.id} changed sensor identity.`,before:l.sensor,after:p.sensor})}}for(let c of[...new Set([...g.invariants.keys(),...m.invariants.keys()])].sort()){let l=g.invariants.get(c),p=m.invariants.get(c),y=`$.arkRules.invariants[${c}]`;if(!l&&p){C(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${p.id} was added (${p.mode}).`,after:p});continue}if(l&&!p){C(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${l.id} was removed.`,before:l});continue}if(!(!l||!p)&&l.mode!==p.mode)if(l.mode==="advisory"&&p.mode==="enforced"){let E=o?.get(p.id),u=Nt(E);u.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${p.id} was promoted to enforced (coverage evidence present).`,before:l.mode,after:p.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${p.id} cannot be promoted to enforced: ${u.reason}`,before:l.mode,after:p.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${p.id} was demoted to advisory.`,before:l.mode,after:p.mode})}}function Dt(e,t,n){let r=[];he(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),he(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),he(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),wt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",o=t.cyclePolicy??"strict";if(i!==o){let a=s[o]===s[i]?"judgment-required":s[o]>s[i]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:i,after:o})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Bi(r,e.layers,t.layers),Ki(r,e.rules,t.rules),zi(r,e,t),Yi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),r.sort((a,d)=>a.path.localeCompare(d.path)||a.id.localeCompare(d.id)),{schemaVersion:$t,classification:qi(r),findings:r}}function Ft(e,t){if(!e||e.schemaVersion!==$t||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=z(e.findingIds),r=z(t.findingIds);return n.length===r.length&&n.every((s,i)=>s===r[i])}function Ae(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function qr(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Ht(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function G(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function Ze(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};i==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=i}}function q(e,t,n){return e.startsWith(t,n)&&!Ht(e[n-1])&&!Ht(e[n+t.length])}function Yr(e,t){let n=G(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=G(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!q(e,"type",n))return!1;let s=G(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||q(e,"as",s)||!qr(e[s]))return!1;for(n=s;n<e.length&&Ht(e[n]);)n+=1;if(n=G(e,n),q(e,"as",n)){if(n=G(e,n+2),!qr(e[n]))return!1;for(;n<e.length&&Ht(e[n]);)n+=1}r=!0}return!1}function Wi(e,t){if(t=G(e,t+6),e[t]==="(")return Ze(e,G(e,t+1));let n=!1;if(q(e,"type",t)){let s=G(e,t+4);e[s]!==","&&!q(e,"from",s)&&(n=!0)}else Yr(e,t)&&(n=!0);let r=Wr(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Ji(e,t){t=t+6;let n=G(e,t),r=!1;if(q(e,"type",n)){let i=G(e,n+4);(e[i]==="{"||e[i]==="*")&&(r=!0)}else Yr(e,n)&&(r=!0);let s=Wr(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Wr(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(q(e,"from",t))return Ze(e,G(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ze(e,t);if(t>0&&(q(e,"import",t)||q(e,"export",t)))return}}function Zi(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function Xi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=G(e,t+7);if(e[r]!=="(")return;r=G(e,r+1);let s=Ze(e,r);return s?{...s,requireCall:!0}:void 0}function Qi(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
9
|
-
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let
|
|
10
|
-
`).length;r.push({file:e.path,symbol:
|
|
11
|
-
`).length,a={kind:"import",file:e.path,line:o,excerpt:s.excerpt},d=eo(e.path,i,t);n.push({from:e.path,specifier:i,to:d?.path??null,resolution:d?"resolved":"unresolved",fromLayer:e.layer,toLayer:d?.layer??null,evidence:a})}return{edges:n,capabilityUses:r}}function eo(e,t,n){let r=e.split("/");r.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?r.pop():r.push(i));let s=r.join("/");for(let i of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let o=n.get(i);if(o)return o}}function Zr(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=ee(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var to={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function no(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function ro(e,t){return no(e,t)?M(x(Pt({config:e,arkRules:t,warnings:[]}))):M(x(e))}function Xe(e,t,n){let r=typeof e=="string"?vt(e,t):Ue(e,t),s=n?.arkRules??le();return{...r,arkRules:s,policyHash:ro(r.config,s)}}function Tn(e){let t=Xe(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Xe(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Dt(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(a=>a.classification==="weakening"||a.classification==="judgment-required").map(a=>a.id).sort(),i=s.length>0,o=i&&Ft(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:i,acknowledged:o,valid:!i||o}}function xe(e){let t=e.files.map(m=>{let c=Ae(m.path);return{path:c,content:m.content,contentHash:M(m.content),layer:Q(c,e.contract.config.layers)??null}}).sort((m,c)=>m.path.localeCompare(c.path)),n=new Map(t.map(m=>[m.path,m])),r=[],s=[];for(let m of t){let c=Jr(m,n);r.push(...c.edges),s.push(...c.capabilityUses)}let i=Zr(r,e.contract.config),o=new Map(e.contract.config.layers.map(m=>[m.name,m])),a=new Map(e.contract.config.layers.map(m=>[m.name,new Set(be(m))]));for(let m of s){let c=n.get(m.file)?.layer;if(!c)continue;let l=o.get(c),p=ie(m.symbol,l?.forbiddenGlobals??[]);if(p){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${c} must not use module "${m.symbol}" because it is the import form of forbidden global "${p}".`,symbol:m.symbol,evidence:m.evidence});continue}a.get(c)?.has(m.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${c} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let d=t.length===0?"complete":"partial",f=d==="complete"?[]:[{...to}],g={schemaVersion:_t,policyHash:e.contract.policyHash,compilerOptionsHash:M(x(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:s,violations:i};return{mode:"lexical-compatibility",completeness:d,completenessReasons:f,valid:d==="complete"&&i.length===0,ir:g}}function Qe(e){let t=new Map(e.files.map(n=>[Ae(n.path),n]));for(let n of e.changes){let r=Ae(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return xe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function On(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function Vt(e){let t=0,n=new Map,r=new Map,s=new Set,i=[],o=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),s.add(d);for(let m of[...e.get(d)??[]].sort())e.has(m)&&(n.has(m)?s.has(m)&&r.set(d,Math.min(r.get(d)??0,n.get(m)??0)):(a(m),r.set(d,Math.min(r.get(d)??0,r.get(m)??0))));if(r.get(d)!==n.get(d))return;let f=[],g;do{if(g=i.pop(),g===void 0)break;s.delete(g),f.push(g)}while(g!==d);f.length>1&&o.push(f.sort())};for(let d of[...e.keys()].sort())n.has(d)||a(d);return o.sort((d,f)=>d[0]<f[0]?-1:d[0]>f[0]?1:0).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Ie(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),r=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&r.has(i.from)&&r.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let o=ee(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!o)continue;let a=!!o.peerIsolation,d=!a&&!!(i.typeOnly||i.namedBindingsTypeOnly),f=o.message??(a?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!a&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...a?{peerIsolation:!0}:{},message:d?`${f} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:f,...d?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let i=Vt(r);s==="soft"||s==="framework-soft"?n.push(...i.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}var so=["no-anemic-model"];function Xr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function io(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let i=e[r+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Xr(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Xr(s)}return new RegExp(`^${n}$`)}function et(e,t){return!t||t.length===0?!0:t.some(n=>io(n).test(e))}function oo(e){return so.includes(e)}function Qr(e){return e.mode==="enforced"&&!oo(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function Te(e,t,n,r=1){let{severity:s,failsStrict:i}=Qr(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:i}}function Pn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function jt(e,t,n){return t.filter(r=>!(!r.exported||!et(r.file,e.appliesTo)||!Pn(r.file,e,n)))}function ao(e,t,n){let r=[];for(let s of jt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(Te(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function lo(e,t,n){let r=[];for(let s of jt(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(Te(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function co(e,t,n){let r=[];for(let s of jt(e,t,n))for(let i of s.mutatingMethods)i.referencesGuardOrPublish||r.push(Te(e,s.file,`Mutating method ${s.className}.${i.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function po(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&Pn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Te(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}function uo(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&Pn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Te(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}function fo(e,t,n){let r=[];for(let s of jt(e,t,n))if(s.dataOnly===!0){let i=Te(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...i,severity:"warning",failsStrict:!1})}return r}function Ut(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...ao(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...lo(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...co(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...po(n,e));break;case"thin-adapter":t.push(...uo(n,e));break;case"no-anemic-model":t.push(...fo(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function Gt(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>et(d,s.appliesTo)))continue;let{severity:o,failsStrict:a}=Qr(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:o,sensor:s.sensor,failsStrict:a})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(a=>et(a,s.appliesTo)))continue;let o=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:o?"error":"warning",sensor:"invariant-coverage",failsStrict:o})}return n.sort((s,i)=>s.file.localeCompare(i.file)||s.arkruleId.localeCompare(i.arkruleId)||s.message.localeCompare(i.message))}var mo=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,go=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,yo=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,ho=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Ao=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Ln(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(ho.source,"g"))??[],r=t.match(new RegExp(Ao.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,i=(t.match(/\bswitch\s*\(/g)??[]).length,o=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+i>=6,a=mo.test(t),d=go.test(t)||yo.test(t),f=n.length>=1||r.length>=2,g=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=a&&f||d&&f||a&&g&&(s>=4||n.length>=1)||d&&a;return!o&&!m?null:{...o?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{}}}function Bt(e){let t={};for(let[n,r]of Object.entries(e)){let s=Ln(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function es(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let i=s[1],o=s.index+s[0].length,a=1,d=o;for(;d<t.length&&a>0;){let _=t[d];_==="{"?a+=1:_==="}"&&(a-=1),d+=1}let f=t.slice(o,d-1),g=f.split(`
|
|
12
|
-
`).map(
|
|
13
|
-
`),m=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(
|
|
14
|
-
`).filter(
|
|
15
|
-
`)),l=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(f),p=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(f),y=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(f)&&!p,I=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(f)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(f),E=[],u=new Set(["if","match","when"]),h=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,S;for(;(S=h.exec(f))!==null;){let _=S[1];if(u.has(_))continue;let v=S.index+S[0].length,L=1,O=v;for(;O<f.length&&L>0;)f[O]==="{"?L+=1:f[O]==="}"&&(L-=1),O+=1;let j=f.slice(v,O-1);if(!/this\.\w+\s*=/.test(j))continue;let A=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(j);E.push({name:_,referencesGuardOrPublish:A})}let k=(f.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,N=(g.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,F=k<=1&&N>=2&&(c||m);n.push({file:e,className:i,exported:!0,hasPublicMutableFields:c||m,hasPublicSetters:l,hasPublicConstructor:y,hasStaticFactory:I,mutatingMethods:[...E],dataOnly:F})}return n}function V(e,t,n={}){return{ruleId:e,message:t,...n}}function tt(e){let{config:t,rules:n,files:r,manifest:s}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(V("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(V("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[l];p!==void 0&&(!Number.isInteger(p)||p<0)&&i.push(V("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],a=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],d=new Set([...o.map(l=>l.name).filter(Boolean),...a.map(l=>l.name).filter(l=>!!l)]);o.length===0&&i.push(V("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let f=new Set,g=new Set;for(let l of o){if(!l.name){i.push(V("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}f.has(l.name)&&g.add(l.name),f.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(y=>typeof y!="string"))&&i.push(V("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let p=Array.isArray(l.patterns)?l.patterns:[];if(p.length===0){i.push(V("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let y of p){let I;try{I=pe(y)}catch(u){i.push(V("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${y}": ${u instanceof Error?u.message:String(u)}`,{layer:l.name,pattern:y}));continue}let E=l.optional===!0||l.reserved===!0||l.allowEmpty===!0;!r.some(u=>I.test(u))&&!E&&i.push(V("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:l.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let l of g)i.push(V("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(d.size>0)for(let l of n??[])l.from&&!d.has(l.from)&&i.push(V("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!d.has(l.to)&&i.push(V("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(o.length>1)for(let l of r){let p=-1,y=[];for(let I of o)for(let E of I.patterns??[]){if(!pe(E).test(l))continue;let u=yn(E,l);u>p?(p=u,y=[I.name]):u===p&&!y.includes(I.name)&&y.push(I.name)}y.length>1&&m.add([...y].sort().join(" + "))}m.size>0&&i.push(V("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let c=r.filter(l=>!Q(l,o));return c.length>0&&i.push(V("CONFIG_UNCLASSIFIED_FILES",`${c.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:c.length,samples:c.slice(0,5)})),i}function Io(e,t){return t.some(n=>{try{return pe(n).test(e)}catch{return!1}})}function bo(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],o=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:I})=>({file:y,line:I})),a=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:I})=>({file:y,line:I})),d=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Io(y.file,i)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),f=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),m={tsSuppressions:o,anyCasts:a,nonLiteralDynamicImports:d,inMemoryProductionStores:f,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},c=[],l=d.filter(y=>y.kind==="import");if(l.length>0){let y=l[0];c.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let p=d.filter(y=>y.kind==="require");if(p.length>0){let y=p[0];c.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>r){let y=o[0];c.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(a.length>s){let y=a[0];c.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(f.length>0){let y=f[0];c.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${f.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&c.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:c}}function So(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function ts(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return En(e,n.length>0?n:Sn.map(r=>({name:r.layer,prefixes:r.prefixes})))}function Eo(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let o=n.get(i.file);!o||!So(i.symbol,s.get(o)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,message:`${o} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let o=n.get(i.file);if(!o)continue;let a=s.get(o),d=a?.forbiddenGlobals??[],f=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&$e(i.symbol,d))){if(i.source==="import-based"){let g=ie(i.symbol,d);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,...f?{edgeKind:f}:{},message:`${o} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}be(a).includes(i.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:o,target:i.symbol,capability:i.capability,...f?{edgeKind:f}:{},message:i.source==="import-based"?`${o} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${o} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let o=n.get(i.file);if(!o)continue;for(let d of De({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))r.push({ruleId:d.ruleId,file:i.file,line:i.line,...d.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:d.message});if(!i.sourceIntent)continue;let a=ts(i.sourceIntent,e.contract);!a||a===o||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:o,toLayer:a,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${a}, but the publishing file is classified as ${o}.`})}for(let i of t.intentReferences){let o=n.get(i.file);if(!o)continue;let a=ts(i.intent,e.contract);if(!a)continue;let d=ee(e.contract.config.rules,o,a);d&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:o,toLayer:a,target:i.intent,message:d.message??`${o} must not reference ${a} intent ${i.intent}.`})}return r}function Ro(e){let{facts:t}=e,n=ke(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",i=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((A,B)=>{let Ne=`${A.code}\0${A.file??""}\0${A.message}`,we=`${B.code}\0${B.file??""}\0${B.message}`;return Ne<we?-1:Ne>we?1:0}),o=t.files.map(A=>({...A,layer:Q(A.path,e.contract.config.layers)??null})),a=new Map(o.map(A=>[A.path,A.layer])),d=t.dependencies.map(A=>{let B=A.target?a.get(A.target)??Q(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:a.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...B?{toLayer:B}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),f=tt({config:e.contract.config,rules:e.contract.config.rules,files:o.map(A=>A.path)}),g=bo(e,t),m=e.contract.arkRules??le(),c=o.map(A=>A.path),p={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Bt(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Ut({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:c,layerForFile:A=>a.get(A)??Q(A,e.contract.config.layers),fileHints:p}),...Gt(m,c)],I=y.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${A.arkruleId} in ${A.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),E=y.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${A.arkruleId} in ${A.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${A.arkruleId} in ${A.arkruleSource} (advisory).`})),h=(m.invariants?.length??0)>0?Lt({arkRules:m,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},S=h.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),k=h.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),F=h.partial&&h.coverage.some(A=>A.mode==="enforced"&&A.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],_=Ie({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(A=>A.layer).map(A=>A.path),contentViolations:[...Eo(e,t,a),...I,...S],edges:d,warnings:[...f,...g.warnings,...E,...k],safety:g.report}),v=s==="complete"&&F.length>0?"partial":s,L=v==="complete"?i:[...i,...F].sort((A,B)=>{let Ne=`${A.code}\0${A.file??""}\0${A.message}`,we=`${B.code}\0${B.file??""}\0${B.message}`;return Ne<we?-1:Ne>we?1:0}),O=_.violations.filter(A=>A.failsStrict!==!1),j=v==="complete"&&O.length===0,de=j&&_.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:v,completenessReasons:L,valid:j,strictValid:de,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:o,layers:e.contract.config.layers.map(A=>A.name),edges:d,capabilityUses:t.capabilityUses,violations:_.violations,warnings:_.warnings}}}function Oe(e){return Ro({contract:e.contract,facts:se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}function ns(e){return M(x(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function Nn(e){let t=xe(e),n=new Map(t.ir.files.map(p=>[p.path,p])),r=[],s=new Set,i=[];for(let p of e.changes){let y=p.path.replace(/\\/g,"/"),I=Ae(p.path);if(!I||I===".."||I.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(I)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:I,line:1,message:`The atomic change set contains more than one operation for ${I}.`});continue}s.add(I),"delete"in p&&p.delete&&!n.has(I)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:I,line:1,message:`Cannot delete ${I} because it is not present in the supplied base tree.`}),r.push("delete"in p&&p.delete?{path:I,delete:!0}:{path:I,content:"content"in p?p.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=Qe({...e,changes:r}),a=new Map(o.ir.files.map(p=>[p.path,p])),d=o.ir.violations.filter(p=>p.ruleId==="CAPABILITY_VIOLATION"||p.ruleId==="FORBIDDEN_GLOBAL").map(p=>{let y=a.get(p.evidence.file)?.layer;return{ruleId:p.ruleId,file:p.evidence.file,line:p.evidence.line,target:p.symbol,...p.capability?{capability:p.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:p.message}}),f=Ie({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(p=>p.path),contentViolations:d,edges:o.ir.edges.filter(p=>!!p.fromLayer).map(p=>({from:p.from,fromLayer:p.fromLayer,...p.to?{to:p.to}:{},...p.toLayer?{toLayer:p.toLayer}:{},line:p.evidence.line,kind:"import",...p.typeOnly?{typeOnly:!0}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(p=>{let y=Ae(p.path),I=n.get(y),E=a.get(y);return{path:y,operation:"delete"in p&&p.delete?"delete":I?"update":"create",...I?{beforeContentHash:I.contentHash}:{},...E?{candidateContentHash:E.contentHash}:{}}}).sort((p,y)=>p.path.localeCompare(y.path)),m=[...i,...f.violations].map(p=>({...p,nextAction:pt(p)})),c=m.filter(p=>p.failsStrict!==!1),l=e.changeMap?ge({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:o.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&o.valid&&c.length===0&&(l?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:ns(t.ir.files),candidateTreeHash:ns(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...l?{convergence:l}:{},changes:g,violations:m,warnings:f.warnings}}function vo(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function Co(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:i,message:`Base and candidate facts must use the same ${r}.`}))}function ko(e,t,n,r){let s=n.get(t),i=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function wn(e){let t=se(e.baseFacts),n=se(e.candidateFacts),r=Oe({contract:e.contract,facts:t}),s=Oe({contract:e.contract,facts:n}),i=new Map(t.files.map(l=>[l.path,l])),o=new Map(n.files.map(l=>[l.path,l])),a=Co(t,n),d=new Map,f=[];for(let l of e.changes){let p=vo(l.path);if(!p){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(d.has(p)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}d.set(p,l);let y=i.get(p),I=o.get(p);if("delete"in l&&l.delete)y||a.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base facts.`}),I&&a.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:p,line:1,message:`Candidate facts still contain deleted file ${p}.`});else{let E="content"in l?l.content:"",u=M(E);I?I.contentHash!==u&&a.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:p,line:1,expectedContentHash:u,candidateContentHash:I.contentHash,message:`Candidate facts for ${p} do not match the declared content.`}):a.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:p,line:1,message:`Candidate facts do not contain changed file ${p}.`})}f.push(ko(l,p,i,o))}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let l of new Set([...i.keys(),...o.keys()])){if(d.has(l))continue;let p=i.get(l),y=o.get(l);p&&y&&x(p)===x(y)||a.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:l,line:1,message:`Candidate facts change ${l}, but the atomic change set does not declare it.`})}let g=e.changeMap?ge({changeMap:e.changeMap,changes:f,baseDependencies:r.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:s.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0,m=[...a,...s.ir.violations].map(l=>({...l,nextAction:pt(l)})),c=m.filter(l=>l.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&c.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:f.sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),violations:m,warnings:s.ir.warnings}}function Kt(e,t){return e.slice(0,t).split(`
|
|
16
|
-
`).length}function rs(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function is(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}function ss(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||is(t,["Domain"])}function _o(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||is(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}function xo(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}function os(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([d,f])=>[rs(d),f])),s=new Map((e.layerContexts??[]).map(d=>[d.name,d.intentPrefixes??[]])),i=(e.layerContexts??[]).find(d=>ss(d.name,d.intentPrefixes))?.name??"DomainModel";for(let[d,f]of Object.entries(e.fileContents).sort(([g],[m])=>g.localeCompare(m))){let g=rs(d);if(xo(g)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(f.slice(0,320)))continue;let m=r.has(g),c=r.get(g),l=c?s.get(c)??[]:[],p=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(g)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(g)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(g),y=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(g),I=/(?:^|\/)actions?(?:\/|\.|$)/i.test(g)||/['"]use server['"]/.test(f),E=/controller|handler|resolver/i.test(d)||y||I||/route\.(?:ts|js|tsx|jsx)$/i.test(g)&&!p||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(f)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(f)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(f),u=m?!!(c&&_o(c,l)&&E):E,h=m?!!(c&&ss(c,l)):/domain|entity|aggregate|model/i.test(d),S=!m||h||u;if(u&&!p){let v=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,L;for(;(L=v.exec(f))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:d,line:Kt(f,L.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:c,suggestedArkRule:{layer:i,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let k=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,N,F=v=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(v)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(v)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(v)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(v)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(v)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(v)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(v)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(v)||/_(?:OID|OIDS)$/i.test(v)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(v)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(v),_=(v,L)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(v)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(v))return!0;let O=L.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(L)&&(/\s/.test(O)||/[.!?…]$/.test(O))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(v))};for(;(N=k.exec(f))!==null;){let v=N[2],L=N[3]??"";!S||F(v)||_(v,L)||p&&!h||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(g)&&!h||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:d,line:Kt(f,N.index),message:`Magic business constant ${v} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,invariantId:`INV-${v}`},neverMechanicalSafe:!0}))}if(h){let v=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,L;for(;(L=v.exec(f))!==null;){let O=L[2]??"",j=(O.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(O.match(/:\s*[A-Za-z]/g)??[]).length>=2&&j<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:d,line:Kt(f,L.index),message:`Class ${L[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(h&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(g)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(g)||/(?:^|\/)errors?(?:\/|$)/i.test(g))){let L=/this\.\w+\s*=/g,O;for(;(O=L.exec(f))!==null;){let j=f.lastIndexOf("class ",O.index),de=j>=0?f.indexOf("{",j):-1,A=j>=0&&de>=j&&de<O.index?f.slice(j,de):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(A))continue;let B=f.slice(Math.max(0,O.index-200),O.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(B)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:d,line:Kt(f,O.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:c,suggestedArkRule:{layer:i,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let o=new Set(e.contractedRuleIds??[]);t.sort((d,f)=>+(f.confidence==="direct-evidence")-+(d.confidence==="direct-evidence")||d.file.localeCompare(f.file)||d.line-f.line||d.kind.localeCompare(f.kind)||d.id.localeCompare(f.id));let a=t.filter(d=>d.suggestedArkRule?.invariantId&&o.has(d.suggestedArkRule.invariantId)||d.suggestedArkRule?.structureId&&o.has(d.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:a,frozen:(e.frozenKeys??[]).length,notAScore:!0}}function as(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}var ls="1.1";var cs="1.0";var zt="docs/diagnostics.md",ds="1.0";function b(e,t,n,r,s,i){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...i?.oftenAdvisory?{oftenAdvisory:!0}:{}}}var nt=Object.freeze([b("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),b("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),b("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),b("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),b("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),b("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),b("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),b("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),b("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),b("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),b("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),b("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),b("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),b("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),b("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),b("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),b("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),b("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),b("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),b("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green."),b("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),b("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),b("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),b("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),b("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),b("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),b("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),b("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),b("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),b("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),b("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),b("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),b("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),b("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),b("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),b("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),b("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),b("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),b("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),b("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),b("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),b("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),b("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),b("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),b("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),b("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),b("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),b("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),b("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),b("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),b("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),b("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),b("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),b("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),b("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),b("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Mn=new Map(nt.map(e=>[e.ruleId,e])),ps=Object.freeze(nt.map(e=>e.ruleId));function us(e){return typeof e=="string"&&e.length>0&&Mn.has(e)}function fs(e){return typeof e!="string"||e.length===0?!1:Mn.has(e)?!0:e.startsWith("ARKRULE_")}function rt(e){if(!(typeof e!="string"||e.length===0))return Mn.get(e)}function $n(e){return`#${rt(e)?.docsAnchor??e}`}function ms(e){return`${zt}${$n(e)}`}function gs(){return{schemaVersion:"1.0",docsPath:zt,codes:nt}}function ys(e){return rt(e)?.fix}function hs(e){return rt(e)?.why}var As="1.0",Dn="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Fn=["full","subset","unavailable"],Hn=["doctor-facts","report-snapshot","none"],it={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},Is=/^sha256:[a-f0-9]{64}$/;function Vn(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!Is.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}function jn(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}function Un(e,t){let n=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${n} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${n}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}function Gn(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}function bs(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&Is.test(e.projectId)?e.projectId:null,r=Vn({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",i=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,o=jn({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:i}),a=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Un(o,i),d={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:st(e.activeViolations),frozenResidual:st(e.frozenResidual)},f={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:st(e.rulesInventoried),underContract:st(e.rulesUnderContract),frozenResidual:st(e.rulesFrozenResidual)},g={writePath:o,host:i,honestLabel:a},m={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},c={schemaVersion:"1.0",arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:g,lastCheck:d,rules:f,nextAction:Gn(e,r,g,d,f)},l=Bn(e.improvementCompass);return l&&(c.improvementCompass=l),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(c.vsBase=e.vsBase),c}var Ss=new Set(Fn),To=new Set(Hn);function qt(e){let t=Ss.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&To.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let o={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:it.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(o.contractHash=r),o}let s=Array.isArray(e.topResidual)?e.topResidual.filter(o=>typeof o=="string"&&o.length>0).slice(0,15):[],i={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(i.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:it.FACTS_PARTIAL,i.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(i.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(i.reason=e.reason),n&&(i.factsSource=n),r&&(i.contractHash=r),i}function Es(e={}){return qt({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??it.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --doctor or --report for residual lenses. Status never invents green.",factsSource:"none",contractHash:e.contractHash})}function Bn(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let n;return typeof t.mode=="string"&&Ss.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",qt({mode:n,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}function Rs(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}function st(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}var vs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Dn,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:"1.0"},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}}}};var ot="1.0",at=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],lt=5,ce=["scalability","resilience","security"],Pe=new Set(ce),Kn={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},zn={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},qn={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function Yn(e){return zn[e]??e}function Wn(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}function Jn(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}function P(e,t,n,r){if(!n||e.evidence.some(i=>i.source===t&&i.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}function H(e,t,n){Pe.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}function Cs(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${zn[e]} \u2014 no residual from current sensors.`}}function ks(){return at.map(e=>Pe.has(e)?{id:e,status:"out-of-scope",summary:qn[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:Cs(e),evidence:[]}:{id:e,status:"ok",summary:Cs(e),evidence:[]})}function Oo(e,t){for(let n of t){let r=Wn(n);if(!r)continue;let s=n.outcome||n.message||void 0,o=(Array.isArray(n.evidence)?n.evidence:[])[0],a=(g,m,c)=>{let l=e.get(g);!l||Pe.has(g)||(P(l,"designSmells",r,s),o&&P(l,"designSmells",o,r),H(l,m,c))},d={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},f={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":a("soc","Business rules still mix with UI or presentation surfaces.",d),a("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",d);break;case"facade-sql-in-routes":a("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",d),a("dip","Transport depends on concrete persistence instead of a port.",f);break;case"io-under-application":a("soc","Application/business code reaches I/O directly \u2014 separation is weak.",d),a("dip","I/O is not inverted behind ports/adapters.",f),a("testability","Direct I/O under application code hurts pure unit testing.",f);break;case"handler-in-persistence":a("soc","HTTP/transport handlers live under persistence folders.",d);break;case"god-module":a("cohesion","Large multi-responsibility modules reduce cohesion.",d),a("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":a("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),a("cohesion","Mixed layout styles scatter the same concern across patterns.",d);break;case"soft-contract":a("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),a("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:a("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",d);break}}}function Po(e){return e.failsStrict===!1||e.typeOnly===!0}function Lo(e,t){for(let n of t){let r=Jn(n);if(!r)continue;let s=n.message,i=r.toUpperCase(),o=(d,f,g)=>{let m=e.get(d);!m||Pe.has(d)||(P(m,"violations",r,s),n.file&&P(m,"violations",n.file,r),H(m,f,g))};if(Po(n)){o("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let a={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(i==="LAYER_IMPORT_VIOLATION"||i.includes("LAYER_IMPORT")||i==="DYNAMIC_IMPORT_VIOLATION"){o("coupling","Import graph edges violate the layer contract.",a);continue}if(i.includes("CYCLE")||i==="CIRCULAR_DEPENDENCY"){o("coupling","Import cycles couple modules tightly.",a);continue}if(i.includes("PEER_ISOLATION")||i==="PEER_ISOLATION_VIOLATION"){o("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(i==="FORBIDDEN_GLOBAL"||i.startsWith("FORBIDDEN_")){o("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),o("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(i==="CAPABILITY_VIOLATION"){o("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),o("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(i.startsWith("ARKRULE_")||i==="INVARIANT_UNCOVERED"){o("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),o("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}function No(e,t){let n=Number(t.cycleCount)||0;if(n>0){let l=e.get("coupling");P(l,"cycles",`count:${n}`),H(l,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let l=e.get("coupling");P(l,"peerIsolation",`count:${r}`),H(l,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let l=e.get("cohesion");P(l,"physicalCohesion",`findings:${s}`),H(l,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let p=e.get("srp");P(p,"physicalCohesion",`findings:${s}`),H(p,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let i=Number(t.pureOrCapabilityResidual)||0,o=Number(t.forbiddenGlobalResidual)||0;if(i>0||o>0){let l=e.get("dip");i>0&&P(l,"capability",`residual:${i}`),o>0&&P(l,"forbiddenGlobals",`residual:${o}`),H(l,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let p=e.get("testability");i>0&&P(p,"capability",`residual:${i}`),o>0&&P(p,"forbiddenGlobals",`residual:${o}`),H(p,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let a=Number(t.arkRulesStructureResidual)||0;if(a>0){let l=e.get("encapsulation");P(l,"arkRules",`structureResidual:${a}`),H(l,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let p=e.get("domain");P(p,"arkRules",`structureResidual:${a}`),H(p,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let l=e.get("maintainability");P(l,"designFitness","design-weak"),H(l,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let l=e.get("maintainability");t.dirtyBaselineRisk===!0&&P(l,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&P(l,"baseline",`stale:${t.baselineStale}`),H(l,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let d=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&d>=10&&e.get("maintainability").status!=="residual"){let l=e.get("maintainability");P(l,"baseline",`frozen:${d}`),H(l,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let f=Number(t.ungovernedDirCount)||0,g=Number(t.emptyLayerCount)||0;if(f>0||g>0){let l=e.get("modularity");f>0&&P(l,"coverage",`ungovernedDirs:${f}`),g>0&&P(l,"coverage",`emptyLayers:${g}`),H(l,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let l=e.get("modularity");P(l,"goldenPattern","absent"),H(l,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let m=e.get("stack");(t.stackKind??null)==="typescript"?m.status==="ok"&&(m.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(m.status="not-instrumented",m.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",m.evidence=[],m.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}function _s(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>Wn(r).localeCompare(Wn(s)));Oo(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let i=Jn(r).localeCompare(Jn(s));return i!==0?i:String(r.file??"").localeCompare(String(s.file??""))});Lo(e,n)}No(e,t)}function xs(e){for(let t of ce){let n=e.get(t);n.status="out-of-scope",n.summary=qn[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}function Ts(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}function Os(e){return e.filter(n=>n.status==="residual"&&!Pe.has(n.id)).slice().sort((n,r)=>{let s=Kn[n.id]??150,i=Kn[r.id]??150;return s!==i?s-i:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}function Ps(e={}){let t=ks(),n=new Map(t.map(s=>[s.id,s]));_s(n,e),xs(n),Ts(t);let r=Os(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let i={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(o=>({...o}))};return s.nextAction&&(i.nextAction={...s.nextAction}),i}),topResidual:r}}function Zn(e){return e.topResidual.map(t=>Yn(t))}function Xn(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}function Ls(e){let t=Zn(e),n=ce.map(i=>Yn(i)),r=Xn(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}var Ns="1.0",ws="<!-- arkgate:agent-projection:begin",Qn="<!-- arkgate:agent-projection:end -->",er="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",Zt=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),Ms=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]),tr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,$s=/<!--\s*arkgate:agent-projection:end\s*-->/i,wo=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,Mo=/\bschema=([A-Za-z0-9._+-]+)/i;function ct(e){let t=String(e??"").replace(/\r\n/g,`
|
|
17
|
-
`),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}function
|
|
18
|
-
`)}function
|
|
8
|
+
`)}`),this.name="EffectiveContractError",this.source=t,this.issues=n}};function Is(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function bs(e,t="ark.config.json"){let n=e.config.arkRules,r=[];if(!n||Object.keys(n).length===0){if(e.discoveredArkRulesFiles&&e.discoveredArkRulesFiles.length>0)for(let l of[...e.discoveredArkRulesFiles].sort())r.push({path:l,message:`ArkRules file ${JSON.stringify(l)} is not referenced by arkRules and will not be enforced`,severity:"advisory"});return{config:e.config,arkRules:Ae(),warnings:r}}let s=new Set(e.config.layers.map(l=>l.name)),o=[],a=[],i=new Set;for(let l of Object.keys(n).sort()){let u=n[l],f=`$.arkRules[${JSON.stringify(l)}]`;if(typeof u!="string"||u.length===0){o.push({path:f,message:"must be a non-empty relative path string"});continue}if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u)){o.push({path:f,message:"must be a project-relative path (absolute paths are not allowed)"});continue}if(!s.has(l)){o.push({path:f,message:`layer ${JSON.stringify(l)} is not declared in layers[]`});continue}let m=Is(u);i.add(m);let d=e.fileContents[m]??e.fileContents[u];if(d===void 0){o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(m)} is missing`});continue}try{let c=ot(JSON.parse(d),m,l);a.push({layer:l,sourceFile:m,file:c.config})}catch(c){if(c instanceof Ce)for(let p of c.issues)o.push({path:`${f}${p.path==="$"?"":p.path.replace(/^\$/,"")}`,message:`${m}: ${p.message}`});else c instanceof SyntaxError?o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(m)} is not valid JSON: ${c.message}`}):o.push({path:f,message:`referenced ArkRules file ${JSON.stringify(m)} failed to load: ${c instanceof Error?c.message:String(c)}`})}}if(e.discoveredArkRulesFiles)for(let l of[...e.discoveredArkRulesFiles].sort()){let u=Is(l);i.has(u)||r.push({path:u,message:`ArkRules file ${JSON.stringify(u)} is not referenced by arkRules and will not be enforced`,severity:"advisory"})}if(o.length>0)throw new at(t,o);return{config:e.config,arkRules:Gt(a),warnings:r}}function Bt(e){let{stewards:t,...n}=e.config;return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}function Ua(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}function Ka(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],s=n.length>1?n[0]:null;for(let o of Object.values(e))if(!(s&&!o.includes(s))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(o)||o.includes(t)))return!0;return!1}function zt(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=[],o=[];for(let a of t){let i=[],l=a.coverage?.test!==!1,u=a.coverage?.symbol;if(!r&&l)for(let c of n){let p=e.fileContents[c];if(p&&Ua(p,a.id)){i.push("test-title");break}}u&&Ka(e.fileContents,u)&&i.push("symbol");let m=(a.coverage?.test===!0||!!u||a.coverage===void 0)&&i.length>0||a.coverage?.test===!1&&!u?!0:i.length>0,d=r&&l&&i.length===0;if(s.push({invariantId:a.id,layer:a.provenance.layer,sourceFile:a.provenance.sourceFile,mode:a.mode,covered:m&&!d,evidence:i,partial:d,description:a.description}),!m||d){let c=a.mode==="enforced"&&!d,p=r||n.length===0?"never-had-tests":"tests-disappeared";o.push({ruleId:"INVARIANT_UNCOVERED",message:d?`Invariant ${a.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:p==="tests-disappeared"?`Invariant ${a.id} is not covered by a test title or declared symbol (tests-disappeared \u2014 suite exists).`:`Invariant ${a.id} is not covered by a test title or declared symbol (never-had-tests).`,file:a.provenance.sourceFile,line:1,arkruleId:a.id,arkruleSource:a.provenance.sourceFile,fromLayer:a.provenance.layer,severity:c?"error":"warning",failsStrict:c,kind:p})}}return{coverage:s,violations:o,partial:s.some(a=>a.partial)}}function qt(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}var Wt="1.0";function N(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function Q(e){return[...new Set(e??[])].sort()}function ue(e,t,n,r,s){let o=Q(n),a=Q(r),i=new Set(o),l=new Set(a),u=a.filter(m=>!i.has(m)),f=o.filter(m=>!l.has(m));u.length===0&&f.length===0||(u.length>0&&N(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),f.length>0&&N(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}function it(e,t,n,r,s,o,a){if(n===r)return;N(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:a,before:n,after:r})}function Yt(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}function Ga(e,t,n){let r=Yt(t,o=>o.name),s=Yt(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&N(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(o),i=s.values.get(o),l=`$.layers[${o}]`;if(!a&&i){N(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:i});continue}if(a&&!i){N(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!i)continue;ue(e,`${l}.patterns`,a.patterns,i.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ue(e,`${l}.exclude`,a.exclude,i.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let u=Lt(a),f=Lt(i);ue(e,`${l}.forbiddenGlobals`,u.rawGlobals,f.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ue(e,`${l}.capabilities`,u.atoms,f.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),Q(a.intentPrefixes).join("\0")!==Q(i.intentPrefixes).join("\0")&&N(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:Q(a.intentPrefixes),after:Q(i.intentPrefixes)}),it(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,i.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),it(e,`${l}.optional`,a.optional===!0,i.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}function Ba(e,t,n){let r=a=>`${a.from}->${a.to}`,s=Yt(t,r),o=Yt(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&N(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let a of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let i=s.values.get(a),l=o.values.get(a),u=`$.rules[${a}]`;if(!i&&l){l.allowed===!1&&N(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:l});continue}if(i&&!l){i.allowed===!1&&N(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:i});continue}if(!i||!l)continue;i.allowed!==l.allowed&&N(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:i.allowed,after:l.allowed});let f=i.peerIsolation===!0,m=l.peerIsolation===!0;if(f!==m){let d=i.from===i.to&&l.from===l.to;N(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:d?m?"strengthening":"weakening":"judgment-required",message:d?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:f,after:m})}Q(i.sliceFolders).join("\0")!==Q(l.sliceFolders).join("\0")&&N(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:Q(i.sliceFolders),after:Q(l.sliceFolders)})}}function za(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let a=r[o]??0,i=s[o]??0;a!==i&&N(e,{kind:i>a?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:i>a?"weakening":"strengthening",message:i>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:i})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])it(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function tr(e){return e.mode==="enforced"?"enforced":"advisory"}function qa(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){N(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${tr(s)}).`,after:s});return}if(r&&!s){N(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=tr(r),i=tr(s);if(a!==i){let l=a==="advisory"&&i==="enforced";N(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:i})}ue(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ue(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),it(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}function Ya(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function vs(e,t){return`${e}::${t}`}function Cs(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(vs(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(vs(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}function Wa(e,t,n,r,s,o){let a=new Map((o??[]).map(d=>[d.invariantId,d])),i=t.arkRules??{},l=n.arkRules??{},u=[...new Set([...Object.keys(i),...Object.keys(l)])].sort();for(let d of u){let c=i[d],p=l[d],g=`$.arkRules[${d}]`;if(c===void 0&&p!==void 0){N(e,{kind:"arkrules-ref-added",path:g,classification:"strengthening",message:`ArkRules reference for layer ${d} was added.`,after:p});continue}if(c!==void 0&&p===void 0){N(e,{kind:"arkrules-ref-removed",path:g,classification:"weakening",message:`ArkRules reference for layer ${d} was removed.`,before:c});continue}c!==p&&N(e,{kind:"arkrules-ref-path-changed",path:g,classification:"judgment-required",message:`ArkRules file path for layer ${d} changed; verify the effective rules still match intent.`,before:c,after:p})}let f=Cs(r),m=Cs(s);for(let d of[...new Set([...f.structure.keys(),...m.structure.keys()])].sort()){let c=f.structure.get(d),p=m.structure.get(d),g=`$.arkRules.structure[${d}]`;if(!c&&p){N(e,{kind:"arkrule-structure-added",path:g,classification:"strengthening",message:`Structure ArkRule ${p.id} was added (${p.mode}).`,after:p});continue}if(c&&!p){N(e,{kind:"arkrule-structure-removed",path:g,classification:"weakening",message:`Structure ArkRule ${c.id} was removed.`,before:c});continue}if(!(!c||!p)){if(c.mode!==p.mode){let k=c.mode==="advisory"&&p.mode==="enforced";N(e,{kind:k?"arkrule-promoted":"arkrule-demoted",path:`${g}.mode`,classification:k?"strengthening":"weakening",message:k?`Structure ArkRule ${p.id} was promoted to enforced.`:`Structure ArkRule ${p.id} was demoted to advisory.`,before:c.mode,after:p.mode})}c.sensor!==p.sensor&&N(e,{kind:"arkrule-sensor-changed",path:`${g}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${p.id} changed sensor identity.`,before:c.sensor,after:p.sensor})}}for(let d of[...new Set([...f.invariants.keys(),...m.invariants.keys()])].sort()){let c=f.invariants.get(d),p=m.invariants.get(d),g=`$.arkRules.invariants[${d}]`;if(!c&&p){N(e,{kind:"arkrule-invariant-added",path:g,classification:"strengthening",message:`Invariant ${p.id} was added (${p.mode}).`,after:p});continue}if(c&&!p){N(e,{kind:"arkrule-invariant-removed",path:g,classification:"weakening",message:`Invariant ${c.id} was removed.`,before:c});continue}if(!(!c||!p)&&c.mode!==p.mode)if(c.mode==="advisory"&&p.mode==="enforced"){let v=a?.get(p.id),R=qt(v);R.ok?N(e,{kind:"arkrule-invariant-promoted",path:`${g}.mode`,classification:"strengthening",message:`Invariant ${p.id} was promoted to enforced (coverage evidence present).`,before:c.mode,after:p.mode}):N(e,{kind:"arkrule-invariant-promote-refused",path:`${g}.mode`,classification:"judgment-required",message:`Invariant ${p.id} cannot be promoted to enforced: ${R.reason}`,before:c.mode,after:p.mode})}else N(e,{kind:"arkrule-invariant-demoted",path:`${g}.mode`,classification:"weakening",message:`Invariant ${p.id} was demoted to advisory.`,before:c.mode,after:p.mode})}}function Jt(e,t,n){let r=[];ue(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ue(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ue(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),it(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},o=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(o!==a){let i=s[a]===s[o]?"judgment-required":s[a]>s[o]?"strengthening":"weakening";N(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:i,message:"The cycle enforcement level changed.",before:o,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&N(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Ga(r,e.layers,t.layers),Ba(r,e.rules,t.rules),za(r,e,t),Wa(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),qa(r,e,t),r.sort((i,l)=>i.path.localeCompare(l.path)||i.id.localeCompare(l.id)),{schemaVersion:Wt,classification:Ya(r),findings:r}}function Zt(e,t){if(!e||e.schemaVersion!==Wt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=Q(e.findingIds),r=Q(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}function _e(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function _s(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function Xt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function X(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function lt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}function ee(e,t,n){return e.startsWith(t,n)&&!Xt(e[n-1])&&!Xt(e[n+t.length])}function xs(e,t){let n=X(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=X(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ee(e,"type",n))return!1;let s=X(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ee(e,"as",s)||!_s(e[s]))return!1;for(n=s;n<e.length&&Xt(e[n]);)n+=1;if(n=X(e,n),ee(e,"as",n)){if(n=X(e,n+2),!_s(e[n]))return!1;for(;n<e.length&&Xt(e[n]);)n+=1}r=!0}return!1}function Ja(e,t){if(t=X(e,t+6),e[t]==="(")return lt(e,X(e,t+1));let n=!1;if(ee(e,"type",t)){let s=X(e,t+4);e[s]!==","&&!ee(e,"from",s)&&(n=!0)}else xs(e,t)&&(n=!0);let r=Ts(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}function Za(e,t){t=t+6;let n=X(e,t),r=!1;if(ee(e,"type",n)){let o=X(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else xs(e,n)&&(r=!0);let s=Ts(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}function Ts(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ee(e,"from",t))return lt(e,X(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return lt(e,t);if(t>0&&(ee(e,"import",t)||ee(e,"export",t)))return}}function Xa(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}function Qa(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=X(e,t+7);if(e[r]!=="(")return;r=X(e,r+1);let s=lt(e,r);return s?{...s,requireCall:!0}:void 0}function ei(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
9
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let o=e.indexOf("*/",n+2);if(o<0)break;n=o+1;continue}if(r==="`"){n=Xa(e,n);continue}if(r==="'"||r==='"'){let o=lt(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&ee(e,"import",n)?Ja(e,n):r==="e"&&ee(e,"export",n)?Za(e,n):r==="r"&&ee(e,"require",n)?Qa(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}function Ns(e,t){let n=[],r=[];for(let s of ei(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let u=Ge(o);if(!u)continue;let f=e.content.slice(0,s.offset).split(`
|
|
10
|
+
`).length;r.push({file:e.path,symbol:o,capability:u,evidence:{kind:"import",file:e.path,line:f,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
|
|
11
|
+
`).length,i={kind:"import",file:e.path,line:a,excerpt:s.excerpt},l=ti(e.path,o,t);n.push({from:e.path,specifier:o,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:i})}return{edges:n,capabilityUses:r}}function ti(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(o);if(a)return a}}function Os(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=se(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}var ni={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function ri(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}function si(e,t){return ri(e,t)?$(L(Bt({config:e,arkRules:t,warnings:[]}))):$(L(e))}function ct(e,t,n){let r=typeof e=="string"?$t(e,t):Xe(e,t),s=n?.arkRules??Ae();return{...r,arkRules:s,policyHash:si(r.config,s)}}function nr(e){let t=ct(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=ct(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Jt(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(i=>i.classification==="weakening"||i.classification==="judgment-required").map(i=>i.id).sort(),o=s.length>0,a=o&&Zt(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:o,acknowledged:a,valid:!o||a}}function Me(e){let t=e.files.map(m=>{let d=_e(m.path);return{path:d,content:m.content,contentHash:$(m.content),layer:re(d,e.contract.config.layers)??null}}).sort((m,d)=>m.path.localeCompare(d.path)),n=new Map(t.map(m=>[m.path,m])),r=[],s=[];for(let m of t){let d=Ns(m,n);r.push(...d.edges),s.push(...d.capabilityUses)}let o=Os(r,e.contract.config),a=new Map(e.contract.config.layers.map(m=>[m.name,m])),i=new Map(e.contract.config.layers.map(m=>[m.name,new Set(Te(m))]));for(let m of s){let d=n.get(m.file)?.layer;if(!d)continue;let c=a.get(d),p=ye(m.symbol,c?.forbiddenGlobals??[]);if(p){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${d} must not use module "${m.symbol}" because it is the import form of forbidden global "${p}".`,symbol:m.symbol,evidence:m.evidence});continue}i.get(d)?.has(m.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${d} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let l=t.length===0?"complete":"partial",u=l==="complete"?[]:[{...ni}],f={schemaVersion:Vt,policyHash:e.contract.policyHash,compilerOptionsHash:$(L(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:l,completenessReasons:u,valid:l==="complete"&&o.length===0,ir:f}}function dt(e){let t=new Map(e.files.map(n=>[_e(n.path),n]));for(let n of e.changes){let r=_e(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Me({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function rr(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function Qt(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],a=[],i=l=>{n.set(l,t),r.set(l,t),t+=1,o.push(l),s.add(l);for(let m of[...e.get(l)??[]].sort())e.has(m)&&(n.has(m)?s.has(m)&&r.set(l,Math.min(r.get(l)??0,n.get(m)??0)):(i(m),r.set(l,Math.min(r.get(l)??0,r.get(m)??0))));if(r.get(l)!==n.get(l))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;s.delete(f),u.push(f)}while(f!==l);u.length>1&&a.push(u.sort())};for(let l of[...e.keys()].sort())n.has(l)||i(l);return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}function xe(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let a=se(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a)continue;let i=!!a.peerIsolation,l=!i&&!!(o.typeOnly||o.namedBindingsTypeOnly),u=a.message??(i?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}). Extract shared code or use events/ports across slices.`:`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`);t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!i&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...i?{peerIsolation:!0}:{},message:l?`${u} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:u,...l?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Qt(r);s==="soft"||s==="framework-soft"?n.push(...o.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}var oi=["no-anemic-model"];function Ls(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ai(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Ls(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Ls(s)}return new RegExp(`^${n}$`)}function ut(e,t){return!t||t.length===0?!0:t.some(n=>ai(n).test(e))}function ii(e){return oi.includes(e)}function Ps(e){return e.mode==="enforced"&&!ii(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}function De(e,t,n,r=1){let{severity:s,failsStrict:o}=Ps(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:o}}function sr(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}function en(e,t,n){return t.filter(r=>!(!r.exported||!ut(r.file,e.appliesTo)||!sr(r.file,e,n)))}function li(e,t,n){let r=[];for(let s of en(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(De(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}function ci(e,t,n){let r=[];for(let s of en(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(De(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}function di(e,t,n){let r=[];for(let s of en(e,t,n))for(let o of s.mutatingMethods)o.referencesGuardOrPublish||r.push(De(e,s.file,`Mutating method ${s.className}.${o.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}function ui(e,t){let n=[];for(let r of t.files)ut(r,e.appliesTo)&&sr(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(De(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}function pi(e,t){let n=[];for(let r of t.files)ut(r,e.appliesTo)&&sr(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(De(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}function fi(e,t,n){let r=[];for(let s of en(e,t,n))if(s.dataOnly===!0){let o=De(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}function tn(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...li(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...ci(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...di(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...ui(n,e));break;case"thin-adapter":t.push(...pi(n,e));break;case"no-anemic-model":t.push(...fi(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}function nn(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>ut(l,s.appliesTo)))continue;let{severity:a,failsStrict:i}=Ps(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:i})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(i=>ut(i,s.appliesTo)))continue;let a=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((s,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}var mi=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|better-sqlite3|ioredis|redis)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm)/,gi=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,yi=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,hi=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Ai=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function or(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(hi.source,"g"))??[],r=t.match(new RegExp(Ai.source,"g"))??[],s=(t.match(/\bif\s*\(/g)??[]).length,o=(t.match(/\bswitch\s*\(/g)??[]).length,a=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&s+o>=6,i=mi.test(t),l=gi.test(t)||yi.test(t),u=n.length>=1||r.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),m=i&&u||l&&u||i&&f&&(s>=4||n.length>=1)||l&&i;return!a&&!m?null:{...a?{orchestrationHeavy:!0}:{},...m?{adapterThick:!0}:{}}}function rn(e){let t={};for(let[n,r]of Object.entries(e)){let s=or(n,r);s&&(t[n.replace(/\\/g,"/")]=s)}return t}function ws(e,t){let n=[],r=/export\s+(?:abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:extends\s+[^{]+)?(?:implements\s+[^{]+)?\{/g,s;for(;(s=r.exec(t))!==null;){let o=s[1],a=s.index+s[0].length,i=1,l=a;for(;l<t.length&&i>0;){let S=t[l];S==="{"?i+=1:S==="}"&&(i-=1),l+=1}let u=t.slice(a,l-1),f=u.split(`
|
|
12
|
+
`).map(S=>/^\s*\/\//.test(S)||/^\s*\/\*|\*\//.test(S)?S:S.replace(/(?:public\s+|protected\s+)?readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g,"").replace(/(?:^|[\s;{])readonly\s+[a-zA-Z_][a-zA-Z0-9_]*\s*(?::[^=;]+)?(?:=\s*[^;]+)?[;,]?/g," ")).join(`
|
|
13
|
+
`),m=/(?:^|\n)\s*(?:public\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(f.replace(/(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)/g,""))&&/(?:^|\n)\s*(public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/m.test(f),d=/(?:^|\n)\s*public\s+(?!static|async|get|set|constructor|readonly)[a-zA-Z_]/.test(f)||/(?:^|[\n;])\s*[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*[^=;\n]+[;=]/m.test(f.split(`
|
|
14
|
+
`).filter(S=>!/^\s*(private|protected|static|constructor|get |set |async |\/)/.test(S)).join(`
|
|
15
|
+
`)),c=/(?:^|[\n;{])\s*(?:public\s+)?set\s+[a-zA-Z_]/.test(u),p=/(?:^|[\n;{])\s*private\s+constructor\s*\(/.test(u),g=/(?:^|[\n;{])\s*(?:public\s+)?constructor\s*\(/.test(u)&&!p,k=/(?:^|[\n;{])\s*static\s+(?:async\s+)?(?:create|of|from|parse|build|make|new)\s*[<(]/.test(u)||/(?:^|[\n;{])\s*static\s+(?:async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\)\s*:\s*[A-Za-z_]/.test(u),v=[],R=new Set(["if","match","when"]),I=/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+|async\s+)*(?!constructor|get|set|static)([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{/g,C;for(;(C=I.exec(u))!==null;){let S=C[1];if(R.has(S))continue;let b=C.index+C[0].length,y=1,A=b;for(;A<u.length&&y>0;)u[A]==="{"?y+=1:u[A]==="}"&&(y-=1),A+=1;let x=u.slice(b,A-1);if(!/this\.\w+\s*=/.test(x))continue;let B=/\b(ensureInvariants|assertInvariants|validate|publish|emit|raise|record)\b/.test(x);v.push({name:S,referencesGuardOrPublish:B})}let H=(u.match(/(?:^|\n)\s*(?:public\s+|private\s+|protected\s+)?(?:async\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length,M=(f.match(/(?:^|[\n;])\s*(?:public\s+)?(?!constructor|static|get|set|private|protected|readonly)[a-zA-Z_][a-zA-Z0-9_]*\s*[:=]/g)??[]).length,j=H<=1&&M>=2&&(d||m);n.push({file:e,className:o,exported:!0,hasPublicMutableFields:d||m,hasPublicSetters:c,hasPublicConstructor:g,hasStaticFactory:k,mutatingMethods:[...v],dataOnly:j})}return n}var Ms=50;function sn(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}function Re(e){let t=sn(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}function on(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}function an(e){return typeof e=="string"&&e.startsWith("ARKRUN_")}function ar(e){if(e?.arkruleId!=null)return!0;let t=typeof e?.ruleId=="string"?e.ruleId:"";return t.startsWith("ARKRULE")||t.startsWith("arkrule")||t.startsWith("ARKRUN_")}function Ds(e,t={}){if(!Array.isArray(e)||Re(t))return e;for(let n of e)ar(n)&&n.failsStrict!==!1&&(n.failsStrict=!1,n.severity==="error"&&(n.severity="warning"));return e}var ir="Structure = heuristics; invariants = catalog+coverage evidence (not business runtime); ArkRun = kernel usage + declarations (not a score). Extra planes never merge into one architecture score. Advisory ArkRules \u2260 merge teeth. Advisory ArkRun \u2260 merge teeth.";function pe(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0}function ln(e={}){let t=sn(e.classification),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null,s=n!=null||r!=null,o=Re(t),a=e.arkRules,i=pe(a?.structureEnforced),l=pe(a?.structureTotal),u=typeof a?.structureAdvisory=="number"?pe(a.structureAdvisory):Math.max(0,l-i),f=pe(a?.invariantEnforced),m=pe(a?.invariantTotal),d=typeof a?.invariantAdvisory=="number"?pe(a.invariantAdvisory):Math.max(0,m-f),c=i>0||f>0,p=e.arkRun?.present===!0,g=e.arkRun?.mode==="enforced"||e.arkRun?.mode==="advisory"?e.arkRun.mode:null,k=pe(e.arkRun?.residualCount),v=p&&g==="enforced",R=v&&o,I=c||v,C=I&&o,H=I&&s&&!o,M;if(C){let S=[];c&&S.push("enforced structure/invariant findings"),v&&S.push("enforced ArkRun skip findings"),M=`Layer graph failures plus ${S.join(" and ")} (advisory extras never fail merge alone).`}else H?M=`Layer graph only \u2014 enforced ${[c?"ArkRules structure/invariant":null,v?"ArkRun":null].filter(b=>!!b).join(" and ")} findings are demoted under the teeth floor (need \u226550% governed and \u22651 populated layer); they do not merge-block until classification is honest.`:M="Layer graph only \u2014 no enforced ArkRules structure/invariant teeth on this tree. Advisory packs do not arm merge teeth."+(p?g==="advisory"?" Advisory ArkRun never merge-blocks.":" ArkRun extra is present but does not arm merge teeth.":" Absence of arkRun is silent.");let j={layers:{role:"inter-layer-edges",alwaysOnGate:!0,note:"Import/export layer graph \u2014 the default merge plane. Absent arkRules or arkRun changes nothing here."},structureSensors:{role:"intra-layer-heuristics",total:l,enforced:i,advisory:u,note:"Structure sensors are heuristics (prefer false negatives). Only mode:enforced fails merge; noisy sensors stay advisory by default. Advisory-only packs never add merge teeth (FG-ARKRULES-ADVISORY-ONLY)."},invariants:{role:"catalog-plus-coverage",total:m,enforced:f,advisory:d,covered:pe(a?.covered),uncovered:pe(a?.uncovered),note:"Invariants are catalog + coverage evidence, not a business runtime. Enforced + proven-uncovered fails merge; absence of enforced rules adds no extra teeth."},arkRun:{role:"kernel-usage-and-declarations",present:p,mode:g,residualCount:k,extraMergeTeeth:R,note:p?g==="enforced"?"Enforced ArkRun arms extra merge teeth only when the layer plane is classified. Residual is a count, never a score.":"Advisory ArkRun never adds merge teeth and never flips valid. Residual is a count, never a score.":"Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. The extra never becomes a score."},extraMergeTeeth:C,dualPlaneStamp:ir,failMergeWhen:M};return s&&(j.classificationGate={governedPercent:n,populatedLayerCount:r,floorPercent:50,allowsTeeth:o}),j}var cr=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"],$s=["publisher","publish","raise","raiseAsync","send","sendTo","subscribe","registerHandler","resolve","resolveSingleton"],Ri=new Set(cr),ki=new Set(["AggregateError","Array","ArrayBuffer","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","URIError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","WeakRef","WeakSet"]),Si=new Set(["Array","Atomics","Buffer","JSON","Math","Number","Object","Promise","Reflect","String","console","fs","path","url","util"]);function Fe(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}var dr=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],lr=new Set(dr);function dn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(lr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(lr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:lr.has(e.slice(0,r))}function cn(e){if(Ri.has(e))return"factory";switch(e){case"publisher":return"publisher";case"publish":return"publish";case"raise":case"raiseAsync":return"raise";case"send":case"sendTo":return"send";case"subscribe":return"subscribe";case"registerHandler":return"register-handler";case"resolve":return"resolve";case"resolveSingleton":return"resolve-singleton";default:return}}function ft(e,t){let n=1;for(let r=0;r<t;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function mt(e){return e.replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\n]/g," ")).replace(/(^|[^:\\])\/\/.*$/gm,t=>t.replace(/\/\/.*$/,n=>" ".repeat(n.length)))}function Ei(e,t){let n=e.slice(t),r=/^\s*(['"])((?:\\.|[^\\])*?)\1/.exec(n);if(!r)return;let s=r[2]??"";return s.length>0?s:void 0}function Fs(e,t,n){let r=Math.max(0,t-n.length-8),s=e.slice(r,t);return new RegExp(`\\b${n}\\s+$`).test(s)}function un(e,t){let n=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,r;for(;(r=n.exec(e))!==null;)r[1]||t(r[2]??"",r[3]??"")}function Ii(e,t){un(mt(e),t)}function pn(e,t){let n=mt(t),r=[],s=/\b(?:import|export)(\s+type)?\s+([\s\S]*?)\s+from\s*['"]([^'"]+)['"]/g,o;for(;(o=s.exec(n))!==null;){let i=o[3]??"";if(!i)continue;let l=o[0]??"";r.push({from:e,specifier:i,kind:/^\s*export/.test(l)?"export":"import",typeOnly:!!o[1],line:ft(t,o.index),resolution:"resolved-external"})}let a=/\b(?:require|import)\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(o=a.exec(n))!==null;){let i=o[1]??"";if(!i)continue;let l=o[0]?.startsWith("import")?"dynamic-import":"require";r.push({from:e,specifier:i,kind:l,typeOnly:!1,line:ft(t,o.index),resolution:"resolved-external"})}return r}function fn(e){let t=[];return Ii(e,n=>{let r=/\{([^}]*)\}/.exec(n);if(r?.[1])for(let s of r[1].split(",")){let o=s.trim();if(!o||o.startsWith("type "))continue;let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(o),i=a?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(o)?.[1],l=a?.[1]??i;i&&l&&/^[A-Z]/.test(l)&&t.push(i,l)}}),pt(t)}function bi(e){let t=new Map,n=new Set;return un(e,(r,s)=>{if(!Fe(s))return;let o=/\*\s+as\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(r);o?.[1]&&n.add(o[1]);let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,|$)/.exec(r.trim());a?.[1]&&t.set(a[1],a[1]);let i=/\{([^}]*)\}/.exec(r);if(i?.[1])for(let l of i[1].split(",")){let u=l.trim();if(!u||u.startsWith("type "))continue;let f=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);if(f){t.set(f[2],f[1]);continue}let m=/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(u);m?.[1]&&t.set(m[1],m[1])}}),{named:t,namespaces:n}}function vi(e,t){let n=new Set(t);return un(e,(r,s)=>{let o=/\{([^}]*)\}/.exec(r);if(o?.[1])for(let a of o[1].split(",")){let i=a.trim();if(!i||i.startsWith("type "))continue;let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)$/.exec(i),u=l?.[2]??/^([A-Za-z_][A-Za-z0-9_]*)$/.exec(i)?.[1],f=l?.[1]??u;!u||!f||!/^[A-Z]/.test(f)||(Fe(s)||t.has(f)||t.has(u))&&(n.add(u),n.add(f))}}),n}function Ci(e,t){let n;return un(e,(r,s)=>{!n&&new RegExp(`\\b${t}\\b`).test(r)&&(n=s)}),n}function mn(e,t){let n=mt(t),r=bi(n),s=[],o=/\b([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,a;for(;(a=o.exec(n))!==null;){let i=a[1],l=a.index;if(Fs(n,l,"function")||Fs(n,l,"class"))continue;let f=n.slice(0,l).match(/([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*$/)?.[1],m=r.named.get(i)??i,d=cn(m)??cn(i);if(!d)continue;let c=r.named.has(i)||f!==void 0&&r.namespaces.has(f);if(d!=="factory"&&(!c&&f===void 0||f&&Si.has(f)&&!c))continue;let p=Ei(n,l+a[0].length);s.push({file:e,line:ft(t,l),kind:d,callee:i,viaImport:c,...f?{receiver:f}:{},...p?{nameLiteral:p}:{}})}return s}function gn(e,t,n){let r=mt(t),s=vi(r,n),o=[],a=/\bnew\s+(?:[A-Za-z_][A-Za-z0-9_]*\s*\.\s*)*([A-Z][A-Za-z0-9_]*)\s*(?:<[^>]*>)?\s*\(/g,i;for(;(i=a.exec(r))!==null;){let l=i[1];if(ki.has(l)||!s.has(l))continue;let u=Ci(r,l);o.push({file:e,line:ft(t,i.index),typeName:l,...u?{importedFrom:u}:{}})}return o}function _i(e,t){let n=0,r;for(let s=t;s<e.length;s+=1){let o=e[s];if(r){if(o==="\\"){s+=1;continue}o===r&&(r=void 0);continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if(o==="[")n+=1;else if(o==="]"&&(n-=1,n===0))return s}return-1}function xi(e,t,n){let r=e.slice(t+1,n),s=[],o=/(['"])((?:\\.|[^\\])*?)\1/g,a;for(;(a=o.exec(r))!==null;){let i=a[2]??"";i.length>0&&s.push(i)}return s}function pt(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function Hs(e,t){let n=mt(t),r=/\b(uses|reactsTo|raises|sends)\s*:/g,s=[],o=[],a=[],i=[],l,u;for(;(u=r.exec(n))!==null;){let f=n.slice(u.index+u[0].length),m=/^\s*\[/.exec(f);if(!m)continue;let d=u.index+u[0].length+(m[0].length-1),c=_i(n,d);if(c<0)continue;let p=xi(n,d,c);if(p.length===0)continue;l===void 0&&(l=u.index);let g=u[1];g==="uses"?s.push(...p):g==="reactsTo"?o.push(...p):g==="raises"?a.push(...p):i.push(...p)}return l===void 0?[]:[{file:e,line:ft(t,l),uses:pt(s),reactsTo:pt(o),raises:pt(a),sends:pt(i)}]}var Us=["arkrun-missing-root","arkrun-kernel-in-domain","arkrun-direct-new","arkrun-undeclared-emit","arkrun-undeclared-handle","arkrun-undeclared-depend","arkrun-transport-bypass"],Ti=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Ni=new Set(Ti);function Oi(e){return Ni.has(e)}var yn={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},ur="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ks(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}function Li(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}function fe(e,t,n,r,s,o,a){let i=e.mode==="enforced"&&a;return{ruleId:yn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:i?"error":"warning",failsStrict:i,nextAction:ge({ruleId:yn[t],fromLayer:o?.fromLayer,target:o?.target})}}function Pi(e,t){let n=[],r=[],s=[],o=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),s.push(...a.raises),o.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}function js(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}function Vs(e){return e==="subscribe"||e==="register-handler"}function wi(e){return e==="resolve"||e==="resolve-singleton"}function Mi(e,t,n){let r=[],s=e.compositionRoots;if(s.length===0)return r.push(fe(e,"arkrun-missing-root","ark.config.json",1,"ArkRun compositionRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let a of t){let i=o.get(a.matchedRoot)??[];i.push(a),o.set(a.matchedRoot,i)}for(let a of s){let i=[...o.get(a)??[]].sort((u,f)=>u.file.localeCompare(f.file));if(i.length===0){r.push(fe(e,"arkrun-missing-root","ark.config.json",1,`ArkRun composition root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(i.some(u=>u.hasKernelFactory))continue;let l=i[0];r.push(fe(e,"arkrun-missing-root",l.file,1,`ArkRun composition root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}function Di(e,t,n,r,s){let o=new Map(t.map(i=>[i.name,i.intentPrefixes??[]])),a=[];for(let i of n){let l=i.specifier;if(!l||!Fe(l))continue;let u=r(i.from);u&&Ks(u,o.get(u)??[])&&a.push(fe(e,"arkrun-kernel-in-domain",i.from,i.line,`${u} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:u,target:l},s))}return a}function Fi(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let i=new Map(t.map(f=>[f.name,f.intentPrefixes??[]])),l=new Set(r.filter(f=>f.hasKernelFactory).map(f=>f.file)),u=[];for(let f of n){if(l.has(f.file))continue;let m=s(f.file);!m||!a.has(m)||Ks(m,i.get(m)??[])||u.push(fe(e,"arkrun-direct-new",f.file,f.line,`${m} must not construct ${f.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:m,target:f.typeName},o))}return u}function $i(e,t,n,r,s){let o=[],a=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:a};let i=new Set(e.managedLayers);if(i.size===0)return{findings:o,completenessReasons:a};for(let l of t){if(!js(l.kind)&&!Vs(l.kind)&&!wi(l.kind))continue;let u=r(l.file);if(!u||!i.has(u))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:ur,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let f=Pi(n,l.file);if(js(l.kind)){if(f.raises.has(l.nameLiteral)||f.sends.has(l.nameLiteral))continue;o.push(fe(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:l.nameLiteral},s));continue}if(Vs(l.kind)){if(f.reactsTo.has(l.nameLiteral))continue;o.push(fe(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:l.nameLiteral},s));continue}f.uses.has(l.nameLiteral)||o.push(fe(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:l.nameLiteral},s))}return{findings:o,completenessReasons:a}}function Hi(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let a of t){if(a.typeOnly)continue;let i=a.specifier;if(!i||!dn(i))continue;let l=n(a.from);!l||!s.has(l)||o.push(fe(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(i)}; use the ArkRun kernel transport.`,{fromLayer:l,target:i},r))}return o}function gt(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Re(e.classification),r=$i(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Mi(t,e.compositionRootHits,n),...Di(t,e.layers,e.dependencies,e.layerForFile,n),...Fi(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Hi(t,e.dependencies,e.layerForFile,n)].sort(Li),o=[...r.completenessReasons].sort((a,i)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,u=`${i.code}\0${i.file??""}\0${i.message}`;return l<u?-1:l>u?1:0});return{findings:s,completenessReasons:o}}function pr(e){return{findings:gt(e).findings.filter(n=>Oi(n.sensor)),completenessReasons:[]}}function ji(e,t){if(e===t)return!0;let n=e.indexOf("*");if(n<0)return!1;let r=e.slice(0,n).replace(/\/$/,"");return r.length>0&&(t===r||t.startsWith(`${r}/`))}function Vi(e,t,n){let r=mn(t,n).some(o=>o.kind==="factory"),s=[];for(let o of e.compositionRoots)ji(o,t)&&s.push({file:t,matchedRoot:o,hasKernelFactory:r});return s}function Gs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=new Set(fn(e.source));return pr({arkRun:t,layers:e.layers,kernelCalls:[],managedNews:gn(e.file,e.source,n),compositionRootHits:Vi(t,e.file,e.source),declarations:[],dependencies:pn(e.file,e.source),layerForFile:e.layerForFile,classification:e.classification})}function W(e,t,n={}){return{ruleId:e,message:t,...n}}function yt(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(c=>typeof c!="string"))&&o.push(W("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))o.push(W("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let c of["maxTsSuppressions","maxAnyCasts"]){let p=t.safety[c];p!==void 0&&(!Number.isInteger(p)||p<0)&&o.push(W("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${c} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],i=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],l=new Set([...a.map(c=>c.name).filter(Boolean),...i.map(c=>c.name).filter(c=>!!c)]);a.length===0&&o.push(W("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,f=new Set;for(let c of a){if(!c.name){o.push(W("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(c.name)&&f.add(c.name),u.add(c.name),c.forbiddenGlobals!==void 0&&(!Array.isArray(c.forbiddenGlobals)||c.forbiddenGlobals.some(g=>typeof g!="string"))&&o.push(W("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${c.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:c.name}));let p=Array.isArray(c.patterns)?c.patterns:[];if(p.length===0){o.push(W("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${c.name}" has no file patterns and will never classify files.`,{layer:c.name}));continue}for(let g of p){let k;try{k=Se(g)}catch(R){o.push(W("CONFIG_INVALID_LAYER_PATTERN",`Layer "${c.name}" has an invalid pattern "${g}": ${R instanceof Error?R.message:String(R)}`,{layer:c.name,pattern:g}));continue}let v=c.optional===!0||c.reserved===!0||c.allowEmpty===!0;!r.some(R=>k.test(R))&&!v&&o.push(W("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${c.name}" pattern "${g}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:c.name,pattern:g,failsStrict:!1,reserved:!1}))}}for(let c of f)o.push(W("CONFIG_DUPLICATE_LAYER",`Layer "${c}" is configured more than once.`,{layer:c}));if(l.size>0)for(let c of n??[])c.from&&!l.has(c.from)&&o.push(W("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${c.from}".`,{fromLayer:c.from,toLayer:c.to})),c.to&&!l.has(c.to)&&o.push(W("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${c.to}".`,{fromLayer:c.from,toLayer:c.to}));let m=new Set;if(a.length>1)for(let c of r){let p=-1,g=[];for(let k of a)for(let v of k.patterns??[]){if(!Se(v).test(c))continue;let R=Un(v,c);R>p?(p=R,g=[k.name]):R===p&&!g.includes(k.name)&&g.push(k.name)}g.length>1&&m.add([...g].sort().join(" + "))}m.size>0&&o.push(W("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let d=r.filter(c=>!re(c,a));return d.length>0&&o.push(W("CONFIG_UNCLASSIFIED_FILES",`${d.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:d.length,samples:d.slice(0,5)})),o}function Ui(e,t){return t.some(n=>{try{return Se(n).test(e)}catch{return!1}})}function Ki(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,o=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(g=>g.kind==="ts-suppression").map(({file:g,line:k})=>({file:g,line:k})),i=t.safetyUses.filter(g=>g.kind==="any-cast").map(({file:g,line:k})=>({file:g,line:k})),l=t.safetyUses.filter(g=>(g.kind==="dynamic-import"||g.kind==="dynamic-require")&&!Ui(g.file,o)).map(g=>({file:g.file,line:g.line,kind:g.kind==="dynamic-require"?"require":"import"})),u=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(g=>g.kind==="in-memory-store").map(g=>({file:g.file,line:g.line,store:g.symbol??"in-memory store"})),f=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(g=>g.peerIsolation===!1||g.allowed===!1&&!!g.from&&g.from===g.to&&g.peerIsolation!==!0).map(g=>({from:g.from,to:g.to})),m={tsSuppressions:a,anyCasts:i,nonLiteralDynamicImports:l,inMemoryProductionStores:u,disabledPeerIsolationRules:f,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},d=[],c=l.filter(g=>g.kind==="import");if(c.length>0){let g=c[0];d.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${c.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let p=l.filter(g=>g.kind==="require");if(p.length>0){let g=p[0];d.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${p.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let g=a[0];d.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(i.length>s){let g=i[0];d.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${i.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(u.length>0){let g=u[0];d.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:g.file,line:g.line,message:`${u.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return f.length>0&&d.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${f.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:d}}function Gi(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}function Bs(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Yn(e,n.length>0?n:qn.map(r=>({name:r.layer,prefixes:r.prefixes})))}function Bi(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let a=n.get(o.file);!a||!Gi(o.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,message:`${a} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let a=n.get(o.file);if(!a)continue;let i=s.get(a),l=i?.forbiddenGlobals??[],u=o.source==="import-based"?t.dependencies.find(f=>f.from===o.file&&f.line===o.line&&f.specifier===o.symbol&&!f.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&Be(o.symbol,l))){if(o.source==="import-based"){let f=ye(o.symbol,l);if(f){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...u?{edgeKind:u}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${f}".`});continue}}Te(i).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...u?{edgeKind:u}:{},message:o.source==="import-based"?`${a} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${a} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let a=n.get(o.file);if(!a)continue;for(let l of ze({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:l.ruleId,file:o.file,line:o.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!o.sourceIntent)continue;let i=Bs(o.sourceIntent,e.contract);!i||i===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:a,toLayer:i,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${i}, but the publishing file is classified as ${a}.`})}for(let o of t.intentReferences){let a=n.get(o.file);if(!a)continue;let i=Bs(o.intent,e.contract);if(!i)continue;let l=se(e.contract.config.rules,a,i);l&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:i,target:o.intent,message:l.message??`${a} must not reference ${i} intent ${o.intent}.`})}return r}function zi(e){let{facts:t}=e,n=we(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((h,ne)=>{let Ue=`${h.code}\0${h.file??""}\0${h.message}`,Ke=`${ne.code}\0${ne.file??""}\0${ne.message}`;return Ue<Ke?-1:Ue>Ke?1:0}),a=t.files.map(h=>({...h,layer:re(h.path,e.contract.config.layers)??null})),i=new Map(a.map(h=>[h.path,h.layer])),l=t.dependencies.map(h=>{let ne=h.target?i.get(h.target)??re(h.target,e.contract.config.layers):void 0;return{from:h.from,fromLayer:i.get(h.from)??null,...h.resolution==="resolved-project"&&h.target?{to:h.target,...ne?{toLayer:ne}:{}}:{},line:h.line,kind:h.kind,typeOnly:h.typeOnly,...h.targetTypeOnlyExports?{targetTypeOnlyExports:h.targetTypeOnlyExports}:{},...h.sourcePureTypeModule?{sourcePureTypeModule:h.sourcePureTypeModule}:{},...h.namedBindingsTypeOnly?{namedBindingsTypeOnly:h.namedBindingsTypeOnly}:{},...h.portProofEligible?{portProofEligible:h.portProofEligible}:{}}}),u=yt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(h=>h.path)}),f=Ki(e,t),m=e.contract.arkRules??Ae(),d=a.map(h=>h.path),p={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?rn(e.coverageInputs.fileContents):{},...e.fileHints??{}},g=[...tn({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:d,layerForFile:h=>i.get(h)??re(h,e.contract.config.layers),fileHints:p}),...nn(m,d)],k=g.filter(h=>h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,nextAction:h.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${h.arkruleId} in ${h.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${h.arkruleId} (declared in ${h.arkruleSource}), then preflight again.`})),v=g.filter(h=>!h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,failsStrict:!1,nextAction:h.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${h.arkruleId} in ${h.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${h.arkruleId} in ${h.arkruleSource} (advisory).`})),I=(m.invariants?.length??0)>0?zt({arkRules:m,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0}):{coverage:[],violations:[],partial:!1},C=I.violations.filter(h=>h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,nextAction:`Add a test title or declared symbol covering ${h.arkruleId} (declared in ${h.arkruleSource}), then preflight again.`})),H=I.violations.filter(h=>!h.failsStrict).map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,arkruleId:h.arkruleId,arkruleSource:h.arkruleSource,failsStrict:!1,nextAction:`Cover invariant ${h.arkruleId} in ${h.arkruleSource} (advisory / partial).`})),M=on(a),j=gt({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:h=>i.get(h)??re(h,e.contract.config.layers),classification:M}),S=e.contract.config.arkRun?.mode,b=j.findings.filter(()=>S==="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:h.failsStrict,...h.severity?{severity:h.severity}:{}})),y=j.findings.filter(()=>S!=="enforced").map(h=>({ruleId:h.ruleId,file:h.file,line:h.line,message:h.message,fromLayer:h.fromLayer,target:h.target,nextAction:h.nextAction,sensor:h.sensor,failsStrict:!1})),x=[...I.partial&&I.coverage.some(h=>h.mode==="enforced"&&h.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...j.completenessReasons],O=xe({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(h=>h.layer).map(h=>h.path),contentViolations:[...Bi(e,t,i),...k,...C,...b],edges:l,warnings:[...u,...f.warnings,...v,...H,...y],safety:f.report}),B=s==="complete"&&x.length>0?"partial":s,me=B==="complete"?o:[...o,...x].sort((h,ne)=>{let Ue=`${h.code}\0${h.file??""}\0${h.message}`,Ke=`${ne.code}\0${ne.file??""}\0${ne.message}`;return Ue<Ke?-1:Ue>Ke?1:0}),Ve=O.violations.filter(h=>h.failsStrict!==!1),Yr=B==="complete"&&Ve.length===0,jo=Yr&&O.warnings.every(h=>h.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:B,completenessReasons:me,valid:Yr,strictValid:jo,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:f.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(h=>h.name),edges:l,capabilityUses:t.capabilityUses,violations:O.violations,warnings:O.warnings}}}function $e(e){return zi({contract:e.contract,facts:ce(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}function zs(e){return $(L(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function fr(e){let t=Me(e),n=new Map(t.ir.files.map(p=>[p.path,p])),r=[],s=new Set,o=[];for(let p of e.changes){let g=p.path.replace(/\\/g,"/"),k=_e(p.path);if(!k||k===".."||k.startsWith("../")||g.startsWith("/")||/^[A-Za-z]:\//.test(g)||g.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(k)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}s.add(k),"delete"in p&&p.delete&&!n.has(k)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base tree.`}),r.push("delete"in p&&p.delete?{path:k,delete:!0}:{path:k,content:"content"in p?p.content:""})}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=dt({...e,changes:r}),i=new Map(a.ir.files.map(p=>[p.path,p])),l=a.ir.violations.filter(p=>p.ruleId==="CAPABILITY_VIOLATION"||p.ruleId==="FORBIDDEN_GLOBAL").map(p=>{let g=i.get(p.evidence.file)?.layer;return{ruleId:p.ruleId,file:p.evidence.file,line:p.evidence.line,target:p.symbol,...p.capability?{capability:p.capability}:{},...g?{fromLayer:g}:{},edgeKind:"import",message:p.message}}),u=xe({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(p=>p.path),contentViolations:l,edges:a.ir.edges.filter(p=>!!p.fromLayer).map(p=>({from:p.from,fromLayer:p.fromLayer,...p.to?{to:p.to}:{},...p.toLayer?{toLayer:p.toLayer}:{},line:p.evidence.line,kind:"import",...p.typeOnly?{typeOnly:!0}:{},...p.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),f=r.map(p=>{let g=_e(p.path),k=n.get(g),v=i.get(g);return{path:g,operation:"delete"in p&&p.delete?"delete":k?"update":"create",...k?{beforeContentHash:k.contentHash}:{},...v?{candidateContentHash:v.contentHash}:{}}}).sort((p,g)=>p.path.localeCompare(g.path)),m=[...o,...u.violations].map(p=>({...p,nextAction:ge(p)})),d=m.filter(p=>p.failsStrict!==!1),c=e.changeMap?ve({changeMap:e.changeMap,changes:f,baseDependencies:t.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:a.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&d.length===0&&(c?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:zs(t.ir.files),candidateTreeHash:zs(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...c?{convergence:c}:{},changes:f,violations:m,warnings:u.warnings}}function qi(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}function Yi(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}function Wi(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}function mr(e){let t=ce(e.baseFacts),n=ce(e.candidateFacts),r=$e({contract:e.contract,facts:t}),s=$e({contract:e.contract,facts:n}),o=new Map(t.files.map(c=>[c.path,c])),a=new Map(n.files.map(c=>[c.path,c])),i=Yi(t,n),l=new Map,u=[];for(let c of e.changes){let p=qi(c.path);if(!p){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(p)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:p,line:1,message:`The atomic change set contains more than one operation for ${p}.`});continue}l.set(p,c);let g=o.get(p),k=a.get(p);if("delete"in c&&c.delete)g||i.push({ruleId:"DELETE_TARGET_MISSING",file:p,line:1,message:`Cannot delete ${p} because it is not present in the supplied base facts.`}),k&&i.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:p,line:1,message:`Candidate facts still contain deleted file ${p}.`});else{let v="content"in c?c.content:"",R=$(v);k?k.contentHash!==R&&i.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:p,line:1,expectedContentHash:R,candidateContentHash:k.contentHash,message:`Candidate facts for ${p} do not match the declared content.`}):i.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:p,line:1,message:`Candidate facts do not contain changed file ${p}.`})}u.push(Wi(c,p,o,a))}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let c of new Set([...o.keys(),...a.keys()])){if(l.has(c))continue;let p=o.get(c),g=a.get(c);p&&g&&L(p)===L(g)||i.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:c,line:1,message:`Candidate facts change ${c}, but the atomic change set does not declare it.`})}let f=e.changeMap?ve({changeMap:e.changeMap,changes:u,baseDependencies:r.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[]),candidateDependencies:s.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[])}):void 0,m=[...i,...s.ir.violations].map(c=>({...c,nextAction:ge(c)})),d=m.filter(c=>c.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&d.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:u.sort((c,p)=>c.path<p.path?-1:c.path>p.path?1:0),violations:m,warnings:s.ir.warnings}}var gr="1.0",Ji=12;function qs(e){return e==="enforced"||e==="advisory"?e:null}function Zi(e){let t=new Set;if(!Array.isArray(e))return[];for(let n of e){let r=n?.ruleId;typeof r!="string"||!an(r)||t.has(r)||t.add(r)}return[...t].sort((n,r)=>n<r?-1:n>r?1:0)}function Xi(e){return!e||typeof e!="object"?{present:!1,mode:null,roots:0,layers:0,requireDeclarations:null}:{present:!0,mode:qs(e.mode),roots:Array.isArray(e.compositionRoots)?e.compositionRoots.length:0,layers:Array.isArray(e.managedLayers)?e.managedLayers.length:0,requireDeclarations:e.requireDeclarations===!0}}function Ys(e={}){let t=Xi(e.arkRun),n=t.present?Zi(e.findings):[],r=n.slice(0,Ji),s=n.length,o=ln({classification:e.classification,arkRules:{active:e.arkRules?.active===!0,structureEnforced:e.arkRules?.structureEnforced,structureTotal:e.arkRules?.structureTotal,structureAdvisory:e.arkRules?.structureAdvisory,invariantEnforced:e.arkRules?.invariantEnforced,invariantTotal:e.arkRules?.invariantTotal,invariantAdvisory:e.arkRules?.invariantAdvisory,covered:e.arkRules?.covered,uncovered:e.arkRules?.uncovered},arkRun:{present:t.present,mode:t.mode,residualCount:s}}),a=t.present&&t.mode==="enforced"&&Re(e.classification),i;return t.present?t.mode==="advisory"?i="Advisory ArkRun residual only \u2014 never flips valid or --strict-merge. Residual is a finding-id count, never a score.":a?i="Enforced ArkRun is on the extra merge plane. Residual is a finding-id count, never a score.":i="Enforced ArkRun extra teeth stay demoted until the layer plane is honestly classified. Residual is a finding-id count, never a score.":i="Absence of arkRun is silent \u2014 Layers and ArkRules verdicts unchanged. Not a score.",{schemaVersion:gr,notAScore:!0,active:t.present,mode:t.mode,compositionRoots:t.roots,managedLayers:t.layers,requireDeclarations:t.requireDeclarations,residual:{count:s,ruleIds:r},extraMergeTeeth:a,failMergeWhen:o.failMergeWhen,note:i,mergePlanes:o}}function hn(e={}){let t=e.present===!0,n=qs(e.mode),r=e.residual,s=null;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&(s=Math.floor(r)),t||(s=s??0),{notAScore:!0,present:t,mode:t?n:null,extraMergeTeeth:t&&n==="enforced"&&e.extraMergeTeeth===!0,residual:s}}function Ws(e){if(!e||e.notAScore!==!0)return[];if(e.active!==!0)return["ArkRun extra is off \u2014 silent on Layers/ArkRules (not a score)."];let t=e.mode??"unknown",n=e.extraMergeTeeth===!0?"armed":"not armed",r=[`mode: ${t} \xB7 extra merge teeth ${n} \xB7 not a score`];if(e.residual.count>0){let s=e.residual.ruleIds.join(", "),o=e.residual.count>e.residual.ruleIds.length?` (+${e.residual.count-e.residual.ruleIds.length} more)`:"";r.push(`Residual: ${s}${o}`)}else r.push("Residual: none on this scan (not a score \u2014 green extras \u2260 finished kernel wiring).");return e.failMergeWhen&&r.push(e.failMergeWhen),r}function An(e,t){return e.slice(0,t).split(`
|
|
16
|
+
`).length}function Js(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Xs(e,t){return e.some(n=>{let r=n.trim().replace(/\.+$/,"");return t.some(s=>r===s||r.startsWith(`${s}.`))})}function Zs(e,t=[]){return/domain|entity|aggregate|model/i.test(e)||Xs(t,["Domain"])}function Qi(e,t=[]){return/application|orchestration|presentation|adapter|framework|interface|delivery|transport|inbound|controller/i.test(e)||Xs(t,["Application","Orchestration","Presentation","Adapter","Interface","Delivery","Transport"])}function el(e){return/(?:^|\/)(?:tests?|__tests__|fixtures?|testdata|mocks?|stubs?|examples?|samples?|seeds?|seeders?|migrations?|excluded|exclusions?)(?:\/|$)/i.test(e)||/(?:^|\/)[^/]*\.(?:test|spec|fixture|mock|stub|seed|seeder)\.[^/]+$/i.test(e)||/(?:^|\/)(?:seed|seeder|fixture|mock|stub)\.[^/]+$/i.test(e)}function Qs(e){let t=[],n=0,r=new Map(Object.entries(e.fileLayers??{}).map(([l,u])=>[Js(l),u])),s=new Map((e.layerContexts??[]).map(l=>[l.name,l.intentPrefixes??[]])),o=(e.layerContexts??[]).find(l=>Zs(l.name,l.intentPrefixes))?.name??"DomainModel";for(let[l,u]of Object.entries(e.fileContents).sort(([f],[m])=>f.localeCompare(m))){let f=Js(l);if(el(f)||/GENERATED FILE\s+[—-]\s+do not edit by hand/i.test(u.slice(0,320)))continue;let m=r.has(f),d=r.get(f),c=d?s.get(d)??[]:[],p=/(?:^|\/)(?:components|ui|layouts|styles|hooks|theme|tokens|i18n|locales?)(?:\/|$)/i.test(f)||/(?:^|\/)(?:src\/)?(?:app|pages)\/.+\.(?:tsx|jsx)$/i.test(f)&&/(?:page|layout|loading|error|template|default)\.(?:tsx|jsx)$/i.test(f),g=/(?:^|\/)(?:app|pages)(?:\/[^/]+)*\/api(?:\/|$)/i.test(f),k=/(?:^|\/)actions?(?:\/|\.|$)/i.test(f)||/['"]use server['"]/.test(u),v=/controller|handler|resolver/i.test(l)||g||k||/route\.(?:ts|js|tsx|jsx)$/i.test(f)&&!p||/@(Controller|Get|Post|Put|Delete|Patch)\b/.test(u)||/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b/.test(u)||/\bexport\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=/.test(u),R=m?!!(d&&Qi(d,c)&&v):v,I=m?!!(d&&Zs(d,c)):/domain|entity|aggregate|model/i.test(l),C=!m||I||R;if(R&&!p){let b=/\b(if\s*\([^)]{0,80}(amount|total|price|qty|quantity|balance)[^)]{0,40}\)|throw new (Error|BadRequest|ValidationError)|z\.object\(|yup\.|class-validator|@Is[A-Z])/g,y;for(;(y=b.exec(u))!==null;)n+=1,t.push({id:`inv-val-${n}`,kind:"validation-in-controller",file:l,line:An(u,y.index),message:"Business validation appears in a controller/handler \u2014 extract an invariant or Domain rule.",confidence:"direct-evidence",governedLayer:d,suggestedArkRule:{layer:o,invariantId:`INV-EXTRACT-${n}`,sensor:"invariant-coverage"},neverMechanicalSafe:!0})}let H=/\b(const|let)\s+([A-Z][A-Z0-9_]{2,})\s*=\s*(\d{2,}|['"][^'"]{8,}['"])/g,M,j=b=>/^(?:TEST|SPEC|TIMEOUT|PORT|VERSION|MAX_RETRY|MIN_RETRY|TTL|CACHE|HEADER|COOKIE|MIME|CONTENT_TYPE|HTTP_STATUS|NODE_ENV|LOG_LEVEL|FEATURE_FLAG|ID_PREFIX|Z_INDEX)(?:_|$)/i.test(b)||/^(?:ROUTE|PATH|LABEL|TITLE|HEADING|CLASS|STYLE|COLOR|THEME|BREAKPOINT|QUERY|PARAM|ICON|ARIA|MSG|COPY|I18N|LOCALE|PAGE|NAV|MENU|TAB|BTN|BUTTON|PLACEHOLDER|TOOLTIP|SHADOW|RADIUS|GAP|PADDING|MARGIN|FONT|WIDTH|HEIGHT|OPACITY|DURATION|EASE|ANIM)_/i.test(b)||/_(?:ROUTE|PATH|LABEL|TITLE|COLOR|THEME|CLASS|STYLE|ICON|ARIA|MSG|COPY|TIMEOUT|PORT|VERSION|RETRY|DELAY|INTERVAL|TTL|CACHE)$/i.test(b)||/_(?:TIMEOUT(?:_MS)?|MS|BYTES|BUCKET|STORAGE_KEY|WINDOW_MS)$/i.test(b)||/^(?:DEFAULT_(?:BASE_URL|TIMEOUT(?:_MS)?|RETRY|PORT|HOST|HEADERS?|CACHE|TTL|MS|LOCALE|LANG|TIMEZONE|TZ)|REQUEST_(?:TIMEOUT(?:_MS)?|HEADERS?|RETRY|ID_PREFIX)|STORAGE_(?:KEY|PREFIX|BUCKET)|DAY_MS$|APP_DOMAIN$|BASE_URL$)$/i.test(b)||/^(?:FAVORITES_STORAGE|LISTINGS_CACHE|DOCS_PATH|METRICS_INTERVAL)/i.test(b)||/^(?:DEV|DEMO|SEED|FIXTURE)_[A-Z0-9_]+$/i.test(b)||/^(?:PG|POSTGRES|OID)_[A-Z0-9_]+$/i.test(b)||/_(?:OID|OIDS)$/i.test(b)||/^(?:INT2|INT4|INT8|FLOAT4|FLOAT8|NUMERIC|DATE|TIME|TIMESTAMP|TIMESTAMPTZ|JSON|JSONB|UUID)OID$/i.test(b)||/(?:^|_)(?:SCHEMA|PROTOCOL|RESOLVER|FORMAT)_(?:URL|URI|VERSION|ID|IDENTITY)$/i.test(b),S=(b,y)=>{if(/^(?:ERROR|SUCCESS|WARNING|INFO|HINT|HELP|EMPTY|TOAST|SNACK|ALERT|BANNER|DIALOG|MODAL|TOOLTIP|CAPTION|SUBTITLE|HEADLINE|USER|UI|DISPLAY|FEEDBACK)_(?:MSG|MESSAGE|TEXT|COPY|LABEL|TITLE|BODY|DESC|DESCRIPTION|HINT|HELP)?/i.test(b)||/_(?:MSG|MESSAGE|TEXT|COPY|TOAST|SNACK|ALERT|BANNER|CAPTION|HINT|HELP_TEXT|ERROR_TEXT|EMPTY_TEXT|PLACEHOLDER_TEXT|USER_MESSAGE|FEEDBACK)$/i.test(b))return!0;let A=y.replace(/^['"]|['"]$/g,"");return!!(/^['"]/.test(y)&&(/\s/.test(A)||/[.!?…]$/.test(A))&&!/^(?:STATUS|STATE|PHASE|ROLE|TYPE|KIND|ORDER|PAYMENT|CART|INVOICE|POLICY)_[A-Z0-9_]+$/i.test(b))};for(;(M=H.exec(u))!==null;){let b=M[2],y=M[3]??"";!C||j(b)||S(b,y)||p&&!I||/(?:^|\/)(?:integrations?|repos?|clients?|infra(?:structure)?|adapters?)(?:\/|$)/i.test(f)&&!I||(n+=1,t.push({id:`inv-magic-${n}`,kind:"magic-business-constant",file:l,line:An(u,M.index),message:`Magic business constant ${b} may belong in a Domain policy or invariant catalog.`,confidence:"heuristic",governedLayer:d,suggestedArkRule:{layer:o,invariantId:`INV-${b}`},neverMechanicalSafe:!0}))}if(I){let b=/export\s+class\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([^}]{0,800})\}/g,y;for(;(y=b.exec(u))!==null;){let A=y[2]??"",x=(A.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\s*\(/g)??[]).length;(A.match(/:\s*[A-Za-z]/g)??[]).length>=2&&x<=1&&(n+=1,t.push({id:`inv-anemic-${n}`,kind:"anemic-entity",file:l,line:An(u,y.index),message:`Class ${y[1]} looks anemic (data-heavy, few behaviors).`,confidence:"heuristic",governedLayer:d,suggestedArkRule:{layer:o,structureId:"no-anemic-model",sensor:"no-anemic-model"},neverMechanicalSafe:!0}))}}if(I&&!(/\.error\.(?:ts|js|tsx|jsx)$/i.test(f)||/(?:^|\/)[^/]*(?:-access)?\.error\./i.test(f)||/(?:^|\/)errors?(?:\/|$)/i.test(f))){let y=/this\.\w+\s*=/g,A;for(;(A=y.exec(u))!==null;){let x=u.lastIndexOf("class ",A.index),O=x>=0?u.indexOf("{",x):-1,B=x>=0&&O>=x&&O<A.index?u.slice(x,O):"";if(/\bextends\s+(?:Error|[A-Za-z_$][A-Za-z0-9_$]*Error)\b/.test(B))continue;let me=u.slice(Math.max(0,A.index-200),A.index+200);if(!/\b(ensureInvariants|assertInvariants|validate|publish|emit)\b/.test(me)){n+=1,t.push({id:`inv-mut-${n}`,kind:"mutation-without-guard",file:l,line:An(u,A.index),message:"Domain field mutation without nearby guard/publish call.",confidence:"heuristic",governedLayer:d,suggestedArkRule:{layer:o,structureId:"events-on-mutation",sensor:"domain-event-on-mutation"},neverMechanicalSafe:!0});break}}}}let a=new Set(e.contractedRuleIds??[]);t.sort((l,u)=>+(u.confidence==="direct-evidence")-+(l.confidence==="direct-evidence")||l.file.localeCompare(u.file)||l.line-u.line||l.kind.localeCompare(u.kind)||l.id.localeCompare(u.id));let i=t.filter(l=>l.suggestedArkRule?.invariantId&&a.has(l.suggestedArkRule.invariantId)||l.suggestedArkRule?.structureId&&a.has(l.suggestedArkRule.structureId)).length;return{candidates:t,inventoried:t.length,underContract:i,frozen:(e.frozenKeys??[]).length,notAScore:!0}}function eo(e){return{pilot:`Extract rule candidate ${e.id} (${e.kind})`,pilotTarget:e.file,smellId:e.kind,move:`Declare in arkrules/${e.suggestedArkRule?.layer??"DomainModel"}.json, implement pure Domain logic, add covering test.`,doNot:["Do not auto-apply codemods","Do not promote to enforced without coverage evidence","Do not batch multiple extractions"],successSignal:"Doctor reports candidate under contract; gate green with residual honest.",killSwitch:"Stop if extraction requires multi-module redesign without a clear aggregate owner.",neverMechanicalSafe:!0,class:"judgment",next:"Run ark_prepare_change / preflight, then re-doctor."}}var to="1.1";var no="1.0";var Rn="docs/diagnostics.md",ro="1.0";function E(e,t,n,r,s,o){return{ruleId:e,title:n,why:r,fix:s,docsAnchor:e,category:t,...o?.oftenAdvisory?{oftenAdvisory:!0}:{}}}var ht=Object.freeze([E("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),E("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),E("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),E("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),E("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),E("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),E("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),E("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),E("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),E("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),E("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),E("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),E("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),E("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),E("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),E("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),E("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),E("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),E("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),E("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green."),E("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from @arkgate/runtime (never a removed arkgate/runtime shim) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),E("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports @arkgate/runtime or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from @arkgate/runtime, never a removed arkgate/runtime shim, then preflight again. Never mechanical-safe."),E("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),E("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),E("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),E("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),E("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),E("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),E("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),E("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),E("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),E("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),E("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),E("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),E("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),E("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),E("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),E("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),E("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),E("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),E("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),E("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),E("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),E("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),E("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),E("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),E("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),E("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),E("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),E("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),E("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),E("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),E("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),E("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),E("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),E("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),E("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),E("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),E("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),yr=new Map(ht.map(e=>[e.ruleId,e])),so=Object.freeze(ht.map(e=>e.ruleId));function oo(e){return typeof e=="string"&&e.length>0&&yr.has(e)}function ao(e){return typeof e!="string"||e.length===0?!1:yr.has(e)?!0:e.startsWith("ARKRULE_")}function At(e){if(!(typeof e!="string"||e.length===0))return yr.get(e)}function hr(e){return`#${At(e)?.docsAnchor??e}`}function io(e){return`${Rn}${hr(e)}`}function lo(){return{schemaVersion:"1.0",docsPath:Rn,codes:ht}}function co(e){return At(e)?.fix}function uo(e){return At(e)?.why}var kn="1.0",Ar="https://unpkg.com/arkgate@4/schemas/ark.status-manifest.schema.json",Rr=["full","subset","unavailable"],kr=["doctor-facts","report-snapshot","none"],kt={FACTS_UNAVAILABLE:"FACTS_UNAVAILABLE",FACTS_PARTIAL:"FACTS_PARTIAL",NO_SESSION_SNAPSHOT:"NO_SESSION_SNAPSHOT"},po=/^sha256:[a-f0-9]{64}$/;function Sr(e){let t=e.expectation;if(t==null||t.expectedRoot===void 0&&t.expectedProjectId===void 0)return{status:"matched",authoritative:!!e.resolvedRoot};if(t&&typeof t!="object")return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project must be an object containing expectedRoot and/or expectedProjectId."};let n=t.expectedRoot,r=t.expectedProjectId;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedRoot must be a non-empty absolute path."};if(r!==void 0&&(typeof r!="string"||!po.test(r)))return{status:"mismatch",authoritative:!1,code:"INVALID_PROJECT_EXPECTATION",message:"project.expectedProjectId must be a sha256:<64 lowercase hex> identity."};if(n===void 0&&r!==void 0)return e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:{status:"unverified",authoritative:!1,expectedProjectId:r,message:"project.expectedProjectId matched or could not be compared, but expectedRoot is required for an authoritative workspace binding."};let s=e.expectedRootRelation??"unknown";return s==="outside"?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ROOT_MISMATCH",message:`Expected workspace ${n}, but this process is bound to ${e.resolvedRoot}.`}:s==="unknown"?{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Could not prove expectedRoot against the resolved project root (stale or incomplete path evidence)."}:s==="descendant"&&r===void 0?{status:"unverified",authoritative:!1,expectedRoot:n,message:`Expected workspace ${n} is inside this project, but an exact project root is required for the initial authoritative handshake.`}:r!==void 0&&e.projectId&&r!==e.projectId?{status:"mismatch",authoritative:!1,expectedRoot:n,expectedProjectId:r,code:"PROJECT_ID_MISMATCH",message:`Expected project id ${r}, but this process is bound to ${e.projectId}.`}:s==="exact"||s==="descendant"&&r&&r===e.projectId?{status:"matched",authoritative:!0,...n?{expectedRoot:n}:{},...r?{expectedProjectId:r}:{}}:{status:"unverified",authoritative:!1,expectedRoot:n,expectedProjectId:r,message:"Project expectation could not be fully verified."}}function Er(e){if(e.writePathUnavailable===!0)return"unavailable";if(e.softWriteHost===!0)return"advisory";if(e.hardWriteActive===!0)return"hard";let t=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"";return!t||t==="unknown"?"unavailable":"advisory"}function Ir(e,t){let n=t&&t!=="unknown"?t:"unknown-host";return e==="hard"?`Local write is hard for ${n} when the covered PreToolUse path is active; CI --strict-merge remains the merge backstop.`:e==="advisory"?`Local write is advisory for ${n}; hard merge boundary is a required status running arkgate-check --strict-merge (alias ark-check).`:"Write-path activation is unavailable or unverified for this invocation (no active host / incomplete evidence)."}function br(e,t,n,r,s){return e.nextActionOverride?.id&&e.nextActionOverride.summary?{id:e.nextActionOverride.id,summary:e.nextActionOverride.summary}:t.status==="mismatch"?{id:"rebind-project-identity",summary:t.message||"Project expectation does not match this process \u2014 call ark_identity / ark status with the correct expectedRoot (and projectId for descendants)."}:t.status==="unverified"&&e.expectation?{id:"complete-identity-handshake",summary:t.message||"Supply project.expectedRoot at the exact project root (and expectedProjectId for descendants) for authoritative status."}:e.resolvedConfigPath?r.verdict==="fail"||(r.activeViolations??0)>0?{id:"fix-active-violations",summary:`Clear ${r.activeViolations??"active"} blocking architecture finding(s), then re-run ark-check (or ark-check --doctor).`}:r.verdict==="incomplete"?{id:"restore-complete-analysis",summary:"Last check was incomplete \u2014 restore TypeScript/analysis inputs and re-run ark-check."}:r.verdict==null&&r.at==null?{id:"run-ark-check",summary:"No last-check snapshot yet \u2014 run ark-check --report (or --doctor) to freeze session evidence."}:n.writePath==="unavailable"?{id:"install-write-path",summary:"Write path is unavailable \u2014 install agent gates for your host (ark start / --install-agent-gates) and keep required CI --strict-merge."}:n.writePath==="advisory"?{id:"keep-ci-merge-hard",summary:"Local write is advisory for this host \u2014 keep a required GitHub status on arkgate-check --strict-merge as the hard merge boundary."}:e.leftoverDesignWork===!0?{id:"map-leftover-design",summary:"Leftover design work remains. Map with /ark-explore, then apply one small refactor with /ark-autopilot. Green imports are not done."}:s.arkRulesLoaded&&(s.frozenResidual??0)>0?{id:"review-arkrules-residual",summary:"ArkRules residual remains frozen \u2014 review inventory debt without claiming a score."}:e.arkRun?.present===!0&&(e.arkRun.residual??0)>0?{id:"review-arkrun-residual",summary:"ArkRun residual remains \u2014 wire kernel usage or declarations through @arkgate/runtime. Not a score."}:e.adopted==="required-merge"||e.adopted==="advisory-only-acked"?{id:"stay-enforced",summary:"Contract looks enforceable for this session \u2014 keep writing through the gate and re-check after structural edits."}:{id:"require-ci-merge-status",summary:'Make arkgate-check --strict-merge a required GitHub status, or write .ark/adoption-stance.json with stance: "advisory-only".'}:{id:"run-ark-start",summary:"No ark.config.json found \u2014 run ark start (preview) then ark start --apply."}}function fo(e){let t=typeof e.resolvedRoot=="string"&&e.resolvedRoot.length>0?e.resolvedRoot:".",n=typeof e.projectId=="string"&&po.test(e.projectId)?e.projectId:null,r=Sr({resolvedRoot:t,projectId:n,expectation:e.expectation,expectedRootRelation:e.expectedRootRelation}),s=typeof e.activeHost=="string"?e.activeHost.trim().toLowerCase():"",o=s&&s!=="unknown"?s:s==="unknown"?"unknown":null,a=Er({hardWriteActive:e.hardWriteActive,softWriteHost:e.softWriteHost,writePathUnavailable:e.writePathUnavailable,activeHost:o}),i=typeof e.honestLabel=="string"&&e.honestLabel.trim().length>0?e.honestLabel.trim():Ir(a,o),l={at:typeof e.lastCheckAt=="string"?e.lastCheckAt:null,verdict:e.lastCheckVerdict==="pass"||e.lastCheckVerdict==="fail"||e.lastCheckVerdict==="incomplete"?e.lastCheckVerdict:null,activeViolations:Rt(e.activeViolations),frozenResidual:Rt(e.frozenResidual)},u={arkRulesLoaded:e.arkRulesLoaded===!0,inventoried:Rt(e.rulesInventoried),underContract:Rt(e.rulesUnderContract),frozenResidual:Rt(e.rulesFrozenResidual)},f={writePath:a,host:o,honestLabel:i},m={projectId:n,resolvedRoot:t,resolvedConfigPath:typeof e.resolvedConfigPath=="string"&&e.resolvedConfigPath.length>0?e.resolvedConfigPath:null,binding:r.status,authoritative:r.authoritative,...r.code?{code:r.code}:{},...r.message?{message:r.message}:{}},d={schemaVersion:kn,arkgateVersion:typeof e.arkgateVersion=="string"&&e.arkgateVersion.length>0?e.arkgateVersion:"unknown",projectIdentity:m,activation:f,lastCheck:l,rules:u,nextAction:br(e,r,f,l,u)},c=vr(e.improvementCompass);return c&&(d.improvementCompass=c),e.vsBase&&typeof e.vsBase.baseRef=="string"&&e.vsBase.baseRef.length>0&&(d.vsBase=e.vsBase),e.arkRun&&typeof e.arkRun=="object"&&(d.arkRun=hn(e.arkRun)),d}var mo=new Set(Rr),tl=new Set(kr);function Sn(e){let t=mo.has(e.mode)?e.mode:"unavailable",n=e.factsSource!=null&&tl.has(e.factsSource)?e.factsSource:t==="unavailable"?"none":void 0,r=typeof e.contractHash=="string"&&e.contractHash.length>0?e.contractHash:void 0;if(t==="unavailable"){let a={schemaVersion:"1.0",notAScore:!0,mode:"unavailable",topResidual:[],reasonCode:typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:kt.FACTS_UNAVAILABLE,reason:typeof e.reason=="string"&&e.reason.length>0?e.reason:"Improvement compass facts are unavailable \u2014 run ark-check --doctor for residual lenses. Status never invents green.",factsSource:n??"none"};return r&&(a.contractHash=r),a}let s=Array.isArray(e.topResidual)?e.topResidual.filter(a=>typeof a=="string"&&a.length>0).slice(0,15):[],o={schemaVersion:"1.0",notAScore:!0,mode:t,topResidual:s};return t==="subset"?(o.reasonCode=typeof e.reasonCode=="string"&&e.reasonCode.length>0?e.reasonCode:kt.FACTS_PARTIAL,o.reason=typeof e.reason=="string"&&e.reason.length>0?e.reason:"Status compass is a subset of doctor residual \u2014 incomplete session facts; run doctor for full."):typeof e.reasonCode=="string"&&e.reasonCode.length>0&&(o.reasonCode=e.reasonCode),typeof e.reason=="string"&&e.reason.length>0&&t==="full"&&(o.reason=e.reason),n&&(o.factsSource=n),r&&(o.contractHash=r),o}function go(e={}){return Sn({mode:"unavailable",topResidual:[],reasonCode:e.reasonCode??kt.NO_SESSION_SNAPSHOT,reason:e.reason??"No session compass facts yet \u2014 run ark-check --doctor or --report for residual lenses. Status never invents green.",factsSource:"none",contractHash:e.contractHash})}function vr(e){if(e==null||typeof e!="object")return null;let t=e;if(t.notAScore!==!0||t.schemaVersion!=="1.0"||"score"in t||"valid"in t||"goal"in t)return null;let n;return typeof t.mode=="string"&&mo.has(t.mode)?n=t.mode:Array.isArray(t.topResidual)?n="subset":n="unavailable",Sn({mode:n,topResidual:Array.isArray(t.topResidual)?t.topResidual:[],reasonCode:typeof t.reasonCode=="string"?t.reasonCode:null,reason:typeof t.reason=="string"?t.reason:null,factsSource:typeof t.factsSource=="string"?t.factsSource:null,contractHash:typeof t.contractHash=="string"?t.contractHash:null})}function yo(e,t){let n=Array.isArray(e)?e:[],r=new Set(Array.isArray(t)?t:[]);for(let s of n)if(!(typeof s!="string"||s.length===0)&&!r.has(s))return!1;return!0}function Rt(e){if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}var ho={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ar,title:"ArkGate status manifest",description:"Unified session/project status snapshot for agents (identity, activation honesty, last check, rules counts, next action). Not a score.",type:"object",additionalProperties:!1,required:["schemaVersion","arkgateVersion","projectIdentity","activation","lastCheck","rules","nextAction"],properties:{schemaVersion:{const:kn},arkgateVersion:{type:"string",minLength:1},projectIdentity:{type:"object",additionalProperties:!1,required:["projectId","resolvedRoot","resolvedConfigPath","binding","authoritative"],properties:{projectId:{anyOf:[{type:"string",pattern:"^sha256:[a-f0-9]{64}$"},{type:"null"}]},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{anyOf:[{type:"string",minLength:1},{type:"null"}]},binding:{enum:["matched","unverified","mismatch"]},authoritative:{type:"boolean"},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},activation:{type:"object",additionalProperties:!1,required:["writePath","host","honestLabel"],properties:{writePath:{enum:["hard","advisory","unavailable"]},host:{anyOf:[{type:"string",minLength:1},{type:"null"}]},honestLabel:{type:"string",minLength:1}}},lastCheck:{type:"object",additionalProperties:!1,required:["at","verdict","activeViolations","frozenResidual"],properties:{at:{anyOf:[{type:"string",minLength:1},{type:"null"}]},verdict:{anyOf:[{enum:["pass","fail","incomplete"]},{type:"null"}]},activeViolations:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},rules:{type:"object",additionalProperties:!1,required:["arkRulesLoaded","inventoried","underContract","frozenResidual"],properties:{arkRulesLoaded:{type:"boolean"},inventoried:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},underContract:{anyOf:[{type:"integer",minimum:0},{type:"null"}]},frozenResidual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}},nextAction:{type:"object",additionalProperties:!1,required:["id","summary"],properties:{id:{type:"string",minLength:1},summary:{type:"string",minLength:1}}},improvementCompass:{type:"object",description:"Thin improvement-compass residual ids with honesty mode (notAScore). full | subset | unavailable. Never a gate input; full lenses on doctor JSON. When full, residual ids \u2286 doctor residual for the same facts. unavailable never invents green residual.",additionalProperties:!1,required:["schemaVersion","notAScore","mode","topResidual"],properties:{schemaVersion:{const:"1.0"},notAScore:{const:!0},mode:{enum:["full","subset","unavailable"]},topResidual:{type:"array",items:{type:"string",minLength:1},maxItems:15},reasonCode:{type:"string",minLength:1},reason:{type:"string",minLength:1},factsSource:{enum:["doctor-facts","report-snapshot","none"]},contractHash:{type:"string",minLength:1}}},vsBase:{type:"object",description:"Checkout vs a git base ref: pin, contract identity, baseline grow. Advisory honesty only \u2014 never a gate input.",additionalProperties:!1,required:["baseRef","line","pinLocal","pinBase","contractEqual","baselineGrew"],properties:{baseRef:{type:"string",minLength:1},line:{type:"string",minLength:1},pinLocal:{anyOf:[{type:"string",minLength:1},{type:"null"}]},pinBase:{anyOf:[{type:"string",minLength:1},{type:"null"}]},contractEqual:{type:"boolean"},baselineGrew:{type:"boolean"}}},arkRun:{type:"object",description:"ArkRun extra residual (notAScore). present/mode from config; residual is a finding-id count (null = unknown, not green). extraMergeTeeth is honesty, never a score.",additionalProperties:!1,required:["notAScore","present","mode","extraMergeTeeth","residual"],properties:{notAScore:{const:!0},present:{type:"boolean"},mode:{anyOf:[{enum:["advisory","enforced"]},{type:"null"}]},extraMergeTeeth:{type:"boolean"},residual:{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}}}};var St="1.0",Et=["soc","cohesion","coupling","srp","dip","ocp","encapsulation","modularity","scalability","resilience","security","maintainability","testability","domain","stack"],It=5,ke=["scalability","resilience","security"],He=new Set(ke),Cr={soc:10,coupling:20,dip:30,domain:40,srp:50,cohesion:60,encapsulation:70,modularity:80,testability:90,maintainability:100,ocp:110,stack:120,scalability:200,resilience:200,security:200},_r={soc:"Separation of concerns",cohesion:"High cohesion",coupling:"Low coupling",srp:"Single responsibility (architecture)",dip:"Dependency inversion",ocp:"Open/closed",encapsulation:"Encapsulation",modularity:"Modularity",scalability:"Scalability / performance",resilience:"Resilience / fault tolerance",security:"Security by design",maintainability:"Maintainability",testability:"Testability",domain:"Domain alignment",stack:"Stack-specific practices"},xr={scalability:"ArkGate does not measure performance or horizontal scale. Use load tests and APM outside Ark.",resilience:"ArkGate does not measure app resilience or chaos readiness. Structural boundaries and optional experimental runtime are not a resilience score.",security:"ArkGate does not run SAST or app-security tooling. Structural least-privilege of effects is partial only \u2014 not a security rating."};function Tr(e){return _r[e]??e}function Nr(e){let t=e.id??e.smellId??"";return typeof t=="string"?t.trim():""}function Or(e){let t=e.ruleId??e.code??"";return typeof t=="string"?t.trim():""}function P(e,t,n,r){if(!n||e.evidence.some(o=>o.source===t&&o.ref===n))return;let s={source:t,ref:n};r&&r.trim()&&(s.detail=r.trim().slice(0,240)),e.evidence.push(s)}function G(e,t,n){He.has(e.id)||(e.status="residual",e.summary=t,n&&(e.nextAction=n))}function Ao(e){switch(e){case"soc":return"No separation-of-concerns residual detected from current sensors.";case"cohesion":return"No cohesion residual (god-module / physical cohesion) from current sensors.";case"coupling":return"No coupling residual (import edges, cycles, peer isolation) from current sensors.";case"srp":return"No single-responsibility residual from current sensors.";case"dip":return"No dependency-inversion residual (pure / capability / forbidden walls) from current sensors.";case"ocp":return"Open/closed is not strongly instrumented \u2014 no switch-chain sensor.";case"encapsulation":return"No encapsulation residual from ArkRules structure sensors.";case"modularity":return"No modularity / placement residual from current sensors.";case"maintainability":return"No maintainability residual (design-weak / baseline honesty) from current sensors.";case"testability":return"No testability residual (impure domain / capability walls) from current sensors.";case"domain":return"No domain-alignment residual from current sensors.";case"stack":return"Stack practices are only partially instrumented (TypeScript / host / Ark idioms).";default:return`${_r[e]} \u2014 no residual from current sensors.`}}function Ro(){return Et.map(e=>He.has(e)?{id:e,status:"out-of-scope",summary:xr[e],evidence:[],nextAction:{kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}:e==="ocp"?{id:e,status:"not-instrumented",summary:Ao(e),evidence:[]}:{id:e,status:"ok",summary:Ao(e),evidence:[]})}function nl(e,t){for(let n of t){let r=Nr(n);if(!r)continue;let s=n.outcome||n.message||void 0,a=(Array.isArray(n.evidence)?n.evidence:[])[0],i=(f,m,d)=>{let c=e.get(f);!c||He.has(f)||(P(c,"designSmells",r,s),a&&P(c,"designSmells",a,r),G(c,m,d))},l={kind:"skill",ref:"/ark-explore",summary:"Map Shape residual (shape-focus), then apply one extraction pilot with /ark-autopilot."},u={kind:"skill",ref:"/ark-autopilot",summary:"Inject a port/adapter for I/O; keep domain pure."};switch(r){case"domain-logic-in-ui":i("soc","Business rules still mix with UI or presentation surfaces.",l),i("domain","Domain logic lives outside Domain \u2014 align rules with Domain ownership.",l);break;case"facade-sql-in-routes":i("soc","Routes/controllers own SQL or ORM access \u2014 concerns are mixed.",l),i("dip","Transport depends on concrete persistence instead of a port.",u);break;case"io-under-application":i("soc","Application/business code reaches I/O directly \u2014 separation is weak.",l),i("dip","I/O is not inverted behind ports/adapters.",u),i("testability","Direct I/O under application code hurts pure unit testing.",u);break;case"handler-in-persistence":i("soc","HTTP/transport handlers live under persistence folders.",l);break;case"god-module":i("cohesion","Large multi-responsibility modules reduce cohesion.",l),i("srp","God modules own too many responsibilities \u2014 split by concern (one pilot).",{kind:"skill",ref:"/ark-autopilot",summary:"One Shape pilot this turn \u2014 never multi-pilot batch."});break;case"mixed-pattern-cluster":i("modularity","Multiple layout styles coexist \u2014 placement is unclear for the next AI turn.",{kind:"skill",ref:"/ark-explore",summary:"Pick a golden pattern and migrate one pilot cluster on touch."}),i("cohesion","Mixed layout styles scatter the same concern across patterns.",l);break;case"soft-contract":i("maintainability","Soft contract walls (layers without deny rules) hide maintainability debt.",{kind:"skill",ref:"/ark-adopt",summary:"Add real layer rules so the AI has hard walls."}),i("coupling","Layers with files but almost no deny rules allow free peer coupling.",{kind:"skill",ref:"/ark-adopt",summary:"Tighten inter-layer allows/denies without weakening enforcement."});break;default:i("maintainability","Design residual remains under an unrecognized smell id \u2014 review evidence.",l);break}}}function rl(e){return e.failsStrict===!1||e.typeOnly===!0}function sl(e,t){for(let n of t){let r=Or(n);if(!r)continue;let s=n.message,o=r.toUpperCase(),a=(l,u,f)=>{let m=e.get(l);!m||He.has(l)||(P(m,"violations",r,s),n.file&&P(m,"violations",n.file,r),G(m,u,f))};if(rl(n)){a("modularity","Type-only placement debt remains \u2014 prefer SharedTypes / owning layer (not runtime coupling).",{kind:"skill",ref:"/ark-place",summary:"Place shared types in a layer both sides may import; type-only debt is not a value edge."});continue}let i={kind:"skill",ref:"/ark-autopilot",summary:"Clear the active edge residual, then re-doctor."};if(o==="LAYER_IMPORT_VIOLATION"||o.includes("LAYER_IMPORT")||o==="DYNAMIC_IMPORT_VIOLATION"){a("coupling","Import graph edges violate the layer contract.",i);continue}if(o.includes("CYCLE")||o==="CIRCULAR_DEPENDENCY"){a("coupling","Import cycles couple modules tightly.",i);continue}if(o.includes("PEER_ISOLATION")||o==="PEER_ISOLATION_VIOLATION"){a("coupling","Peer isolation residual \u2014 slices import each other freely.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation fixes are judgment-class \u2014 one cluster at a time."});continue}if(o==="FORBIDDEN_GLOBAL"||o.startsWith("FORBIDDEN_")){a("dip","Forbidden globals / effect surfaces break dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject a port instead of the forbidden global."}),a("testability","Forbidden ambient effects reduce pure-domain testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Replace ambient effects with injectable ports."});continue}if(o==="CAPABILITY_VIOLATION"){a("dip","Denied capability use \u2014 invert through an allowed adapter/port.",{kind:"skill",ref:"/ark-autopilot",summary:"Capability walls require port injection (judgment, not mechanical-safe)."}),a("testability","Capability violations couple domain code to I/O \u2014 harder to unit-test.",{kind:"skill",ref:"/ark-autopilot",summary:"Keep pure layers free of denied capabilities."});continue}if(o.startsWith("ARKRULE_")||o==="INVARIANT_UNCOVERED"){a("encapsulation","ArkRules structure / invariant residual inside a layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Label [ArkRules]; structure fixes are judgment \u2014 never invent mechanical-safe."}),a("domain","Intra-layer domain structure or invariant coverage residual.",{kind:"skill",ref:"/ark-explore",summary:"Inventory candidates \u2192 one ArkRules pilot with coverage evidence."});continue}}}function ol(e,t){let n=Number(t.cycleCount)||0;if(n>0){let c=e.get("coupling");P(c,"cycles",`count:${n}`),G(c,"Import cycles couple modules tightly.",{kind:"skill",ref:"/ark-autopilot",summary:"Break cycles with a judgment extraction \u2014 one pilot."})}let r=typeof t.peerIsolationCount=="boolean"?t.peerIsolationCount?1:0:Number(t.peerIsolationCount)||0;if(r>0){let c=e.get("coupling");P(c,"peerIsolation",`count:${r}`),G(c,"Peer isolation residual remains.",{kind:"skill",ref:"/ark-autopilot",summary:"Peer isolation is judgment-class residual."})}let s=Number(t.physicalCohesionFindingCount)||0;if(s>0){let c=e.get("cohesion");P(c,"physicalCohesion",`findings:${s}`),G(c,"Physical cohesion residual \u2014 mirrored concept clusters across anchors.",{kind:"skill",ref:"/ark-explore",summary:"Review reshape pilot; one decision-aware pilot at a time."});let p=e.get("srp");P(p,"physicalCohesion",`findings:${s}`),G(p,"Mirrored clusters suggest split-by-concern residual (architecture SRP).",{kind:"skill",ref:"/ark-autopilot",summary:"One reshape/extraction pilot this turn."})}let o=Number(t.pureOrCapabilityResidual)||0,a=Number(t.forbiddenGlobalResidual)||0;if(o>0||a>0){let c=e.get("dip");o>0&&P(c,"capability",`residual:${o}`),a>0&&P(c,"forbiddenGlobals",`residual:${a}`),G(c,"Pure / capability / forbidden residual weakens dependency inversion.",{kind:"skill",ref:"/ark-autopilot",summary:"Inject ports; keep pure layers free of effects."});let p=e.get("testability");o>0&&P(p,"capability",`residual:${o}`),a>0&&P(p,"forbiddenGlobals",`residual:${a}`),G(p,"Impure domain or capability residual reduces testability.",{kind:"skill",ref:"/ark-autopilot",summary:"Prefer ports over concrete I/O in pure/domain modules."})}let i=Number(t.arkRulesStructureResidual)||0;if(i>0){let c=e.get("encapsulation");P(c,"arkRules",`structureResidual:${i}`),G(c,"ArkRules structure residual \u2014 encapsulation inside the layer.",{kind:"skill",ref:"/ark-autopilot",summary:"Fix structure sensors under [ArkRules] without inventing mechanical-safe."});let p=e.get("domain");P(p,"arkRules",`structureResidual:${i}`),G(p,"ArkRules residual may mean domain shape is not yet under contract.",{kind:"skill",ref:"/ark-explore",summary:"Map inventory candidates; one pilot rule at a time."})}else t.arkRulesLoaded===!1||t.arkRulesLoaded==null;if(t.designWeak===!0){let c=e.get("maintainability");P(c,"designFitness","design-weak"),G(c,"Design-weak: checked edges may be clean, but design residual remains \u2014 not finished.",{kind:"skill",ref:"/ark-explore",summary:"Shape door: explore shape-focus \u2192 dual-plan B \u2192 one /ark-autopilot pilot."})}if(t.dirtyBaselineRisk===!0||(Number(t.baselineStale)||0)>0){let c=e.get("maintainability");t.dirtyBaselineRisk===!0&&P(c,"baseline","dirty-freeze-risk"),(Number(t.baselineStale)||0)>0&&P(c,"baseline",`stale:${t.baselineStale}`),G(c,"Baseline honesty residual \u2014 frozen debt or stale keys need review.",{kind:"command",ref:"ark-check --doctor",summary:"Review baseline freeze honesty; do not freeze new wrong debt."})}let l=Number(t.frozenResidual)||0;if(t.baselineExists===!0&&l>=10&&e.get("maintainability").status!=="residual"){let c=e.get("maintainability");P(c,"baseline",`frozen:${l}`),G(c,"Substantial frozen residual remains under the baseline \u2014 review debt honestly.",{kind:"command",ref:"ark-check --doctor",summary:"Review freezes; do not freeze new wrong debt to clear residual."})}let u=Number(t.ungovernedDirCount)||0,f=Number(t.emptyLayerCount)||0;if(u>0||f>0){let c=e.get("modularity");u>0&&P(c,"coverage",`ungovernedDirs:${u}`),f>0&&P(c,"coverage",`emptyLayers:${f}`),G(c,"Placement / modularity residual \u2014 ungoverned dirs or empty layer globs.",{kind:"skill",ref:"/ark-adopt",summary:"Classify ungoverned paths; fix empty layer patterns."})}if(t.designWeak===!0&&t.goldenPatternPresent===!1){let c=e.get("modularity");P(c,"goldenPattern","absent"),G(c,"Design-weak without a golden pattern \u2014 new code lacks a placement norm for the AI.",{kind:"skill",ref:"/ark-place",summary:"Record an advisory golden pattern for new code (does not clear design-weak)."})}let m=e.get("stack");(t.stackKind??null)==="typescript"?m.status==="ok"&&(m.summary="Stack practices are partially instrumented for TypeScript / host / Ark idioms only \u2014 not a full framework checklist."):(m.status="not-instrumented",m.summary="Stack-specific best practices outside TypeScript/host/Ark idioms are not instrumented.",m.evidence=[],m.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Ark does not score non-TS stack idioms."})}function ko(e,t){if(Array.isArray(t.designSmells)&&t.designSmells.length>0){let n=[...t.designSmells].sort((r,s)=>Nr(r).localeCompare(Nr(s)));nl(e,n)}if(Array.isArray(t.violations)&&t.violations.length>0){let n=[...t.violations].sort((r,s)=>{let o=Or(r).localeCompare(Or(s));return o!==0?o:String(r.file??"").localeCompare(String(s.file??""))});sl(e,n)}ol(e,t)}function So(e){for(let t of ke){let n=e.get(t);n.status="out-of-scope",n.summary=xr[t],n.evidence=[],n.nextAction={kind:"docs",ref:"docs/use.md#improvement-compass",summary:"Out of scope for ArkGate \u2014 use dedicated tooling outside the gate."}}}function Eo(e){for(let t of e)t.evidence.sort((n,r)=>{let s=n.source.localeCompare(r.source);return s!==0?s:n.ref.localeCompare(r.ref)})}function Io(e){return e.filter(n=>n.status==="residual"&&!He.has(n.id)).slice().sort((n,r)=>{let s=Cr[n.id]??150,o=Cr[r.id]??150;return s!==o?s-o:n.id.localeCompare(r.id)}).slice(0,5).map(n=>n.id)}function bo(e={}){let t=Ro(),n=new Map(t.map(s=>[s.id,s]));ko(n,e),So(n),Eo(t);let r=Io(t);return{schemaVersion:"1.0",notAScore:!0,lenses:t.map(s=>{let o={id:s.id,status:s.status,summary:s.summary,evidence:s.evidence.map(a=>({...a}))};return s.nextAction&&(o.nextAction={...s.nextAction}),o}),topResidual:r}}function Lr(e){return e.topResidual.map(t=>Tr(t))}function Pr(e){for(let t of e.topResidual){let n=e.lenses.find(r=>r.id===t);if(n?.nextAction)return{...n.nextAction}}return null}function vo(e){let t=Lr(e),n=ke.map(o=>Tr(o)),r=Pr(e),s=[];return t.length>0?s.push(`Residual: ${t.join(" \xB7 ")}`):s.push("Residual: none on instrumented lenses (not a score \u2014 green edges \u2260 finished design)."),s.push(`Out of scope (honest): ${n.join(" \xB7 ")}`),r&&s.push(`Next: ${r.ref} \u2014 ${r.summary}`),s}var Co="1.0",_o="<!-- arkgate:agent-projection:begin",wr="<!-- arkgate:agent-projection:end -->",Mr="This projection is **non-authoritative**. Enforcement is `ark-check` / host write hooks / required CI (`--strict-merge`), not AGENTS.md, skills, or this block.",vn=Object.freeze(["ark-check","host-write-hooks","ci-strict-merge"]),xo=Object.freeze(["LAYER_IMPORT_VIOLATION","LAYER_INTENT_REFERENCE_VIOLATION","CIRCULAR_DEPENDENCY","CAPABILITY_VIOLATION","RAW_EVENT_PUBLISH","ARKRULE_STRUCTURE","ATOMIC_PREFLIGHT_UNAVAILABLE","ANALYSIS_PARSE_INCOMPLETE","ARK_UNKNOWN"]),Dr=/<!--\s*arkgate:agent-projection:begin\b([^>]*)-->/i,To=/<!--\s*arkgate:agent-projection:end\s*-->/i,al=/\barkgateVersion=([A-Za-z0-9._+-]+)/i,il=/\bschema=([A-Za-z0-9._+-]+)/i;function bt(e){let t=String(e??"").replace(/\r\n/g,`
|
|
17
|
+
`),n=2166136261;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return`fnv1a-${(n>>>0).toString(16).padStart(8,"0")}`}function En(e){return String(e??"").replace(/\r\n/g,`
|
|
18
|
+
`)}function je(e){let t=En(e);return t.endsWith(`
|
|
19
19
|
`)?t:`${t}
|
|
20
|
-
`}function
|
|
20
|
+
`}function Cn(e){return typeof e!="string"||e.trim().length===0?"unknown":e.trim().replace(/[>\s]/g,"")}function No(e){return e==="compact"?"compact":"full"}function Fr(e){let t=Cn(e.arkgateVersion);return`<!-- arkgate:agent-projection:begin schema=${typeof e.schemaVersion=="string"&&e.schemaVersion.trim()?e.schemaVersion.trim():"1.0"} arkgateVersion=${t} nonAuthoritative=true -->`}function In(e){return!Array.isArray(e)||e.length===0?"_No project layers loaded \u2014 read `ark.config.json` or run `ark start` / `ark_manifest`._":`| Layer | Patterns | Intent prefixes |
|
|
21
21
|
|-------|----------|-----------------|
|
|
22
|
-
${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],
|
|
23
|
-
`)}`}function
|
|
22
|
+
${e.map(n=>{let r=n.name?.trim()||"Unknown",s=n.patterns??[],o=n.intentPrefixes??[],a=s.map(l=>`\`${l}\``).join(", ")||"\u2014",i=o.map(l=>`\`${l}\``).join(", ")||"\u2014";return`| ${r} | ${a} | ${i} |`}).join(`
|
|
23
|
+
`)}`}function $r(e,t){let n=t.trim()||"docs/diagnostics.md";return!Array.isArray(e)||e.length===0?`Full public codes: \`${n}\` (and package \`DIAGNOSTIC_CATALOG\`).`:`${e.filter(s=>s&&typeof s.ruleId=="string"&&s.ruleId.length>0).map(s=>{let o=typeof s.title=="string"&&s.title.trim()?s.title.trim():s.ruleId;return`- \`${s.ruleId}\` \u2014 ${o}`}).join(`
|
|
24
24
|
`)}
|
|
25
25
|
|
|
26
|
-
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}function
|
|
27
|
-
`),""),
|
|
26
|
+
Full catalog: \`${n}\` (\`#RULE_ID\` anchors).`}function _n(e){let t=Cn(e.arkgateVersion),n=No(e.profile),r=typeof e.checkCommand=="string"&&e.checkCommand.trim()?e.checkCommand.trim():"ark-check --strict-config",s=typeof e.diagnosticsDocsPath=="string"&&e.diagnosticsDocsPath.trim()?e.diagnosticsDocsPath.trim():"docs/diagnostics.md",o=typeof e.host=="string"?e.host.trim().toLowerCase():"",a=o&&o!=="unknown"?o:null,i=Array.isArray(e.layers)?e.layers:[],l=Array.isArray(e.catalogShortList)?e.catalogShortList:[],u=["## ArkGate agent contract projection","",Mr,"",`- **arkgateVersion:** \`${t}\` (must match the installed package; regenerate with \`ark agents-md --write\` after upgrade)`,"- **projectionSchema:** `1.0`",`- **profile:** \`${n}\`${a?` \xB7 **host:** \`${a}\``:""}`,`- **after edits:** \`${r}\``,""];return n==="compact"?u.push("### Primary path","","1. Run doctor (`ark-check --doctor`) \u2014 status light + primary next action. Prefer the project-local CLI; do not wait on MCP \u201Cstill connecting\u201D.","2. Read the improvement compass (not a score). Name leftover work in plain language; never \u201Cdone\u201D on green imports alone while leftover design work remains.","3. Identity handshake is optional when the CLI already resolved the project root. Call `ark_identity` only when using MCP evidence.","4. Read architecture config with `ark_manifest` (same expectation) or the local `ark.config.json`. `ark://manifest` is compatibility-only / unverified.","5. Place files inside configured layers; validate; run the check command above on violations \u2014 fix architecture, do not weaken the gate.","6. Single door: import-rule debt \u2192 fix; leftover design work / residual shape lenses \u2192 map then guided apply with user OK.","","### Contract layers (summary)","",In(i),""):u.push("### Contract layers","",In(i),"","When creating a **new** kind of code that no layer covers, update `ark.config.json` first (`/ark-adopt`), then place the file.","","### Diagnostic codes (short list)","",$r(l,s),"","### Session truth","","- Machine snapshot: `ark status --json` (or MCP `ark_status`) \u2014 identity, activation honesty, last check, residual counts. **Not a score.**","- Authoritative contract: local `ark.config.json` / CLI, or `ark_manifest` after a matched `ark_identity` handshake. Identity is optional when CLI already resolved the root.","- Host docs: the same projection schema is merged into `AGENTS.md` and `CLAUDE.md` (`ark agents-md --write`).",""),u.push("### Enforcement surfaces (authoritative)","",vn.map(f=>`- \`${f}\``).join(`
|
|
27
|
+
`),""),u.join(`
|
|
28
28
|
`).replace(/\n{3,}/g,`
|
|
29
29
|
|
|
30
30
|
`).trimEnd()+`
|
|
31
|
-
`}function
|
|
32
|
-
${t}${
|
|
33
|
-
`}function
|
|
34
|
-
`)&&(
|
|
35
|
-
`,
|
|
31
|
+
`}function Oo(e){let t=_n(e);return`${Fr({arkgateVersion:e.arkgateVersion,schemaVersion:"1.0"})}
|
|
32
|
+
${t}${wr}
|
|
33
|
+
`}function Lo(e){let t=_n(e),n=Array.isArray(e.layers)?e.layers:[],r=Array.isArray(e.catalogShortList)?e.catalogShortList:[];return{schemaVersion:"1.0",arkgateVersion:Cn(e.arkgateVersion),nonAuthoritative:!0,enforcementSurfaces:[...vn],contentIdentity:bt(t),layerCount:n.length,catalogCodeCount:r.filter(s=>s?.ruleId).length,profile:No(e.profile)}}function bn(e){let t=En(e??""),n=Dr.exec(t);if(!n)return{block:null,body:null,before:t,after:"",beginAttrs:null};let r=n.index,s=r+n[0].length,o=t.slice(s),a=To.exec(o);if(!a)return{block:null,body:null,before:t,after:"",beginAttrs:null};let i=a.index,l=i+a[0].length,u=o.slice(0,i);u.startsWith(`
|
|
34
|
+
`)&&(u=u.slice(1));let f=t.slice(r,s+l),m=o.slice(l);return{block:f,body:u,before:t.slice(0,r),after:m,beginAttrs:n[1]??""}}function Hr(e){let t=String(e??""),r=Dr.exec(t)?.[1]??t,s=al.exec(r),o=il.exec(r),a=/\bnonAuthoritative\s*=\s*true\b/i.test(r);return{arkgateVersion:s?.[1]??null,schemaVersion:o?.[1]??null,nonAuthoritative:a}}function Po(e,t){let n=Hr(e).arkgateVersion;return n?n===Cn(t):!1}function wo(e){return String(e??"").includes("non-authoritative")}function Mo(e,t){let n=je(En(t)),s=bn(n).body??n.replace(Dr,"").replace(To,"").trim()+`
|
|
35
|
+
`,o=bt(s);if(e==null||!String(e).trim())return{content:je(`# Ark Enforcement
|
|
36
36
|
|
|
37
|
-
${n}`),action:"created",previousBlock:null,contentIdentity:
|
|
37
|
+
${n}`),action:"created",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!1};let a=En(e),i=bn(a);if(i.block!=null){let u=i.body??"";if(bt(u)===o)return{content:je(a),action:"unchanged",previousBlock:i.block,contentIdentity:o,preservedOutsideBlock:!0};let f=i.before.replace(/\s*$/,`
|
|
38
38
|
|
|
39
|
-
`),m=
|
|
40
|
-
`);return{content:
|
|
41
|
-
${m}`),action:"block-replaced",previousBlock:
|
|
39
|
+
`),m=i.after.replace(/^\s*/,`
|
|
40
|
+
`);return{content:je(`${f}${n.trimEnd()}
|
|
41
|
+
${m}`),action:"block-replaced",previousBlock:i.block,contentIdentity:o,preservedOutsideBlock:!0}}let l=/^(#\s+[^\n]*\n)/m.exec(a);if(l&&l.index!=null){let u=l.index+l[1].length,f=a.slice(0,u).replace(/\s*$/,`
|
|
42
42
|
|
|
43
|
-
`),m=
|
|
44
|
-
`);return{content:
|
|
45
|
-
${m}`),action:"block-inserted",previousBlock:null,contentIdentity:
|
|
43
|
+
`),m=a.slice(u).replace(/^\s*/,`
|
|
44
|
+
`);return{content:je(`${f}${n.trimEnd()}
|
|
45
|
+
${m}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}return{content:je(`${n.trimEnd()}
|
|
46
46
|
|
|
47
|
-
${
|
|
47
|
+
${a.trimStart()}`),action:"block-inserted",previousBlock:null,contentIdentity:o,preservedOutsideBlock:!0}}var Do="1.0",jr="templates/agent-skills",Vr="templates/skills",Ur="SKILL.md",vt=Object.freeze(["ark-adopt","ark-architect","ark-autopilot","ark-contract","ark-coverage","ark-explain","ark-explore","ark-fix","ark-loop","ark-place","ark-runtime","ark-think","ark-upgrade"]),Kr=vt.length,ll=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Gr(e){return typeof e!="string"||e.length<1||e.length>64?!1:ll.test(e)}function Tn(e){return vt.includes(e)}function Br(e){let t=String(e??"").replace(/^\uFEFF/,""),n=t.includes(`\r
|
|
48
48
|
`)?`\r
|
|
49
49
|
`:`
|
|
50
|
-
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let
|
|
51
|
-
`)}function
|
|
50
|
+
`,r=t.split(/\r?\n/);if(r[0]!=="---")return{hasFrontmatter:!1,frontmatter:null,body:t};let s=r.indexOf("---",1);if(s===-1)return{hasFrontmatter:!1,frontmatter:null,body:t};let o={};for(let f=1;f<s;f+=1){let m=r[f]??"";if(m.trim()===""||m.trimStart().startsWith("#"))continue;let d=m.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if(!d)continue;let c=d[1],p=d[2]??"";(p.startsWith('"')&&p.endsWith('"')&&p.length>=2||p.startsWith("'")&&p.endsWith("'")&&p.length>=2)&&(p=p.slice(1,-1)),o[c]=p}let a=r.slice(s+1).join(n),i=typeof o.name=="string"&&o.name.length>0?o.name:null,l=typeof o.description=="string"&&o.description.length>0?o.description:null,u=typeof o.license=="string"&&o.license.length>0?o.license:null;return{hasFrontmatter:!0,frontmatter:{fields:o,name:i,description:l,license:u},body:a}}function zr(e){let t=e.requireArkSkillName!==!1,n=e.requireBody!==!1,r=[],s=String(e.directoryName??""),o=Br(e.content);if(!o.hasFrontmatter||!o.frontmatter)return r.push({code:"MISSING_FRONTMATTER",message:`Skill "${s}" is missing YAML frontmatter fences.`,skillName:s||void 0}),r;let{name:a,description:i}=o.frontmatter,l=a??(s||void 0);return!a||!Gr(a)?r.push({code:"INVALID_NAME",message:`Skill name "${a??""}" is invalid (Agent Skills: 1\u201364 chars, [a-z0-9-], no leading/trailing/consecutive hyphens).`,skillName:l}):a!==s?r.push({code:"NAME_DIRECTORY_MISMATCH",message:`Frontmatter name "${a}" must match directory name "${s}".`,skillName:a}):t&&!Tn(a)&&r.push({code:"UNKNOWN_SKILL_NAME",message:`Skill name "${a}" is not in the frozen Ark 13-skill catalog (no new skill names).`,skillName:a}),i?i.length>1024&&r.push({code:"DESCRIPTION_TOO_LONG",message:`Skill "${s}" description exceeds 1024 characters (${i.length}).`,skillName:l}):r.push({code:"MISSING_DESCRIPTION",message:`Skill "${s}" is missing a non-empty description.`,skillName:l}),n&&o.body.trim().length===0&&r.push({code:"EMPTY_BODY",message:`Skill "${s}" has an empty instruction body.`,skillName:l}),r}function Fo(e){let t=[],n=new Set,r=[];for(let s of e){let o=String(s.name??"");if(n.has(o)){t.push({code:"DUPLICATE_SKILL",message:`Duplicate skill entry "${o}".`,skillName:o});continue}n.add(o),r.push(o),t.push(...zr({directoryName:o,content:s.content,requireArkSkillName:!0,requireBody:!0})),s.flatTemplateContent!=null&&xn(s.content)!==xn(s.flatTemplateContent)&&t.push({code:"CONTENT_MISMATCH",message:`Agent Skills SKILL.md for "${o}" does not match flat template templates/skills/${o}.md.`,skillName:o})}for(let s of vt)n.has(s)||t.push({code:"MISSING_SKILL",message:`Missing frozen skill "${s}" from Agent Skills package.`,skillName:s});for(let s of r)Tn(s)||(t.some(o=>o.code==="UNKNOWN_SKILL_NAME"&&o.skillName===s)?t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}):t.push({code:"EXTRA_SKILL",message:`Extra skill "${s}" is not in the frozen Ark 13-skill catalog.`,skillName:s}));return r.sort(),{ok:t.length===0,issues:t,names:r,expectedCount:Kr,presentCount:r.length}}function xn(e){return String(e??"").replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
51
|
+
`)}function qr(e){return`${e}/${Ur}`}function $o(e){return`${jr}/${qr(e)}`}function Ho(e){return`${Vr}/${e}.md`}0&&(module.exports={ADAPTER_DIAGNOSTIC_DOCS_RELATIVE_PATH,AGENT_PROJECTION_BEGIN_MARKER,AGENT_PROJECTION_END_MARKER,AGENT_PROJECTION_ENFORCEMENT_SURFACES,AGENT_PROJECTION_NON_ENFORCEMENT_LABEL,AGENT_SKILLS_PACKAGE_RELATIVE_ROOT,AGENT_SKILL_ENTRY_FILENAME,ANALYSIS_IR_SCHEMA_VERSION,ARKRUN_INTERACTION_NAME_INCOMPLETE,ARKRUN_KERNEL_FACTORY_CALLEES,ARKRUN_KERNEL_INTERACTION_CALLEES,ARKRUN_RULE_IDS,ARKRUN_TIER1_SENSOR_IDS,ARKRUN_TRANSPORT_BYPASS_SPECIFIERS,ARK_AGENT_PROJECTION_SCHEMA_VERSION,ARK_AGENT_SKILLS_PACKAGE_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,ARK_DESIGN_DELTA_SCHEMA_VERSION,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,ARK_IMPROVEMENT_COMPASS_SCHEMA_VERSION,ARK_PROJECT_IDENTITY_SCHEMA,ARK_PROJECT_IDENTITY_SCHEMA_URL,ARK_PROJECT_IDENTITY_SCHEMA_VERSION,ARK_RULES_SCHEMA,ARK_RULES_SCHEMA_VERSION,ARK_RULE_SENSORS,ARK_RUN_DOCTOR_SCHEMA_VERSION,ARK_SKILL_NAMES,ARK_SKILL_NAME_COUNT,ARK_STATUS_MANIFEST_SCHEMA,ARK_STATUS_MANIFEST_SCHEMA_URL,ARK_STATUS_MANIFEST_SCHEMA_VERSION,DEFAULT_AGENT_PROJECTION_RULE_IDS,DIAGNOSTIC_CATALOG,DIAGNOSTIC_CATALOG_SCHEMA_VERSION,DIAGNOSTIC_DOCS_RELATIVE_PATH,DIAGNOSTIC_RULE_IDS,EXTRA_MERGE_TEETH_GOVERNED_FLOOR,EffectiveContractError,FLAT_SKILL_TEMPLATES_RELATIVE_ROOT,IMPROVEMENT_COMPASS_OUT_OF_SCOPE_LENSES,IMPROVEMENT_COMPASS_TOP_RESIDUAL_CAP,IMPROVEMENT_LENS_IDS,MERGE_PLANES_DUAL_STAMP,POLICY_DELTA_SCHEMA_VERSION,PROJECT_BINDING_SCHEMA,PROJECT_EXPECTATION_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,STATUS_COMPASS_FACTS_SOURCES,STATUS_COMPASS_MODES,STATUS_COMPASS_REASON_CODES,adapterDocsCodePath,adapterFindingOccurrenceTargetKeys,adapterFindingRefFromTargetKey,adapterFindingTargetKey,agentProjectionContentIdentity,agentSkillEntryRelativePath,agentSkillPackageFileRelativePath,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,analyzeResolvedProject,arkRunKernelCallKind,buildAgentProjectionBeginMarker,buildAgentProjectionBlock,buildAgentProjectionBody,buildAgentProjectionMeta,buildArkRuleFileHints,buildEffectiveArkRules,buildImprovementCompass,buildRulesInventory,buildStatusManifest,canPromoteInvariant,catalogFixForRuleId,catalogWhyForRuleId,classifyArkPolicyDelta,classifyResolvedLayerCoverage,classifyStatusWritePath,collectAnalysisConfigWarnings,collectEmptyAppliesToFindings,collectForbiddenCapabilityUses,composeMergePlanesHonesty,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,createProjectId,createProjectIdentity,createResolvedCandidateFacts,defaultHonestLabel,demoteExtraPlaneTeethUnderClassificationFloor,deriveArkRuleFileHints,detectArchitectureCycles,deterministicHash,diagnosticDocsFragment,diagnosticDocsPath,effectiveContractPolicyPayload,elevenLayerProfile,emptyEffectiveArkRules,evaluateArchitectureGraph,evaluateArkRuleSensors,evaluateArkRunEditorSensors,evaluateArkRunEditorSensorsFromSource,evaluateArkRunSensors,evaluateInvariantCoverage,evaluateStatusBinding,explainViolation,extraMergeTeethAllowed,extractAgentProjectionBlock,extractArkRunDeclarationsFromSource,extractArkRunImportedConstructorNamesFromSource,extractArkRunKernelCallsFromSource,extractArkRunManagedNewsFromSource,extractArkRunValueImportDependenciesFromSource,extractClassShapesFromSource,extractSemanticDependencies,flatSkillTemplateFileRelativePath,formatAgentProjectionCatalogShortList,formatAgentProjectionLayers,formatArkRunDoctorLines,formatImprovementCompassDoctorLines,formatImprovementCompassResidualLabels,getDiagnosticCatalogEntry,inventoryToExtractionCard,isArkRunKernelModuleSpecifier,isArkRunRuleId,isArkRunTransportBypassSpecifier,isArkSkillName,isCataloguedOrArkRuleFamily,isExtraPlaneFinding,isKnownDiagnosticCode,isValidAgentSkillName,loadArkConfigContract,loadArkRulesContract,loadContract,loadResolvedCandidateFacts,mergeAgentProjectionDocument,normalizeExtraMergeTeethClassification,normalizeSkillContent,normalizeStatusImprovementCompass,parseAgentProjectionStamp,parseArkConfigJson,parseArkRulesJson,parseSkillDocument,policyDeltaAcknowledgementMatches,preflightChange,preflightResolvedChange,primaryImprovementCompassNextAction,projectStatusArkRun,projectStatusImprovementCompass,projectionHasNonEnforcementLabel,projectionMatchesPackageVersion,resolveEffectiveContract,resolveStatusNextAction,resolvedFactsEvidenceRequirementsHash,serializeDiagnosticCatalog,stableSerialize,statusCompassResidualIsSubsetOfDoctor,summarizeArkRunSection,toAdapterDiagnostic,unavailableStatusImprovementCompass,validateAgentSkillDocument,validateAgentSkillsPackage,version});
|