arkgate 4.6.6 → 4.6.7
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 +30 -2
- package/README.md +5 -4
- package/bin/ark-check-runtime.mjs +8 -340
- package/bin/ark-mcp-runtime.mjs +7 -323
- package/bin/ark-shared.mjs +24 -158
- package/bin/lib/check-args.mjs +173 -0
- package/bin/lib/check-config-detect.mjs +101 -0
- package/bin/lib/check-watch.mjs +80 -0
- package/bin/lib/deep-module-coach.mjs +3 -0
- package/bin/lib/doctor-human.mjs +509 -0
- package/bin/lib/doctor-plan.mjs +42 -429
- package/bin/lib/github-enforcement.mjs +22 -9
- package/bin/lib/html-report.mjs +24 -7
- package/bin/lib/mcp-hook-payload.mjs +328 -0
- package/bin/lib/package-manager.mjs +174 -0
- package/bin/lib/policy-delta-io.mjs +4 -0
- package/bin/lib/team-parliament-io.mjs +4 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/docs/README.md +2 -2
- package/docs/package-surface.md +2 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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.6";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(`
|
|
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
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}):
|
|
3
3
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
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}):
|
package/dist/index.d.ts
CHANGED
|
@@ -260,7 +260,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
|
|
|
260
260
|
declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
|
|
261
261
|
|
|
262
262
|
/** ArkGate library version — single source of truth. */
|
|
263
|
-
declare const version = "4.6.
|
|
263
|
+
declare const version = "4.6.7";
|
|
264
264
|
|
|
265
265
|
/** Versioned public result contract shared by every ArkGate enforcement adapter. */
|
|
266
266
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var rs="4.6.6";var ss=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,is=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,os=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function as(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return ss.test(n)?"pure-shared":r==="PersistenceAdapters"&&(is.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":os.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}function _t(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=as(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 We(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return _t(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 Ot="1.5",xn="docs/diagnostics.md";function R(e){return typeof e=="string"&&e.length>0?e:void 0}function _n(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Pt(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 xt(e){let t=new Map;return e.map(n=>{let r=Pt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function Tn(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 On(e){return`${xn}#${e}`}function ls(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return _t({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 Tt(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??Pt(e),a=Tn(o);return{ruleId:r,severity:s,message:R(e.message)??r,location:{file:R(e.file)??"<unknown>",line:_n(e.line,1),column:_n(e.column,1)},evidence:i,nextAction:R(e.nextAction)??ls(r,i,e),findingRef:a,targetKey:o,docsCodePath:On(r)}}function cs(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=xt(i),d=xt(o),f=[...i.map((m,c)=>Tt(m,"error",a[c])),...o.map((m,c)=>Tt(m,"warning",d[c]))],g={schemaVersion:Ot,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 ds={$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:Ot},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 ps="1.0",Pn="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Je="^sha256:[a-f0-9]{64}$",Ln={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:Je,description:"Project id previously returned by ark_identity or ark_manifest."}}},Nn={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:Je},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},us={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Pn,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:Je},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Je},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Ln,binding:Nn}};function fs(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 ms(e){return{schemaVersion:"1.0",...e}}var Nt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Mt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),$t=Object.freeze(Object.keys(Mt).sort()),Lt=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"}),wt=Object.freeze({process:Object.freeze(["process","node:process"])});function Le(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Lt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Lt[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:Lt[e.slice(0,i)]??null}function se(e,t){for(let n of t)if(wt[n]?.includes(e))return n;return null}function Ze(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Mt[r];if(s)return s}return null}function ye(e){if(e?.pure===!0)return[...Nt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Nt.includes(r));return[...new Set(n)].sort()}function Ne(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 Xe(e){let t=new Set,n=new Set,r=Object.keys(Mt);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 wt[s]??[])t.add(`import-exact:${o}`)}for(let s of ye(e)){if(t.add(`import:${s}`),s==="process")for(let i of wt.process)t.add(`import-exact:${i}`);for(let i of r)Ze(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var wn=new Map;function Mn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Qe(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 gs(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 le(e){let t=wn.get(e);if(t)return t;let n=Qe(e),r=gs(n),s="",i=0;for(let a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Mn(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+=Mn(d)}let o=new RegExp(`^${s}$`);return wn.set(e,o),o}function ys(e){return Qe(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Dt(e,t){let n=Qe(String(e)),r=ys(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=>le(o).test(n))){for(let o of i.patterns??[])if(le(o).test(n)){let a=Dt(o,n);a>s&&(s=a,r=i.name)}}return r}function $n(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 hs(e){let t=new Set;for(let n of e??[]){let s=Qe(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 As(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 hs(r?.patterns)}function Is(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=As(s,t,r?.layers),d=i&&o?$n(i,a):void 0,f=i&&o?$n(o,a):void 0;if(Is({fromPath:i,toPath:o,folderCount:a.length,fromSlice:d,toSlice:f}))return s;continue}if(t!==n)return s}}function he(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Hn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Dn(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 Vn(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 Ft(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ht(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):Ft(t,r)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function Ae(e,t){let n,r=[],s=(o,a,d,f=!1)=>r.push({specifier:d,kind:a,line:Hn(t,o),typeOnly:f,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",he(e,o.moduleSpecifier),Dn(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",he(e,o.moduleSpecifier),Dn(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",he(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Ht(e,n??(n=Vn(e,t)),t,o.expression);(a||f)&&s(o,f?"require":"dynamic-import",he(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),r}function bs(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=he(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function Ss(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 Fn(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=Vn(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=bs(e,c);if(!l)return;let p=Ft(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:Ht(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=Ft(s,l.name);!p||!y||i.set(y,p)}let d=[],f=new Set,g=(c,l)=>{let p=Hn(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?Fn(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&Ss(e,c)&&!Ht(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?he(e,y.propertyName)??y.propertyName.text:y.name.text,E=Fn(r,[...p,I]);E&&g(E,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function Vt(e,t,n){let r=[];for(let s of n?.dependencies??Ae(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Le(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Ie(e,t,$t)){let i=Ze(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 jt={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."},Ut=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 Gt(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 ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function we(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:jt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:jt.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function be(e,t){return e.slice(0,t).split(`
|
|
1
|
+
var rs="4.6.7";var ss=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,is=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,os=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function as(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return ss.test(n)?"pure-shared":r==="PersistenceAdapters"&&(is.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":os.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}function _t(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=as(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 We(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return _t(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 Ot="1.5",xn="docs/diagnostics.md";function R(e){return typeof e=="string"&&e.length>0?e:void 0}function _n(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Pt(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 xt(e){let t=new Map;return e.map(n=>{let r=Pt(n),s=(t.get(r)??0)+1;return t.set(r,s),s===1?r:`${r}#${s}`})}function Tn(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 On(e){return`${xn}#${e}`}function ls(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return _t({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 Tt(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??Pt(e),a=Tn(o);return{ruleId:r,severity:s,message:R(e.message)??r,location:{file:R(e.file)??"<unknown>",line:_n(e.line,1),column:_n(e.column,1)},evidence:i,nextAction:R(e.nextAction)??ls(r,i,e),findingRef:a,targetKey:o,docsCodePath:On(r)}}function cs(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=xt(i),d=xt(o),f=[...i.map((m,c)=>Tt(m,"error",a[c])),...o.map((m,c)=>Tt(m,"warning",d[c]))],g={schemaVersion:Ot,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 ds={$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:Ot},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 ps="1.0",Pn="https://unpkg.com/arkgate@4/schemas/ark.project-identity.schema.json",Je="^sha256:[a-f0-9]{64}$",Ln={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:Je,description:"Project id previously returned by ark_identity or ark_manifest."}}},Nn={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:Je},code:{enum:["PROJECT_ROOT_MISMATCH","PROJECT_ID_MISMATCH","INVALID_PROJECT_EXPECTATION"]},message:{type:"string",minLength:1}}},us={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Pn,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:Je},resolvedRoot:{type:"string",minLength:1},resolvedConfigPath:{type:"string",minLength:1},arkgateVersion:{type:"string",minLength:1},contractHash:{type:"string",pattern:Je},contractSource:{enum:["project","default-profile","manifest"]},runtimeId:{type:"string",minLength:1},processStartedAt:{type:"string",format:"date-time"}},$defs:{expectation:Ln,binding:Nn}};function fs(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 ms(e){return{schemaVersion:"1.0",...e}}var Nt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Mt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),$t=Object.freeze(Object.keys(Mt).sort()),Lt=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"}),wt=Object.freeze({process:Object.freeze(["process","node:process"])});function Le(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Lt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=Lt[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:Lt[e.slice(0,i)]??null}function se(e,t){for(let n of t)if(wt[n]?.includes(e))return n;return null}function Ze(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Mt[r];if(s)return s}return null}function ye(e){if(e?.pure===!0)return[...Nt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Nt.includes(r));return[...new Set(n)].sort()}function Ne(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 Xe(e){let t=new Set,n=new Set,r=Object.keys(Mt);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 wt[s]??[])t.add(`import-exact:${o}`)}for(let s of ye(e)){if(t.add(`import:${s}`),s==="process")for(let i of wt.process)t.add(`import-exact:${i}`);for(let i of r)Ze(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var wn=new Map;function Mn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Qe(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 gs(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 le(e){let t=wn.get(e);if(t)return t;let n=Qe(e),r=gs(n),s="",i=0;for(let a=0;a<n.length;a+=1){let d=n[a];d==="\\"&&a+1<n.length?(s+=Mn(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+=Mn(d)}let o=new RegExp(`^${s}$`);return wn.set(e,o),o}function ys(e){return Qe(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Dt(e,t){let n=Qe(String(e)),r=ys(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=>le(o).test(n))){for(let o of i.patterns??[])if(le(o).test(n)){let a=Dt(o,n);a>s&&(s=a,r=i.name)}}return r}function $n(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 hs(e){let t=new Set;for(let n of e??[]){let s=Qe(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 As(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 hs(r?.patterns)}function Is(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=As(s,t,r?.layers),d=i&&o?$n(i,a):void 0,f=i&&o?$n(o,a):void 0;if(Is({fromPath:i,toPath:o,folderCount:a.length,fromSlice:d,toSlice:f}))return s;continue}if(t!==n)return s}}function he(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Hn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Dn(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 Vn(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 Ft(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ht(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):Ft(t,r)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function Ae(e,t){let n,r=[],s=(o,a,d,f=!1)=>r.push({specifier:d,kind:a,line:Hn(t,o),typeOnly:f,unresolved:d===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))s(o,"import",he(e,o.moduleSpecifier),Dn(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)s(o,"export",he(e,o.moduleSpecifier),Dn(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))s(o,"require",he(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let a=o.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Ht(e,n??(n=Vn(e,t)),t,o.expression);(a||f)&&s(o,f?"require":"dynamic-import",he(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),r}function bs(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=he(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function Ss(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 Fn(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=Vn(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=bs(e,c);if(!l)return;let p=Ft(s,l.root),y=p?i.get(p):void 0;return y?[...y,...l.segments.slice(1)]:Ht(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=Ft(s,l.name);!p||!y||i.set(y,p)}let d=[],f=new Set,g=(c,l)=>{let p=Hn(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?Fn(r,p):void 0;y&&g(y,c)}else e.isIdentifier(c)&&r.has(c.text)&&Ss(e,c)&&!Ht(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?he(e,y.propertyName)??y.propertyName.text:y.name.text,E=Fn(r,[...p,I]);E&&g(E,c.initializer)}}e.forEachChild(c,m)};return m(t),d}function Vt(e,t,n){let r=[];for(let s of n?.dependencies??Ae(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Le(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Ie(e,t,$t)){let i=Ze(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 jt={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."},Ut=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 Gt(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 ce(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function we(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ce(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:jt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:jt.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function be(e,t){return e.slice(0,t).split(`
|
|
2
2
|
`).length}function Es(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 Rs(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 vs(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 Cs(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 ks(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function _s(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function $e(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function xs(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function jn(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:xs(e,r.name)===n)}function De(e,t,n){return jn(e,t,n)!==void 0}function Me(e,t,n){let r=jn(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function Ts(e,t){let n=Me(e,t,"metadata");return De(e,n,"source")}function Un(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Un(e,t.name):!1:!1}function Os(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 Ps(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=$e(e,n);return r!==void 0&&ce(r)||De(e,n,"intent")||Un(e,n)}function Ls(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Ts(e,n)||De(e,r,"source")||De(e,s,"source")}function Ns(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=Me(e,n,"metadata");return $e(e,Me(e,i,"source"))??$e(e,Me(e,r,"source"))??$e(e,Me(e,s,"source"))}function ws(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(Os(e,m)){let c=m.arguments[0],l=$e(e,c);for(let y of we({publishCall:!0,rawIntentName:l,objectHasIntent:De(e,c,"intent"),arkPublishCandidate:Ps(e,m),hasSource:Ls(e,m)}))d.push(w(y.ruleId,y.message,{line:f(m),filePath:o}));let p=Ns(e,m);if(r&&a&&p&&ce(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 Gn(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?Ae(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})):Rs(i),y=e.typescript?vs(e.typescript,i):Es(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)||_s(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:be(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:be(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:be(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||!Cs(u.value)&&!ks(u.value)||a.push(w("FORBIDDEN_IMPORT",`Forbidden ${u.kind} target: "${u.value}".`,{line:be(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)ce(u.value)&&!t.has(u.value)&&a.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${u.value}"`,{line:be(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(!ce(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:be(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(...Ie(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=se(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 Vt(e.typescript,c))u.has(S.capability)&&(S.source==="ambient-global"&&Ne(S.symbol,h)||S.source==="import-based"&&se(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(...ws(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 Ms="1.1",tt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Bn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],$s=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ds(){let e=[];for(let t of Bn)for(let n of Bn)t===n||$s.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var nt=Ds(),Bt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],te={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Kt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:tt,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:tt,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:nt,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}):
|
|
3
3
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
4
4
|
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Kn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function et(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Se(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Fs(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Fe(e,t,n,r,s){if(t.$ref){let i=Fs(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Fe(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(!Kn(e)){s.push({path:n,message:`must be an object; received ${Se(e)}`});return}let i=t.properties??{};for(let o of t.required??[])e[o]===void 0&&s.push({path:et(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||s.push({path:et(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||Fe(e[a],o,et(n,a),r,s)}for(let[o,a]of Object.entries(i))e[o]!==void 0&&Fe(e[o],a,et(n,o),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Se(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)=>Fe(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 ${Se(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 ${Se(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Se(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Hs(e){return{...e,$schema:e.$schema===void 0?tt: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?nt.map(t=>({...t})):e.rules}}function Vs(){let e=new Set(["1.1"]);for(let t of Bt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function js(e,t="ark.config.json"){if(!Kn(e))throw new ne(t,[{path:"$",message:`must be an object; received ${Se(e)}`}]);let n=Vs(),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<Bt.length+1;){o+=1;let d=Bt.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:Hs(i),migratedFrom:a}}function rt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=js(e,t),s=[];if(Fe(n,Kt,"$",Kt,s),s.length>0)throw new ne(t,s);return{config:n,migratedFrom:r}}function zt(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 rt(n,t)}function zn(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:tt,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Us(e){return e.endsWith(".")?e:`${e}.`}function Gs(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 it(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Us)})),n=[...t].sort(Gs),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 qn(e,t={}){return it({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Bs=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],st=it({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Bs,rules:nt.map(e=>({...e}))}),Ks={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 Yn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return zn({include:e.include??[t],layers:st.layers.map(s=>({name:s.name,patterns:(Ks[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...st.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 O(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(O).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${O(t[n])}`).join(",")}}`}var de="1.1";var Wn=["network","filesystem","clock","randomness","environment","process","persistence"];function re(e,t){let n=O(e),r=O(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 He(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(O(t))}function zs(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(O(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 Zn(e){let t=zs(e);return{...t,factsHash:M(O(t))}}function qt(e){return Zn(Qn(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 Ee(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 Xn(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 Re(e,t,n){let r=Xn(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 ie(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 Jn(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 qs(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 Qn(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=ie(e,"schemaVersion",["1.0","1.1"],"$"),r=ie(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:ie(h,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:Xn(h,"parseDiagnosticCount",u),exportsOnlyTypes:$(h,"exportsOnlyTypes",u),typeOnlyExportNames:Jn(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=Ee(h,"specifier",u),k=Ee(h,"target",u),N=ie(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:ie(h,"kind",["import","export","dynamic-import","require"],u),typeOnly:$(h,"typeOnly",u),line:Re(h,"line",u),resolution:N,...k?{target:W(h,"target",u)}:{},...h.namedBindings!==void 0?{namedBindings:Jn(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:Re(h,"line",u),symbol:D(h,"symbol",u),capability:ie(h,"capability",Wn,u),source:ie(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:Re(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=Ee(h,"rawIntentName",u),k=Ee(h,"sourceIntent",u);return{file:W(h,"file",u),line:Re(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:Re(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=Ee(h,"symbol",u),k=ie(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:Re(h,"line",u),kind:k,...S?{symbol:S}:{}}});qs(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=Ee(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 oe(e){let t=K(e,"$"),n=D(t,"factsHash","$"),r=D(t,"candidateTreeHash","$"),s=Zn(Qn(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 Ys=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},ve={type:"integer",minimum:1},X={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Yt={$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:x,message:x,file:X}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:X,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:X,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:ve,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:X,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:X,line:ve,symbol:x,capability:{enum:Ys},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:X,line:ve,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:X,line:ve,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:X,line:ve,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:X,line:ve,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:X,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:x},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Wt="1.0";function U(e){return`${e.from}->${e.to}`}function Ve(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 Ce(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(Ve("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(Ve("contradictory",c,`${c.from} -> ${c.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ve("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({...Ve("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({...Ve("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 Ws="1.0",Jt="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",nr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Js=["no-anemic-model"],er={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Zt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Jt,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:Jt},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:[...nr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:er,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:er}}}},pe=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
|
package/docs/README.md
CHANGED
|
@@ -58,8 +58,8 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
|
|
|
58
58
|
| Field adoption kit (scaffolding, not closed) | [field/](field/) |
|
|
59
59
|
| Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
|
|
60
60
|
|
|
61
|
-
Current: [releases/4.6.
|
|
62
|
-
Prior: [releases/4.6.
|
|
61
|
+
Current published: [releases/4.6.7.md](releases/4.6.7.md) (`arkgate@4.6.7` on npm `latest`).
|
|
62
|
+
Prior: [releases/4.6.6.md](releases/4.6.6.md) · [4.6.5](releases/4.6.5.md) · [4.6.4](releases/4.6.4.md) · [4.6.3](releases/4.6.3.md) · [4.6.2](releases/4.6.2.md) · [4.6.1](releases/4.6.1.md) · [4.6.0](releases/4.6.0.md).
|
|
63
63
|
Older notes: [releases/](releases/). Config: [configuration.md](configuration.md).
|
|
64
64
|
|
|
65
65
|
---
|
package/docs/package-surface.md
CHANGED
|
@@ -212,7 +212,8 @@ production deployment would need to satisfy; it is not a readiness certification
|
|
|
212
212
|
## Release notes (maintainers)
|
|
213
213
|
|
|
214
214
|
Ship notes for a version live under [releases/](https://github.com/pedroknigge/arkgate/tree/main/docs/releases)
|
|
215
|
-
(current: [4.6.
|
|
215
|
+
(current published: [4.6.7.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.7.md);
|
|
216
|
+
prior published: [4.6.6.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.6.md);
|
|
216
217
|
prior published: [4.6.5.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.5.md);
|
|
217
218
|
prior published: [4.6.3.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.3.md);
|
|
218
219
|
prior published: [4.6.2.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.2.md), [4.6.1.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.1.md), [4.6.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.6.0.md), [4.5.7.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.5.7.md), [4.5.6.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.5.6.md), [4.5.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.5.0.md), [4.4.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.4.0.md), [4.3.0.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/4.3.0.md),
|