arkgate 4.1.0 → 4.1.1

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/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var kt=Object.defineProperty;var Bn=Object.getOwnPropertyDescriptor;var qn=Object.getOwnPropertyNames;var zn=Object.prototype.hasOwnProperty;var Kn=(e,t)=>{for(var n in t)kt(e,n,{get:t[n],enumerable:!0})},Yn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qn(t))!zn.call(e,s)&&s!==n&&kt(e,s,{get:()=>t[s],enumerable:!(r=Bn(t,s))||r.enumerable});return e};var Wn=e=>Yn(kt({},"__esModule",{value:!0}),e);var As={};Kn(As,{ANALYSIS_IR_SCHEMA_VERSION:()=>at,ARK_ANALYSIS_RESULT_SCHEMA:()=>nn,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>en,ARK_CONFIG_SCHEMA:()=>tt,ARK_CONFIG_SCHEMA_VERSION:()=>yn,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Gn,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Un,ARK_RULES_SCHEMA:()=>lt,ARK_RULES_SCHEMA_VERSION:()=>Cn,ARK_RULE_SENSORS:()=>Bt,EffectiveContractError:()=>Ge,POLICY_DELTA_SCHEMA_VERSION:()=>mt,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>it,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Q,analyzeArchitectureConvergence:()=>oe,analyzeChange:()=>ze,analyzePolicyDelta:()=>qt,analyzeProject:()=>ve,analyzeResolvedProject:()=>Ee,buildArkRuleFileHints:()=>Et,buildEffectiveArkRules:()=>ct,buildRulesInventory:()=>Vn,canPromoteInvariant:()=>ut,classifyArkPolicyDelta:()=>gt,collectAnalysisConfigWarnings:()=>Ye,collectEmptyAppliesToFindings:()=>It,collectForbiddenCapabilityUses:()=>ie,createAICodeGate:()=>Ht,createAdapterResult:()=>tn,createArchitectureProfile:()=>Me,createArchitectureProfileFromArkConfig:()=>jt,createElevenLayerArkConfig:()=>Ut,createResolvedCandidateFacts:()=>st,deriveArkRuleFileHints:()=>Yt,detectArchitectureCycles:()=>bt,deterministicHash:()=>O,effectiveContractPolicyPayload:()=>dt,elevenLayerProfile:()=>Ne,emptyEffectiveArkRules:()=>te,evaluateArchitectureGraph:()=>pe,evaluateArkRuleSensors:()=>vt,evaluateInvariantCoverage:()=>pt,explainViolation:()=>zt,extractClassShapesFromSource:()=>Mn,extractSemanticDependencies:()=>se,inventoryToExtractionCard:()=>jn,loadArkConfigContract:()=>Fe,loadArkRulesContract:()=>Ue,loadContract:()=>qe,loadResolvedCandidateFacts:()=>Z,parseArkConfigJson:()=>rt,parseArkRulesJson:()=>Sn,policyDeltaAcknowledgementMatches:()=>ht,preflightChange:()=>Wt,preflightResolvedChange:()=>Zt,resolveEffectiveContract:()=>xn,resolvedFactsEvidenceRequirementsHash:()=>be,stableSerialize:()=>S,toAdapterDiagnostic:()=>We,version:()=>Xt});module.exports=Wn(As);var Xt="4.1.0";var en="1.4";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function Qt(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Zn(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, 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 We(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(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}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{},...I(e.arkruleId)?{arkruleId:I(e.arkruleId)}:{},...I(e.arkruleSource)?{arkruleSource:I(e.arkruleSource)}:{}};return{ruleId:n,severity:r,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:Qt(e.line,1),column:Qt(e.column,1)},evidence:s,nextAction:I(e.nextAction)??Zn(n,s,e)}}function tn(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(o=>({code:I(o.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(o.message)??`Analysis ${t}: required evidence is incomplete.`,...I(o.file)?{file:I(o.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let o of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[o])throw new Error(`${o} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(o=>We(o,"error")),...(e.warnings??[]).map(o=>We(o,"warning"))],a={schemaVersion:"1.4",completenessReasons:r,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...s};let o={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...o}:{...a,mode:n,valid:!1,completeness:t,...o}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...s}:{...a,mode:n,valid:!1,completeness:t,...s}}var nn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.4"},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}}}}}};var wt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),$t=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Pt=Object.freeze(Object.keys($t).sort()),xt=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"}),Ot=Object.freeze({process:Object.freeze(["process","node:process"])});function we(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=xt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=xt[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:xt[e.slice(0,i)]??null}function J(e,t){for(let n of t)if(Ot[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=$t[r];if(s)return s}return null}function fe(e){if(e?.pure===!0)return[...wt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>wt.includes(r));return[...new Set(n)].sort()}function Oe(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 Je(e){let t=new Set,n=new Set,r=Object.keys($t);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ot[s]??[])t.add(`import-exact:${a}`)}for(let s of fe(e)){if(t.add(`import:${s}`),s==="process")for(let i of Ot.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 rn=new Map;function sn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Xe(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 Jn(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 re(e){let t=rn.get(e);if(t)return t;let n=Xe(e),r=Jn(n),s="",i=0;for(let o=0;o<n.length;o+=1){let u=n[o];u==="\\"&&o+1<n.length?(s+=sn(n[o+1]),o+=1):u==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":u==="?"?s+="[^/]":u==="{"&&r?(s+="(?:",i+=1):u==="}"&&r&&i>0?(s+=")",i-=1):u===","&&r&&i>0?s+="|":s+=sn(u)}let a=new RegExp(`^${s}$`);return rn.set(e,a),a}function Xn(e){return Xe(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Tt(e,t){let n=Xe(String(e)),r=Xn(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,u=-1;for(let m of r){let h=-1;for(let g=o;g<a.length;g+=1)if(a[g]===m){h=g;break}if(h<0)return i;u=h,o=h+1}return(u+1)*1e6+r.length*1e4+s}function z(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>re(a).test(n))){for(let a of i.patterns??[])if(re(a).test(n)){let o=Tt(a,n);o>s&&(s=o,r=i.name)}}return r}function an(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 Qn(e){let t=new Set;for(let n of e??[]){let s=Xe(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function er(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 Qn(r?.patterns)}function K(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,a=r?.toPath;if(!i||!a)return s;let o=er(s,t,r?.layers);if(o.length===0)return s;let u=an(i,o),m=an(a,o);if(!u||!m||u!==m)return s;continue}if(t!==n)return s}}function ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function cn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function on(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 dn(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 Lt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function _t(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):Lt(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function se(e,t){let n,r=[],s=(a,o,u,m=!1)=>r.push({specifier:u,kind:o,line:cn(t,a),typeOnly:m,unresolved:u===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",ye(e,a.moduleSpecifier),on(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",ye(e,a.moduleSpecifier),on(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",ye(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,m=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!_t(e,n??(n=dn(e,t)),t,a.expression);(o||m)&&s(a,m?"require":"dynamic-import",ye(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function tr(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=ye(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 nr(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 ln(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=dn(e,t),i=new Map,a=new Set;for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let o=l=>{let c=tr(e,l);if(!c)return;let d=Lt(s,c.root),f=d?i.get(d):void 0;return f?[...f,...c.segments.slice(1)]:_t(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let d=o(c.initializer),f=Lt(s,c.name);!d||!f||i.set(f,d)}let u=[],m=new Set,h=(l,c)=>{let d=cn(t,c),f=`${l}:${c.getStart(t)}`;m.has(f)||(m.add(f),u.push({name:l,line:d,node:c}))},g=l=>{let c=l.parent&&(e.isPropertyAccessExpression(l.parent)||e.isElementAccessExpression(l.parent))&&l.parent.expression===l;if((e.isPropertyAccessExpression(l)||e.isElementAccessExpression(l))&&!c){let d=o(l),f=d?ln(r,d):void 0;f&&h(f,l)}else e.isIdentifier(l)&&r.has(l.text)&&nr(e,l)&&!_t(e,s,t,l)&&h(l.text,l);if(e.isVariableDeclaration(l)&&e.isObjectBindingPattern(l.name)&&l.initializer){let d=o(l.initializer);if(d)for(let f of l.name.elements){if(!e.isIdentifier(f.name))continue;let b=f.propertyName?ye(e,f.propertyName)??f.propertyName.text:f.name.text,R=ln(r,[...d,b]);R&&h(R,l.initializer)}}e.forEachChild(l,g)};return g(t),u}function Ft(e,t,n){let r=[];for(let s of n?.dependencies??se(e,t)){if(s.typeOnly||!s.specifier)continue;let i=we(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,Pt)){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 Nt={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."},Mt=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 Dt(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 ae(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function $e(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ae(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Nt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Nt.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function me(e,t){return e.slice(0,t).split(`
1
+ "use strict";var kt=Object.defineProperty;var Bn=Object.getOwnPropertyDescriptor;var qn=Object.getOwnPropertyNames;var zn=Object.prototype.hasOwnProperty;var Kn=(e,t)=>{for(var n in t)kt(e,n,{get:t[n],enumerable:!0})},Yn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qn(t))!zn.call(e,s)&&s!==n&&kt(e,s,{get:()=>t[s],enumerable:!(r=Bn(t,s))||r.enumerable});return e};var Wn=e=>Yn(kt({},"__esModule",{value:!0}),e);var As={};Kn(As,{ANALYSIS_IR_SCHEMA_VERSION:()=>at,ARK_ANALYSIS_RESULT_SCHEMA:()=>nn,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>en,ARK_CONFIG_SCHEMA:()=>tt,ARK_CONFIG_SCHEMA_VERSION:()=>yn,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Gn,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Un,ARK_RULES_SCHEMA:()=>lt,ARK_RULES_SCHEMA_VERSION:()=>Cn,ARK_RULE_SENSORS:()=>Bt,EffectiveContractError:()=>Ge,POLICY_DELTA_SCHEMA_VERSION:()=>mt,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>it,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>Q,analyzeArchitectureConvergence:()=>oe,analyzeChange:()=>ze,analyzePolicyDelta:()=>qt,analyzeProject:()=>ve,analyzeResolvedProject:()=>Ee,buildArkRuleFileHints:()=>Et,buildEffectiveArkRules:()=>ct,buildRulesInventory:()=>Vn,canPromoteInvariant:()=>ut,classifyArkPolicyDelta:()=>gt,collectAnalysisConfigWarnings:()=>Ye,collectEmptyAppliesToFindings:()=>It,collectForbiddenCapabilityUses:()=>ie,createAICodeGate:()=>Ht,createAdapterResult:()=>tn,createArchitectureProfile:()=>Me,createArchitectureProfileFromArkConfig:()=>jt,createElevenLayerArkConfig:()=>Ut,createResolvedCandidateFacts:()=>st,deriveArkRuleFileHints:()=>Yt,detectArchitectureCycles:()=>bt,deterministicHash:()=>O,effectiveContractPolicyPayload:()=>dt,elevenLayerProfile:()=>Ne,emptyEffectiveArkRules:()=>te,evaluateArchitectureGraph:()=>pe,evaluateArkRuleSensors:()=>vt,evaluateInvariantCoverage:()=>pt,explainViolation:()=>zt,extractClassShapesFromSource:()=>Mn,extractSemanticDependencies:()=>se,inventoryToExtractionCard:()=>jn,loadArkConfigContract:()=>Fe,loadArkRulesContract:()=>Ue,loadContract:()=>qe,loadResolvedCandidateFacts:()=>Z,parseArkConfigJson:()=>rt,parseArkRulesJson:()=>Sn,policyDeltaAcknowledgementMatches:()=>ht,preflightChange:()=>Wt,preflightResolvedChange:()=>Zt,resolveEffectiveContract:()=>xn,resolvedFactsEvidenceRequirementsHash:()=>be,stableSerialize:()=>S,toAdapterDiagnostic:()=>We,version:()=>Xt});module.exports=Wn(As);var Xt="4.1.1";var en="1.4";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function Qt(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Zn(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, 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 We(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(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}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{},...I(e.arkruleId)?{arkruleId:I(e.arkruleId)}:{},...I(e.arkruleSource)?{arkruleSource:I(e.arkruleSource)}:{}};return{ruleId:n,severity:r,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:Qt(e.line,1),column:Qt(e.column,1)},evidence:s,nextAction:I(e.nextAction)??Zn(n,s,e)}}function tn(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(o=>({code:I(o.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(o.message)??`Analysis ${t}: required evidence is incomplete.`,...I(o.file)?{file:I(o.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let o of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[o])throw new Error(`${o} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(o=>We(o,"error")),...(e.warnings??[]).map(o=>We(o,"warning"))],a={schemaVersion:"1.4",completenessReasons:r,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...s};let o={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...o}:{...a,mode:n,valid:!1,completeness:t,...o}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...s}:{...a,mode:n,valid:!1,completeness:t,...s}}var nn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.4"},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}}}}}};var wt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),$t=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Pt=Object.freeze(Object.keys($t).sort()),xt=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"}),Ot=Object.freeze({process:Object.freeze(["process","node:process"])});function we(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=xt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=xt[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:xt[e.slice(0,i)]??null}function J(e,t){for(let n of t)if(Ot[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=$t[r];if(s)return s}return null}function fe(e){if(e?.pure===!0)return[...wt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>wt.includes(r));return[...new Set(n)].sort()}function Oe(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 Je(e){let t=new Set,n=new Set,r=Object.keys($t);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ot[s]??[])t.add(`import-exact:${a}`)}for(let s of fe(e)){if(t.add(`import:${s}`),s==="process")for(let i of Ot.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 rn=new Map;function sn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Xe(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 Jn(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 re(e){let t=rn.get(e);if(t)return t;let n=Xe(e),r=Jn(n),s="",i=0;for(let o=0;o<n.length;o+=1){let u=n[o];u==="\\"&&o+1<n.length?(s+=sn(n[o+1]),o+=1):u==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":u==="?"?s+="[^/]":u==="{"&&r?(s+="(?:",i+=1):u==="}"&&r&&i>0?(s+=")",i-=1):u===","&&r&&i>0?s+="|":s+=sn(u)}let a=new RegExp(`^${s}$`);return rn.set(e,a),a}function Xn(e){return Xe(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function Tt(e,t){let n=Xe(String(e)),r=Xn(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,u=-1;for(let m of r){let h=-1;for(let g=o;g<a.length;g+=1)if(a[g]===m){h=g;break}if(h<0)return i;u=h,o=h+1}return(u+1)*1e6+r.length*1e4+s}function z(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>re(a).test(n))){for(let a of i.patterns??[])if(re(a).test(n)){let o=Tt(a,n);o>s&&(s=o,r=i.name)}}return r}function an(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 Qn(e){let t=new Set;for(let n of e??[]){let s=Xe(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function er(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 Qn(r?.patterns)}function K(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,a=r?.toPath;if(!i||!a)return s;let o=er(s,t,r?.layers);if(o.length===0)return s;let u=an(i,o),m=an(a,o);if(!u||!m||u!==m)return s;continue}if(t!==n)return s}}function ye(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function cn(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function on(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 dn(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 Lt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function _t(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):Lt(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function se(e,t){let n,r=[],s=(a,o,u,m=!1)=>r.push({specifier:u,kind:o,line:cn(t,a),typeOnly:m,unresolved:u===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",ye(e,a.moduleSpecifier),on(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",ye(e,a.moduleSpecifier),on(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",ye(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,m=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!_t(e,n??(n=dn(e,t)),t,a.expression);(o||m)&&s(a,m?"require":"dynamic-import",ye(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function tr(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=ye(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 nr(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 ln(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=dn(e,t),i=new Map,a=new Set;for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let o=l=>{let c=tr(e,l);if(!c)return;let d=Lt(s,c.root),f=d?i.get(d):void 0;return f?[...f,...c.segments.slice(1)]:_t(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let d=o(c.initializer),f=Lt(s,c.name);!d||!f||i.set(f,d)}let u=[],m=new Set,h=(l,c)=>{let d=cn(t,c),f=`${l}:${c.getStart(t)}`;m.has(f)||(m.add(f),u.push({name:l,line:d,node:c}))},g=l=>{let c=l.parent&&(e.isPropertyAccessExpression(l.parent)||e.isElementAccessExpression(l.parent))&&l.parent.expression===l;if((e.isPropertyAccessExpression(l)||e.isElementAccessExpression(l))&&!c){let d=o(l),f=d?ln(r,d):void 0;f&&h(f,l)}else e.isIdentifier(l)&&r.has(l.text)&&nr(e,l)&&!_t(e,s,t,l)&&h(l.text,l);if(e.isVariableDeclaration(l)&&e.isObjectBindingPattern(l.name)&&l.initializer){let d=o(l.initializer);if(d)for(let f of l.name.elements){if(!e.isIdentifier(f.name))continue;let b=f.propertyName?ye(e,f.propertyName)??f.propertyName.text:f.name.text,R=ln(r,[...d,b]);R&&h(R,l.initializer)}}e.forEachChild(l,g)};return g(t),u}function Ft(e,t,n){let r=[];for(let s of n?.dependencies??se(e,t)){if(s.typeOnly||!s.specifier)continue;let i=we(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,Pt)){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 Nt={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."},Mt=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 Dt(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 ae(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function $e(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ae(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Nt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Nt.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function me(e,t){return e.slice(0,t).split(`
2
2
  `).length}function rr(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 sr(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]),a=s[0],o=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:i,kind:r.kind,typeOnly:o})}}return t.sort((r,s)=>r.index-s.index)}function ir(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 ar(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 or(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function lr(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Te(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function cr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function pn(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:cr(e,r.name)===n)}function Le(e,t,n){return pn(e,t,n)!==void 0}function Pe(e,t,n){let r=pn(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function dr(e,t){let n=Pe(e,t,"metadata");return Le(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 pr(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 ur(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Te(e,n);return r!==void 0&&ae(r)||Le(e,n,"intent")||un(e,n)}function fr(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return dr(e,n)||Le(e,r,"source")||Le(e,s,"source")}function yr(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=Pe(e,n,"metadata");return Te(e,Pe(e,i,"source"))??Te(e,Pe(e,r,"source"))??Te(e,Pe(e,s,"source"))}function mr(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,o=i?.layer,u=[],m=g=>s.getLineAndCharacterOfPosition(g.getStart(s)).line+1,h=g=>{if(pr(e,g)){let l=g.arguments[0],c=Te(e,l);for(let f of $e({publishCall:!0,rawIntentName:c,objectHasIntent:Le(e,l,"intent"),arkPublishCandidate:ur(e,g),hasSource:fr(e,g)}))u.push(w(f.ruleId,f.message,{line:m(g),filePath:a}));let d=yr(e,g);if(r&&o&&d&&ae(d)){let f=r.resolveLayer(d);f&&f!==o&&u.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${f}, but the target file is classified as ${o}.`,{line:m(g),filePath:a,target:d,fromLayer:o,toLayer:f}))}}e.forEachChild(g,h)};return h(s),u}function Ht(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,a){let o=[],u=a,m=u?.filePath,h=u?.layer,g=e.typescript,l=g?g.createSourceFile(m??"generated.ts",i,g.ScriptTarget.Latest,!0):void 0,c=l?se(e.typescript,l):void 0,d=c?c.filter(p=>p.specifier!==void 0).map(p=>({value:p.specifier,index:p.node.getStart(l),kind:p.kind,typeOnly:p.typeOnly})):sr(i),f=e.typescript?ir(e.typescript,i):rr(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(m))for(let p of c?.filter(({unresolved:y})=>y)??[]){let y=p.kind==="require";o.push(w(y?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${y?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:p.line,filePath:m}))}let b=h!==void 0&&(r.has(h)||lr(h)),R=h!==void 0?` If "${h}" 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 p of n)if(p instanceof RegExp){p.lastIndex=0;let y=p.exec(i);p.lastIndex=0,y&&o.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${p}`,{line:y.index===void 0?void 0:me(i,y.index),filePath:m,suggestion:"Remove infrastructure imports from domain/application layers."+R}))}else i.includes(p)&&o.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${p}`,{line:me(i,i.indexOf(p)),filePath:m}));for(let p of d){let y=e.resolveImportTarget?.(p.value,m)??(e.resolveImportLayer?{layer:e.resolveImportLayer(p.value,m)}:void 0),v=typeof m=="string"?e.resolveImportTarget?.(m)??(e.resolveImportLayer?{layer:h,relPath:void 0}:void 0):void 0,C=y?.layer;if(C&&h){let T=K(e.architectureProfile?.rules,h,C,{fromPath:v?.relPath,toPath:y?.relPath,layers:e.architectureLayers});if(T){if(p.typeOnly&&!T.peerIsolation)continue;let _=!!T.peerIsolation;o.push(w("LAYER_IMPORT_VIOLATION",T.message??(_?`Layer "${h}" must not import across slices into "${C}".`:`Layer "${h}" must not import "${C}".`),{line:me(i,p.index),source:p.value,target:p.value,filePath:m,fromLayer:h,toLayer:C,suggestion:_?"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:p.kind,peerIsolation:_,...p.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||p.typeOnly||!ar(p.value)&&!or(p.value)||o.push(w("FORBIDDEN_IMPORT",`Forbidden ${p.kind} target: "${p.value}".`,{line:me(i,p.index),source:p.value,target:p.value,filePath:m,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+R,details:{importKind:p.kind}}))}if(e.policies)for(let p of e.policies){let y=p.check({source:i,context:a});if(y!==!0)if(Array.isArray(y))for(let v of y)o.push(w("POLICY_VIOLATION",v.message,{filePath:m,suggestion:`Fix violation of policy "${p.name}".`}));else y===!1?o.push(w("POLICY_VIOLATION",`Policy ${p.name} failed on generated code`)):o.push(w("POLICY_VIOLATION",y.message))}if(s&&t.size>0)for(let p of f)ae(p.value)&&!t.has(p.value)&&o.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${p.value}"`,{line:me(i,p.index),filePath:m,target:p.value,suggestion:`Register intent "${p.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&h)for(let p of f){if(!ae(p.value))continue;let y=e.architectureProfile.resolveLayer(p.value);if(!y)continue;let v=K(e.architectureProfile.rules,h,y);v&&o.push(w("LAYER_REFERENCE_VIOLATION",v.message??`Layer "${h}" must not reference "${y}" through "${p.value}".`,{line:me(i,p.index),filePath:m,target:p.value,fromLayer:h,toLayer:y,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:v}}))}if(e.extensions)for(let p of e.extensions)try{let y=p.analyze(i,a);o.push(...y)}catch(y){o.push(w("EXTENSION_ERROR",`Extension "${p.name}" failed: ${y instanceof Error?y.message:String(y)}`))}if(e.typescript&&l&&h&&e.forbiddenGlobals?.[h]?.length)try{let p=e.forbiddenGlobals[h];o.push(...ie(e.typescript,l,p).map(y=>w("FORBIDDEN_GLOBAL",`${h} must not use the ambient global "${y.name}".`,{line:y.line,filePath:m,target:y.name,fromLayer:h,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let y of c??[]){if(y.typeOnly||!y.specifier)continue;let v=J(y.specifier,p);v&&o.push(w("FORBIDDEN_GLOBAL",`${h} must not use module "${y.specifier}" because it is the import form of forbidden global "${v}".`,{line:y.line,filePath:m,source:y.specifier,target:y.specifier,fromLayer:h,details:{importKind:y.kind,forbiddenGlobal:v},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript&&l&&h&&e.capabilityWalls?.[h]?.length)try{let p=new Set(e.capabilityWalls[h]),y=e.forbiddenGlobals?.[h]??[];for(let v of Ft(e.typescript,l))p.has(v.capability)&&(v.source==="ambient-global"&&Oe(v.symbol,y)||v.source==="import-based"&&J(v.symbol,y)||o.push(w("CAPABILITY_VIOLATION",v.source==="import-based"?`${h} denies the ${v.capability} capability; found import of "${v.symbol}".`:`${h} denies the ${v.capability} capability; found ambient "${v.symbol}".`,{line:v.line,filePath:m,target:v.symbol,capability:v.capability,fromLayer:h,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript)try{o.push(...mr(e.typescript,i,a,e.architectureProfile))}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:o.length===0,violations:o}}}}var yn="1.1",et="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",fn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],gr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function hr(){let e=[];for(let t of fn)for(let n of fn)t===n||gr.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var nt=hr(),Vt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],X={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},tt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:et,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:et,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:{...X,minItems:1,default:["src"]},exclude:{...X,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:{...X,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...X,minItems:1},exclude:X,intentPrefixes:X,description:{type:"string",minLength:1},forbiddenGlobals:X,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"}}},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:{...X,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}}}}},Y=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 mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ge(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ar(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function _e(e,t,n,r,s){if(t.$ref){let i=Ar(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}_e(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(!mn(e)){s.push({path:n,message:`must be an object; received ${ge(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:Qe(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:Qe(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||_e(e[o],a,Qe(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&_e(e[a],o,Qe(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${ge(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(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>_e(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${ge(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 ${ge(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${ge(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function br(e){return{...e,$schema:e.$schema===void 0?et: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 Rr(){let e=new Set(["1.1"]);for(let t of Vt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function vr(e,t="ark.config.json"){if(!mn(e))throw new Y(t,[{path:"$",message:`must be an object; received ${ge(e)}`}]);let n=Rr(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<Vt.length+1;){a+=1;let u=Vt.find(m=>m.from===s);if(!u)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=u.to,i.schemaVersion=s}if(s!=="1.1")throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let o=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:br(i),migratedFrom:o}}function Fe(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=vr(e,t),s=[];if(_e(n,tt,"$",tt,s),s.length>0)throw new Y(t,s);return{config:n,migratedFrom:r}}function rt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Y(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Fe(n,t)}function gn(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:et,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function Ir(e){return e.endsWith(".")?e:`${e}.`}function Er(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 Me(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(Ir)})),n=[...t].sort(Er),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(a=>s.startsWith(a)))?.name}}}function jt(e,t={}){return Me({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 Cr=[{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}],Ne=Me({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Cr,rules:nt.map(e=>({...e}))}),Sr={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 Ut(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return gn({include:e.include??[t],layers:Ne.layers.map(s=>({name:s.name,patterns:(Sr[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ne.rules]})}function O(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 S(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(S).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${S(t[n])}`).join(",")}}`}var Q="1.1";var hn=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=S(e),r=S(t);return n<r?-1:n>r?1:0}function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function be(e){let t={schemaVersion:"1.1",include:B(e.include??[]),exclude:B(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:B(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:B(n.patterns??[]),exclude:B(n.exclude??[]),forbiddenGlobals:B(n.forbiddenGlobals??[]),intentPrefixes:B(n.intentPrefixes??[]),capabilityDeny:B(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(W),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return O(S(t))}function kr(e){let t=e.completenessReasons.map(l=>({code:l.code,message:l.message,...l.file?{file:l.file}:{}})).sort(W),n=e.files.map(l=>({...l,typeOnlyExportNames:B(l.typeOnlyExportNames)})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),r=e.dependencies.map(l=>({...l,...l.namedBindings?{namedBindings:B(l.namedBindings)}:{}})).sort(W),s=e.capabilityUses.map(l=>({...l})).sort(W),i=e.ambientUses.map(l=>({...l})).sort(W),a=e.publishCalls.map(l=>({...l})).sort(W),o=e.intentReferences.map(l=>({...l})).sort(W),u=e.safetyUses.map(l=>({...l})).sort(W),m=(e.classShapes??[]).map(l=>({...l,mutatingMethods:[...l.mutatingMethods??[]].map(c=>({...c}))})).sort(W),h=e.files.map(({path:l,contentHash:c})=>({path:l,contentHash:c})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),g=O(S(h));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:a,intentReferences:o,safetyUses:u,classShapes:m}}function bn(e){let t=kr(e);return{...t,factsHash:O(S(t))}}function st(e){return bn(vn(M(e,"$"),!1))}function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function V(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 P(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 he(e,t,n){if(e[t]!==void 0)return P(e,t,n)}function U(e,t,n){let r=P(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 o of s.split("/"))if(!(!o||o==="."))if(o===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(o);let a=i.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Rn(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 Ae(e,t,n){let r=Rn(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function ee(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 An(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 xr(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 vn(e,t){V(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ee(e,"schemaVersion",["1.0","1.1"],"$"),r=ee(e,"completeness",["complete","partial","unavailable"],"$"),s=G(e,"completenessReasons","$").map((b,R)=>{let p=`$.completenessReasons[${R}]`,y=M(b,p);V(y,["code","message","file"],p);let v=y.file===void 0?void 0:U(y,"file",p);return{code:P(y,"code",p),message:P(y,"message",p),...v?{file:v}:{}}});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=G(e,"files","$").map((b,R)=>{let p=`$.files[${R}]`,y=M(b,p);return V(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],p),{path:U(y,"path",p),contentHash:P(y,"contentHash",p),parseStatus:ee(y,"parseStatus",["parsed","invalid"],p),parseDiagnosticCount:Rn(y,"parseDiagnosticCount",p),exportsOnlyTypes:$(y,"exportsOnlyTypes",p),typeOnlyExportNames:An(y.typeOnlyExportNames,`${p}.typeOnlyExportNames`),hasTopLevelSideEffects:$(y,"hasTopLevelSideEffects",p)}}),a=G(e,"dependencies","$").map((b,R)=>{let p=`$.dependencies[${R}]`,y=M(b,p);V(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],p);let v=he(y,"specifier",p),C=he(y,"target",p),T=ee(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],p);if(T==="resolved-project"&&!C)throw new Error(`${p}.target is required for resolved-project dependencies.`);if(T!=="resolved-project"&&C)throw new Error(`${p}.target is only allowed for resolved-project dependencies.`);if(T!=="dynamic"&&!v)throw new Error(`${p}.specifier is required unless resolution is dynamic.`);return{from:U(y,"from",p),...v?{specifier:v}:{},kind:ee(y,"kind",["import","export","dynamic-import","require"],p),typeOnly:$(y,"typeOnly",p),line:Ae(y,"line",p),resolution:T,...C?{target:U(y,"target",p)}:{},...y.namedBindings!==void 0?{namedBindings:An(y.namedBindings,`${p}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(y,"targetTypeOnlyExports",p)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(y,"sourcePureTypeModule",p)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(y,"namedBindingsTypeOnly",p)}:{},...y.portProofEligible!==void 0?{portProofEligible:$(y,"portProofEligible",p)}:{}}}),o=G(e,"capabilityUses","$").map((b,R)=>{let p=`$.capabilityUses[${R}]`,y=M(b,p);return V(y,["file","line","symbol","capability","source"],p),{file:U(y,"file",p),line:Ae(y,"line",p),symbol:P(y,"symbol",p),capability:ee(y,"capability",hn,p),source:ee(y,"source",["ambient-global","import-based"],p)}}),u=G(e,"ambientUses","$").map((b,R)=>{let p=`$.ambientUses[${R}]`,y=M(b,p);return V(y,["file","line","symbol"],p),{file:U(y,"file",p),line:Ae(y,"line",p),symbol:P(y,"symbol",p)}}),m=G(e,"publishCalls","$").map((b,R)=>{let p=`$.publishCalls[${R}]`,y=M(b,p);V(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],p);let v=he(y,"rawIntentName",p),C=he(y,"sourceIntent",p);return{file:U(y,"file",p),line:Ae(y,"line",p),...v?{rawIntentName:v}:{},objectHasIntent:$(y,"objectHasIntent",p),arkPublishCandidate:$(y,"arkPublishCandidate",p),hasSource:$(y,"hasSource",p),...C?{sourceIntent:C}:{}}}),h=G(e,"intentReferences","$").map((b,R)=>{let p=`$.intentReferences[${R}]`,y=M(b,p);return V(y,["file","line","intent"],p),{file:U(y,"file",p),line:Ae(y,"line",p),intent:P(y,"intent",p)}}),g=G(e,"safetyUses","$").map((b,R)=>{let p=`$.safetyUses[${R}]`,y=M(b,p);V(y,["file","line","kind","symbol"],p);let v=he(y,"symbol",p),C=ee(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],p);if(C==="in-memory-store"&&!v)throw new Error(`${p}.symbol is required for in-memory-store facts.`);if(C!=="in-memory-store"&&v)throw new Error(`${p}.symbol is only allowed for in-memory-store facts.`);return{file:U(y,"file",p),line:Ae(y,"line",p),kind:C,...v?{symbol:v}:{}}});xr(i,b=>b.path,"$.files");let l=new Set(i.map(b=>b.path));for(let b of i){if(b.parseStatus==="parsed"&&b.parseDiagnosticCount!==0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(b.parseStatus==="invalid"&&b.parseDiagnosticCount===0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(b=>b.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let b of a)if(!l.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);for(let[b,R]of[["$.capabilityUses",o],["$.ambientUses",u],["$.publishCalls",m],["$.intentReferences",h],["$.safetyUses",g]])for(let p of R)if(!l.has(p.file))throw new Error(`${b} references missing file ${p.file}.`);let c=he(e,"projectPackageName","$"),f=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((b,R)=>{let p=`$.classShapes[${R}]`,y=M(b,p);V(y,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],p);let v=G(y,"mutatingMethods",p).map((C,T)=>{let _=`${p}.mutatingMethods[${T}]`,x=M(C,_);return V(x,["name","referencesGuardOrPublish"],_),{name:P(x,"name",_),referencesGuardOrPublish:$(x,"referencesGuardOrPublish",_)}});return{file:U(y,"file",p),className:P(y,"className",p),exported:$(y,"exported",p),hasPublicMutableFields:$(y,"hasPublicMutableFields",p),hasPublicSetters:$(y,"hasPublicSetters",p),hasPublicConstructor:$(y,"hasPublicConstructor",p),hasStaticFactory:$(y,"hasStaticFactory",p),mutatingMethods:v,...y.dataOnly===void 0?{}:{dataOnly:$(y,"dataOnly",p)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:P(e,"resolverIdentity","$"),compilerIdentity:P(e,"compilerIdentity","$"),compilerOptionsHash:P(e,"compilerOptionsHash","$"),tsconfigHash:P(e,"tsconfigHash","$"),evidenceRequirementsHash:P(e,"evidenceRequirementsHash","$"),...c?{projectPackageName:c}:{},files:i,dependencies:a,capabilityUses:o,ambientUses:u,publishCalls:m,intentReferences:h,safetyUses:g,classShapes:f}}function Z(e){let t=M(e,"$"),n=P(t,"factsHash","$"),r=P(t,"candidateTreeHash","$"),s=bn(vn(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 wr=["network","filesystem","clock","randomness","environment","process","persistence"],k={type:"string",minLength:1},Re={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},it={$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:k,message:k,file:q}}},resolverIdentity:k,compilerIdentity:k,compilerOptionsHash:k,tsconfigHash:k,candidateTreeHash:k,evidenceRequirementsHash:k,projectPackageName:k,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:k,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:k},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:q,specifier:k,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Re,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:k},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:q,line:Re,symbol:k,capability:{enum:wr},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:Re,symbol:k}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:Re,rawIntentName:k,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:k}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:Re,intent:k}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:Re,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:k},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:q,className:k,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:k,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:k},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 at="1.0";function F(e){return`${e.from}->${e.to}`}function De(e,t,n,r="dependency"){return{id:`${e}:${r}:${F(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${F(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${F(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${F(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${F(t)} from the candidate, then preflight again.`}:{}}}function oe(e){let t=[],n=new Map(e.changeMap.map.files.map(l=>[l.path,l])),r=new Map(e.changes.map(l=>[l.path,l])),s=new Map(e.changeMap.map.dependencies.map(l=>[F(l),l])),i=new Map(e.baseDependencies.map(l=>[F(l),l])),a=new Map(e.candidateDependencies.map(l=>[F(l),l]));for(let l of[...n.values()].sort((c,d)=>c.path.localeCompare(d.path))){let c=r.get(l.path);c?c.operation!==l.operation?t.push({id:`contradictory:file:${l.path}`,classification:"contradictory",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} was planned as ${l.operation} but the actual operation is ${c.operation}.`,nextAction:`Change ${l.path} to the planned ${l.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${l.path}`,classification:"satisfied",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} matches the planned ${l.operation} operation.`}):t.push({id:`missing:file:${l.path}`,classification:"missing",subject:"file",path:l.path,expectedOperation:l.operation,message:`${l.path} was planned as ${l.operation} but is absent from the actual change.`,nextAction:`${l.operation[0].toUpperCase()}${l.operation.slice(1)} ${l.path} in the complete change set, then preflight again.`})}for(let l of[...r.values()].sort((c,d)=>c.path.localeCompare(d.path)))n.has(l.path)||t.push({id:`unplanned:file:${l.path}`,classification:"unplanned",subject:"file",path:l.path,actualOperation:l.operation,message:`${l.path} has an unplanned ${l.operation} operation.`,nextAction:`Remove ${l.path} from the change set, then preflight again.`});let o=new Set;for(let l of[...s.values()].sort((c,d)=>F(c).localeCompare(F(d)))){if(a.has(F(l))){t.push(De("satisfied",l,`${l.from} -> ${l.to} exists in the candidate architecture.`));continue}let c={from:l.to,to:l.from};a.has(F(c))?(o.add(F(c)),t.push(De("contradictory",l,`${l.from} -> ${l.to} was planned, but the candidate contains the reverse edge.`))):t.push(De("missing",l,`${l.from} -> ${l.to} is absent from the candidate architecture.`))}let u=new Set([...n.keys(),...r.keys()]);for(let[l,c]of[...a].sort(([d],[f])=>d.localeCompare(f)))i.has(l)||s.has(l)||o.has(l)||!u.has(c.from)&&!u.has(c.to)||t.push({...De("unplanned",c,`${c.from} -> ${c.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let m=new Set(e.changeMap.map.files.filter(l=>l.operation==="delete").map(l=>l.path));for(let[l,c]of[...i].sort(([d],[f])=>d.localeCompare(f)))a.has(l)||m.has(c.from)||m.has(c.to)||!u.has(c.from)&&!u.has(c.to)||t.push({...De("unplanned",c,`${c.from} -> ${c.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((l,c)=>h[l.classification]-h[c.classification]||(l.subject===c.subject?0:l.subject==="file"?-1:1)||l.id.localeCompare(c.id));let g={satisfied:t.filter(l=>l.classification==="satisfied").length,missing:t.filter(l=>l.classification==="missing").length,contradictory:t.filter(l=>l.classification==="contradictory").length,unplanned:t.filter(l=>l.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}var Cn="1.0",Gt="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Bt=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],Or=["no-anemic-model"],In={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},lt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Gt,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:Gt},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:[...Bt]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:In,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:In}}}},le=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
package/dist/index.d.ts CHANGED
@@ -244,7 +244,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
244
244
  declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
245
245
 
246
246
  /** ArkGate library version — single source of truth. */
247
- declare const version = "4.1.0";
247
+ declare const version = "4.1.1";
248
248
 
249
249
  /** Versioned public result contract shared by every ArkGate enforcement adapter. */
250
250
  /** 1.4 adds optional evidence.arkruleId + evidence.arkruleSource (ADR 0012 / AR03). */
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var $n="4.1.0";var Pn="1.4";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function Ut(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Tn(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, 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 lt(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(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}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{},...I(e.arkruleId)?{arkruleId:I(e.arkruleId)}:{},...I(e.arkruleSource)?{arkruleSource:I(e.arkruleSource)}:{}};return{ruleId:n,severity:r,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:Ut(e.line,1),column:Ut(e.column,1)},evidence:s,nextAction:I(e.nextAction)??Tn(n,s,e)}}function Ln(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(o=>({code:I(o.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(o.message)??`Analysis ${t}: required evidence is incomplete.`,...I(o.file)?{file:I(o.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let o of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[o])throw new Error(`${o} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(o=>lt(o,"error")),...(e.warnings??[]).map(o=>lt(o,"warning"))],a={schemaVersion:"1.4",completenessReasons:r,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...s};let o={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...o}:{...a,mode:n,valid:!1,completeness:t,...o}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...s}:{...a,mode:n,valid:!1,completeness:t,...s}}var _n={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.4"},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}}}}}};var dt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ut=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),ft=Object.freeze(Object.keys(ut).sort()),ct=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"}),pt=Object.freeze({process:Object.freeze(["process","node:process"])});function Se(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ct[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=ct[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:ct[e.slice(0,i)]??null}function Z(e,t){for(let n of t)if(pt[n]?.includes(e))return n;return null}function je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=ut[r];if(s)return s}return null}function ce(e){if(e?.pure===!0)return[...dt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dt.includes(r));return[...new Set(n)].sort()}function ke(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 Ue(e){let t=new Set,n=new Set,r=Object.keys(ut);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of pt[s]??[])t.add(`import-exact:${a}`)}for(let s of ce(e)){if(t.add(`import:${s}`),s==="process")for(let i of pt.process)t.add(`import-exact:${i}`);for(let i of r)je(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Gt=new Map;function Bt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Ge(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 Fn(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 te(e){let t=Gt.get(e);if(t)return t;let n=Ge(e),r=Fn(n),s="",i=0;for(let o=0;o<n.length;o+=1){let u=n[o];u==="\\"&&o+1<n.length?(s+=Bt(n[o+1]),o+=1):u==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":u==="?"?s+="[^/]":u==="{"&&r?(s+="(?:",i+=1):u==="}"&&r&&i>0?(s+=")",i-=1):u===","&&r&&i>0?s+="|":s+=Bt(u)}let a=new RegExp(`^${s}$`);return Gt.set(e,a),a}function Nn(e){return Ge(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function yt(e,t){let n=Ge(String(e)),r=Nn(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,u=-1;for(let m of r){let h=-1;for(let g=o;g<a.length;g+=1)if(a[g]===m){h=g;break}if(h<0)return i;u=h,o=h+1}return(u+1)*1e6+r.length*1e4+s}function z(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>te(a).test(n))){for(let a of i.patterns??[])if(te(a).test(n)){let o=yt(a,n);o>s&&(s=o,r=i.name)}}return r}function qt(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 Mn(e){let t=new Set;for(let n of e??[]){let s=Ge(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function Dn(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 Mn(r?.patterns)}function K(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,a=r?.toPath;if(!i||!a)return s;let o=Dn(s,t,r?.layers);if(o.length===0)return s;let u=qt(i,o),m=qt(a,o);if(!u||!m||u!==m)return s;continue}if(t!==n)return s}}function de(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Yt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function zt(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 Wt(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 mt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function gt(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):mt(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function pe(e,t){let n,r=[],s=(a,o,u,m=!1)=>r.push({specifier:u,kind:o,line:Yt(t,a),typeOnly:m,unresolved:u===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",de(e,a.moduleSpecifier),zt(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",de(e,a.moduleSpecifier),zt(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",de(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,m=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!gt(e,n??(n=Wt(e,t)),t,a.expression);(o||m)&&s(a,m?"require":"dynamic-import",de(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function Hn(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=de(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 Vn(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 Kt(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 ue(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Wt(e,t),i=new Map,a=new Set;for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let o=l=>{let c=Hn(e,l);if(!c)return;let d=mt(s,c.root),f=d?i.get(d):void 0;return f?[...f,...c.segments.slice(1)]:gt(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let d=o(c.initializer),f=mt(s,c.name);!d||!f||i.set(f,d)}let u=[],m=new Set,h=(l,c)=>{let d=Yt(t,c),f=`${l}:${c.getStart(t)}`;m.has(f)||(m.add(f),u.push({name:l,line:d,node:c}))},g=l=>{let c=l.parent&&(e.isPropertyAccessExpression(l.parent)||e.isElementAccessExpression(l.parent))&&l.parent.expression===l;if((e.isPropertyAccessExpression(l)||e.isElementAccessExpression(l))&&!c){let d=o(l),f=d?Kt(r,d):void 0;f&&h(f,l)}else e.isIdentifier(l)&&r.has(l.text)&&Vn(e,l)&&!gt(e,s,t,l)&&h(l.text,l);if(e.isVariableDeclaration(l)&&e.isObjectBindingPattern(l.name)&&l.initializer){let d=o(l.initializer);if(d)for(let f of l.name.elements){if(!e.isIdentifier(f.name))continue;let b=f.propertyName?de(e,f.propertyName)??f.propertyName.text:f.name.text,R=Kt(r,[...d,b]);R&&h(R,l.initializer)}}e.forEachChild(l,g)};return g(t),u}function ht(e,t,n){let r=[];for(let s of n?.dependencies??pe(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Se(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??ue(e,t,ft)){let i=je(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 At={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."},bt=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 Rt(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 ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function xe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:At.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:At.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function fe(e,t){return e.slice(0,t).split(`
1
+ var $n="4.1.1";var Pn="1.4";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function Ut(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Tn(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, 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 lt(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(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}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{},...I(e.arkruleId)?{arkruleId:I(e.arkruleId)}:{},...I(e.arkruleSource)?{arkruleSource:I(e.arkruleSource)}:{}};return{ruleId:n,severity:r,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:Ut(e.line,1),column:Ut(e.column,1)},evidence:s,nextAction:I(e.nextAction)??Tn(n,s,e)}}function Ln(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(o=>({code:I(o.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(o.message)??`Analysis ${t}: required evidence is incomplete.`,...I(o.file)?{file:I(o.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],s={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let o of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!s[o])throw new Error(`${o} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(o=>lt(o,"error")),...(e.warnings??[]).map(o=>lt(o,"warning"))],a={schemaVersion:"1.4",completenessReasons:r,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...s};let o={policyHash:s.policyHash,resolverIdentity:s.resolverIdentity,factsHash:s.factsHash,candidateTreeHash:s.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...o}:{...a,mode:n,valid:!1,completeness:t,...o}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...s}:{...a,mode:n,valid:!1,completeness:t,...s}}var _n={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.4"},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}}}}}};var dt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),ut=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),ft=Object.freeze(Object.keys(ut).sort()),ct=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"}),pt=Object.freeze({process:Object.freeze(["process","node:process"])});function Se(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ct[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=ct[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:ct[e.slice(0,i)]??null}function Z(e,t){for(let n of t)if(pt[n]?.includes(e))return n;return null}function je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=ut[r];if(s)return s}return null}function ce(e){if(e?.pure===!0)return[...dt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dt.includes(r));return[...new Set(n)].sort()}function ke(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 Ue(e){let t=new Set,n=new Set,r=Object.keys(ut);for(let s of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===s||a.startsWith(`${s}.`));if(i.length===0)n.add(s);else for(let a of i)t.add(`ambient:${a}`);for(let a of pt[s]??[])t.add(`import-exact:${a}`)}for(let s of ce(e)){if(t.add(`import:${s}`),s==="process")for(let i of pt.process)t.add(`import-exact:${i}`);for(let i of r)je(i)===s&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Gt=new Map;function Bt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Ge(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 Fn(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 te(e){let t=Gt.get(e);if(t)return t;let n=Ge(e),r=Fn(n),s="",i=0;for(let o=0;o<n.length;o+=1){let u=n[o];u==="\\"&&o+1<n.length?(s+=Bt(n[o+1]),o+=1):u==="*"?n[o+1]==="*"?n[o+2]==="/"?(s+="(?:.*/)?",o+=2):(s+=".*",o+=1):s+="[^/]*":u==="?"?s+="[^/]":u==="{"&&r?(s+="(?:",i+=1):u==="}"&&r&&i>0?(s+=")",i-=1):u===","&&r&&i>0?s+="|":s+=Bt(u)}let a=new RegExp(`^${s}$`);return Gt.set(e,a),a}function Nn(e){return Ge(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function yt(e,t){let n=Ge(String(e)),r=Nn(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let o=0,u=-1;for(let m of r){let h=-1;for(let g=o;g<a.length;g+=1)if(a[g]===m){h=g;break}if(h<0)return i;u=h,o=h+1}return(u+1)*1e6+r.length*1e4+s}function z(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>te(a).test(n))){for(let a of i.patterns??[])if(te(a).test(n)){let o=yt(a,n);o>s&&(s=o,r=i.name)}}return r}function qt(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 Mn(e){let t=new Set;for(let n of e??[]){let s=Ge(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let o=s[i-1];o&&!o.includes("*")&&!o.includes("{")&&!o.includes("}")&&t.add(o)}}}return[...t]}function Dn(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 Mn(r?.patterns)}function K(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,a=r?.toPath;if(!i||!a)return s;let o=Dn(s,t,r?.layers);if(o.length===0)return s;let u=qt(i,o),m=qt(a,o);if(!u||!m||u!==m)return s;continue}if(t!==n)return s}}function de(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Yt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function zt(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 Wt(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 mt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function gt(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=s?t.getShorthandAssignmentValueSymbol(r.parent):mt(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function pe(e,t){let n,r=[],s=(a,o,u,m=!1)=>r.push({specifier:u,kind:o,line:Yt(t,a),typeOnly:m,unresolved:u===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))s(a,"import",de(e,a.moduleSpecifier),zt(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",de(e,a.moduleSpecifier),zt(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",de(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let o=a.expression.kind===e.SyntaxKind.ImportKeyword,m=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!gt(e,n??(n=Wt(e,t)),t,a.expression);(o||m)&&s(a,m?"require":"dynamic-import",de(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),r}function Hn(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=de(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 Vn(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 Kt(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 ue(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Wt(e,t),i=new Map,a=new Set;for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations)e.isIdentifier(c.name)&&a.add(c.name.text);let o=l=>{let c=Hn(e,l);if(!c)return;let d=mt(s,c.root),f=d?i.get(d):void 0;return f?[...f,...c.segments.slice(1)]:gt(e,s,t,c.root)||a.has(c.root.text)?void 0:c.segments};for(let l of t.statements)if(e.isVariableStatement(l))for(let c of l.declarationList.declarations){if(!c.initializer||!e.isIdentifier(c.name))continue;let d=o(c.initializer),f=mt(s,c.name);!d||!f||i.set(f,d)}let u=[],m=new Set,h=(l,c)=>{let d=Yt(t,c),f=`${l}:${c.getStart(t)}`;m.has(f)||(m.add(f),u.push({name:l,line:d,node:c}))},g=l=>{let c=l.parent&&(e.isPropertyAccessExpression(l.parent)||e.isElementAccessExpression(l.parent))&&l.parent.expression===l;if((e.isPropertyAccessExpression(l)||e.isElementAccessExpression(l))&&!c){let d=o(l),f=d?Kt(r,d):void 0;f&&h(f,l)}else e.isIdentifier(l)&&r.has(l.text)&&Vn(e,l)&&!gt(e,s,t,l)&&h(l.text,l);if(e.isVariableDeclaration(l)&&e.isObjectBindingPattern(l.name)&&l.initializer){let d=o(l.initializer);if(d)for(let f of l.name.elements){if(!e.isIdentifier(f.name))continue;let b=f.propertyName?de(e,f.propertyName)??f.propertyName.text:f.name.text,R=Kt(r,[...d,b]);R&&h(R,l.initializer)}}e.forEachChild(l,g)};return g(t),u}function ht(e,t,n){let r=[];for(let s of n?.dependencies??pe(e,t)){if(s.typeOnly||!s.specifier)continue;let i=Se(s.specifier);i&&r.push({capability:i,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??ue(e,t,ft)){let i=je(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 At={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."},bt=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 Rt(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 ne(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function xe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&ne(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:At.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:At.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n){return{ruleId:e,code:e,message:t,...n}}function fe(e,t){return e.slice(0,t).split(`
2
2
  `).length}function jn(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 Un(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]),a=s[0],o=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:s[1],index:i,kind:r.kind,typeOnly:o})}}return t.sort((r,s)=>r.index-s.index)}function Gn(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 Bn(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 qn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function zn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Oe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Kn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Zt(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Kn(e,r.name)===n)}function $e(e,t,n){return Zt(e,t,n)!==void 0}function we(e,t,n){let r=Zt(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function Yn(e,t){let n=we(e,t,"metadata");return $e(e,n,"source")}function Jt(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Jt(e,t.name):!1:!1}function Wn(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 Zn(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Oe(e,n);return r!==void 0&&ne(r)||$e(e,n,"intent")||Jt(e,n)}function Jn(e,t){if(!e.isCallExpression(t))return!1;let[n,r,s]=t.arguments;return Yn(e,n)||$e(e,r,"source")||$e(e,s,"source")}function Xn(e,t){if(!e.isCallExpression(t))return;let[n,r,s]=t.arguments,i=we(e,n,"metadata");return Oe(e,we(e,i,"source"))??Oe(e,we(e,r,"source"))??Oe(e,we(e,s,"source"))}function Qn(e,t,n,r){let s=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,o=i?.layer,u=[],m=g=>s.getLineAndCharacterOfPosition(g.getStart(s)).line+1,h=g=>{if(Wn(e,g)){let l=g.arguments[0],c=Oe(e,l);for(let f of xe({publishCall:!0,rawIntentName:c,objectHasIntent:$e(e,l,"intent"),arkPublishCandidate:Zn(e,g),hasSource:Jn(e,g)}))u.push(w(f.ruleId,f.message,{line:m(g),filePath:a}));let d=Xn(e,g);if(r&&o&&d&&ne(d)){let f=r.resolveLayer(d);f&&f!==o&&u.push(w("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${d}" resolves to ${f}, but the target file is classified as ${o}.`,{line:m(g),filePath:a,target:d,fromLayer:o,toLayer:f}))}}e.forEachChild(g,h)};return h(s),u}function Xt(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,a){let o=[],u=a,m=u?.filePath,h=u?.layer,g=e.typescript,l=g?g.createSourceFile(m??"generated.ts",i,g.ScriptTarget.Latest,!0):void 0,c=l?pe(e.typescript,l):void 0,d=c?c.filter(p=>p.specifier!==void 0).map(p=>({value:p.specifier,index:p.node.getStart(l),kind:p.kind,typeOnly:p.typeOnly})):Un(i),f=e.typescript?Gn(e.typescript,i):jn(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(m))for(let p of c?.filter(({unresolved:y})=>y)??[]){let y=p.kind==="require";o.push(w(y?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${y?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:p.line,filePath:m}))}let b=h!==void 0&&(r.has(h)||zn(h)),R=h!==void 0?` If "${h}" 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 p of n)if(p instanceof RegExp){p.lastIndex=0;let y=p.exec(i);p.lastIndex=0,y&&o.push(w("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${p}`,{line:y.index===void 0?void 0:fe(i,y.index),filePath:m,suggestion:"Remove infrastructure imports from domain/application layers."+R}))}else i.includes(p)&&o.push(w("FORBIDDEN_SUBSTRING",`Forbidden substring: ${p}`,{line:fe(i,i.indexOf(p)),filePath:m}));for(let p of d){let y=e.resolveImportTarget?.(p.value,m)??(e.resolveImportLayer?{layer:e.resolveImportLayer(p.value,m)}:void 0),v=typeof m=="string"?e.resolveImportTarget?.(m)??(e.resolveImportLayer?{layer:h,relPath:void 0}:void 0):void 0,C=y?.layer;if(C&&h){let T=K(e.architectureProfile?.rules,h,C,{fromPath:v?.relPath,toPath:y?.relPath,layers:e.architectureLayers});if(T){if(p.typeOnly&&!T.peerIsolation)continue;let _=!!T.peerIsolation;o.push(w("LAYER_IMPORT_VIOLATION",T.message??(_?`Layer "${h}" must not import across slices into "${C}".`:`Layer "${h}" must not import "${C}".`),{line:fe(i,p.index),source:p.value,target:p.value,filePath:m,fromLayer:h,toLayer:C,suggestion:_?"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:p.kind,peerIsolation:_,...p.typeOnly?{typeOnly:!0}:{}}}));continue}continue}b||p.typeOnly||!Bn(p.value)&&!qn(p.value)||o.push(w("FORBIDDEN_IMPORT",`Forbidden ${p.kind} target: "${p.value}".`,{line:fe(i,p.index),source:p.value,target:p.value,filePath:m,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+R,details:{importKind:p.kind}}))}if(e.policies)for(let p of e.policies){let y=p.check({source:i,context:a});if(y!==!0)if(Array.isArray(y))for(let v of y)o.push(w("POLICY_VIOLATION",v.message,{filePath:m,suggestion:`Fix violation of policy "${p.name}".`}));else y===!1?o.push(w("POLICY_VIOLATION",`Policy ${p.name} failed on generated code`)):o.push(w("POLICY_VIOLATION",y.message))}if(s&&t.size>0)for(let p of f)ne(p.value)&&!t.has(p.value)&&o.push(w("UNKNOWN_INTENT",`Unknown intent reference: "${p.value}"`,{line:fe(i,p.index),filePath:m,target:p.value,suggestion:`Register intent "${p.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&h)for(let p of f){if(!ne(p.value))continue;let y=e.architectureProfile.resolveLayer(p.value);if(!y)continue;let v=K(e.architectureProfile.rules,h,y);v&&o.push(w("LAYER_REFERENCE_VIOLATION",v.message??`Layer "${h}" must not reference "${y}" through "${p.value}".`,{line:fe(i,p.index),filePath:m,target:p.value,fromLayer:h,toLayer:y,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:v}}))}if(e.extensions)for(let p of e.extensions)try{let y=p.analyze(i,a);o.push(...y)}catch(y){o.push(w("EXTENSION_ERROR",`Extension "${p.name}" failed: ${y instanceof Error?y.message:String(y)}`))}if(e.typescript&&l&&h&&e.forbiddenGlobals?.[h]?.length)try{let p=e.forbiddenGlobals[h];o.push(...ue(e.typescript,l,p).map(y=>w("FORBIDDEN_GLOBAL",`${h} must not use the ambient global "${y.name}".`,{line:y.line,filePath:m,target:y.name,fromLayer:h,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let y of c??[]){if(y.typeOnly||!y.specifier)continue;let v=Z(y.specifier,p);v&&o.push(w("FORBIDDEN_GLOBAL",`${h} must not use module "${y.specifier}" because it is the import form of forbidden global "${v}".`,{line:y.line,filePath:m,source:y.specifier,target:y.specifier,fromLayer:h,details:{importKind:y.kind,forbiddenGlobal:v},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript&&l&&h&&e.capabilityWalls?.[h]?.length)try{let p=new Set(e.capabilityWalls[h]),y=e.forbiddenGlobals?.[h]??[];for(let v of ht(e.typescript,l))p.has(v.capability)&&(v.source==="ambient-global"&&ke(v.symbol,y)||v.source==="import-based"&&Z(v.symbol,y)||o.push(w("CAPABILITY_VIOLATION",v.source==="import-based"?`${h} denies the ${v.capability} capability; found import of "${v.symbol}".`:`${h} denies the ${v.capability} capability; found ambient "${v.symbol}".`,{line:v.line,filePath:m,target:v.symbol,capability:v.capability,fromLayer:h,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript)try{o.push(...Qn(e.typescript,i,a,e.architectureProfile))}catch(p){o.push(w("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:o.length===0,violations:o}}}}var er="1.1",qe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Qt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],tr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function nr(){let e=[];for(let t of Qt)for(let n of Qt)t===n||tr.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ze=nr(),vt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],J={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},It={$schema:"https://json-schema.org/draft/2020-12/schema",$id:qe,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:qe,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:{...J,minItems:1,default:["src"]},exclude:{...J,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ze,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...J,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...J,minItems:1},exclude:J,intentPrefixes:J,description:{type:"string",minLength:1},forbiddenGlobals:J,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"}}},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:{...J,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}}}}},Y=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 en(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Be(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ye(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function rr(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Pe(e,t,n,r,s){if(t.$ref){let i=rr(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Pe(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(!en(e)){s.push({path:n,message:`must be an object; received ${ye(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:Be(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:Be(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let o of Object.keys(e))o in i||Pe(e[o],a,Be(n,o),r,s)}for(let[a,o]of Object.entries(i))e[a]!==void 0&&Pe(e[a],o,Be(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${ye(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(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Pe(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${ye(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 ${ye(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${ye(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function sr(e){return{...e,$schema:e.$schema===void 0?qe: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?ze.map(t=>({...t})):e.rules}}function ir(){let e=new Set(["1.1"]);for(let t of vt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function ar(e,t="ark.config.json"){if(!en(e))throw new Y(t,[{path:"$",message:`must be an object; received ${ye(e)}`}]);let n=ir(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<vt.length+1;){a+=1;let u=vt.find(m=>m.from===s);if(!u)throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=u.to,i.schemaVersion=s}if(s!=="1.1")throw new Y(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let o=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:sr(i),migratedFrom:o}}function Ke(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=ar(e,t),s=[];if(Pe(n,It,"$",It,s),s.length>0)throw new Y(t,s);return{config:n,migratedFrom:r}}function Et(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new Y(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Ke(n,t)}function tn(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:qe,schemaVersion:"1.1"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function or(e){return e.endsWith(".")?e:`${e}.`}function lr(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 We(e){let t=e.layers.map(s=>({...s,prefixes:s.prefixes.map(or)})),n=[...t].sort(lr),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(a=>s.startsWith(a)))?.name}}}function nn(e,t={}){return We({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 cr=[{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}],Ye=We({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:cr,rules:ze.map(e=>({...e}))}),dr={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 rn(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return tn({include:e.include??[t],layers:Ye.layers.map(s=>({name:s.name,patterns:(dr[s.name]??[s.name]).map(i=>`${r}${i}/**`),intentPrefixes:s.prefixes,optional:n})),rules:[...Ye.rules]})}function O(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 re="1.1";var sn=["network","filesystem","clock","randomness","environment","process","persistence"];function W(e,t){let n=x(e),r=x(t);return n<r?-1:n>r?1:0}function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function Te(e){let t={schemaVersion:"1.1",include:B(e.include??[]),exclude:B(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:B(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:B(n.patterns??[]),exclude:B(n.exclude??[]),forbiddenGlobals:B(n.forbiddenGlobals??[]),intentPrefixes:B(n.intentPrefixes??[]),capabilityDeny:B(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(W),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return O(x(t))}function pr(e){let t=e.completenessReasons.map(l=>({code:l.code,message:l.message,...l.file?{file:l.file}:{}})).sort(W),n=e.files.map(l=>({...l,typeOnlyExportNames:B(l.typeOnlyExportNames)})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),r=e.dependencies.map(l=>({...l,...l.namedBindings?{namedBindings:B(l.namedBindings)}:{}})).sort(W),s=e.capabilityUses.map(l=>({...l})).sort(W),i=e.ambientUses.map(l=>({...l})).sort(W),a=e.publishCalls.map(l=>({...l})).sort(W),o=e.intentReferences.map(l=>({...l})).sort(W),u=e.safetyUses.map(l=>({...l})).sort(W),m=(e.classShapes??[]).map(l=>({...l,mutatingMethods:[...l.mutatingMethods??[]].map(c=>({...c}))})).sort(W),h=e.files.map(({path:l,contentHash:c})=>({path:l,contentHash:c})).sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0),g=O(x(h));return{schemaVersion:"1.1",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:i,publishCalls:a,intentReferences:o,safetyUses:u,classShapes:m}}function on(e){let t=pr(e);return{...t,factsHash:O(x(t))}}function Ct(e){return on(cn(M(e,"$"),!1))}function M(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function V(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 P(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 me(e,t,n){if(e[t]!==void 0)return P(e,t,n)}function U(e,t,n){let r=P(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 o of s.split("/"))if(!(!o||o==="."))if(o===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(o);let a=i.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function $(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function ln(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 ge(e,t,n){let r=ln(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}function X(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 an(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 ur(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 cn(e,t){V(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=X(e,"schemaVersion",["1.0","1.1"],"$"),r=X(e,"completeness",["complete","partial","unavailable"],"$"),s=G(e,"completenessReasons","$").map((b,R)=>{let p=`$.completenessReasons[${R}]`,y=M(b,p);V(y,["code","message","file"],p);let v=y.file===void 0?void 0:U(y,"file",p);return{code:P(y,"code",p),message:P(y,"message",p),...v?{file:v}:{}}});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=G(e,"files","$").map((b,R)=>{let p=`$.files[${R}]`,y=M(b,p);return V(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],p),{path:U(y,"path",p),contentHash:P(y,"contentHash",p),parseStatus:X(y,"parseStatus",["parsed","invalid"],p),parseDiagnosticCount:ln(y,"parseDiagnosticCount",p),exportsOnlyTypes:$(y,"exportsOnlyTypes",p),typeOnlyExportNames:an(y.typeOnlyExportNames,`${p}.typeOnlyExportNames`),hasTopLevelSideEffects:$(y,"hasTopLevelSideEffects",p)}}),a=G(e,"dependencies","$").map((b,R)=>{let p=`$.dependencies[${R}]`,y=M(b,p);V(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],p);let v=me(y,"specifier",p),C=me(y,"target",p),T=X(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],p);if(T==="resolved-project"&&!C)throw new Error(`${p}.target is required for resolved-project dependencies.`);if(T!=="resolved-project"&&C)throw new Error(`${p}.target is only allowed for resolved-project dependencies.`);if(T!=="dynamic"&&!v)throw new Error(`${p}.specifier is required unless resolution is dynamic.`);return{from:U(y,"from",p),...v?{specifier:v}:{},kind:X(y,"kind",["import","export","dynamic-import","require"],p),typeOnly:$(y,"typeOnly",p),line:ge(y,"line",p),resolution:T,...C?{target:U(y,"target",p)}:{},...y.namedBindings!==void 0?{namedBindings:an(y.namedBindings,`${p}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:$(y,"targetTypeOnlyExports",p)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:$(y,"sourcePureTypeModule",p)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:$(y,"namedBindingsTypeOnly",p)}:{},...y.portProofEligible!==void 0?{portProofEligible:$(y,"portProofEligible",p)}:{}}}),o=G(e,"capabilityUses","$").map((b,R)=>{let p=`$.capabilityUses[${R}]`,y=M(b,p);return V(y,["file","line","symbol","capability","source"],p),{file:U(y,"file",p),line:ge(y,"line",p),symbol:P(y,"symbol",p),capability:X(y,"capability",sn,p),source:X(y,"source",["ambient-global","import-based"],p)}}),u=G(e,"ambientUses","$").map((b,R)=>{let p=`$.ambientUses[${R}]`,y=M(b,p);return V(y,["file","line","symbol"],p),{file:U(y,"file",p),line:ge(y,"line",p),symbol:P(y,"symbol",p)}}),m=G(e,"publishCalls","$").map((b,R)=>{let p=`$.publishCalls[${R}]`,y=M(b,p);V(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],p);let v=me(y,"rawIntentName",p),C=me(y,"sourceIntent",p);return{file:U(y,"file",p),line:ge(y,"line",p),...v?{rawIntentName:v}:{},objectHasIntent:$(y,"objectHasIntent",p),arkPublishCandidate:$(y,"arkPublishCandidate",p),hasSource:$(y,"hasSource",p),...C?{sourceIntent:C}:{}}}),h=G(e,"intentReferences","$").map((b,R)=>{let p=`$.intentReferences[${R}]`,y=M(b,p);return V(y,["file","line","intent"],p),{file:U(y,"file",p),line:ge(y,"line",p),intent:P(y,"intent",p)}}),g=G(e,"safetyUses","$").map((b,R)=>{let p=`$.safetyUses[${R}]`,y=M(b,p);V(y,["file","line","kind","symbol"],p);let v=me(y,"symbol",p),C=X(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],p);if(C==="in-memory-store"&&!v)throw new Error(`${p}.symbol is required for in-memory-store facts.`);if(C!=="in-memory-store"&&v)throw new Error(`${p}.symbol is only allowed for in-memory-store facts.`);return{file:U(y,"file",p),line:ge(y,"line",p),kind:C,...v?{symbol:v}:{}}});ur(i,b=>b.path,"$.files");let l=new Set(i.map(b=>b.path));for(let b of i){if(b.parseStatus==="parsed"&&b.parseDiagnosticCount!==0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(b.parseStatus==="invalid"&&b.parseDiagnosticCount===0)throw new Error(`$.files[${b.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(b=>b.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let b of a)if(!l.has(b.from))throw new Error(`$.dependencies references missing source file ${b.from}.`);for(let[b,R]of[["$.capabilityUses",o],["$.ambientUses",u],["$.publishCalls",m],["$.intentReferences",h],["$.safetyUses",g]])for(let p of R)if(!l.has(p.file))throw new Error(`${b} references missing file ${p.file}.`);let c=me(e,"projectPackageName","$"),f=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((b,R)=>{let p=`$.classShapes[${R}]`,y=M(b,p);V(y,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],p);let v=G(y,"mutatingMethods",p).map((C,T)=>{let _=`${p}.mutatingMethods[${T}]`,k=M(C,_);return V(k,["name","referencesGuardOrPublish"],_),{name:P(k,"name",_),referencesGuardOrPublish:$(k,"referencesGuardOrPublish",_)}});return{file:U(y,"file",p),className:P(y,"className",p),exported:$(y,"exported",p),hasPublicMutableFields:$(y,"hasPublicMutableFields",p),hasPublicSetters:$(y,"hasPublicSetters",p),hasPublicConstructor:$(y,"hasPublicConstructor",p),hasStaticFactory:$(y,"hasStaticFactory",p),mutatingMethods:v,...y.dataOnly===void 0?{}:{dataOnly:$(y,"dataOnly",p)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:P(e,"resolverIdentity","$"),compilerIdentity:P(e,"compilerIdentity","$"),compilerOptionsHash:P(e,"compilerOptionsHash","$"),tsconfigHash:P(e,"tsconfigHash","$"),evidenceRequirementsHash:P(e,"evidenceRequirementsHash","$"),...c?{projectPackageName:c}:{},files:i,dependencies:a,capabilityUses:o,ambientUses:u,publishCalls:m,intentReferences:h,safetyUses:g,classShapes:f}}function Q(e){let t=M(e,"$"),n=P(t,"factsHash","$"),r=P(t,"candidateTreeHash","$"),s=on(cn(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 fr=["network","filesystem","clock","randomness","environment","process","persistence"],S={type:"string",minLength:1},he={type:"integer",minimum:1},q={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},St={$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:S,message:S,file:q}}},resolverIdentity:S,compilerIdentity:S,compilerOptionsHash:S,tsconfigHash:S,candidateTreeHash:S,evidenceRequirementsHash:S,projectPackageName:S,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:q,contentHash:S,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:S},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:q,specifier:S,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:he,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:q,namedBindings:{type:"array",items:S},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:q,line:he,symbol:S,capability:{enum:fr},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:q,line:he,symbol:S}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:q,line:he,rawIntentName:S,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:S}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:q,line:he,intent:S}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:q,line:he,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:S},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:q,className:S,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:S,referencesGuardOrPublish:{type:"boolean"}}}}}}},factsHash:S},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 kt="1.0";function F(e){return`${e.from}->${e.to}`}function Le(e,t,n,r="dependency"){return{id:`${e}:${r}:${F(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${F(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${F(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${F(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${F(t)} from the candidate, then preflight again.`}:{}}}function Ae(e){let t=[],n=new Map(e.changeMap.map.files.map(l=>[l.path,l])),r=new Map(e.changes.map(l=>[l.path,l])),s=new Map(e.changeMap.map.dependencies.map(l=>[F(l),l])),i=new Map(e.baseDependencies.map(l=>[F(l),l])),a=new Map(e.candidateDependencies.map(l=>[F(l),l]));for(let l of[...n.values()].sort((c,d)=>c.path.localeCompare(d.path))){let c=r.get(l.path);c?c.operation!==l.operation?t.push({id:`contradictory:file:${l.path}`,classification:"contradictory",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} was planned as ${l.operation} but the actual operation is ${c.operation}.`,nextAction:`Change ${l.path} to the planned ${l.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${l.path}`,classification:"satisfied",subject:"file",path:l.path,expectedOperation:l.operation,actualOperation:c.operation,message:`${l.path} matches the planned ${l.operation} operation.`}):t.push({id:`missing:file:${l.path}`,classification:"missing",subject:"file",path:l.path,expectedOperation:l.operation,message:`${l.path} was planned as ${l.operation} but is absent from the actual change.`,nextAction:`${l.operation[0].toUpperCase()}${l.operation.slice(1)} ${l.path} in the complete change set, then preflight again.`})}for(let l of[...r.values()].sort((c,d)=>c.path.localeCompare(d.path)))n.has(l.path)||t.push({id:`unplanned:file:${l.path}`,classification:"unplanned",subject:"file",path:l.path,actualOperation:l.operation,message:`${l.path} has an unplanned ${l.operation} operation.`,nextAction:`Remove ${l.path} from the change set, then preflight again.`});let o=new Set;for(let l of[...s.values()].sort((c,d)=>F(c).localeCompare(F(d)))){if(a.has(F(l))){t.push(Le("satisfied",l,`${l.from} -> ${l.to} exists in the candidate architecture.`));continue}let c={from:l.to,to:l.from};a.has(F(c))?(o.add(F(c)),t.push(Le("contradictory",l,`${l.from} -> ${l.to} was planned, but the candidate contains the reverse edge.`))):t.push(Le("missing",l,`${l.from} -> ${l.to} is absent from the candidate architecture.`))}let u=new Set([...n.keys(),...r.keys()]);for(let[l,c]of[...a].sort(([d],[f])=>d.localeCompare(f)))i.has(l)||s.has(l)||o.has(l)||!u.has(c.from)&&!u.has(c.to)||t.push({...Le("unplanned",c,`${c.from} -> ${c.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let m=new Set(e.changeMap.map.files.filter(l=>l.operation==="delete").map(l=>l.path));for(let[l,c]of[...i].sort(([d],[f])=>d.localeCompare(f)))a.has(l)||m.has(c.from)||m.has(c.to)||!u.has(c.from)&&!u.has(c.to)||t.push({...Le("unplanned",c,`${c.from} -> ${c.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((l,c)=>h[l.classification]-h[c.classification]||(l.subject===c.subject?0:l.subject==="file"?-1:1)||l.id.localeCompare(c.id));let g={satisfied:t.filter(l=>l.classification==="satisfied").length,missing:t.filter(l=>l.classification==="missing").length,contradictory:t.filter(l=>l.classification==="contradictory").length,unplanned:t.filter(l=>l.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:g.missing===0&&g.contradictory===0&&g.unplanned===0,behavioralCompletion:"not-evaluated",summary:g,findings:t}}var yr="1.0",xt="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",un=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","no-anemic-model","invariant-coverage"],mr=["no-anemic-model"],dn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},wt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xt,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:xt},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:[...un]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:dn,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:dn}}}},se=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkRules (${t}):
package/docs/README.md CHANGED
@@ -52,13 +52,13 @@ These are **not** the day-to-day product path. They stay in the repo for evidenc
52
52
  | Area | Path |
53
53
  |------|------|
54
54
  | Release notes (by version) | [releases/](releases/) · [CHANGELOG.md](../CHANGELOG.md) |
55
- | Epic plans (seeded + shipped) | [plans/](plans/) |
55
+ | Epic plans (seeded + shipped) | [plans/](plans/) · latest: [enforcement-evidence-and-docs-truth](plans/enforcement-evidence-and-docs-truth/README.md) (Phase EH shipped; 4.1.1 prepared) |
56
56
  | Claims audit | [audit/claims-matrix.md](audit/claims-matrix.md) |
57
57
  | Field adoption kit (scaffolding, not closed) | [field/](field/) |
58
58
  | Runtime hardening (experimental) | [production-hardening.md](production-hardening.md) |
59
59
 
60
- Current published: [releases/4.0.1.md](releases/4.0.1.md) (`arkgate@4.0.1` on npm `latest`).
61
- Next prepared: [releases/4.1.0.md](releases/4.1.0.md) (`arkgate@4.1.0`field product phases + CI PR slim; not published until registry).
60
+ Current published: [releases/4.1.0.md](releases/4.1.0.md) (`arkgate@4.1.0` on npm `latest`).
61
+ Prepared next: [releases/4.1.1.md](releases/4.1.1.md) (Phase EH **Status: prepared**, not on npm until publish).
62
62
  Previous major: [releases/4.0.0.md](releases/4.0.0.md) (`arkgate@4.0.0`).
63
63
  Config: [configuration.md](configuration.md) · Agent skills dual-plane: [agent-guide.md](agent-guide.md).
64
64
 
@@ -68,5 +68,5 @@ Config: [configuration.md](configuration.md) · Agent skills dual-plane: [agent-
68
68
 
69
69
  1. **Audience first** — every page should be use, develop, or contribute.
70
70
  2. **One primary flow** — `start` → doctor → optional guided work.
71
- 3. **Honest hardness** — host write guarantees differ; CI required status is the shared merge boundary.
71
+ 3. **Honest hardness** — host write guarantees differ; a **required GitHub status context** running the merge CLI is the shared hard boundary.
72
72
  4. **History is not the product** — version archaeology lives under `releases/` and `plans/`, not the front door.
@@ -40,9 +40,11 @@ npx ark-check --install-agent-gates --skills-only --force
40
40
 
41
41
  **Write-path honesty:** Claude/Grok/Antigravity can hard-block listed PreToolUse ops when
42
42
  installed and trusted. Cursor/Codex/OpenCode remain **advisory at write**. For every host, the
43
- repository-wide hard boundary is a **required** CI status (`arkgate-check --strict-merge`)
44
- never claim Cursor/Codex/OpenCode hard write. See [ai-gates.md](ai-gates.md) and the README host
45
- matrix.
43
+ repository-wide hard boundary is a **required GitHub status context** that runs
44
+ `arkgate-check --strict-merge` (alias `ark-check --strict-merge`) the CLI name is not the
45
+ status context name. Never claim Cursor/Codex/OpenCode hard write. Soft-write alone does not mean
46
+ the project is unfinished; doctor keeps it as an environment residual. See [ai-gates.md](ai-gates.md)
47
+ and the README host matrix.
46
48
 
47
49
  ## Architecture playbook and `ark-check --recommend`
48
50
 
package/docs/ai-gates.md CHANGED
@@ -307,8 +307,10 @@ required CI status is the hard repository boundary.
307
307
  npx ark-check --install-agent-gates --tools codex
308
308
  ```
309
309
 
310
- The generated hook includes `--hook-repair`, so a rejected patch carries the same structured
311
- repair envelope as Claude and Grok. Codex still needs hook trust enabled for the project.
310
+ The generated hook includes `--hook-repair`, so a rejected patch **may emit** a structured
311
+ repair envelope (same JSON shape as Claude/Grok). **Reinjection is not guaranteed** on Codex
312
+ local write stays advisory/bypassable; the host must re-apply any fix, and required CI remains
313
+ the hard merge boundary. Codex still needs hook trust enabled for the project.
312
314
 
313
315
  Modern Codex resolves MCP servers from the active project's `.codex/config.toml`. Ark writes
314
316
  that file with relative paths, so every repository owns its primary `ark` binding without
@@ -387,7 +389,7 @@ Ark verifies those references against each selected host catalog.
387
389
  `--skills-only --tools codex --force` (repo) or `--codex-home --force` (home) fix.
388
390
  - Codex **write path is advisory**: MCP + best-effort `.codex/hooks.json` is **not** a hard
389
391
  write boundary and is **not** equivalent to Claude/Grok PreToolUse hard-write + repair.
390
- The hard merge backstop is CI `--strict-merge` (or `--strict`) plus a required status check.
392
+ The hard merge backstop is CI `--strict-merge` (or `--strict`) as a **required GitHub status context** (not “workflow file present”).
391
393
  - CI workflows that run ark-check without the fail-closed profile (or with only
392
394
  `--strict-config`) surface gap `enforcement-ci-not-fail-closed`.
393
395
 
@@ -591,13 +593,34 @@ for standalone linting where no project contract applies.
591
593
  Whatever the agent side does, run the merge profile in CI:
592
594
 
593
595
  ```yaml
594
- - run: npx ark-check --root . --config ark.config.json --strict-merge --fail-on-new-smells --base-ref "${{ github.event.pull_request.base.sha || github.event.before }}"
596
+ # EH04: first push may have all-zero github.event.before only pass --base-ref when resolvable.
597
+ - name: Ark architecture check
598
+ env:
599
+ ARK_POLICY_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }}
600
+ run: |
601
+ set -euo pipefail
602
+ BASE_REF="${ARK_POLICY_BASE_REF:-}"
603
+ if [[ "$BASE_REF" =~ ^0{40,64}$ ]]; then BASE_REF=""; fi
604
+ if [ -n "$BASE_REF" ] && git cat-file -e "${BASE_REF}^{commit}" 2>/dev/null; then
605
+ export ARK_POLICY_BASE_REF="$BASE_REF"
606
+ npx ark-check --root . --config ark.config.json --strict-merge \
607
+ --fail-on-new-smells --base-ref "$BASE_REF"
608
+ else
609
+ export ARK_POLICY_BASE_REF=""
610
+ npx ark-check --root . --config ark.config.json --strict-merge
611
+ fi
595
612
  ```
596
613
 
597
614
  This explicit brownfield ratchet records schema `1.0` identities, touched paths, and stable
598
- evidence; missing base exits `2`. Its first semantic smell is `domain-logic-in-ui`; residual,
599
- path-only moves, and unrelated work stay green. Generated Claude/Grok hooks share the delta and
600
- golden-pattern repair hint. MCP exposes the result but stays advisory.
615
+ evidence; missing base with `--fail-on-new-smells` exits `2`, so the generated workflow skips the
616
+ delta when the SHA is all-zero or unresolvable while keeping the full merge gate. Its first
617
+ semantic smell is `domain-logic-in-ui`; residual, path-only moves, and unrelated work stay green.
618
+ Generated Claude/Grok hooks share the delta and golden-pattern repair hint. MCP exposes the result
619
+ but stays advisory.
620
+
621
+ **CLI vs required status:** `arkgate-check --strict-merge` / `ark-check --strict-merge` is the
622
+ **command**. The hard merge boundary is making that job a **required GitHub status context** —
623
+ not “workflow file present.”
601
624
 
602
625
  Or use the repository's composite Action at a pinned release or commit:
603
626