arkgate 4.8.22 → 4.8.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +2 -2
- package/bin/ark-check-runtime.mjs +4 -2
- package/bin/ark-layer-match.mjs +606 -11
- package/bin/lib/analysis-engine.mjs +11 -11
- package/bin/lib/config-contract.mjs +492 -1
- package/bin/lib/diagnostic-catalog.mjs +32 -0
- package/bin/lib/doctor-advisories.mjs +60 -1
- package/bin/lib/doctor-plan.mjs +2 -2
- package/bin/lib/enforcement-honesty.mjs +22 -0
- package/bin/lib/flat-parent-pilot.mjs +252 -0
- package/bin/lib/html-report-advisories.mjs +2 -0
- package/bin/lib/html-report-depth.mjs +3 -1
- package/bin/lib/physical-cohesion.mjs +16 -18
- package/bin/lib/pilot-loop.mjs +21 -8
- package/bin/lib/team-parliament-io.mjs +4 -2
- package/dist/{configTypes-CTELo87-.d.ts → configTypes-Bbf_MFGe.d.ts} +36 -2
- package/dist/{diagnosticCatalog-WD2TPSwZ.d.ts → diagnosticCatalog-35mrwAHe.d.ts} +13 -3
- package/dist/eslint/index.cjs +4 -4
- package/dist/eslint/index.d.ts +51 -5
- package/dist/eslint/index.js +4 -4
- package/dist/index.cjs +35 -35
- package/dist/index.d.ts +104 -5
- package/dist/index.js +35 -35
- package/dist/nestjs/index.cjs +9 -9
- package/dist/nestjs/index.d.ts +3 -3
- package/dist/nestjs/index.js +9 -9
- package/dist/runtime/index.cjs +13 -13
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.js +13 -13
- package/dist/{types-yDNEQ603.d.ts → types-Bdj32QwA.d.ts} +1 -1
- package/dist/{types-fQ9-KrBj.d.ts → types-Ik_OakcI.d.ts} +1 -1
- package/docs/README.md +2 -1
- package/docs/agent-guide.md +9 -1
- package/docs/configuration.md +92 -1
- package/docs/diagnostics.md +32 -0
- package/docs/product-voice.md +1 -1
- package/package.json +1 -1
- package/schemas/ark.config.schema.json +124 -2
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
// GENERATED from src/kernel/analysis.ts by scripts/generate-analysis-engine.mjs.
|
|
2
2
|
// Do not edit this file directly.
|
|
3
|
-
var Lr=Object.defineProperty;var i=(e,t)=>Lr(e,"name",{value:t,configurable:!0});function j(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(j,"deterministicHash");function N(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(N).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${N(t[n])}`).join(",")}}`}i(N,"stableSerialize");var be="1.2";var qt=["network","filesystem","clock","randomness","environment","process","persistence"];function K(e,t){let n=N(e),r=N(t);return n<r?-1:n>r?1:0}i(K,"compareCanonical");function V(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(V,"sortedUnique");function We(e){let t={schemaVersion:"1.2",include:V(e.include??[]),exclude:V(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:V(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:V(n.patterns??[]),exclude:V(n.exclude??[]),forbiddenGlobals:V(n.forbiddenGlobals??[]),intentPrefixes:V(n.intentPrefixes??[]),capabilityDeny:V(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(K),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:V(e.arkRun.compositionRoots),managedLayers:V(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return j(N(t))}i(We,"resolvedFactsEvidenceRequirementsHash");function Dr(e){let t=e.completenessReasons.map(b=>({code:b.code,message:b.message,...b.file?{file:b.file}:{}})).sort(K),n=e.files.map(b=>({...b,typeOnlyExportNames:V(b.typeOnlyExportNames)})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),r=e.dependencies.map(b=>({...b,...b.namedBindings?{namedBindings:V(b.namedBindings)}:{}})).sort(K),s=e.capabilityUses.map(b=>({...b})).sort(K),o=e.ambientUses.map(b=>({...b})).sort(K),a=e.publishCalls.map(b=>({...b})).sort(K),d=e.intentReferences.map(b=>({...b})).sort(K),l=e.safetyUses.map(b=>({...b})).sort(K),p=(e.classShapes??[]).map(b=>({...b,mutatingMethods:[...b.mutatingMethods??[]].map(T=>({...T}))})).sort(K),h=(e.arkRunKernelCalls??[]).map(b=>({...b})).sort(K),A=(e.arkRunManagedNews??[]).map(b=>({...b})).sort(K),u=(e.arkRunCompositionRootHits??[]).map(b=>({...b})).sort(K),f=(e.arkRunDeclarations??[]).map(b=>({...b,uses:V(b.uses),reactsTo:V(b.reactsTo),raises:V(b.raises),sends:V(b.sends)})).sort(K),c=(e.arkOrderPlaneCalls??[]).map(b=>({...b})).sort(K),y=(e.arkOrderGenericUpdates??[]).map(b=>({...b})).sort(K),k=(e.arkOrderRootHits??[]).map(b=>({...b})).sort(K),E=(e.arkOrderXiFieldWrites??[]).map(b=>({...b})).sort(K),I=(e.arkOrderIngestWritesXi??[]).map(b=>({...b})).sort(K),O=(e.arkOrderReleaseKeyCounts??[]).map(b=>({...b})).sort(K),$=e.files.map(({path:b,contentHash:T})=>({path:b,contentHash:T})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),W=j(N($));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:W,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:a,intentReferences:d,safetyUses:l,classShapes:p,arkRunKernelCalls:h,arkRunManagedNews:A,arkRunCompositionRootHits:u,arkRunDeclarations:f,arkOrderPlaneCalls:c,arkOrderGenericUpdates:y,arkOrderRootHits:k,arkOrderXiFieldWrites:E,arkOrderIngestWritesXi:I,arkOrderReleaseKeyCounts:O}}i(Dr,"canonicalResolvedFactsInput");function Yt(e){let t=Dr(e);return{...t,factsHash:j(N(t))}}i(Yt,"createCanonicalResolvedCandidateFacts");function qe(e){return Yt(Zt(F(e,"$"),!1))}i(qe,"createResolvedCandidateFacts");function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(F,"asRecord");function P(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}i(P,"assertOnlyKeys");function _(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(_,"requiredText");function oe(e,t,n){if(e[t]!==void 0)return _(e,t,n)}i(oe,"optionalText");function L(e,t,n){let r=_(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let o=[];for(let d of s.split("/"))if(!(!d||d==="."))if(d===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(d);let a=o.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(L,"requiredProjectPath");function D(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(D,"requiredBoolean");function Xt(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(Xt,"requiredInteger");function z(e,t,n){let r=Xt(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(z,"requiredPositiveInteger");function M(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(M,"requiredArray");function ae(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}i(ae,"enumValue");function ve(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(ve,"parseStringArray");function Mr(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}i(Mr,"assertUnique");function Zt(e,t){P(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ae(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ae(e,"completeness",["complete","partial","unavailable"],"$"),s=M(e,"completenessReasons","$").map((v,S)=>{let g=`$.completenessReasons[${S}]`,R=F(v,g);P(R,["code","message","file"],g);let x=R.file===void 0?void 0:L(R,"file",g);return{code:_(R,"code",g),message:_(R,"message",g),...x?{file:x}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=M(e,"files","$").map((v,S)=>{let g=`$.files[${S}]`,R=F(v,g);return P(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],g),{path:L(R,"path",g),contentHash:_(R,"contentHash",g),parseStatus:ae(R,"parseStatus",["parsed","invalid"],g),parseDiagnosticCount:Xt(R,"parseDiagnosticCount",g),exportsOnlyTypes:D(R,"exportsOnlyTypes",g),typeOnlyExportNames:ve(R.typeOnlyExportNames,`${g}.typeOnlyExportNames`),hasTopLevelSideEffects:D(R,"hasTopLevelSideEffects",g)}}),a=M(e,"dependencies","$").map((v,S)=>{let g=`$.dependencies[${S}]`,R=F(v,g);P(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],g);let x=oe(R,"specifier",g),U=oe(R,"target",g),de=ae(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],g);if(de==="resolved-project"&&!U)throw new Error(`${g}.target is required for resolved-project dependencies.`);if(de!=="resolved-project"&&U)throw new Error(`${g}.target is only allowed for resolved-project dependencies.`);if(de!=="dynamic"&&!x)throw new Error(`${g}.specifier is required unless resolution is dynamic.`);return{from:L(R,"from",g),...x?{specifier:x}:{},kind:ae(R,"kind",["import","export","dynamic-import","require"],g),typeOnly:D(R,"typeOnly",g),line:z(R,"line",g),resolution:de,...U?{target:L(R,"target",g)}:{},...R.namedBindings!==void 0?{namedBindings:ve(R.namedBindings,`${g}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:D(R,"targetTypeOnlyExports",g)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:D(R,"sourcePureTypeModule",g)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:D(R,"namedBindingsTypeOnly",g)}:{},...R.portProofEligible!==void 0?{portProofEligible:D(R,"portProofEligible",g)}:{}}}),d=M(e,"capabilityUses","$").map((v,S)=>{let g=`$.capabilityUses[${S}]`,R=F(v,g);return P(R,["file","line","symbol","capability","source"],g),{file:L(R,"file",g),line:z(R,"line",g),symbol:_(R,"symbol",g),capability:ae(R,"capability",qt,g),source:ae(R,"source",["ambient-global","import-based"],g)}}),l=M(e,"ambientUses","$").map((v,S)=>{let g=`$.ambientUses[${S}]`,R=F(v,g);return P(R,["file","line","symbol"],g),{file:L(R,"file",g),line:z(R,"line",g),symbol:_(R,"symbol",g)}}),p=M(e,"publishCalls","$").map((v,S)=>{let g=`$.publishCalls[${S}]`,R=F(v,g);P(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],g);let x=oe(R,"rawIntentName",g),U=oe(R,"sourceIntent",g);return{file:L(R,"file",g),line:z(R,"line",g),...x?{rawIntentName:x}:{},objectHasIntent:D(R,"objectHasIntent",g),arkPublishCandidate:D(R,"arkPublishCandidate",g),hasSource:D(R,"hasSource",g),...U?{sourceIntent:U}:{}}}),h=M(e,"intentReferences","$").map((v,S)=>{let g=`$.intentReferences[${S}]`,R=F(v,g);return P(R,["file","line","intent"],g),{file:L(R,"file",g),line:z(R,"line",g),intent:_(R,"intent",g)}}),A=M(e,"safetyUses","$").map((v,S)=>{let g=`$.safetyUses[${S}]`,R=F(v,g);P(R,["file","line","kind","symbol"],g);let x=oe(R,"symbol",g),U=ae(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],g);if(U==="in-memory-store"&&!x)throw new Error(`${g}.symbol is required for in-memory-store facts.`);if(U!=="in-memory-store"&&x)throw new Error(`${g}.symbol is only allowed for in-memory-store facts.`);return{file:L(R,"file",g),line:z(R,"line",g),kind:U,...x?{symbol:x}:{}}});Mr(o,v=>v.path,"$.files");let u=new Set(o.map(v=>v.path));for(let v of o){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of a)if(!u.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let c=(e.arkRunKernelCalls===void 0?[]:M(e,"arkRunKernelCalls","$")).map((v,S)=>{let g=`$.arkRunKernelCalls[${S}]`,R=F(v,g);P(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],g);let x=oe(R,"receiver",g),U=oe(R,"nameLiteral",g);return{file:L(R,"file",g),line:z(R,"line",g),kind:ae(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],g),callee:_(R,"callee",g),viaImport:D(R,"viaImport",g),...x?{receiver:x}:{},...U?{nameLiteral:U}:{}}}),k=(e.arkRunManagedNews===void 0?[]:M(e,"arkRunManagedNews","$")).map((v,S)=>{let g=`$.arkRunManagedNews[${S}]`,R=F(v,g);P(R,["file","line","typeName","importedFrom"],g);let x=oe(R,"importedFrom",g);return{file:L(R,"file",g),line:z(R,"line",g),typeName:_(R,"typeName",g),...x?{importedFrom:x}:{}}}),I=(e.arkRunCompositionRootHits===void 0?[]:M(e,"arkRunCompositionRootHits","$")).map((v,S)=>{let g=`$.arkRunCompositionRootHits[${S}]`,R=F(v,g);return P(R,["file","matchedRoot","hasKernelFactory"],g),{file:L(R,"file",g),matchedRoot:_(R,"matchedRoot",g),hasKernelFactory:D(R,"hasKernelFactory",g)}}),O=e.arkRunDeclarations===void 0?[]:M(e,"arkRunDeclarations","$"),W=(e.arkOrderPlaneCalls===void 0?[]:M(e,"arkOrderPlaneCalls","$")).map((v,S)=>{let g=`$.arkOrderPlaneCalls[${S}]`,R=F(v,g);return P(R,["file","line","callee"],g),{file:L(R,"file",g),line:z(R,"line",g),callee:_(R,"callee",g)}}),T=(e.arkOrderGenericUpdates===void 0?[]:M(e,"arkOrderGenericUpdates","$")).map((v,S)=>{let g=`$.arkOrderGenericUpdates[${S}]`,R=F(v,g);return P(R,["file","line","method"],g),{file:L(R,"file",g),line:z(R,"line",g),method:_(R,"method",g)}}),ge=(e.arkOrderRootHits===void 0?[]:M(e,"arkOrderRootHits","$")).map((v,S)=>{let g=`$.arkOrderRootHits[${S}]`,R=F(v,g);return P(R,["file","matchedRoot","hasPlaneFactory"],g),{file:L(R,"file",g),matchedRoot:_(R,"matchedRoot",g),hasPlaneFactory:D(R,"hasPlaneFactory",g)}}),se=(e.arkOrderXiFieldWrites===void 0?[]:M(e,"arkOrderXiFieldWrites","$")).map((v,S)=>{let g=`$.arkOrderXiFieldWrites[${S}]`,R=F(v,g);return P(R,["file","line","key"],g),{file:L(R,"file",g),line:z(R,"line",g),key:_(R,"key",g)}}),me=(e.arkOrderIngestWritesXi===void 0?[]:M(e,"arkOrderIngestWritesXi","$")).map((v,S)=>{let g=`$.arkOrderIngestWritesXi[${S}]`,R=F(v,g);return P(R,["file","line"],g),{file:L(R,"file",g),line:z(R,"line",g)}}),ke=(e.arkOrderReleaseKeyCounts===void 0?[]:M(e,"arkOrderReleaseKeyCounts","$")).map((v,S)=>{let g=`$.arkOrderReleaseKeyCounts[${S}]`,R=F(v,g);return P(R,["file","line","keyCount"],g),{file:L(R,"file",g),line:z(R,"line",g),keyCount:z(R,"keyCount",g)}}),_e=O.map((v,S)=>{let g=`$.arkRunDeclarations[${S}]`,R=F(v,g);return P(R,["file","line","uses","reactsTo","raises","sends"],g),{file:L(R,"file",g),line:z(R,"line",g),uses:ve(R.uses,`${g}.uses`),reactsTo:ve(R.reactsTo,`${g}.reactsTo`),raises:ve(R.raises,`${g}.raises`),sends:ve(R.sends,`${g}.sends`)}});for(let[v,S]of[["$.capabilityUses",d],["$.ambientUses",l],["$.publishCalls",p],["$.intentReferences",h],["$.safetyUses",A],["$.arkRunKernelCalls",c],["$.arkRunManagedNews",k],["$.arkRunCompositionRootHits",I],["$.arkRunDeclarations",_e],["$.arkOrderPlaneCalls",W],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",ge],["$.arkOrderXiFieldWrites",se],["$.arkOrderIngestWritesXi",me],["$.arkOrderReleaseKeyCounts",ke]])for(let g of S)if(!u.has(g.file))throw new Error(`${v} references missing file ${g.file}.`);let ze=oe(e,"projectPackageName","$"),Wt=(e.classShapes===void 0?[]:M(e,"classShapes","$")).map((v,S)=>{let g=`$.classShapes[${S}]`,R=F(v,g);P(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],g);let x=M(R,"mutatingMethods",g).map((U,de)=>{let m=`${g}.mutatingMethods[${de}]`,q=F(U,m);return P(q,["name","referencesGuardOrPublish"],m),{name:_(q,"name",m),referencesGuardOrPublish:D(q,"referencesGuardOrPublish",m)}});return{file:L(R,"file",g),className:_(R,"className",g),exported:D(R,"exported",g),hasPublicMutableFields:D(R,"hasPublicMutableFields",g),hasPublicSetters:D(R,"hasPublicSetters",g),hasPublicConstructor:D(R,"hasPublicConstructor",g),hasStaticFactory:D(R,"hasStaticFactory",g),mutatingMethods:x,...R.dataOnly===void 0?{}:{dataOnly:D(R,"dataOnly",g)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:_(e,"resolverIdentity","$"),compilerIdentity:_(e,"compilerIdentity","$"),compilerOptionsHash:_(e,"compilerOptionsHash","$"),tsconfigHash:_(e,"tsconfigHash","$"),evidenceRequirementsHash:_(e,"evidenceRequirementsHash","$"),...ze?{projectPackageName:ze}:{},files:o,dependencies:a,capabilityUses:d,ambientUses:l,publishCalls:p,intentReferences:h,safetyUses:A,classShapes:Wt,arkRunKernelCalls:c,arkRunManagedNews:k,arkRunCompositionRootHits:I,arkRunDeclarations:_e,arkOrderPlaneCalls:W,arkOrderGenericUpdates:T,arkOrderRootHits:ge,arkOrderXiFieldWrites:se,arkOrderIngestWritesXi:me,arkOrderReleaseKeyCounts:ke}}i(Zt,"parseResolvedFactsInput");function ye(e){let t=F(e,"$"),n=_(t,"factsHash","$"),r=_(t,"candidateTreeHash","$"),s=Yt(Zt(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}i(ye,"loadResolvedCandidateFacts");var Hr=["network","filesystem","clock","randomness","environment","process","persistence"],w={type:"string",minLength:1},Y={type:"integer",minimum:1},H={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Jt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:w,message:w,file:H}}},resolverIdentity:w,compilerIdentity:w,compilerOptionsHash:w,tsconfigHash:w,candidateTreeHash:w,evidenceRequirementsHash:w,projectPackageName:w,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:H,contentHash:w,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:w},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:H,specifier:w,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Y,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:H,namedBindings:{type:"array",items:w},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:H,line:Y,symbol:w,capability:{enum:Hr},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:H,line:Y,symbol:w}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:H,line:Y,rawIntentName:w,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:w}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:H,line:Y,intent:w}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:H,line:Y,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:w},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:H,className:w,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:w,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:H,line:Y,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:w,viaImport:{type:"boolean"},receiver:w,nameLiteral:w}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:H,line:Y,typeName:w,importedFrom:w}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:H,matchedRoot:w,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:H,line:Y,uses:{type:"array",items:w},reactsTo:{type:"array",items:w},raises:{type:"array",items:w},sends:{type:"array",items:w}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:H,line:Y,callee:w}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:H,line:Y,method:w}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:H,matchedRoot:w,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:H,line:Y,key:w}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:H,line:Y}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:H,line:Y,keyCount:{type:"integer",minimum:1}}}},factsHash:w},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 Qt="1.0";var ut=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ye=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),pt=Object.freeze(Object.keys(Ye).sort()),dt=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"}),ft=Object.freeze({process:Object.freeze(["process","node:process"])});function Fe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=dt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=dt[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:dt[e.slice(0,o)]??null}i(Fe,"capabilityForModuleSpecifier");function Ne(e,t){for(let n of t)if(ft[n]?.includes(e))return n;return null}i(Ne,"forbiddenGlobalForModuleSpecifier");function Pe(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=Ye[r];if(s)return s}return null}i(Pe,"capabilityForAmbientName");function Ie(e){if(e?.pure===!0)return[...ut].sort();let n=(e?.capabilities?.deny??[]).filter(r=>ut.includes(r));return[...new Set(n)].sort()}i(Ie,"effectiveCapabilityDeny");function gt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}i(gt,"ambientCoveredByForbiddenGlobals");function Xe(e){let t=new Set,n=new Set,r=Object.keys(Ye);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(a=>a===s||a.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let a of o)t.add(`ambient:${a}`);for(let a of ft[s]??[])t.add(`import-exact:${a}`)}for(let s of Ie(e)){if(t.add(`import:${s}`),s==="process")for(let o of ft.process)t.add(`import-exact:${o}`);for(let o of r)Pe(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Xe,"loweredLayerCoverage");function Kr(e){let t=new Set,n=Pe(e);n&&t.add(n);for(let[r,s]of Object.entries(Ye))(r===e||r.startsWith(`${e}.`))&&t.add(s);return[...t].sort()}i(Kr,"lowerForbiddenGlobal");var en=new Map;function tn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(tn,"escapeLiteral");function Je(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}i(Je,"normalizeGlobSeparators");function Ur(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(Ur,"bracesBalanced");function ie(e){let t=en.get(e);if(t)return t;let n=Je(e),r=Ur(n),s="",o=0;for(let d=0;d<n.length;d+=1){let l=n[d];l==="\\"&&d+1<n.length?(s+=tn(n[d+1]),d+=1):l==="*"?n[d+1]==="*"?n[d+2]==="/"?(s+="(?:.*/)?",d+=2):(s+=".*",d+=1):s+="[^/]*":l==="?"?s+="[^/]":l==="{"&&r?(s+="(?:",o+=1):l==="}"&&r&&o>0?(s+=")",o-=1):l===","&&r&&o>0?s+="|":s+=tn(l)}let a=new RegExp(`^${s}$`);return en.set(e,a),a}i(ie,"globToRegExp");function jr(e){return Je(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(jr,"concreteGlobSegments");function yt(e,t){let n=Je(String(e)),r=jr(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let d=0,l=-1;for(let p of r){let h=-1;for(let A=d;A<a.length;A+=1)if(a[A]===p){h=A;break}if(h<0)return o;l=h,d=h+1}return(l+1)*1e6+r.length*1e4+s}i(yt,"patternSpecificity");function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(a=>ie(a).test(n))){for(let a of o.patterns??[])if(ie(a).test(n)){let d=yt(a,n);d>s&&(s=d,r=o.name)}}return r}i(Q,"layerForRelativePath");function Ze(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",s=String(e).split(/[/\\]/).filter(Boolean);if(s.length===0)return;let o=new Set;for(let a of t)if(!(typeof a!="string"||a.length===0)){if(sn(a)){let d=Vr(s,a,r);if(d)return d;continue}!a.includes("/")&&!a.includes("\\")&&!a.includes("*")&&o.add(a.toLowerCase())}return Wr(s,o)}i(Ze,"sliceIdForPath");function sn(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}i(sn,"isAnchoredSliceEntry");function Vr(e,t,n){let r=t.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),s=cn(e,r[0]??"");for(let o of s){let a=Gr(e,r,o,n);if(a)return a}}i(Vr,"anchoredSliceId");function Gr(e,t,n,r="path"){let s=[],o=-1,a=n;for(let d=0;d<t.length;d+=1){let l=t[d];if(l==="*"){if(a>=e.length-1){for(let p=d;p<t.length;p+=1)if(t[p]!=="*")return;break}s.push(e[a].toLowerCase()),a+=1;continue}if(l==="**"||a>=e.length||e[a].toLowerCase()!==l)return;s.push(e[a].toLowerCase()),o=s.length-1,a+=1}if(s.length!==0)return r==="stars"?o<0?void 0:s.slice(o).join("/"):s.join("/")}i(Gr,"bindAnchoredSlice");function on(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,s=new Map;for(let o of n.sliceFolders??[]){if(typeof o!="string"||o.length===0)continue;let a=Br(o);if(!a)continue;let d=o.split(/[/\\]/).filter(h=>h.length>0).join("/").toLowerCase(),l=s.get(a)??new Set;if(l.has(d))continue;l.add(d),s.set(a,l);let p=r.get(a)??[];p.push(o),r.set(a,p)}for(let[o,a]of r)a.length<2||t.push({from:n.from,to:n.to,stem:o,paths:a,message:zr(n.from,n.to,a,o)})}return t}i(on,"sliceIdentityCollisions");function Br(e){if(!sn(e))return;let t=e.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),n=-1;for(let s=0;s<t.length;s+=1){let o=t[s]??"";if(o==="**")return;o!=="*"&&(n=s)}if(n<0)return;let r=t.slice(n);if(!r.some((s,o)=>o>0&&s!=="*"))return r.join("/")}i(Br,"starsIdentityStem");function zr(e,t,n,r){let s=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${s}. They bind as ${r}.`}i(zr,"formatSliceIdentityCollision");function Wr(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}i(Wr,"bareSliceId");function qr(e){let t=new Set;for(let n of e??[]){let s=Je(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let a=s[o];if((a==="**"||a==="*")&&o>0){let d=s[o-1];d&&!d.includes("*")&&!d.includes("{")&&!d.includes("}")&&t.add(d)}}}return[...t]}i(qr,"inferSliceFoldersFromPatterns");function an(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 qr(r?.patterns)}i(an,"resolveSliceFolders");function nn(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(nn,"normalizeSegments");function ln(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(ln,"trimTrailingSlashes");var Yr=["src","app"];function cn(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Yr.includes(n)&&r!==n?[0,1]:[0]}i(cn,"anchorOffsets");function Xr(e){let t=ln(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Xr,"isBlanketRoot");function mt(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=nn(n);for(let o of t){if(typeof o!="string"||o.length===0||Xr(o))continue;if(o.includes("*")){let l=ln(o.toLowerCase());if(ie(l).test(r)||ie(`${l}/**`).test(r))return!0;continue}let a=nn(o);if(a.length===0)continue;let d=cn(s,a[0]??"");for(let l of d){if(l+a.length>s.length)continue;let p=!0;for(let h=0;h<a.length;h+=1)if(s[l+h]!==a[h]){p=!1;break}if(p)return!0}}return!1}i(mt,"pathUnderSharedRoot");function rn(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(rn,"sliceMatchesDeclaration");function Zr(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&rn(r.from,t)&&rn(r.to,n))}i(Zr,"crossSliceEdgeAllowed");function Jr(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(Jr,"peerIsolationDecision");function Qe(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(s=>!!s);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}i(Qe,"peerIsolationDenyExplanation");function dn(e,t,n,r){return Le(e,t,n,r)?.rule}i(dn,"findDeniedEdgeRule");function Le(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,a=r?.toPath,d=an(s,t,r?.layers),l=o?Ze(o,d,s.sliceIdentity):void 0,p=a?Ze(a,d,s.sliceIdentity):void 0,h=Jr({fromPath:o,toPath:a,folderCount:d.length,fromSlice:l,toSlice:p,fromShared:!l&&mt(o,s.sharedRoots),toShared:!p&&mt(a,s.sharedRoots),crossSliceAllowed:Zr(s.allowedCrossSlice,l,p),sharedImportsSlice:s.sharedImportsSlice});if(h.denied)return{rule:s,peerIsolationReason:h.reason,fromSlice:l,toSlice:p};continue}if(t!==n)return{rule:s}}}i(Le,"findDeniedEdgeDecision");function un(e,t,n,r){let s=r?.fromPath,o=r?.toPath;if(!(!s||!o))for(let a of e??[]){if(a.from!==t||a.to!==n||a.allowed!==!1||!a.peerIsolation||a.sharedImportsSlice==="deny")continue;let d=an(a,t,r?.layers),l=Ze(s,d,a.sliceIdentity),p=Ze(o,d,a.sliceIdentity);if(!(l||!p)&&mt(s,a.sharedRoots))return{fromPath:s,toPath:o,toSlice:p}}}i(un,"findSharedImportsSliceBridge");var ht={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."},Rt=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 At(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}i(At,"resolveIntentLayer");function fn(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(fn,"looksLikeArkIntent");function kt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&fn(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ht.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ht.PUBLISH_MISSING_SOURCE}),t}i(kt,"classifyPublishFacts");var pn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Qr=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var gn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},xa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:pn,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:pn},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:[...Qr]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:gn,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:gn}}}};function De(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(De,"emptyEffectiveArkRules");function mn(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}i(mn,"structureFreezeTarget");var es=["no-anemic-model"],kn=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Na=new RegExp(`\\b(${kn.join("|")})\\b`),bn="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Pa=new RegExp(`\\bthis\\.${bn}\\.push\\s*\\(`),La=new RegExp(`^this\\.${bn}\\s*=\\s*\\[\\s*\\]`);var ts="truncatedUntil";function ns(){return`${kn.join(", ")}, or events-array .push(`}i(ns,"expectedDomainInvariantWordsPhrase");function bt(e){let t=Object.getOwnPropertyDescriptor(e,ts)?.value;return typeof t=="number"?t:void 0}i(bt,"shapeTruncatedUntil");function rs(e){let t=bt(e);return t==null?"":` shape analysed until character ${t}`}i(rs,"shapeTruncationSuffix");function yn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(yn,"escapeGlobLiteral");function ss(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=yn(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=yn(s)}return new RegExp(`^${n}$`)}i(ss,"globToRegExp");function Ee(e,t){return!t||t.length===0?!0:t.some(n=>ss(n).test(e))}i(Ee,"matchesAppliesTo");function vn(e){return es.includes(e)}i(vn,"isTier2");function In(e){return e.mode==="enforced"&&!vn(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(In,"severityFor");function ue(e,t,n,r=1){let{severity:s,failsStrict:o}=In(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:o}}i(ue,"baseViolation");function et(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(et,"isInRuleLayer");function tt(e,t,n){return t.filter(r=>!(!r.exported||!Ee(r.file,e.appliesTo)||!et(r.file,e,n)))}i(tt,"shapesForRule");function os(e,t,n){let r=[];for(let s of tt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(ue(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(os,"evaluateAggregatePrivateState");function as(e,t,n){let r=[];for(let s of tt(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(ue(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(as,"evaluateAlwaysValidFactory");function is(e,t,n){let r=[],s=ns();for(let o of tt(e,t,n)){let a=rs(o);bt(o)!=null&&r.push(ue(e,o.file,`Exported class ${o.className} shape analysed until character ${bt(o)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let d of o.mutatingMethods)d.referencesGuardOrPublish||r.push(ue(e,o.file,`Mutating method ${o.className}.${d.name} does not reference ${s} (sensor domain-event-on-mutation).${a}`))}return r}i(is,"evaluateDomainEventOnMutation");function ls(e,t){let n=[];for(let r of t.files)Ee(r,e.appliesTo)&&et(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(ue(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(ls,"evaluateOrchestrationOnly");function cs(e,t){let n=[];for(let r of t.files)Ee(r,e.appliesTo)&&et(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(ue(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(cs,"evaluateThinAdapter");function ds(e,t){let n=[];for(let r of t.files)Ee(r,e.appliesTo)&&et(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(ue(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(ds,"evaluateWritesViaAggregate");function us(e,t,n){let r=[];for(let s of tt(e,t,n))if(s.dataOnly===!0){let o=ue(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}i(us,"evaluateNoAnemicModel");function En(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...os(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...as(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...is(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...ls(n,e));break;case"thin-adapter":t.push(...cs(n,e));break;case"writes-via-aggregate":t.push(...ds(n,e));break;case"no-anemic-model":t.push(...us(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(En,"evaluateArkRuleSensors");function Sn(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>Ee(l,s.appliesTo)))continue;let{severity:a,failsStrict:d}=In(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a,sensor:s.sensor,failsStrict:d})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(d=>Ee(d,s.appliesTo)))continue;let a=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((s,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}i(Sn,"collectEmptyAppliesToFindings");var hn=64;function fs(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}i(fs,"stripTrailingDots");function ps(e){let t=e.trim(),n=t.length>hn?t.slice(0,hn):t;return fs(n)}i(ps,"normalizeIntentPrefix");function gs(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}i(gs,"layerNameLooksDomain");function ms(e){return e.some(t=>{let n=ps(t);return n==="Domain"||n.startsWith("Domain.")})}i(ms,"ownsDomainIntent");function ys(e,t=[]){return gs(e)||ms(t)}i(ys,"isDomainRoleLayerName");function Cn(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(l=>ys(l.name,l.intentPrefixes??[])).map(l=>l.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(l=>{let p=typeof l.layer=="string"?l.layer:"";return p.length>0&&n.has(p)}))return[];if((e.arkRules.invariants??[]).filter(l=>n.has(l.provenance.layer)).length>0)return[];let o=t.find(l=>e.arkRules.byLayer?.[l])??t[0],a=e.arkRules.byLayer?.[o]?.sourceFile??`arkrules/${o}.json`,d=(e.arkRules.structure??[]).some(l=>l.mode==="enforced"&&n.has(l.provenance.layer)&&!vn(l.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${o} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${a}.`,file:a,line:1,fromLayer:o,arkruleId:"invariant-catalog",arkruleSource:a,severity:d?"error":"warning",sensor:"invariant-coverage",failsStrict:d}]}i(Cn,"collectEmptyInvariantCatalogFindings");var Rn=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,An=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,hs=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function Rs(e){return e==="PersistenceAdapters"}i(Rs,"isPersistenceDriverLayer");function As(e,t){if(Rn.test(e)||An.test(e))return!0;if(!t)return!1;for(let n of t){if(Rs(n.layer))return!0;let r=n.specifier;if(!r)continue;let s=`from '${r}'`;if(Rn.test(s)||An.test(s))return!0}return!1}i(As,"sourceImportsPersistenceDriver");var ks=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,bs=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,vs=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Is=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Es(e,t,n){if(!t)return null;let r=As(t,n),s=r&&hs.test(t);if(t.length<40)return s?{persistenceWrite:!0}:null;let o=t.match(new RegExp(vs.source,"g"))??[],a=t.match(new RegExp(Is.source,"g"))??[],d=(t.match(/\bif\s*\(/g)??[]).length,l=(t.match(/\bswitch\s*\(/g)??[]).length,p=o.length>=2||o.length>=1&&a.length>=2||a.length>=3&&d+l>=6,h=ks.test(t)||bs.test(t),A=o.length>=1||a.length>=2,u=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),f=r&&A||h&&A||r&&u&&(d>=4||o.length>=1)||h&&r;return!p&&!f&&!s?null:{...p?{orchestrationHeavy:!0}:{},...f?{adapterThick:!0}:{},...s?{persistenceWrite:!0}:{}}}i(Es,"deriveArkRuleFileHints");function wn(e,t){let n={};for(let[r,s]of Object.entries(e)){let o=r.replace(/\\/g,"/"),a=Es(r,s,t?.[o]);a&&(n[o]=a)}return n}i(wn,"buildArkRuleFileHints");var Ss="INVARIANT_TESTS_PATH_MISSING",Cs="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",ws="INVARIANT_COVERAGE_ROOTS_MISSING",Os="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function On(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let s=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${s}.`}i(On,"formatCoverageDiscards");function $n(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let s=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return s===""||s==="."?!0:n===s||n.startsWith(`${s}/`)})}i($n,"isUnderCoverageRoot");function It(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(It,"escapeRegExp");function Se(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(Se,"normalizePath");function Et(e,t){let n=[],r=0,s=e.length;for(;r<s;){let o=e[r],a=e[r+1];if(o==="/"&&a==="/"){for(;r<s&&e[r]!==`
|
|
4
|
-
`;)n.push(" "),r+=1;continue}if(o==="/"&&
|
|
3
|
+
var fs=Object.defineProperty;var a=(e,t)=>fs(e,"name",{value:t,configurable:!0});function V(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")}`}a(V,"deterministicHash");function F(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(F).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${F(t[n])}`).join(",")}}`}a(F,"stableSerialize");var Ie="1.2";var pn=["network","filesystem","clock","randomness","environment","process","persistence"];function K(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}a(K,"compareCanonical");function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(B,"sortedUnique");function st(e){let t={schemaVersion:"1.2",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(K),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:B(e.arkRun.compositionRoots),managedLayers:B(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return V(F(t))}a(st,"resolvedFactsEvidenceRequirementsHash");function ps(e){let t=e.completenessReasons.map(b=>({code:b.code,message:b.message,...b.file?{file:b.file}:{}})).sort(K),n=e.files.map(b=>({...b,typeOnlyExportNames:B(b.typeOnlyExportNames)})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),r=e.dependencies.map(b=>({...b,...b.namedBindings?{namedBindings:B(b.namedBindings)}:{}})).sort(K),s=e.capabilityUses.map(b=>({...b})).sort(K),o=e.ambientUses.map(b=>({...b})).sort(K),i=e.publishCalls.map(b=>({...b})).sort(K),l=e.intentReferences.map(b=>({...b})).sort(K),c=e.safetyUses.map(b=>({...b})).sort(K),f=(e.classShapes??[]).map(b=>({...b,mutatingMethods:[...b.mutatingMethods??[]].map(T=>({...T}))})).sort(K),h=(e.arkRunKernelCalls??[]).map(b=>({...b})).sort(K),R=(e.arkRunManagedNews??[]).map(b=>({...b})).sort(K),u=(e.arkRunCompositionRootHits??[]).map(b=>({...b})).sort(K),p=(e.arkRunDeclarations??[]).map(b=>({...b,uses:B(b.uses),reactsTo:B(b.reactsTo),raises:B(b.raises),sends:B(b.sends)})).sort(K),d=(e.arkOrderPlaneCalls??[]).map(b=>({...b})).sort(K),g=(e.arkOrderGenericUpdates??[]).map(b=>({...b})).sort(K),k=(e.arkOrderRootHits??[]).map(b=>({...b})).sort(K),I=(e.arkOrderXiFieldWrites??[]).map(b=>({...b})).sort(K),S=(e.arkOrderIngestWritesXi??[]).map(b=>({...b})).sort(K),x=(e.arkOrderReleaseKeyCounts??[]).map(b=>({...b})).sort(K),$=e.files.map(({path:b,contentHash:T})=>({path:b,contentHash:T})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),q=V(F($));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:q,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:f,arkRunKernelCalls:h,arkRunManagedNews:R,arkRunCompositionRootHits:u,arkRunDeclarations:p,arkOrderPlaneCalls:d,arkOrderGenericUpdates:g,arkOrderRootHits:k,arkOrderXiFieldWrites:I,arkOrderIngestWritesXi:S,arkOrderReleaseKeyCounts:x}}a(ps,"canonicalResolvedFactsInput");function gn(e){let t=ps(e);return{...t,factsHash:V(F(t))}}a(gn,"createCanonicalResolvedCandidateFacts");function ot(e){return gn(hn(L(e,"$"),!1))}a(ot,"createResolvedCandidateFacts");function L(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(L,"asRecord");function N(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}a(N,"assertOnlyKeys");function _(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}a(_,"requiredText");function ae(e,t,n){if(e[t]!==void 0)return _(e,t,n)}a(ae,"optionalText");function D(e,t,n){let r=_(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let o=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(l);let i=o.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(D,"requiredProjectPath");function M(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(M,"requiredBoolean");function mn(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)}a(mn,"requiredInteger");function z(e,t,n){let r=mn(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(z,"requiredPositiveInteger");function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(H,"requiredArray");function le(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}a(le,"enumValue");function Ee(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]}a(Ee,"parseStringArray");function gs(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}a(gs,"assertUnique");function hn(e,t){N(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=le(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=le(e,"completeness",["complete","partial","unavailable"],"$"),s=H(e,"completenessReasons","$").map((v,C)=>{let m=`$.completenessReasons[${C}]`,A=L(v,m);N(A,["code","message","file"],m);let O=A.file===void 0?void 0:D(A,"file",m);return{code:_(A,"code",m),message:_(A,"message",m),...O?{file:O}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=H(e,"files","$").map((v,C)=>{let m=`$.files[${C}]`,A=L(v,m);return N(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],m),{path:D(A,"path",m),contentHash:_(A,"contentHash",m),parseStatus:le(A,"parseStatus",["parsed","invalid"],m),parseDiagnosticCount:mn(A,"parseDiagnosticCount",m),exportsOnlyTypes:M(A,"exportsOnlyTypes",m),typeOnlyExportNames:Ee(A.typeOnlyExportNames,`${m}.typeOnlyExportNames`),hasTopLevelSideEffects:M(A,"hasTopLevelSideEffects",m)}}),i=H(e,"dependencies","$").map((v,C)=>{let m=`$.dependencies[${C}]`,A=L(v,m);N(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],m);let O=ae(A,"specifier",m),j=ae(A,"target",m),ue=le(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],m);if(ue==="resolved-project"&&!j)throw new Error(`${m}.target is required for resolved-project dependencies.`);if(ue!=="resolved-project"&&j)throw new Error(`${m}.target is only allowed for resolved-project dependencies.`);if(ue!=="dynamic"&&!O)throw new Error(`${m}.specifier is required unless resolution is dynamic.`);return{from:D(A,"from",m),...O?{specifier:O}:{},kind:le(A,"kind",["import","export","dynamic-import","require"],m),typeOnly:M(A,"typeOnly",m),line:z(A,"line",m),resolution:ue,...j?{target:D(A,"target",m)}:{},...A.namedBindings!==void 0?{namedBindings:Ee(A.namedBindings,`${m}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:M(A,"targetTypeOnlyExports",m)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:M(A,"sourcePureTypeModule",m)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:M(A,"namedBindingsTypeOnly",m)}:{},...A.portProofEligible!==void 0?{portProofEligible:M(A,"portProofEligible",m)}:{}}}),l=H(e,"capabilityUses","$").map((v,C)=>{let m=`$.capabilityUses[${C}]`,A=L(v,m);return N(A,["file","line","symbol","capability","source"],m),{file:D(A,"file",m),line:z(A,"line",m),symbol:_(A,"symbol",m),capability:le(A,"capability",pn,m),source:le(A,"source",["ambient-global","import-based"],m)}}),c=H(e,"ambientUses","$").map((v,C)=>{let m=`$.ambientUses[${C}]`,A=L(v,m);return N(A,["file","line","symbol"],m),{file:D(A,"file",m),line:z(A,"line",m),symbol:_(A,"symbol",m)}}),f=H(e,"publishCalls","$").map((v,C)=>{let m=`$.publishCalls[${C}]`,A=L(v,m);N(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],m);let O=ae(A,"rawIntentName",m),j=ae(A,"sourceIntent",m);return{file:D(A,"file",m),line:z(A,"line",m),...O?{rawIntentName:O}:{},objectHasIntent:M(A,"objectHasIntent",m),arkPublishCandidate:M(A,"arkPublishCandidate",m),hasSource:M(A,"hasSource",m),...j?{sourceIntent:j}:{}}}),h=H(e,"intentReferences","$").map((v,C)=>{let m=`$.intentReferences[${C}]`,A=L(v,m);return N(A,["file","line","intent"],m),{file:D(A,"file",m),line:z(A,"line",m),intent:_(A,"intent",m)}}),R=H(e,"safetyUses","$").map((v,C)=>{let m=`$.safetyUses[${C}]`,A=L(v,m);N(A,["file","line","kind","symbol"],m);let O=ae(A,"symbol",m),j=le(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],m);if(j==="in-memory-store"&&!O)throw new Error(`${m}.symbol is required for in-memory-store facts.`);if(j!=="in-memory-store"&&O)throw new Error(`${m}.symbol is only allowed for in-memory-store facts.`);return{file:D(A,"file",m),line:z(A,"line",m),kind:j,...O?{symbol:O}:{}}});gs(o,v=>v.path,"$.files");let u=new Set(o.map(v=>v.path));for(let v of o){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of i)if(!u.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:H(e,"arkRunKernelCalls","$")).map((v,C)=>{let m=`$.arkRunKernelCalls[${C}]`,A=L(v,m);N(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],m);let O=ae(A,"receiver",m),j=ae(A,"nameLiteral",m);return{file:D(A,"file",m),line:z(A,"line",m),kind:le(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],m),callee:_(A,"callee",m),viaImport:M(A,"viaImport",m),...O?{receiver:O}:{},...j?{nameLiteral:j}:{}}}),k=(e.arkRunManagedNews===void 0?[]:H(e,"arkRunManagedNews","$")).map((v,C)=>{let m=`$.arkRunManagedNews[${C}]`,A=L(v,m);N(A,["file","line","typeName","importedFrom"],m);let O=ae(A,"importedFrom",m);return{file:D(A,"file",m),line:z(A,"line",m),typeName:_(A,"typeName",m),...O?{importedFrom:O}:{}}}),S=(e.arkRunCompositionRootHits===void 0?[]:H(e,"arkRunCompositionRootHits","$")).map((v,C)=>{let m=`$.arkRunCompositionRootHits[${C}]`,A=L(v,m);return N(A,["file","matchedRoot","hasKernelFactory"],m),{file:D(A,"file",m),matchedRoot:_(A,"matchedRoot",m),hasKernelFactory:M(A,"hasKernelFactory",m)}}),x=e.arkRunDeclarations===void 0?[]:H(e,"arkRunDeclarations","$"),q=(e.arkOrderPlaneCalls===void 0?[]:H(e,"arkOrderPlaneCalls","$")).map((v,C)=>{let m=`$.arkOrderPlaneCalls[${C}]`,A=L(v,m);return N(A,["file","line","callee"],m),{file:D(A,"file",m),line:z(A,"line",m),callee:_(A,"callee",m)}}),T=(e.arkOrderGenericUpdates===void 0?[]:H(e,"arkOrderGenericUpdates","$")).map((v,C)=>{let m=`$.arkOrderGenericUpdates[${C}]`,A=L(v,m);return N(A,["file","line","method"],m),{file:D(A,"file",m),line:z(A,"line",m),method:_(A,"method",m)}}),me=(e.arkOrderRootHits===void 0?[]:H(e,"arkOrderRootHits","$")).map((v,C)=>{let m=`$.arkOrderRootHits[${C}]`,A=L(v,m);return N(A,["file","matchedRoot","hasPlaneFactory"],m),{file:D(A,"file",m),matchedRoot:_(A,"matchedRoot",m),hasPlaneFactory:M(A,"hasPlaneFactory",m)}}),ie=(e.arkOrderXiFieldWrites===void 0?[]:H(e,"arkOrderXiFieldWrites","$")).map((v,C)=>{let m=`$.arkOrderXiFieldWrites[${C}]`,A=L(v,m);return N(A,["file","line","key"],m),{file:D(A,"file",m),line:z(A,"line",m),key:_(A,"key",m)}}),he=(e.arkOrderIngestWritesXi===void 0?[]:H(e,"arkOrderIngestWritesXi","$")).map((v,C)=>{let m=`$.arkOrderIngestWritesXi[${C}]`,A=L(v,m);return N(A,["file","line"],m),{file:D(A,"file",m),line:z(A,"line",m)}}),Se=(e.arkOrderReleaseKeyCounts===void 0?[]:H(e,"arkOrderReleaseKeyCounts","$")).map((v,C)=>{let m=`$.arkOrderReleaseKeyCounts[${C}]`,A=L(v,m);return N(A,["file","line","keyCount"],m),{file:D(A,"file",m),line:z(A,"line",m),keyCount:z(A,"keyCount",m)}}),De=x.map((v,C)=>{let m=`$.arkRunDeclarations[${C}]`,A=L(v,m);return N(A,["file","line","uses","reactsTo","raises","sends"],m),{file:D(A,"file",m),line:z(A,"line",m),uses:Ee(A.uses,`${m}.uses`),reactsTo:Ee(A.reactsTo,`${m}.reactsTo`),raises:Ee(A.raises,`${m}.raises`),sends:Ee(A.sends,`${m}.sends`)}});for(let[v,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",f],["$.intentReferences",h],["$.safetyUses",R],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",k],["$.arkRunCompositionRootHits",S],["$.arkRunDeclarations",De],["$.arkOrderPlaneCalls",q],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",me],["$.arkOrderXiFieldWrites",ie],["$.arkOrderIngestWritesXi",he],["$.arkOrderReleaseKeyCounts",Se]])for(let m of C)if(!u.has(m.file))throw new Error(`${v} references missing file ${m.file}.`);let rt=ae(e,"projectPackageName","$"),fn=(e.classShapes===void 0?[]:H(e,"classShapes","$")).map((v,C)=>{let m=`$.classShapes[${C}]`,A=L(v,m);N(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],m);let O=H(A,"mutatingMethods",m).map((j,ue)=>{let y=`${m}.mutatingMethods[${ue}]`,Y=L(j,y);return N(Y,["name","referencesGuardOrPublish"],y),{name:_(Y,"name",y),referencesGuardOrPublish:M(Y,"referencesGuardOrPublish",y)}});return{file:D(A,"file",m),className:_(A,"className",m),exported:M(A,"exported",m),hasPublicMutableFields:M(A,"hasPublicMutableFields",m),hasPublicSetters:M(A,"hasPublicSetters",m),hasPublicConstructor:M(A,"hasPublicConstructor",m),hasStaticFactory:M(A,"hasStaticFactory",m),mutatingMethods:O,...A.dataOnly===void 0?{}:{dataOnly:M(A,"dataOnly",m)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:_(e,"resolverIdentity","$"),compilerIdentity:_(e,"compilerIdentity","$"),compilerOptionsHash:_(e,"compilerOptionsHash","$"),tsconfigHash:_(e,"tsconfigHash","$"),evidenceRequirementsHash:_(e,"evidenceRequirementsHash","$"),...rt?{projectPackageName:rt}:{},files:o,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:f,intentReferences:h,safetyUses:R,classShapes:fn,arkRunKernelCalls:d,arkRunManagedNews:k,arkRunCompositionRootHits:S,arkRunDeclarations:De,arkOrderPlaneCalls:q,arkOrderGenericUpdates:T,arkOrderRootHits:me,arkOrderXiFieldWrites:ie,arkOrderIngestWritesXi:he,arkOrderReleaseKeyCounts:Se}}a(hn,"parseResolvedFactsInput");function ye(e){let t=L(e,"$"),n=_(t,"factsHash","$"),r=_(t,"candidateTreeHash","$"),s=gn(hn(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}a(ye,"loadResolvedCandidateFacts");var ms=["network","filesystem","clock","randomness","environment","process","persistence"],w={type:"string",minLength:1},X={type:"integer",minimum:1},U={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},yn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:w,message:w,file:U}}},resolverIdentity:w,compilerIdentity:w,compilerOptionsHash:w,tsconfigHash:w,candidateTreeHash:w,evidenceRequirementsHash:w,projectPackageName:w,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:U,contentHash:w,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:w},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:U,specifier:w,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:X,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:U,namedBindings:{type:"array",items:w},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:U,line:X,symbol:w,capability:{enum:ms},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:U,line:X,symbol:w}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:U,line:X,rawIntentName:w,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:w}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:U,line:X,intent:w}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:U,line:X,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:w},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:U,className:w,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:w,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:U,line:X,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:w,viaImport:{type:"boolean"},receiver:w,nameLiteral:w}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:U,line:X,typeName:w,importedFrom:w}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:U,matchedRoot:w,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:U,line:X,uses:{type:"array",items:w},reactsTo:{type:"array",items:w},raises:{type:"array",items:w},sends:{type:"array",items:w}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:U,line:X,callee:w}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:U,line:X,method:w}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:U,matchedRoot:w,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:U,line:X,key:w}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:U,line:X}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:U,line:X,keyCount:{type:"integer",minimum:1}}}},factsHash:w},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 Rn="1.0";var It=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),it=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ct=Object.freeze(Object.keys(it).sort()),St=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"}),Et=Object.freeze({process:Object.freeze(["process","node:process"])});function Ue(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=St[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=St[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:St[e.slice(0,o)]??null}a(Ue,"capabilityForModuleSpecifier");function Ke(e,t){for(let n of t)if(Et[n]?.includes(e))return n;return null}a(Ke,"forbiddenGlobalForModuleSpecifier");function je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=it[r];if(s)return s}return null}a(je,"capabilityForAmbientName");function Ce(e){if(e?.pure===!0)return[...It].sort();let n=(e?.capabilities?.deny??[]).filter(r=>It.includes(r));return[...new Set(n)].sort()}a(Ce,"effectiveCapabilityDeny");function wt(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}a(wt,"ambientCoveredByForbiddenGlobals");function at(e){let t=new Set,n=new Set,r=Object.keys(it);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(i=>i===s||i.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let i of o)t.add(`ambient:${i}`);for(let i of Et[s]??[])t.add(`import-exact:${i}`)}for(let s of Ce(e)){if(t.add(`import:${s}`),s==="process")for(let o of Et.process)t.add(`import-exact:${o}`);for(let o of r)je(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(at,"loweredLayerCoverage");function hs(e){let t=new Set,n=je(e);n&&t.add(n);for(let[r,s]of Object.entries(it))(r===e||r.startsWith(`${e}.`))&&t.add(s);return[...t].sort()}a(hs,"lowerForbiddenGlobal");var An="4.8.22",kn=new Map;function bn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(bn,"escapeLiteral");function dt(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}a(dt,"normalizeGlobSeparators");function ys(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}a(ys,"bracesBalanced");function oe(e){let t=kn.get(e);if(t)return t;let n=dt(e),r=ys(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=bn(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=bn(c)}let i=new RegExp(`^${s}$`);return kn.set(e,i),i}a(oe,"globToRegExp");function Rs(e){return dt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Rs,"concreteGlobSegments");function Ot(e,t){let n=dt(String(e)),r=Rs(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let l=0,c=-1;for(let f of r){let h=-1;for(let R=l;R<i.length;R+=1)if(i[R]===f){h=R;break}if(h<0)return o;c=h,l=h+1}return(c+1)*1e6+r.length*1e4+s}a(Ot,"patternSpecificity");function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(i=>oe(i).test(n))){for(let i of o.patterns??[])if(oe(i).test(n)){let l=Ot(i,n);l>s&&(s=l,r=o.name)}}return r}a(Q,"layerForRelativePath");function _t(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",s=String(e).split(/[/\\]/).filter(Boolean);if(s.length===0)return;let o=new Set;for(let i of t)if(!(typeof i!="string"||i.length===0)){if(En(i)){let l=As(s,i,r);if(l)return l;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&o.add(i.toLowerCase())}return Ss(s,o)}a(_t,"sliceIdForPath");function En(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(En,"isAnchoredSliceEntry");function As(e,t,n){let r=t.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),s=wn(e,r[0]??"");for(let o of s){let i=ks(e,r,o,n);if(i)return i}}a(As,"anchoredSliceId");function ks(e,t,n,r="path"){let s=[],o=-1,i=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(i>=e.length-1){for(let f=l;f<t.length;f+=1)if(t[f]!=="*")return;break}s.push(e[i].toLowerCase()),i+=1;continue}if(c==="**"||i>=e.length||e[i].toLowerCase()!==c)return;s.push(e[i].toLowerCase()),o=s.length-1,i+=1}if(s.length!==0)return r==="stars"?o<0?void 0:s.slice(o).join("/"):s.join("/")}a(ks,"bindAnchoredSlice");function Cn(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,s=new Map;for(let o of n.sliceFolders??[]){if(typeof o!="string"||o.length===0)continue;let i=bs(o);if(!i)continue;let l=o.split(/[/\\]/).filter(h=>h.length>0).join("/").toLowerCase(),c=s.get(i)??new Set;if(c.has(l))continue;c.add(l),s.set(i,c);let f=r.get(i)??[];f.push(o),r.set(i,f)}for(let[o,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:o,paths:i,message:vs(n.from,n.to,i,o)})}return t}a(Cn,"sliceIdentityCollisions");function bs(e){if(!En(e))return;let t=e.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),n=-1;for(let s=0;s<t.length;s+=1){let o=t[s]??"";if(o==="**")return;o!=="*"&&(n=s)}if(n<0)return;let r=t.slice(n);if(!r.some((s,o)=>o>0&&s!=="*"))return r.join("/")}a(bs,"starsIdentityStem");function vs(e,t,n,r){let s=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${s}. They bind as ${r}.`}a(vs,"formatSliceIdentityCollision");function Ss(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}a(Ss,"bareSliceId");function Is(e){let t=new Set;for(let n of e??[]){let s=dt(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let i=s[o];if((i==="**"||i==="*")&&o>0){let l=s[o-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(Is,"inferSliceFoldersFromPatterns");function $t(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 Is(r?.patterns)}a($t,"resolveSliceFolders");function vn(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(vn,"normalizeSegments");function Be(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Be,"trimTrailingSlashes");var Es=["src","app"];function wn(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Es.includes(n)&&r!==n?[0,1]:[0]}a(wn,"anchorOffsets");function Cs(e){let t=Be(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Cs,"isBlanketRoot");function Ve(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=vn(n);for(let o of t){if(typeof o!="string"||o.length===0||Cs(o))continue;if(o.includes("*")){let c=Be(o.toLowerCase());if(oe(c).test(r)||oe(`${c}/**`).test(r))return!0;continue}let i=vn(o);if(i.length===0)continue;let l=wn(s,i[0]??"");for(let c of l){if(c+i.length>s.length)continue;let f=!0;for(let h=0;h<i.length;h+=1)if(s[c+h]!==i[h]){f=!1;break}if(f)return!0}}return!1}a(Ve,"pathUnderSharedRoot");function Sn(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(Sn,"sliceMatchesDeclaration");function ws(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Sn(r.from,t)&&Sn(r.to,n))}a(ws,"crossSliceEdgeAllowed");function xs(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(xs,"peerIsolationDecision");function xn(e){return Be(e.trim().replace(/\\/g,"/")).toLowerCase()}a(xn,"aliasGlobPattern");function Os(e,t){let n=xn(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),s=xt(r),o=oe(n);return o.test(r)||s!==r&&o.test(s)}a(Os,"aliasGlobMatches");function _s(e){let t=xn(e).split("/").filter(Boolean);return t.length<2||t.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:t.slice(0,-1).join("/"),childId:t.join("/")}}a(_s,"splitAliasTarget");function $s(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Os(n.from,e))return _s(n.to);return null}a($s,"firstSliceAlias");function we(e,t,n){if(!e)return{};let r=n??t.sliceFolders,s=_t(e,r?[...r]:void 0,t.sliceIdentity),o=lt(e,s,t.childSlices);if(s||o.childId||o.mismatched)return o.childId?{universeId:s,childId:o.childId}:{universeId:s};let i=$s(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(we,"resolveGovernedSlice");function Ts(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(s=>!!s);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(Ts,"peerIsolationDenyExplanation");function Ls(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Ls,"crossParentExplanation");function Fs(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(Fs,"crossSiblingExplanation");function Ns(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(Ns,"parentImportsChildExplanation");function Ge(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(Ge,"universePairLabel");function Ps(e){return String(e).split(/[/\\]/).filter(Boolean).slice(0,-1)}a(Ps,"directorySegments");function Ds(e,t){if(!t?.length)return!1;let n=new Set;for(let r of t)typeof r=="string"&&r.length>0&&n.add(r.toLowerCase());return n.size===0?!1:Ps(e).some(r=>n.has(r.toLowerCase()))}a(Ds,"pathHasCommonFolder");function lt(e,t,n){if(!e||!n?.sliceFolders?.length)return{};if(Ds(e,n.commonFolders))return{};let r=_t(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let s=r.toLowerCase(),o=t.toLowerCase();return s===o?{}:s.startsWith(`${o}/`)?{childId:r}:{mismatched:{childId:r,universeId:t}}}a(lt,"resolveChildSliceId");function Ms(e){return Be(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ms,"siblingEntryKey");function xt(e){return e.replace(/^(?:src|app)\//,"")}a(xt,"stripSrcOrApp");function Hs(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=xt(t);if(!r)return!1;let s=xt(n);return n===r||n.startsWith(`${r}/`)||s===r||s.startsWith(`${r}/`)}a(Hs,"pathUnderSubtree");function Us(e,t,n){if(!t||!n?.length)return!1;let r=t.toLowerCase();for(let s of n){if(typeof s!="string")continue;let o=Ms(s);if(!(!o||o.includes("*"))&&(r===o||e&&Hs(e,o)))return!0}return!1}a(Us,"importerInEnforcedSubtree");function Ks(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!Us(t,n,e.enforce)}a(Ks,"siblingCrossingAdvisory");function ct(e){if(typeof e!="string")return null;let t=Be(e.trim().replace(/\\/g,"/")).toLowerCase();if(!t.includes("/"))return null;let n=t.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(ct,"childSlicePatternSegments");function In(e,t){let n=ct(e),r=ct(t);if(!n||!r||n.length!==r.length)return!1;for(let s=0;s<n.length;s+=1){let o=n[s];if(o!=="*"&&o!==r[s])return!1}return!0}a(In,"childSlicePatternMatches");function js(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&In(r.from,t)&&In(r.to,n))return!0;return!1}a(js,"childCrossSliceAllowed");function Vs(e,t){let n=ct(e),r=ct(t);if(!n||!r)return!1;let s=n.slice(0,-1),o=r.slice(0,-1);if(s.length!==o.length)return!0;for(let i=0;i<s.length;i+=1){let l=s[i],c=o[i];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(Vs,"childAllowanceSpansUniverses");function Gs(e){let t=xs({fromPath:e.fromPath,toPath:e.toPath,folderCount:e.folderCount,fromSlice:e.fromSlice,toSlice:e.toSlice,fromShared:e.fromShared,toShared:e.toShared,crossSliceAllowed:e.crossSliceAllowed,sharedImportsSlice:e.rule.sharedImportsSlice});if(t.denied){let i=!!e.rule.childSlices&&t.reason==="cross-slice";return{crossing:t.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...i?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:i?Ls(e.fromSlice,e.toSlice):Ts(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??lt(e.fromPath,e.fromSlice,n).childId,s=e.toChild??lt(e.toPath,e.toSlice,n).childId,o={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&s&&r!==s?js(n.allowedCrossSlice,r,s)?o:{crossing:"cross-sibling",decision:Ks(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:Fs(r,s,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&s&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:Ns(s),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:o}a(Gs,"evaluateNestedSliceWall");function ut(e){let t=e.verdict.explanation;if(e.surface==="intent"){let n=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return e.verdict.reasonId&&t?`${n} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${n} ${t}`:e.ruleMessage?t?`${e.ruleMessage} (${t})`:e.ruleMessage:n}if(e.ruleMessage)return t?`${e.ruleMessage} (${t})`:e.ruleMessage;if(t){let n=e.kind??"import";return`${e.fromLayer} must not ${n} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(ut,"composeSliceDenialMessage");function ft(e){if(!e||e.decision==="allow")return{};let t=Ge(e.fromUniverse),n=Ge(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(ft,"sliceFindingExtras");function On(e,t){let n=[],r=!1,s=new Set,o=new Set;for(let i of e??[])if(i?.childSlices&&(r||(r=!0,n.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,message:`childSlices needs an arkgate newer than ${An}. Version ${An} and older reject the key because the rule schema sets additionalProperties: false.`})),!!i.peerIsolation)){for(let l of t){let c=_t(l,i.sliceFolders,i.sliceIdentity),f=lt(l,c,i.childSlices);if(!f.mismatched)continue;let h=`${i.from}\0${i.to}\0${f.mismatched.universeId}\0${f.mismatched.childId}`;s.has(h)||(s.add(h),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:i.from,toLayer:i.to,path:l,message:`${i.from} \u2192 ${i.to}: child id ${f.mismatched.childId} does not extend universe id ${f.mismatched.universeId} (${l}).`}))}for(let l of i.childSlices.allowedCrossSlice??[]){if(!l||typeof l.from!="string"||typeof l.to!="string"||!Vs(l.from,l.to))continue;let c=`${l.from.trim().toLowerCase()}\0${l.to.trim().toLowerCase()}`;o.has(c)||(o.add(c),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`childSlices.allowedCrossSlice ${l.from} \u2192 ${l.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(On,"childSliceConfigFindings");function _n(e,t,n,r){return We(e,t,n,r)?.rule}a(_n,"findDeniedEdgeRule");function We(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,i=r?.toPath,l=$t(s,t,r?.layers),c=we(o,s,l),f=we(i,s,l),h=c.universeId,R=f.universeId,u=Gs({rule:s,fromPath:o,toPath:i,folderCount:l.length,fromSlice:h,toSlice:R,fromChild:c.childId,toChild:f.childId,fromShared:!h&&Ve(o,s.sharedRoots),toShared:!R&&Ve(i,s.sharedRoots),crossSliceAllowed:ws(s.allowedCrossSlice,h,R)});if(u.decision!=="allow")return{rule:s,peerIsolationReason:u.peerIsolationReason,fromSlice:h,toSlice:R,sliceVerdict:u};continue}if(t!==n)return{rule:s}}}a(We,"findDeniedEdgeDecision");function $n(e,t,n,r){let s=r?.fromPath,o=r?.toPath;if(!(!s||!o))for(let i of e??[]){if(i.from!==t||i.to!==n||i.allowed!==!1||!i.peerIsolation||i.sharedImportsSlice==="deny")continue;let l=$t(i,t,r?.layers),c=we(s,i,l).universeId,f=we(o,i,l).universeId;if(!(c||!f)&&Ve(s,i.sharedRoots))return{fromPath:s,toPath:o,toSlice:f}}}a($n,"findSharedImportsSliceBridge");function Tn(e,t,n){return $t(e,t,n)}a(Tn,"peerSliceFolders");var Tt={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."},Lt=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 Ft(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}a(Ft,"resolveIntentLayer");function Ln(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(Ln,"looksLikeArkIntent");function Nt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ln(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Tt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Tt.PUBLISH_MISSING_SOURCE}),t}a(Nt,"classifyPublishFacts");var Fn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Bs=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Nn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ja={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Fn,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:Fn},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:[...Bs]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Nn,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:Nn}}}};function ze(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(ze,"emptyEffectiveArkRules");function Pn(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}a(Pn,"structureFreezeTarget");var Ws=["no-anemic-model"],Kn=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],nl=new RegExp(`\\b(${Kn.join("|")})\\b`),jn="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",rl=new RegExp(`\\bthis\\.${jn}\\.push\\s*\\(`),sl=new RegExp(`^this\\.${jn}\\s*=\\s*\\[\\s*\\]`);var zs="truncatedUntil";function qs(){return`${Kn.join(", ")}, or events-array .push(`}a(qs,"expectedDomainInvariantWordsPhrase");function Pt(e){let t=Object.getOwnPropertyDescriptor(e,zs)?.value;return typeof t=="number"?t:void 0}a(Pt,"shapeTruncatedUntil");function Ys(e){let t=Pt(e);return t==null?"":` shape analysed until character ${t}`}a(Ys,"shapeTruncationSuffix");function Dn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Dn,"escapeGlobLiteral");function Xs(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Dn(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Dn(s)}return new RegExp(`^${n}$`)}a(Xs,"globToRegExp");function xe(e,t){return!t||t.length===0?!0:t.some(n=>Xs(n).test(e))}a(xe,"matchesAppliesTo");function Vn(e){return Ws.includes(e)}a(Vn,"isTier2");function Gn(e){return e.mode==="enforced"&&!Vn(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Gn,"severityFor");function fe(e,t,n,r=1){let{severity:s,failsStrict:o}=Gn(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:o}}a(fe,"baseViolation");function pt(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(pt,"isInRuleLayer");function gt(e,t,n){return t.filter(r=>!(!r.exported||!xe(r.file,e.appliesTo)||!pt(r.file,e,n)))}a(gt,"shapesForRule");function Js(e,t,n){let r=[];for(let s of gt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(fe(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(Js,"evaluateAggregatePrivateState");function Zs(e,t,n){let r=[];for(let s of gt(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(fe(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(Zs,"evaluateAlwaysValidFactory");function Qs(e,t,n){let r=[],s=qs();for(let o of gt(e,t,n)){let i=Ys(o);Pt(o)!=null&&r.push(fe(e,o.file,`Exported class ${o.className} shape analysed until character ${Pt(o)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of o.mutatingMethods)l.referencesGuardOrPublish||r.push(fe(e,o.file,`Mutating method ${o.className}.${l.name} does not reference ${s} (sensor domain-event-on-mutation).${i}`))}return r}a(Qs,"evaluateDomainEventOnMutation");function eo(e,t){let n=[];for(let r of t.files)xe(r,e.appliesTo)&&pt(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(fe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(eo,"evaluateOrchestrationOnly");function to(e,t){let n=[];for(let r of t.files)xe(r,e.appliesTo)&&pt(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(fe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(to,"evaluateThinAdapter");function no(e,t){let n=[];for(let r of t.files)xe(r,e.appliesTo)&&pt(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(fe(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}a(no,"evaluateWritesViaAggregate");function ro(e,t,n){let r=[];for(let s of gt(e,t,n))if(s.dataOnly===!0){let o=fe(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}a(ro,"evaluateNoAnemicModel");function Bn(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Js(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Zs(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Qs(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...eo(n,e));break;case"thin-adapter":t.push(...to(n,e));break;case"writes-via-aggregate":t.push(...no(n,e));break;case"no-anemic-model":t.push(...ro(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}a(Bn,"evaluateArkRuleSensors");function Wn(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(c=>xe(c,s.appliesTo)))continue;let{severity:i,failsStrict:l}=Gn(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i,sensor:s.sensor,failsStrict:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>xe(l,s.appliesTo)))continue;let i=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((s,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}a(Wn,"collectEmptyAppliesToFindings");var Mn=64;function so(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}a(so,"stripTrailingDots");function oo(e){let t=e.trim(),n=t.length>Mn?t.slice(0,Mn):t;return so(n)}a(oo,"normalizeIntentPrefix");function io(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(io,"layerNameLooksDomain");function ao(e){return e.some(t=>{let n=oo(t);return n==="Domain"||n.startsWith("Domain.")})}a(ao,"ownsDomainIntent");function lo(e,t=[]){return io(e)||ao(t)}a(lo,"isDomainRoleLayerName");function zn(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>lo(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let f=typeof c.layer=="string"?c.layer:"";return f.length>0&&n.has(f)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let o=t.find(c=>e.arkRules.byLayer?.[c])??t[0],i=e.arkRules.byLayer?.[o]?.sourceFile??`arkrules/${o}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!Vn(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${o} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${i}.`,file:i,line:1,fromLayer:o,arkruleId:"invariant-catalog",arkruleSource:i,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}a(zn,"collectEmptyInvariantCatalogFindings");var Hn=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,Un=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,co=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function uo(e){return e==="PersistenceAdapters"}a(uo,"isPersistenceDriverLayer");function fo(e,t){if(Hn.test(e)||Un.test(e))return!0;if(!t)return!1;for(let n of t){if(uo(n.layer))return!0;let r=n.specifier;if(!r)continue;let s=`from '${r}'`;if(Hn.test(s)||Un.test(s))return!0}return!1}a(fo,"sourceImportsPersistenceDriver");var po=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,go=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,mo=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,ho=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function yo(e,t,n){if(!t)return null;let r=fo(t,n),s=r&&co.test(t);if(t.length<40)return s?{persistenceWrite:!0}:null;let o=t.match(new RegExp(mo.source,"g"))??[],i=t.match(new RegExp(ho.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,f=o.length>=2||o.length>=1&&i.length>=2||i.length>=3&&l+c>=6,h=po.test(t)||go.test(t),R=o.length>=1||i.length>=2,u=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),p=r&&R||h&&R||r&&u&&(l>=4||o.length>=1)||h&&r;return!f&&!p&&!s?null:{...f?{orchestrationHeavy:!0}:{},...p?{adapterThick:!0}:{},...s?{persistenceWrite:!0}:{}}}a(yo,"deriveArkRuleFileHints");function qn(e,t){let n={};for(let[r,s]of Object.entries(e)){let o=r.replace(/\\/g,"/"),i=yo(r,s,t?.[o]);i&&(n[o]=i)}return n}a(qn,"buildArkRuleFileHints");var Ro="INVARIANT_TESTS_PATH_MISSING",Ao="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",ko="INVARIANT_COVERAGE_ROOTS_MISSING",bo="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Yn(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let s=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${s}.`}a(Yn,"formatCoverageDiscards");function Zn(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let s=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return s===""||s==="."?!0:n===s||n.startsWith(`${s}/`)})}a(Zn,"isUnderCoverageRoot");function Mt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Mt,"escapeRegExp");function Oe(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Oe,"normalizePath");function Ht(e,t){let n=[],r=0,s=e.length;for(;r<s;){let o=e[r],i=e[r+1];if(o==="/"&&i==="/"){for(;r<s&&e[r]!==`
|
|
4
|
+
`;)n.push(" "),r+=1;continue}if(o==="/"&&i==="*"){for(n.push(" "," "),r+=2;r<s&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
|
|
5
5
|
`?`
|
|
6
|
-
`:" "),r+=1;r<s&&(n.push(" "," "),r+=2);continue}if(o==='"'||o==="'"||o==="`"){let
|
|
7
|
-
`?" ":
|
|
6
|
+
`:" "),r+=1;r<s&&(n.push(" "," "),r+=2);continue}if(o==='"'||o==="'"||o==="`"){let l=o;for(n.push(t?" ":o),r+=1;r<s;){let c=e[r];if(c==="\\"){let f=e[r+1];t?n.push(" ",f===void 0?"":" "):(n.push("\\"),f!==void 0&&n.push(f)),r+=f===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
|
|
7
|
+
`?" ":c),r+=1}continue}n.push(o),r+=1}return n.join("")}a(Ht,"maskNonCode");function vo(e,t){if(!t)return;let n=Mt(t),o=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(Ht(e,!1))?.[2];return o===void 0?void 0:o}a(vo,"matchTestTitle");function So(e,t){if(!t)return;let n=Mt(t),r=Ht(e,!0),s=[{shape:"function",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:declare\\s+)?(?:async\\s+)?function\\s*\\*?\\s*${n}\\s*[(<]`},{shape:"class",source:`(?:^|[\\s;{}])(?:export\\s+(?:default\\s+)?)?(?:abstract\\s+)?class\\s+${n}\\b`},{shape:"const",source:`(?:^|[\\s;{}])export\\s+(?:const|let|var)\\s+${n}(?:\\s*:(?:[^=]|=>)+?)?\\s*=(?!>)`},{shape:"type",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?type\\s+${n}\\b`},{shape:"interface",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?interface\\s+${n}\\b`},{shape:"enum",source:`(?:^|[\\s;{}])(?:export\\s+)?(?:declare\\s+)?(?:const\\s+)?enum\\s+${n}\\b`},{shape:"method",source:`(?:^|[\\n;{}])\\s*(?:(?:public|private|protected|static|async|readonly|override|abstract|get|set|declare)\\s+)*${n}\\s*(?:<[^>\\n]*>)?\\s*\\([^;{}]*\\)\\s*(?::\\s*[^;{]+)?\\s*\\{`}];for(let o of s)if(new RegExp(o.source).test(r))return o.shape}a(So,"declarationShape");function Io(e,t){let n=e.lastIndexOf(`
|
|
8
8
|
`,t-1)+1,r=e.indexOf(`
|
|
9
|
-
`,t);return e.slice(n,r===-1?e.length:r)}
|
|
10
|
-
`;)a(s,"comment"),s+=1;continue}if(d==="/"&&l==="*"){for(a(s,"comment"),a(s+1,"comment"),s+=2;s<o&&!(e[s]==="*"&&e[s+1]==="/");)a(s,"comment"),s+=1;s<o&&(a(s,"comment"),a(s+1,"comment"),s+=2);continue}if(d==='"'||d==="'"||d==="`"){let p=d;for(a(s,"string"),s+=1;s<o;){let h=e[s];if(h==="\\"){a(s,"string"),e[s+1]!==void 0&&a(s+1,"string"),s+=e[s+1]===void 0?1:2;continue}if(h===p){a(s,"string"),s+=1;break}a(s,"string"),s+=1}continue}a(s,"code"),s+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}i(xn,"mentionContext");function Tn(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}i(Tn,"symbolNeedle");function Fs(e){return Tn(e.coverage?.symbol)?.name??e.id}i(Fs,"declaredLabel");function _n(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}i(_n,"sortedContentFiles");function Ns(e,t,n=!0){let r=t.testFiles??[],s=new Set(r.map(f=>Se(f))),o=(t.coverageRoots??[]).filter(f=>typeof f=="string"&&f.length>0),a=e.coverage?.test!==!1&&n,d=Tn(e.coverage?.symbol??void 0),l,p;if(a){for(let f of r){let c=t.fileContents[f];if(!c)continue;let y=xs(c,e.id);if(y!==void 0){if(o.length===0||$n(f,o)){l={file:f,title:y};break}p??={file:f,title:y}}}l??=p}let h;if(d)for(let f of _n(t.fileContents)){if(s.has(Se(f)))continue;let c=t.fileContents[f];if(!c||d.className&&!c.includes(d.className))continue;let y=_s(c,d.name);if(y){h={file:f,shape:y};break}}let A;if(!l&&!h){if(a)for(let f of r){let c=t.fileContents[f];if(!c)continue;let y=xn(c,e.id,!0);if(y){A={file:f,context:y};break}}if(!A&&d)for(let f of _n(t.fileContents)){if(s.has(Se(f)))continue;let c=t.fileContents[f];if(!c)continue;let y=xn(c,d.name,!1);if(y){A={file:f,context:y};break}}}let u=l?{kind:"test-title",file:l.file,title:l.title}:h?{kind:"declaration",file:h.file,shape:h.shape}:A?{kind:"mention-only",file:A.file,context:A.context}:{kind:"none"};return u.kind==="mention-only"&&u.context==="comment"&&d&&Ps(t.fileContents,s,d.name,u.file)&&(u={kind:"declaration-miss",symbol:d.name}),{best:u,...l?{testTitle:l}:{},...h?{declaration:h}:{}}}i(Ns,"rankCoverage");function Ps(e,t,n,r){let s=new RegExp(`(?:^|[^A-Za-z0-9_$])${It(n)}(?=$|[^A-Za-z0-9_$])`),o=Se(r);for(let a of Object.keys(e)){if(t.has(Se(a))||Se(a)===o)continue;let d=e[a];if(d&&s.test(Et(d,!0)))return!0}return!1}i(Ps,"symbolInCodeElsewhere");function Ls(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}i(Ls,"countsAsCoverage");function Ds(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}i(Ds,"mentionWhere");function Ms(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${Fs(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${Ds(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}i(Ms,"describeCoverage");function Fn(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=e.coverageBudgetExhausted===!0,o=e.coverageStats,a=On(o),d=On(o,!0),l=o?`coverage file budget exhausted: ${o.filesLoaded} files loaded at the ${o.maxFiles}-file cap, ${o.testFilesRetained} tests retained, ${o.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof o.filesRead=="number"?`; ${o.filesRead} were read`:""})`:"coverage file budget exhausted",p=(e.coverageRoots??[]).filter(c=>typeof c=="string"&&c.length>0),h=p.length>0,A=p.join(", "),u=[],f=[];for(let c of t){let y=c.coverage?.test!==!1,k=c.coverage?.symbol,E=!r&&y,I=Ns(c,{fileContents:e.fileContents,testFiles:n,coverageRoots:p},E),O=I.best,$=[];E&&I.testTitle&&$.push("test-title"),I.declaration&&$.push("symbol");let W=Ls(O),b,T;E&&I.testTitle&&(b=I.testTitle.file,h&&(T=!$n(b,p)));let Oe=I.declaration?.file,ge=I.declaration?.shape,se=(c.coverage?.test===!0||!!k||c.coverage===void 0)&&W||c.coverage?.test===!1&&!k?!0:W,re=r&&y&&!W;if(u.push({invariantId:c.id,layer:c.provenance.layer,sourceFile:c.provenance.sourceFile,mode:c.mode,covered:se&&!re,evidence:$,partial:re,description:c.description,...b!==void 0?{testEvidenceFile:b}:{},...Oe!==void 0?{symbolEvidenceFile:Oe}:{},...ge!==void 0?{shape:ge}:{},...T!==void 0?{outsideDeclaredRoots:T}:{},coverageRootsDeclared:h}),T===!0&&b!==void 0&&f.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${c.id} is covered only by ${b}, which is outside the declared coverage roots (${A}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:b,line:1,arkruleId:c.id,arkruleSource:c.provenance.sourceFile,fromLayer:c.provenance.layer,severity:"warning",failsStrict:!1}),!se||re){let me=c.mode==="enforced"&&!re,xe=r||n.length===0?"never-had-tests":"tests-disappeared";f.push({ruleId:"INVARIANT_UNCOVERED",message:(re?s?`Invariant ${c.id} coverage cannot be proven (${l}); reporting partial, not covered.`:`Invariant ${c.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${c.id}: ${Ms(c,O)} (${xe==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(re&&s?d:a),file:c.provenance.sourceFile,line:1,arkruleId:c.id,arkruleSource:c.provenance.sourceFile,fromLayer:c.provenance.layer,severity:me?"error":"warning",failsStrict:me,kind:xe})}}return{coverage:u,violations:f,partial:u.some(c=>c.partial)}}i(Fn,"evaluateInvariantCoverage");function Nn(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(Nn,"canPromoteInvariant");function vt(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}i(vt,"nonEmptyPathStrings");function Hs(e){return!e||typeof e!="object"?[]:[...vt(e.testGlobs),...vt(e.coverageRoots)]}i(Hs,"configuredInvariantTestsPaths");function Ks(e){return Hs(e).length>0}i(Ks,"hasConfiguredInvariantTestsPath");function St(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(St,"catalogDemandsInvariantTestsPath");function Pn(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&St(e.invariants);return e.adopted!==!0||!t?[]:Ks(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Ss,message:Cs,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}i(Pn,"collectMissingInvariantTestsPathFindings");function Us(e){return!e||typeof e!="object"?[]:vt(e.coverageRoots)}i(Us,"configuredCoverageRoots");function js(e){return Us(e).length>0}i(js,"hasConfiguredCoverageRoots");function Ct(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(Ct,"catalogHasEnforcedInvariant");function Ln(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Ct(e.invariants)?js(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:ws,message:Os,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}i(Ln,"collectMissingCoverageRootsFindings");function Vs(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(Vs,"normalizeExtraMergeTeethClassification");function nt(e){let t=Vs(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(nt,"extraMergeTeethAllowed");function Dn(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(Dn,"classifyResolvedLayerCoverage");var Gs=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Va=new Set(Gs);function Mn(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Mn,"isArkRunKernelModuleSpecifier");var Bs=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],wt=new Set(Bs);function Hn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(wt.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(wt.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:wt.has(e.slice(0,r))}i(Hn,"isArkRunTransportBypassSpecifier");var zs=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ws=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,qs=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Ys(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return zs.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ws.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":qs.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(Ys,"classifyLayerImportKind");function Xs(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=Ys(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(Xs,"layerImportNextAction");function Zs(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Zs,"arkRunCallSiteName");function Js(e){let t=Zs(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(Js,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Xs(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Js(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(fe,"deterministicNextAction");var Qs=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],ti=new Set(Qs);var Kn={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},eo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Vn(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(Vn,"isDomainRoleLayer");function to(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(to,"compareFindings");function le(e,t,n,r,s,o,a){let d=e.mode==="enforced"&&a;return{ruleId:Kn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:d?"error":"warning",failsStrict:d,nextAction:fe({ruleId:Kn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(le,"finding");function no(e,t){let n=[],r=[],s=[],o=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),s.push(...a.raises),o.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}i(no,"bagForFile");function Un(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(Un,"emitKinds");function jn(e){return e==="subscribe"||e==="register-handler"}i(jn,"handleKinds");function ro(e){return e==="resolve"||e==="resolve-singleton"}i(ro,"dependKinds");function so(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(le(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let a of t){let d=o.get(a.matchedRoot)??[];d.push(a),o.set(a.matchedRoot,d)}for(let a of s){let d=[...o.get(a)??[]].sort((p,h)=>p.file.localeCompare(h.file));if(d.length===0){r.push(le(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(d.some(p=>p.hasKernelFactory))continue;let l=d[0];r.push(le(e,"arkrun-missing-root",l.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(so,"evaluateMissingRoot");function oo(e,t,n,r,s){let o=new Map(t.map(d=>[d.name,d.intentPrefixes??[]])),a=[];for(let d of n){let l=d.specifier;if(!l||!Mn(l))continue;let p=r(d.from);p&&Vn(p,o.get(p)??[])&&a.push(le(e,"arkrun-kernel-in-domain",d.from,d.line,`${p} must not import kernel module ${JSON.stringify(l)}.`,{fromLayer:p,target:l},s))}return a}i(oo,"evaluateKernelInDomain");function ao(e,t,n,r,s,o){let a=new Set(e.managedLayers);if(a.size===0)return[];let d=new Map(t.map(h=>[h.name,h.intentPrefixes??[]])),l=new Set(r.filter(h=>h.hasKernelFactory).map(h=>h.file)),p=[];for(let h of n){if(l.has(h.file))continue;let A=h.typeName;if(e.ignoreDirectNewForErrors!==!1&&(A.endsWith("Error")||A==="Error")||A.endsWith("DTO")||A.endsWith("VO"))continue;let u=s(h.file);!u||!a.has(u)||Vn(u,d.get(u)??[])||p.push(le(e,"arkrun-direct-new",h.file,h.line,`${u} must not construct ${h.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:h.typeName},o))}return p}i(ao,"evaluateDirectNew");function io(e,t,n,r,s){let o=[],a=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:a};let d=new Set(e.managedLayers);if(d.size===0)return{findings:o,completenessReasons:a};for(let l of t){if(!Un(l.kind)&&!jn(l.kind)&&!ro(l.kind))continue;let p=r(l.file);if(!p||!d.has(p))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:eo,file:l.file,message:`ArkRun ${l.kind} call in ${l.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let h=no(n,l.file);if(Un(l.kind)){if(h.raises.has(l.nameLiteral)||h.sends.has(l.nameLiteral))continue;o.push(le(e,"arkrun-undeclared-emit",l.file,l.line,`Emit ${JSON.stringify(l.nameLiteral)} is not declared in raises or sends.`,{fromLayer:p,target:l.nameLiteral},s));continue}if(jn(l.kind)){if(h.reactsTo.has(l.nameLiteral))continue;o.push(le(e,"arkrun-undeclared-handle",l.file,l.line,`Handle ${JSON.stringify(l.nameLiteral)} is not declared in reactsTo.`,{fromLayer:p,target:l.nameLiteral},s));continue}h.uses.has(l.nameLiteral)||o.push(le(e,"arkrun-undeclared-depend",l.file,l.line,`Depend ${JSON.stringify(l.nameLiteral)} is not declared in uses.`,{fromLayer:p,target:l.nameLiteral},s))}return{findings:o,completenessReasons:a}}i(io,"evaluateUndeclared");function lo(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let a of t){if(a.typeOnly)continue;let d=a.specifier;if(!d||!Hn(d))continue;let l=n(a.from);!l||!s.has(l)||o.push(le(e,"arkrun-transport-bypass",a.from,a.line,`${l} must not import broker/queue/emitter ${JSON.stringify(d)}; use the ArkRun kernel transport.`,{fromLayer:l,target:d},r))}return o}i(lo,"evaluateTransportBypass");function Gn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=nt(e.classification),r=io(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...so(t,e.compositionRootHits,n),...oo(t,e.layers,e.dependencies,e.layerForFile,n),...ao(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...lo(t,e.dependencies,e.layerForFile,n)].sort(to),o=[...r.completenessReasons].sort((a,d)=>{let l=`${a.code}\0${a.file??""}\0${a.message}`,p=`${d.code}\0${d.file??""}\0${d.message}`;return l<p?-1:l>p?1:0});return{findings:s,completenessReasons:o}}i(Gn,"evaluateArkRunSensors");function Bn(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(Bn,"isArkOrderModuleSpecifier");var zn=new Map;function Wn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Wn,"escapeAppliesToLiteral");function co(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}i(co,"normalizeAppliesToGlob");function uo(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(uo,"appliesToBracesBalanced");function fo(e){let t=zn.get(e);if(t)return t;let n=co(e),r=uo(n),s="",o=0;for(let d=0;d<n.length;d+=1){let l=n[d];l==="\\"&&d+1<n.length?(s+=Wn(n[d+1]),d+=1):l==="*"?n[d+1]==="*"?n[d+2]==="/"?(s+="(?:.*/)?",d+=2):(s+=".*",d+=1):s+="[^/]*":l==="?"?s+="[^/]":l==="{"&&r?(s+="(?:",o+=1):l==="}"&&r&&o>0?(s+=")",o-=1):l===","&&r&&o>0?s+="|":s+=Wn(l)}let a=new RegExp(`^${s}$`);return zn.set(e,a),a}i(fo,"globToRegExp");var qn={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function po(e,t){return!t||t.length===0?!0:t.some(n=>fo(n).test(e))}i(po,"matchesArkOrderAppliesTo");function go(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}i(go,"isDomainRoleLayer");function pe(e,t,n,r,s,o,a){let d=e.mode==="enforced"&&a;return{ruleId:qn[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:d?"error":"warning",failsStrict:d,nextAction:fe({ruleId:qn[t],fromLayer:o?.fromLayer,target:o?.target})}}i(pe,"finding");function Yn(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=nt(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(pe(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let l=new Map;for(let p of e.planeRootHits){let h=l.get(p.matchedRoot)??[];h.push(p),l.set(p.matchedRoot,h)}for(let p of s){let h=l.get(p)??[];if(h.length===0){r.push(pe(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(p)} matched no governed files and has no createOrderPlane factory.`,{target:p},n));continue}h.some(A=>A.hasPlaneFactory)||r.push(pe(t,"arkorder-missing-plane",h[0].file,1,`ArkOrder plane root ${JSON.stringify(p)} has no createOrderPlane factory.`,{target:p},n))}}let o=new Map(e.layers.map(l=>[l.name,l.intentPrefixes??[]]));for(let l of e.dependencies){let p=l.specifier;if(!p||!Bn(p))continue;let h=e.layerForFile(l.from);h&&go(h,o.get(h)??[])&&r.push(pe(t,"arkorder-kernel-in-domain",l.from,l.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:h,target:p},n))}for(let l of e.genericUpdates)r.push(pe(t,"arkorder-generic-update",l.file,l.line,`Generic ${l.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:l.method},n));let a=t.xiKeys??[];for(let l of e.releaseKeyCounts??[])l.keyCount<=t.maxXiKeys||r.push(pe(t,"arkorder-too-many-params",l.file,l.line,`release() freezes ${l.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(l.keyCount)},n));for(let l of e.ingestWritesXi??[])r.push(pe(t,"arkorder-ingest-writes-xi",l.file,l.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let d=new Set(t.managedLayers);for(let l of a.length===0?[]:e.xiFieldWrites??[]){let p=e.layerForFile(l.file);!p||!d.has(p)||po(l.file,t.appliesTo)&&r.push(pe(t,"arkorder-xi-field-write",l.file,l.line,`This file writes ${JSON.stringify(l.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:p,target:l.key},n))}return r.sort((l,p)=>l.file.localeCompare(p.file)||l.ruleId.localeCompare(p.ruleId)||l.line-p.line),{findings:r,completenessReasons:[]}}i(Yn,"evaluateArkOrderSensors");var he={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Xn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...he,default:[]},kernelRoots:{...he},managedLayers:{...he,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Zn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...he,default:[]},managedLayers:{...he,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...he,default:[]},appliesTo:{...he,default:[]}}};function Me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Me,"isObject");function Jn(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)Me(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Jn,"declaredLayerNames");function Qn(e){if(!Me(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}i(Qn,"defaultedArkRun");function er(e){if(!Me(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}i(er,"defaultedArkOrder");function tr(e,t){let n=e.arkRun;if(n===void 0||!Me(n))return;let r=Jn(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(tr,"validateArkRunExtra");function nr(e,t){let n=e.arkOrder;if(n===void 0||!Me(n))return;let r=Jn(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,a)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}i(nr,"validateArkOrderExtra");function rt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(rt,"normalizeStewardId");function rr(e){let t=rt(e);return!t||Ot(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(rr,"isGitHubHandle");function mo(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Ot(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(mo,"isGitHubEmail");function yo(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&rr(t[1])?rt(t[1]):null}i(yo,"githubHandleFromEmail");function sr(e){let t=yo(e);if(t)return t;let n=rt(e);return!n||Ot(n)?null:rr(n)||mo(n)?n:null}i(sr,"canonicalStewardId");var ho=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Ot(e){let t=rt(e);return!t||ho.test(t)}i(Ot,"isAutomationAuthor");var te="1.3",Ro=["public","auth","admin","internal"];function Ao(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(Ao,"isFutureHouseLayer");function ko(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}i(ko,"layerOwnersList");function ir(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ao(t)&&!ko(t)).map(t=>t.name)}i(ir,"layersMissingRequiredOwners");function lr(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}i(lr,"missingLayerOwnersNextAction");var xt="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",or=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],bo=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function vo(){let e=[];for(let t of or)for(let n of or)t===n||bo.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(vo,"createDefaultRules");var cr=vo(),_t=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],X={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ar={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xt,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:xt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:te,default:te},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:cr,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}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...X,default:[]},requireLayerOwners:{type:"boolean"}},$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},trustBoundary:{type:"string",enum:[...Ro]},owners:{...X,minItems: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"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...X,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...X,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...X,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...X,minItems:1}}},arkRun:Xn,arkOrder:Zn}},ce=class extends Error{static{i(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
9
|
+
`,t);return e.slice(n,r===-1?e.length:r)}a(Io,"lineAt");function Eo(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(Eo,"isImportLine");function Xn(e,t,n){if(!t||!e.includes(t))return;let r=new Set,s=0,o=e.length,i=a((l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(Eo(Io(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;s<o;){let l=e[s],c=e[s+1];if(l==="/"&&c==="/"){for(;s<o&&e[s]!==`
|
|
10
|
+
`;)i(s,"comment"),s+=1;continue}if(l==="/"&&c==="*"){for(i(s,"comment"),i(s+1,"comment"),s+=2;s<o&&!(e[s]==="*"&&e[s+1]==="/");)i(s,"comment"),s+=1;s<o&&(i(s,"comment"),i(s+1,"comment"),s+=2);continue}if(l==='"'||l==="'"||l==="`"){let f=l;for(i(s,"string"),s+=1;s<o;){let h=e[s];if(h==="\\"){i(s,"string"),e[s+1]!==void 0&&i(s+1,"string"),s+=e[s+1]===void 0?1:2;continue}if(h===f){i(s,"string"),s+=1;break}i(s,"string"),s+=1}continue}i(s,"code"),s+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(Xn,"mentionContext");function Qn(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}a(Qn,"symbolNeedle");function Co(e){return Qn(e.coverage?.symbol)?.name??e.id}a(Co,"declaredLabel");function Jn(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Jn,"sortedContentFiles");function wo(e,t,n=!0){let r=t.testFiles??[],s=new Set(r.map(p=>Oe(p))),o=(t.coverageRoots??[]).filter(p=>typeof p=="string"&&p.length>0),i=e.coverage?.test!==!1&&n,l=Qn(e.coverage?.symbol??void 0),c,f;if(i){for(let p of r){let d=t.fileContents[p];if(!d)continue;let g=vo(d,e.id);if(g!==void 0){if(o.length===0||Zn(p,o)){c={file:p,title:g};break}f??={file:p,title:g}}}c??=f}let h;if(l)for(let p of Jn(t.fileContents)){if(s.has(Oe(p)))continue;let d=t.fileContents[p];if(!d||l.className&&!d.includes(l.className))continue;let g=So(d,l.name);if(g){h={file:p,shape:g};break}}let R;if(!c&&!h){if(i)for(let p of r){let d=t.fileContents[p];if(!d)continue;let g=Xn(d,e.id,!0);if(g){R={file:p,context:g};break}}if(!R&&l)for(let p of Jn(t.fileContents)){if(s.has(Oe(p)))continue;let d=t.fileContents[p];if(!d)continue;let g=Xn(d,l.name,!1);if(g){R={file:p,context:g};break}}}let u=c?{kind:"test-title",file:c.file,title:c.title}:h?{kind:"declaration",file:h.file,shape:h.shape}:R?{kind:"mention-only",file:R.file,context:R.context}:{kind:"none"};return u.kind==="mention-only"&&u.context==="comment"&&l&&xo(t.fileContents,s,l.name,u.file)&&(u={kind:"declaration-miss",symbol:l.name}),{best:u,...c?{testTitle:c}:{},...h?{declaration:h}:{}}}a(wo,"rankCoverage");function xo(e,t,n,r){let s=new RegExp(`(?:^|[^A-Za-z0-9_$])${Mt(n)}(?=$|[^A-Za-z0-9_$])`),o=Oe(r);for(let i of Object.keys(e)){if(t.has(Oe(i))||Oe(i)===o)continue;let l=e[i];if(l&&s.test(Ht(l,!0)))return!0}return!1}a(xo,"symbolInCodeElsewhere");function Oo(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Oo,"countsAsCoverage");function _o(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}a(_o,"mentionWhere");function $o(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${Co(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${_o(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}a($o,"describeCoverage");function er(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=e.coverageBudgetExhausted===!0,o=e.coverageStats,i=Yn(o),l=Yn(o,!0),c=o?`coverage file budget exhausted: ${o.filesLoaded} files loaded at the ${o.maxFiles}-file cap, ${o.testFilesRetained} tests retained, ${o.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof o.filesRead=="number"?`; ${o.filesRead} were read`:""})`:"coverage file budget exhausted",f=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),h=f.length>0,R=f.join(", "),u=[],p=[];for(let d of t){let g=d.coverage?.test!==!1,k=d.coverage?.symbol,I=!r&&g,S=wo(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:f},I),x=S.best,$=[];I&&S.testTitle&&$.push("test-title"),S.declaration&&$.push("symbol");let q=Oo(x),b,T;I&&S.testTitle&&(b=S.testTitle.file,h&&(T=!Zn(b,f)));let Ne=S.declaration?.file,me=S.declaration?.shape,ie=(d.coverage?.test===!0||!!k||d.coverage===void 0)&&q||d.coverage?.test===!1&&!k?!0:q,se=r&&g&&!q;if(u.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:ie&&!se,evidence:$,partial:se,description:d.description,...b!==void 0?{testEvidenceFile:b}:{},...Ne!==void 0?{symbolEvidenceFile:Ne}:{},...me!==void 0?{shape:me}:{},...T!==void 0?{outsideDeclaredRoots:T}:{},coverageRootsDeclared:h}),T===!0&&b!==void 0&&p.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${b}, which is outside the declared coverage roots (${R}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:b,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!ie||se){let he=d.mode==="enforced"&&!se,Pe=r||n.length===0?"never-had-tests":"tests-disappeared";p.push({ruleId:"INVARIANT_UNCOVERED",message:(se?s?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${$o(d,x)} (${Pe==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(se&&s?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:he?"error":"warning",failsStrict:he,kind:Pe})}}return{coverage:u,violations:p,partial:u.some(d=>d.partial)}}a(er,"evaluateInvariantCoverage");function tr(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a(tr,"canPromoteInvariant");function Dt(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}a(Dt,"nonEmptyPathStrings");function To(e){return!e||typeof e!="object"?[]:[...Dt(e.testGlobs),...Dt(e.coverageRoots)]}a(To,"configuredInvariantTestsPaths");function Lo(e){return To(e).length>0}a(Lo,"hasConfiguredInvariantTestsPath");function Ut(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Ut,"catalogDemandsInvariantTestsPath");function nr(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Ut(e.invariants);return e.adopted!==!0||!t?[]:Lo(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Ro,message:Ao,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(nr,"collectMissingInvariantTestsPathFindings");function Fo(e){return!e||typeof e!="object"?[]:Dt(e.coverageRoots)}a(Fo,"configuredCoverageRoots");function No(e){return Fo(e).length>0}a(No,"hasConfiguredCoverageRoots");function Kt(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Kt,"catalogHasEnforcedInvariant");function rr(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Kt(e.invariants)?No(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:ko,message:bo,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(rr,"collectMissingCoverageRootsFindings");function Po(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}a(Po,"normalizeExtraMergeTeethClassification");function mt(e){let t=Po(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}a(mt,"extraMergeTeethAllowed");function sr(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(sr,"classifyResolvedLayerCoverage");var Do=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var ul=new Set(Do);function or(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(or,"isArkRunKernelModuleSpecifier");var Mo=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],jt=new Set(Mo);function ir(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(jt.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(jt.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:jt.has(e.slice(0,r))}a(ir,"isArkRunTransportBypassSpecifier");var Ho=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Uo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ko=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function jo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Ho.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Uo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Ko.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}a(jo,"classifyLayerImportKind");function Vo(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=jo(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}a(Vo,"layerImportNextAction");function Go(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Go,"arkRunCallSiteName");function Bo(e){let t=Go(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(Bo,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Vo(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Bo(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(pe,"deterministicNextAction");var Wo=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Sl=new Set(Wo);var ar={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},zo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function dr(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}a(dr,"isDomainRoleLayer");function qo(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(qo,"compareFindings");function ce(e,t,n,r,s,o,i){let l=e.mode==="enforced"&&i;return{ruleId:ar[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:ar[t],fromLayer:o?.fromLayer,target:o?.target})}}a(ce,"finding");function Yo(e,t){let n=[],r=[],s=[],o=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),s.push(...i.raises),o.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}a(Yo,"bagForFile");function lr(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(lr,"emitKinds");function cr(e){return e==="subscribe"||e==="register-handler"}a(cr,"handleKinds");function Xo(e){return e==="resolve"||e==="resolve-singleton"}a(Xo,"dependKinds");function Jo(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(ce(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let i of t){let l=o.get(i.matchedRoot)??[];l.push(i),o.set(i.matchedRoot,l)}for(let i of s){let l=[...o.get(i)??[]].sort((f,h)=>f.file.localeCompare(h.file));if(l.length===0){r.push(ce(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(f=>f.hasKernelFactory))continue;let c=l[0];r.push(ce(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(Jo,"evaluateMissingRoot");function Zo(e,t,n,r,s){let o=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!or(c))continue;let f=r(l.from);f&&dr(f,o.get(f)??[])&&i.push(ce(e,"arkrun-kernel-in-domain",l.from,l.line,`${f} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:f,target:c},s))}return i}a(Zo,"evaluateKernelInDomain");function Qo(e,t,n,r,s,o){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(h=>[h.name,h.intentPrefixes??[]])),c=new Set(r.filter(h=>h.hasKernelFactory).map(h=>h.file)),f=[];for(let h of n){if(c.has(h.file))continue;let R=h.typeName;if(e.ignoreDirectNewForErrors!==!1&&(R.endsWith("Error")||R==="Error")||R.endsWith("DTO")||R.endsWith("VO"))continue;let u=s(h.file);!u||!i.has(u)||dr(u,l.get(u)??[])||f.push(ce(e,"arkrun-direct-new",h.file,h.line,`${u} must not construct ${h.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:h.typeName},o))}return f}a(Qo,"evaluateDirectNew");function ei(e,t,n,r,s){let o=[],i=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:o,completenessReasons:i};for(let c of t){if(!lr(c.kind)&&!cr(c.kind)&&!Xo(c.kind))continue;let f=r(c.file);if(!f||!l.has(f))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:zo,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let h=Yo(n,c.file);if(lr(c.kind)){if(h.raises.has(c.nameLiteral)||h.sends.has(c.nameLiteral))continue;o.push(ce(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:f,target:c.nameLiteral},s));continue}if(cr(c.kind)){if(h.reactsTo.has(c.nameLiteral))continue;o.push(ce(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:f,target:c.nameLiteral},s));continue}h.uses.has(c.nameLiteral)||o.push(ce(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:f,target:c.nameLiteral},s))}return{findings:o,completenessReasons:i}}a(ei,"evaluateUndeclared");function ti(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!ir(l))continue;let c=n(i.from);!c||!s.has(c)||o.push(ce(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return o}a(ti,"evaluateTransportBypass");function ur(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=mt(e.classification),r=ei(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Jo(t,e.compositionRootHits,n),...Zo(t,e.layers,e.dependencies,e.layerForFile,n),...Qo(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...ti(t,e.dependencies,e.layerForFile,n)].sort(qo),o=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,f=`${l.code}\0${l.file??""}\0${l.message}`;return c<f?-1:c>f?1:0});return{findings:s,completenessReasons:o}}a(ur,"evaluateArkRunSensors");function fr(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(fr,"isArkOrderModuleSpecifier");var pr=new Map;function gr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(gr,"escapeAppliesToLiteral");function ni(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}a(ni,"normalizeAppliesToGlob");function ri(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}a(ri,"appliesToBracesBalanced");function si(e){let t=pr.get(e);if(t)return t;let n=ni(e),r=ri(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=gr(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=gr(c)}let i=new RegExp(`^${s}$`);return pr.set(e,i),i}a(si,"globToRegExp");var mr={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function oi(e,t){return!t||t.length===0?!0:t.some(n=>si(n).test(e))}a(oi,"matchesArkOrderAppliesTo");function ii(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}a(ii,"isDomainRoleLayer");function ge(e,t,n,r,s,o,i){let l=e.mode==="enforced"&&i;return{ruleId:mr[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:mr[t],fromLayer:o?.fromLayer,target:o?.target})}}a(ge,"finding");function hr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=mt(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(ge(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let f of e.planeRootHits){let h=c.get(f.matchedRoot)??[];h.push(f),c.set(f.matchedRoot,h)}for(let f of s){let h=c.get(f)??[];if(h.length===0){r.push(ge(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(f)} matched no governed files and has no createOrderPlane factory.`,{target:f},n));continue}h.some(R=>R.hasPlaneFactory)||r.push(ge(t,"arkorder-missing-plane",h[0].file,1,`ArkOrder plane root ${JSON.stringify(f)} has no createOrderPlane factory.`,{target:f},n))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let f=c.specifier;if(!f||!fr(f))continue;let h=e.layerForFile(c.from);h&&ii(h,o.get(h)??[])&&r.push(ge(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:h,target:f},n))}for(let c of e.genericUpdates)r.push(ge(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(ge(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(ge(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let f=e.layerForFile(c.file);!f||!l.has(f)||oi(c.file,t.appliesTo)&&r.push(ge(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:f,target:c.key},n))}return r.sort((c,f)=>c.file.localeCompare(f.file)||c.ruleId.localeCompare(f.ruleId)||c.line-f.line),{findings:r,completenessReasons:[]}}a(hr,"evaluateArkOrderSensors");var Re={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},yr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Re,default:[]},kernelRoots:{...Re},managedLayers:{...Re,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Rr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Re,default:[]},managedLayers:{...Re,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Re,default:[]},appliesTo:{...Re,default:[]}}};function qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(qe,"isObject");function Ar(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)qe(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Ar,"declaredLayerNames");function kr(e){if(!qe(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}a(kr,"defaultedArkRun");function br(e){if(!qe(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}a(br,"defaultedArkOrder");function vr(e,t){let n=e.arkRun;if(n===void 0||!qe(n))return;let r=Ar(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(vr,"validateArkRunExtra");function Sr(e,t){let n=e.arkOrder;if(n===void 0||!qe(n))return;let r=Ar(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Sr,"validateArkOrderExtra");function ht(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(ht,"normalizeStewardId");function Ir(e){let t=ht(e);return!t||Vt(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Ir,"isGitHubHandle");function ai(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Vt(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}a(ai,"isGitHubEmail");function li(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Ir(t[1])?ht(t[1]):null}a(li,"githubHandleFromEmail");function Er(e){let t=li(e);if(t)return t;let n=ht(e);return!n||Vt(n)?null:Ir(n)||ai(n)?n:null}a(Er,"canonicalStewardId");var ci=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Vt(e){let t=ht(e);return!t||ci.test(t)}a(Vt,"isAutomationAuthor");var te="1.3",di=["public","auth","admin","internal"];function ui(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(ui,"isFutureHouseLayer");function fi(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a(fi,"layerOwnersList");function Tr(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!ui(t)&&!fi(t)).map(t=>t.name)}a(Tr,"layersMissingRequiredOwners");function Lr(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(Lr,"missingLayerOwnersNextAction");var Gt="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Cr=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],pi=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function gi(){let e=[];for(let t of Cr)for(let n of Cr)t===n||pi.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(gi,"createDefaultRules");var Fr=gi(),Bt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],W={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},wr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Gt,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:Gt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:te,default:te},name:{type:"string",minLength:1},include:{...W,minItems:1,default:["src"]},exclude:{...W,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Fr,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...W,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...W,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...W,minItems:1},exclude:W,intentPrefixes:W,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...di]},owners:{...W,minItems:1},forbiddenGlobals:W,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...W,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...W,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny","deny-cross-parent"],description:"deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. arkgate 4.8.22 and older reject deny-cross-parent."},childSlices:{type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Absent keeps today's universe wall. sliceFolders names children. commonFolders and flat files are universe common. siblings is "deny" (default), "advisory", or { default, enforce }. parentMayImportChild defaults to false. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...W,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...W,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce } so listed subtrees are errors while the default stays advisory. A string-enum build rejects the object at config load (must be one of deny, advisory).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...W}}}]},parentMayImportChild:{type:"boolean"},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A bare name, a universe id alone, an unknown universe, and a wildcard in to are rejected. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each alias as an owed move. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...W,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...W,minItems:1}}},arkRun:yr,arkOrder:Rr}},de=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
11
11
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
12
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function dr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(dr,"isObject");function st(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(st,"propertyPath");function Ce(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Ce,"valueType");function Io(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(Io,"resolveSchemaRef");function He(e,t,n,r,s){if(t.$ref){let o=Io(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}He(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!dr(e)){s.push({path:n,message:`must be an object; received ${Ce(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:st(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:st(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let d of Object.keys(e))d in o||He(e[d],a,st(n,d),r,s)}for(let[a,d]of Object.entries(o))e[a]!==void 0&&He(e[a],d,st(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Ce(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(a=>JSON.stringify(a));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,a)=>He(o,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${Ce(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 ${Ce(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Ce(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(He,"validateNode");function Eo(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,s)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let o=r.owners;Array.isArray(o)&&o.forEach((a,d)=>{typeof a=="string"&&(sr(a)||t.push({path:`$.layers[${s}].owners[${d}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}i(Eo,"validateLayerOwners");function So(e){let t={...e,$schema:e.$schema===void 0?xt:e.$schema,schemaVersion:e.schemaVersion===void 0?te:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?cr.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=Qn(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=er(e.arkOrder)),t}i(So,"defaultedConfig");function Co(e){return e===te?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(Co,"migratedFromOf");function wo(){let e=new Set([te]);for(let t of _t)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(wo,"knownInputVersions");function Oo(e,t="ark.config.json"){if(!dr(e))throw new ce(t,[{path:"$",message:`must be an object; received ${Ce(e)}`}]);let n=wo(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ce(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${te}`}]);if(r!=="unversioned"&&!n.has(r))throw new ce(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);let s=r,o={...e},a=0;for(;s!==te&&a<_t.length+1;){a+=1;let d=_t.find(l=>l.from===s);if(!d)throw new ce(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${te}`}]);s=d.to,o.schemaVersion=s}if(s!==te)throw new ce(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);return{candidate:So(o),migratedFrom:Co(r)}}i(Oo,"migrateArkConfig");function $t(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Oo(e,t),s=[];if(He(n,ar,"$",ar,s),tr(n,s),nr(n,s),Eo(n,s),s.length>0)throw new ce(t,s);return{config:n,migratedFrom:r}}i($t,"loadArkConfigContract");function ur(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ce(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return $t(n,t)}i(ur,"parseArkConfigJson");function G(e,t,n={}){return{ruleId:e,message:t,...n}}i(G,"configWarning");function Tt(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(c=>typeof c!="string"))&&o.push(G("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))o.push(G("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let c of["maxTsSuppressions","maxAnyCasts"]){let y=t.safety[c];y!==void 0&&(!Number.isInteger(y)||y<0)&&o.push(G("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${c} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],d=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],l=new Set([...a.map(c=>c.name).filter(Boolean),...d.map(c=>c.name).filter(c=>!!c)]);a.length===0&&o.push(G("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,h=new Set;for(let c of a){if(!c.name){o.push(G("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(c.name)&&h.add(c.name),p.add(c.name),c.forbiddenGlobals!==void 0&&(!Array.isArray(c.forbiddenGlobals)||c.forbiddenGlobals.some(k=>typeof k!="string"))&&o.push(G("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${c.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:c.name}));let y=Array.isArray(c.patterns)?c.patterns:[];if(y.length===0){o.push(G("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${c.name}" has no file patterns and will never classify files.`,{layer:c.name}));continue}for(let k of y){let E;try{E=ie(k)}catch(O){o.push(G("CONFIG_INVALID_LAYER_PATTERN",`Layer "${c.name}" has an invalid pattern "${k}": ${O instanceof Error?O.message:String(O)}`,{layer:c.name,pattern:k}));continue}let I=c.optional===!0||c.reserved===!0||c.allowEmpty===!0;!r.some(O=>E.test(O))&&!I&&o.push(G("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${c.name}" pattern "${k}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:c.name,pattern:k,failsStrict:!1,reserved:!1}))}}for(let c of h)o.push(G("CONFIG_DUPLICATE_LAYER",`Layer "${c}" is configured more than once.`,{layer:c}));if(l.size>0)for(let c of n??[])c.from&&!l.has(c.from)&&o.push(G("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${c.from}".`,{fromLayer:c.from,toLayer:c.to})),c.to&&!l.has(c.to)&&o.push(G("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${c.to}".`,{fromLayer:c.from,toLayer:c.to}));let A=new Set;if(a.length>1)for(let c of r){let y=-1,k=[];for(let E of a)for(let I of E.patterns??[]){if(!ie(I).test(c))continue;let O=yt(I,c);O>y?(y=O,k=[E.name]):O===y&&!k.includes(E.name)&&k.push(E.name)}k.length>1&&A.add([...k].sort().join(" + "))}A.size>0&&o.push(G("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...A].join(", ")}.`,{pairs:[...A]}));let u=r.filter(c=>!Q(c,a));u.length>0&&o.push(G("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)}));for(let c of on(n))o.push(G("CONFIG_SLICE_IDENTITY_COLLISION",c.message,{paths:[...c.paths],fromLayer:c.from,toLayer:c.to,failsStrict:!1}));let f=ir(t);if(f.length>0){let c=f[0]??"this layer";o.push(G("CONFIG_LAYER_MISSING_OWNER",`${c} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:f,nextAction:lr(c)}))}return o}i(Tt,"collectAnalysisConfigWarnings");function fr(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],a=[],d=i(l=>{n.set(l,t),r.set(l,t),t+=1,o.push(l),s.add(l);for(let A of[...e.get(l)??[]].sort())e.has(A)&&(n.has(A)?s.has(A)&&r.set(l,Math.min(r.get(l)??0,n.get(A)??0)):(d(A),r.set(l,Math.min(r.get(l)??0,r.get(A)??0))));if(r.get(l)!==n.get(l))return;let p=[],h;do{if(h=o.pop(),h===void 0)break;s.delete(h),p.push(h)}while(h!==l);p.length>1&&a.push(p.sort())},"connect");for(let l of[...e.keys()].sort())n.has(l)||d(l);return a.sort((l,p)=>l[0]<p[0]?-1:l[0]>p[0]?1:0).map(l=>({ruleId:"CIRCULAR_DEPENDENCY",file:l[0],line:1,target:l.join(" \u2192 "),message:`Circular dependency among ${l.length} files: ${l.join(" \u2192 ")} \u2192 ${l[0]}.`,cycleKind:"value"}))}i(fr,"detectArchitectureCycles");function Ke(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let a=Le(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a){let u=un(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});u&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:u.fromPath,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:u.toPath,toSlice:u.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${u.fromPath} \u2192 slice ${u.toSlice} (${u.toPath}). The wall is direct-only.`});continue}let d=a.rule,l=!!d.peerIsolation,p=!l&&!!(o.typeOnly||o.namedBindingsTypeOnly),h=l?Qe(a.peerIsolationReason??"cross-slice",{fromPath:o.from,toPath:o.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,A=d.message?h?`${d.message} (${h})`:d.message:h?`${o.fromLayer} must not ${o.kind} another slice of ${o.toLayer} (${o.from} \u2192 ${o.to}): ${h}`:`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!l&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...l?{peerIsolation:!0}:{},message:p?`${A} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:A,...p?{failsStrict:!1,severity:"warning"}:{}})}let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=fr(r);s==="soft"||s==="framework-soft"?n.push(...o.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}i(Ke,"evaluateArchitectureGraph");function pr(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",s=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:mn({sensor:e.sensor,code:e.code})}:{},...r||s?{freezable:!1}:{},nextAction:t}}i(pr,"toArkRuleEngineViolation");function xo(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(xo,"arkRulesMapIsOn");function gr(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}i(gr,"arkRuleFindingNextAction");function _o(e,t){return t.some(n=>{try{return ie(n).test(e)}catch{return!1}})}i(_o,"matchesAny");function $o(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,o=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:k})=>({file:y,line:k})),d=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:k})=>({file:y,line:k})),l=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!_o(y.file,o)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),p=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),A={tsSuppressions:a,anyCasts:d,nonLiteralDynamicImports:l,inMemoryProductionStores:p,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},u=[],f=l.filter(y=>y.kind==="import");if(f.length>0){let y=f[0];u.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${f.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let c=l.filter(y=>y.kind==="require");if(c.length>0){let y=c[0];u.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${c.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];u.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(d.length>s){let y=d[0];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${d.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(p.length>0){let y=p[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${p.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return h.length>0&&u.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${h.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:A,warnings:u}}i($o,"evaluateSafety");function To(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(To,"ambientForbiddenGlobal");function mr(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return At(e,n.length>0?n:Rt.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(mr,"intentLayer");function Fo(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let a=n.get(o.file);!a||!To(o.symbol,s.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,message:`${a} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let a=n.get(o.file);if(!a)continue;let d=s.get(a),l=d?.forbiddenGlobals??[],p=o.source==="import-based"?t.dependencies.find(h=>h.from===o.file&&h.line===o.line&&h.specifier===o.symbol&&!h.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&>(o.symbol,l))){if(o.source==="import-based"){let h=Ne(o.symbol,l);if(h){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:a,target:o.symbol,...p?{edgeKind:p}:{},message:`${a} must not use module "${o.symbol}" because it is the import form of forbidden global "${h}".`});continue}}Ie(d).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:a,target:o.symbol,capability:o.capability,...p?{edgeKind:p}:{},message:o.source==="import-based"?`${a} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${a} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let a=n.get(o.file);if(!a)continue;for(let l of kt({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:l.ruleId,file:o.file,line:o.line,...l.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:l.message});if(!o.sourceIntent)continue;let d=mr(o.sourceIntent,e.contract);!d||d===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:a,toLayer:d,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${d}, but the publishing file is classified as ${a}.`})}for(let o of t.intentReferences){let a=n.get(o.file);if(!a)continue;let d=mr(o.intent,e.contract);if(!d)continue;let l=Le(e.contract.config.rules,a,d,{fromPath:o.file,layers:e.contract.config.layers});if(!l)continue;let p=l.rule.peerIsolation?Qe(l.peerIsolationReason??"cross-slice",{fromPath:o.file,fromSlice:l.fromSlice,toSlice:l.toSlice}):void 0,h=`${a} must not reference ${d} intent ${o.intent}.`,A=p&&l.peerIsolationReason!=="cross-slice"?`${h} ${p}`:l.rule.message?p?`${l.rule.message} (${p})`:l.rule.message:h;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:a,toLayer:d,target:o.intent,...l.rule.peerIsolation?{peerIsolation:!0}:{},message:A})}return r}i(Fo,"contentViolations");function Ft(e){let{facts:t}=e,n=We(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((m,q)=>{let $e=`${m.code}\0${m.file??""}\0${m.message}`,Te=`${q.code}\0${q.file??""}\0${q.message}`;return $e<Te?-1:$e>Te?1:0}),a=t.files.map(m=>({...m,layer:Q(m.path,e.contract.config.layers)??null})),d=new Map(a.map(m=>[m.path,m.layer])),l=t.dependencies.map(m=>{let q=m.target?d.get(m.target)??Q(m.target,e.contract.config.layers):void 0;return{from:m.from,fromLayer:d.get(m.from)??null,...m.resolution==="resolved-project"&&m.target?{to:m.target,...q?{toLayer:q}:{}}:{},line:m.line,kind:m.kind,typeOnly:m.typeOnly,...m.targetTypeOnlyExports?{targetTypeOnlyExports:m.targetTypeOnlyExports}:{},...m.sourcePureTypeModule?{sourcePureTypeModule:m.sourcePureTypeModule}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:m.namedBindingsTypeOnly}:{},...m.portProofEligible?{portProofEligible:m.portProofEligible}:{}}}),p=Tt({config:e.contract.config,rules:e.contract.config.rules,files:a.map(m=>m.path)}),h=$o(e,t),A=e.contract.arkRules??De(),u=a.map(m=>m.path),c={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?wn(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=i(m=>d.get(m)??Q(m,e.contract.config.layers),"resolveLayer"),k=[...En({arkRules:A,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:y,fileHints:c}),...Sn(A,u),...Cn({arkRulesActive:xo(e.contract.config),arkRules:A,layers:e.contract.config.layers??[],files:u.map(m=>({path:m,layer:y(m)}))})],E=(A.invariants?.length??0)>0,I=Ln({hasEnforcedInvariant:Ct(A.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),O=I.length>0?[]:Pn({adopted:e.adopted===!0,hasDomainInvariants:St(A.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),$=[...I.map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...O.map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],W=k.filter(m=>m.failsStrict).map(m=>pr(m,gr(m,!1))),b=k.filter(m=>!m.failsStrict).map(m=>({...pr(m,gr(m,!0)),failsStrict:!1})),T=E?Fn({arkRules:A,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},Oe=T.violations.filter(m=>m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,nextAction:`Add a test title or declared symbol covering ${m.arkruleId} (declared in ${m.arkruleSource}), then preflight again.`})),ge=T.violations.filter(m=>!m.failsStrict).map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,arkruleId:m.arkruleId,arkruleSource:m.arkruleSource,failsStrict:!1,nextAction:m.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${m.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${m.arkruleId} in ${m.arkruleSource} (advisory / partial).`})),Be=Dn(a),se=Gn({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(m=>d.get(m)??Q(m,e.contract.config.layers),"layerForFile"),classification:Be}),re=e.contract.config.arkRun?.mode,me=se.findings.filter(()=>re==="enforced").map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,target:m.target,nextAction:m.nextAction,sensor:m.sensor,failsStrict:m.failsStrict,...m.severity?{severity:m.severity}:{}})),xe=se.findings.filter(()=>re!=="enforced").map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,target:m.target,nextAction:m.nextAction,sensor:m.sensor,failsStrict:!1})),ke=Yn({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(m=>d.get(m)??Q(m,e.contract.config.layers),"layerForFile"),classification:Be}),_e=e.contract.config.arkOrder?.mode,ze=ke.findings.filter(()=>_e==="enforced").map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,target:m.target,nextAction:m.nextAction,sensor:m.sensor,failsStrict:m.failsStrict,...m.severity?{severity:m.severity}:{}})),zt=ke.findings.filter(()=>_e!=="enforced").map(m=>({ruleId:m.ruleId,file:m.file,line:m.line,message:m.message,fromLayer:m.fromLayer,target:m.target,nextAction:m.nextAction,sensor:m.sensor,failsStrict:!1})),v=[...T.partial&&T.coverage.some(m=>m.mode==="enforced"&&m.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...se.completenessReasons,...ke.completenessReasons],S=Ke({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(m=>m.layer).map(m=>m.path),contentViolations:[...Fo(e,t,d),...W,...$,...Oe,...me,...ze],edges:l,warnings:[...p,...h.warnings,...b,...ge,...xe,...zt],safety:h.report}),g=s==="complete"&&v.length>0?"partial":s,R=g==="complete"?o:[...o,...v].sort((m,q)=>{let $e=`${m.code}\0${m.file??""}\0${m.message}`,Te=`${q.code}\0${q.file??""}\0${q.message}`;return $e<Te?-1:$e>Te?1:0}),x=S.violations.filter(m=>m.failsStrict!==!1),U=g==="complete"&&x.length===0,de=U&&S.warnings.every(m=>m.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:g,completenessReasons:R,valid:U,strictValid:de,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(m=>m.name),edges:l,capabilityUses:t.capabilityUses,violations:S.violations,warnings:S.warnings}}}i(Ft,"analyzeCanonicalResolvedProject");function ot(e){return Ft({contract:e.contract,facts:ye(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(ot,"analyzeResolvedProject");var Nt="1.0";var at=class extends Error{static{i(this,"ArchitectureChangeMapValidationError")}issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
|
|
12
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ne,"isObject");function ke(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(ke,"propertyPath");function _e(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(_e,"valueType");function mi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(mi,"resolveSchemaRef");function Xe(e,t,n,r,s){if(t.$ref){let o=mi(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Xe(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ne(e)){s.push({path:n,message:`must be an object; received ${_e(e)}`});return}let o=t.properties??{};for(let i of t.required??[])e[i]===void 0&&s.push({path:ke(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in o||s.push({path:ke(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in o||Xe(e[l],i,ke(n,l),r,s)}for(let[i,l]of Object.entries(o))e[i]!==void 0&&Xe(e[i],l,ke(n,i),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${_e(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(i=>JSON.stringify(i));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,i)=>Xe(o,t.items,`${n}[${i}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${_e(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 ${_e(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${_e(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}a(Xe,"validateNode");var hi=["deny","advisory"],xr='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"] }';function yi(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,s)=>{if(!ne(r))return;let o=r.childSlices;if(!ne(o)||o.siblings===void 0)return;let i=o.siblings,l=`$.rules[${s}].childSlices.siblings`;if(typeof i=="string"){hi.includes(i)||t.push({path:l,message:xr});return}if(!ne(i)){t.push({path:l,message:xr});return}for(let f of Object.keys(i))f!=="default"&&f!=="enforce"&&t.push({path:ke(l,f),message:"unknown field"});if(i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((f,h)=>{let R=`${l}.enforce[${h}]`;if(typeof f!="string"||f.trim().length===0){t.push({path:R,message:"must be a non-empty child slice id or subtree path"});return}let u=Te(f.trim().replace(/\\/g,"/"));if(u.split("/").some(p=>p.length===0||p==="."||p==="..")){t.push({path:R,message:"must be a child slice id or subtree path without . or .."});return}if(u.includes("*")){t.push({path:R,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(u)){t.push({path:R,message:"duplicate enforce entry"});return}c.add(u)})})}a(yi,"validateChildSliceSiblings");var Ri="must be a slice id with a slash. A bare name is ambiguous across universes.",Ai="* matches one whole path segment. ** and a partial segment are not wildcards.";function ki(e){let t=Te(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return Ri;let n=t.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return Ai}return null}a(ki,"childCrossSlicePatternIssue");function Or(e){return Te(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Or,"childCrossSlicePatternKey");function bi(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,s)=>{if(!ne(r))return;let o=r.childSlices;if(!ne(o)||o.allowedCrossSlice===void 0)return;let i=o.allowedCrossSlice,l=`$.rules[${s}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((f,h)=>{let R=`${l}[${h}]`;if(!ne(f)){t.push({path:R,message:"must be an object with from and to"});return}for(let p of Object.keys(f))p!=="from"&&p!=="to"&&t.push({path:ke(R,p),message:"unknown field"});for(let p of["from","to"]){let d=f[p],g=`${R}.${p}`;if(typeof d!="string"||d.trim().length===0){t.push({path:g,message:"must be a non-empty slice id"});continue}let k=ki(d);k&&t.push({path:g,message:k})}if(typeof f.from!="string"||typeof f.to!="string")return;let u=`${Or(f.from)}\0${Or(f.to)}`;if(!u.startsWith("\0")&&!u.endsWith("\0")){if(c.has(u)){t.push({path:R,message:"duplicate child slice allowance"});return}c.add(u)}})})}a(bi,"validateChildSliceAllowedCrossSlice");var $e="must be a child of an existing universe (the universe id this rule already names, plus one child segment). A bare name, a universe id alone, an unknown universe, and a wildcard are rejected.",vi="overlaps a slice folder. An alias covers only files outside the slice trees.",Si="two slice aliases match the same file";function Ii(e){return Te(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Ii,"aliasPathSegments");function Nr(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(Nr,"concreteGlobPrefix");function Ye(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}a(Ye,"segmentsArePrefix");function Ei(e){let t=e.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(t.length<2||t[0]==="*"||t[0]==="**"||!t.some(r=>r==="*"))return null;let n=[];for(let r of t){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(Ei,"anchoredSlicePrefix");function Ci(e,t){let n=Nr(e),r=n.length<e.length,s=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Ye(t,n)||Ye(t,s)?!0:r?Ye(n,t)&&n.length<t.length||Ye(n,["src",...t])&&n.length<t.length+1||Ye(n,["app",...t])&&n.length<t.length+1:!1}a(Ci,"globOverlapsAnchored");function wi(e,t){for(let r=0;r<e.length;r+=1){if(e[r]!==t&&e[r]!=="*")continue;let s=e.slice(r+1);if(s.length>=2||s.some(o=>o==="*"||o==="**"))return!0}let n=Nr(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(wi,"globOverlapsBare");function xi(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(s=>s.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return wi(e,n[0]);let r=Ei(t);return r?Ci(e,r):!1}a(xi,"globOverlapsSliceEntry");function Oi(e){let t=Te(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty path glob";if(t==="*"||t==="**")return"must not cover the whole tree";for(let n of t.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(Oi,"aliasGlobIssue");function _i(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let s of e){if(typeof s!="string"||s.length===0)continue;let o=s.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(o.length===1&&o[0]&&!o[0].includes("*")){n.push({literals:[o[0],null]});continue}if(!o.some(i=>i==="**"||i.includes("*")&&i!=="*")&&o.includes("*")){if(r){let i=-1;for(let l=0;l<o.length;l+=1)o[l]!=="*"&&(i=l);if(i<0)continue;n.push({literals:o.slice(i).map(l=>l==="*"?null:l)});continue}n.push({literals:o.map(i=>i==="*"?null:i)})}}return n}a(_i,"universeShapes");function _r(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(_r,"shapeMatches");function $i(e,t){let n=Te(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(s=>s.length===0||s==="."||s==="..")||n.includes("*")||!n.includes("/"))return $e;let r=n.split("/").map(s=>s.toLowerCase());return t.length===0||t.some(s=>_r(s,r))?$e:t.some(s=>_r(s,r.slice(0,-1)))?null:$e}a($i,"aliasTargetIssue");function $r(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a($r,"aliasGlobVariants");function Ti(e,t){let n=$r(e),r=$r(t);for(let s of n)if(Ae(s,t,0,0,new Map))return!0;for(let s of r)if(Ae(e,s,0,0,new Map))return!0;return!1}a(Ti,"aliasesCanMatchSameFile");function Ae(e,t,n,r,s){let o=`${n}:${r}`,i=s.get(o);if(i!==void 0)return i;let l=!1;if(n===e.length&&r===t.length)l=!0;else if(n<e.length&&e[n]==="**")l=Ae(e,t,n+1,r,s)||r<t.length&&Ae(e,t,n,r+1,s);else if(r<t.length&&t[r]==="**")l=Ae(e,t,n,r+1,s)||n<e.length&&Ae(e,t,n+1,r,s);else if(n<e.length&&r<t.length){let c=e[n],f=t[r];(c===f||c==="*"||f==="*")&&(l=Ae(e,t,n+1,r+1,s))}return s.set(o,l),l}a(Ae,"globsCanMatchSame");function Li(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,s)=>{if(!ne(r))return;let o=r.childSlices;if(!ne(o)||o.sliceAliases===void 0)return;let i=o.sliceAliases,l=`$.rules[${s}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=_i(r.sliceFolders,r.sliceIdentity),f=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(o.sliceFolders)?o.sliceFolders:[]].filter(R=>typeof R=="string"&&R.length>0),h=[];i.forEach((R,u)=>{let p=`${l}[${u}]`;if(!ne(R)){t.push({path:p,message:"must be an object with from and to"});return}for(let k of Object.keys(R))k!=="from"&&k!=="to"&&t.push({path:ke(p,k),message:"unknown field"});let d=R.from,g=R.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${p}.from`,message:"must be a non-empty path glob"});else{let k=Oi(d);if(k)t.push({path:`${p}.from`,message:k});else{let I=Ii(d);f.some(S=>xi(I,S))&&t.push({path:`${p}.from`,message:vi});for(let S of h)if(Ti(S,I)){t.push({path:p,message:Si});break}h.push(I)}}if(typeof g!="string"||g.trim().length===0)t.push({path:`${p}.to`,message:$e});else{let k=$i(g,c);k&&t.push({path:`${p}.to`,message:k})}})})}a(Li,"validateChildSliceAliases");function Fi(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,s)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let o=r.owners;Array.isArray(o)&&o.forEach((i,l)=>{typeof i=="string"&&(Er(i)||t.push({path:`$.layers[${s}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Fi,"validateLayerOwners");function Ni(e){let t={...e,$schema:e.$schema===void 0?Gt:e.$schema,schemaVersion:e.schemaVersion===void 0?te:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Fr.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=kr(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=br(e.arkOrder)),t}a(Ni,"defaultedConfig");function Pi(e){return e===te?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Pi,"migratedFromOf");function Di(){let e=new Set([te]);for(let t of Bt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Di,"knownInputVersions");function Mi(e,t="ark.config.json"){if(!ne(e))throw new de(t,[{path:"$",message:`must be an object; received ${_e(e)}`}]);let n=Di(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${te}`}]);if(r!=="unversioned"&&!n.has(r))throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);let s=r,o={...e},i=0;for(;s!==te&&i<Bt.length+1;){i+=1;let l=Bt.find(c=>c.from===s);if(!l)throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${te}`}]);s=l.to,o.schemaVersion=s}if(s!==te)throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);return{candidate:Ni(o),migratedFrom:Pi(r)}}a(Mi,"migrateArkConfig");function Wt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Mi(e,t),s=[];if(Xe(n,wr,"$",wr,s),vr(n,s),Sr(n,s),Fi(n,s),yi(n,s),bi(n,s),Li(n,s),s.length>0)throw new de(t,s);return{config:n,migratedFrom:r}}a(Wt,"loadArkConfigContract");function Pr(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new de(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Wt(n,t)}a(Pr,"parseArkConfigJson");function Te(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Te,"trimTrailingSlashes");function G(e,t,n={}){return{ruleId:e,message:t,...n}}a(G,"configWarning");function zt(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&o.push(G("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))o.push(G("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let g=t.safety[d];g!==void 0&&(!Number.isInteger(g)||g<0)&&o.push(G("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...i.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);i.length===0&&o.push(G("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let f=new Set,h=new Set;for(let d of i){if(!d.name){o.push(G("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}f.has(d.name)&&h.add(d.name),f.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(k=>typeof k!="string"))&&o.push(G("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let g=Array.isArray(d.patterns)?d.patterns:[];if(g.length===0){o.push(G("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let k of g){let I;try{I=oe(k)}catch(x){o.push(G("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${k}": ${x instanceof Error?x.message:String(x)}`,{layer:d.name,pattern:k}));continue}let S=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(x=>I.test(x))&&!S&&o.push(G("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${k}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:k,failsStrict:!1,reserved:!1}))}}for(let d of h)o.push(G("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&o.push(G("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&o.push(G("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let R=new Set;if(i.length>1)for(let d of r){let g=-1,k=[];for(let I of i)for(let S of I.patterns??[]){if(!oe(S).test(d))continue;let x=Ot(S,d);x>g?(g=x,k=[I.name]):x===g&&!k.includes(I.name)&&k.push(I.name)}k.length>1&&R.add([...k].sort().join(" + "))}R.size>0&&o.push(G("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...R].join(", ")}.`,{pairs:[...R]}));let u=r.filter(d=>!Q(d,i));u.length>0&&o.push(G("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)}));for(let d of Cn(n))o.push(G("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));for(let d of On(n,r))o.push(G(d.ruleId,d.message,{failsStrict:!1,...d.path?{file:d.path}:{},...d.fromLayer?{fromLayer:d.fromLayer}:{},...d.toLayer?{toLayer:d.toLayer}:{}}));let p=Tr(t);if(p.length>0){let d=p[0]??"this layer";o.push(G("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:p,nextAction:Lr(d)}))}return o}a(zt,"collectAnalysisConfigWarnings");function Mr(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,o.push(c),s.add(c);for(let R of[...e.get(c)??[]].sort())e.has(R)&&(n.has(R)?s.has(R)&&r.set(c,Math.min(r.get(c)??0,n.get(R)??0)):(l(R),r.set(c,Math.min(r.get(c)??0,r.get(R)??0))));if(r.get(c)!==n.get(c))return;let f=[],h;do{if(h=o.pop(),h===void 0)break;s.delete(h),f.push(h)}while(h!==c);f.length>1&&i.push(f.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(Mr,"detectArchitectureCycles");function Je(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let i=We(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!i){let u=$n(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});u&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:u.fromPath,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:u.toPath,toSlice:u.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${u.fromPath} \u2192 slice ${u.toSlice} (${u.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,f=!c&&!!(o.typeOnly||o.namedBindingsTypeOnly),h=i.sliceVerdict,R=h?ut({surface:"import",verdict:h,fromLayer:o.fromLayer,toLayer:o.toLayer,kind:o.kind,fromPath:o.from,toPath:o.to,ruleMessage:l.message}):l.message??`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...c?{peerIsolation:!0}:{},...ft(h),message:f?`${R} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:R,...f?{failsStrict:!1,severity:"warning"}:{}})}t.push(...Ki(e));let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Mr(r);s==="soft"||s==="framework-soft"?n.push(...o.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}a(Je,"evaluateArchitectureGraph");var Hi="CROSS_PARENT_VIA_SHARED",Ui="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function Dr(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&r.sharedImportsSlice==="deny-cross-parent")return r}a(Dr,"denyingCrossParentRule");function qt(e,t,n,r){let s=we(n,e,Tn(e,t,r)).universeId;return s?{kind:"slice",id:s}:Ve(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(qt,"placeFile");function Ki(e){let t=e.rules??[];if(!t.some(o=>o.sharedImportsSlice==="deny-cross-parent"))return[];let n=new Map;for(let o of e.edges){let i=ji(o);if(!i)continue;let l=n.get(i.from);l?l.push(i):n.set(i.from,[i])}for(let o of n.values())o.sort((i,l)=>i.to<l.to?-1:i.to>l.to?1:i.line-l.line);let r=new Map,s=[...n.values()].flat();s.sort((o,i)=>o.from<i.from?-1:o.from>i.from?1:o.to<i.to?-1:o.to>i.to?1:0);for(let o of s){let i=Dr(t,o.fromLayer,o.toLayer);if(!i)continue;let l=qt(i,o.fromLayer,o.from,e.config.layers),c=qt(i,o.fromLayer,o.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared")continue;let f=[{file:o.to,path:[o.from,o.to]}],h=new Set([o.to]);for(;f.length>0;){let R=f.shift();if(!R)break;for(let u of n.get(R.file)??[]){let p=Dr(t,u.fromLayer,u.toLayer);if(!p)continue;let d=qt(p,u.fromLayer,u.to,e.config.layers);if(d.kind==="shared"){if(h.has(u.to))continue;h.add(u.to),f.push({file:u.to,path:[...R.path,u.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase())continue;let g=[...R.path,u.to],k=`${o.from}\0${u.to}`,I={file:o.from,target:u.to,line:o.line,fromLayer:o.fromLayer,toLayer:u.toLayer,fromSlice:l.id,toSlice:d.id,path:g},S=r.get(k);(!S||g.length<S.path.length||g.length===S.path.length&&g.join("\0")<S.path.join("\0"))&&r.set(k,I)}}}return[...r.values()].sort((o,i)=>o.file<i.file?-1:o.file>i.file?1:o.target<i.target?-1:o.target>i.target?1:0).map(o=>{let i=Ge(o.fromSlice),l=Ge(o.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:Hi,file:o.file,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.target,peerIsolation:!0,...i&&l?{universeFrom:i,universeTo:l}:{},message:`${o.fromLayer} reaches ${o.toLayer} in another universe through a shared root (${o.path.join(" \u2192 ")}): cross-parent via shared ${o.fromSlice} \u2192 ${o.toSlice}. ${Ui}`}})}a(Ki,"crossParentViaSharedViolations");function ji(e){if(!(!e.to||e.to===e.from||!e.fromLayer||!e.toLayer))return{from:e.from,to:e.to,line:e.line,fromLayer:e.fromLayer,toLayer:e.toLayer}}a(ji,"valueHop");function Hr(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",s=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:Pn({sensor:e.sensor,code:e.code})}:{},...r||s?{freezable:!1}:{},nextAction:t}}a(Hr,"toArkRuleEngineViolation");function Vi(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Vi,"arkRulesMapIsOn");function Ur(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}a(Ur,"arkRuleFindingNextAction");function Gi(e,t){return t.some(n=>{try{return oe(n).test(e)}catch{return!1}})}a(Gi,"matchesAny");function Bi(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,o=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(g=>g.kind==="ts-suppression").map(({file:g,line:k})=>({file:g,line:k})),l=t.safetyUses.filter(g=>g.kind==="any-cast").map(({file:g,line:k})=>({file:g,line:k})),c=t.safetyUses.filter(g=>(g.kind==="dynamic-import"||g.kind==="dynamic-require")&&!Gi(g.file,o)).map(g=>({file:g.file,line:g.line,kind:g.kind==="dynamic-require"?"require":"import"})),f=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(g=>g.kind==="in-memory-store").map(g=>({file:g.file,line:g.line,store:g.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(g=>g.peerIsolation===!1||g.allowed===!1&&!!g.from&&g.from===g.to&&g.peerIsolation!==!0).map(g=>({from:g.from,to:g.to})),R={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:f,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},u=[],p=c.filter(g=>g.kind==="import");if(p.length>0){let g=p[0];u.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(g=>g.kind==="require");if(d.length>0){let g=d[0];u.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let g=i[0];u.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>s){let g=l[0];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(f.length>0){let g=f[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:g.file,line:g.line,message:`${f.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return h.length>0&&u.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${h.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:R,warnings:u}}a(Bi,"evaluateSafety");function Wi(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(Wi,"ambientForbiddenGlobal");function Kr(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Ft(e,n.length>0?n:Lt.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Kr,"intentLayer");function zi(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let i=n.get(o.file);!i||!Wi(o.symbol,s.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:i,target:o.symbol,message:`${i} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let i=n.get(o.file);if(!i)continue;let l=s.get(i),c=l?.forbiddenGlobals??[],f=o.source==="import-based"?t.dependencies.find(h=>h.from===o.file&&h.line===o.line&&h.specifier===o.symbol&&!h.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&wt(o.symbol,c))){if(o.source==="import-based"){let h=Ke(o.symbol,c);if(h){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:i,target:o.symbol,...f?{edgeKind:f}:{},message:`${i} must not use module "${o.symbol}" because it is the import form of forbidden global "${h}".`});continue}}Ce(l).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:i,target:o.symbol,capability:o.capability,...f?{edgeKind:f}:{},message:o.source==="import-based"?`${i} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${i} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let i=n.get(o.file);if(!i)continue;for(let c of Nt({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:c.ruleId,file:o.file,line:o.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:c.message});if(!o.sourceIntent)continue;let l=Kr(o.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:i,toLayer:l,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let o of t.intentReferences){let i=n.get(o.file);if(!i)continue;let l=Kr(o.intent,e.contract);if(!l)continue;let c=We(e.contract.config.rules,i,l,{fromPath:o.file,layers:e.contract.config.layers});if(!c)continue;let f=c.sliceVerdict,h=`${i} must not reference ${l} intent ${o.intent}.`,R=f?ut({surface:"intent",verdict:f,fromLayer:i,toLayer:l,fromPath:o.file,ruleMessage:c.rule.message,defaultMessage:h}):c.rule.message??h;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:i,toLayer:l,target:o.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},...ft(f),message:R})}return r}a(zi,"contentViolations");function Yt(e){let{facts:t}=e,n=st(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((y,Y)=>{let Me=`${y.code}\0${y.file??""}\0${y.message}`,He=`${Y.code}\0${Y.file??""}\0${Y.message}`;return Me<He?-1:Me>He?1:0}),i=t.files.map(y=>({...y,layer:Q(y.path,e.contract.config.layers)??null})),l=new Map(i.map(y=>[y.path,y.layer])),c=t.dependencies.map(y=>{let Y=y.target?l.get(y.target)??Q(y.target,e.contract.config.layers):void 0;return{from:y.from,fromLayer:l.get(y.from)??null,...y.resolution==="resolved-project"&&y.target?{to:y.target,...Y?{toLayer:Y}:{}}:{},line:y.line,kind:y.kind,typeOnly:y.typeOnly,...y.targetTypeOnlyExports?{targetTypeOnlyExports:y.targetTypeOnlyExports}:{},...y.sourcePureTypeModule?{sourcePureTypeModule:y.sourcePureTypeModule}:{},...y.namedBindingsTypeOnly?{namedBindingsTypeOnly:y.namedBindingsTypeOnly}:{},...y.portProofEligible?{portProofEligible:y.portProofEligible}:{}}}),f=zt({config:e.contract.config,rules:e.contract.config.rules,files:i.map(y=>y.path)}),h=Bi(e,t),R=e.contract.arkRules??ze(),u=i.map(y=>y.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?qn(e.coverageInputs.fileContents):{},...e.fileHints??{}},g=a(y=>l.get(y)??Q(y,e.contract.config.layers),"resolveLayer"),k=[...Bn({arkRules:R,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:g,fileHints:d}),...Wn(R,u),...zn({arkRulesActive:Vi(e.contract.config),arkRules:R,layers:e.contract.config.layers??[],files:u.map(y=>({path:y,layer:g(y)}))})],I=(R.invariants?.length??0)>0,S=rr({hasEnforcedInvariant:Kt(R.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),x=S.length>0?[]:nr({adopted:e.adopted===!0,hasDomainInvariants:Ut(R.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),$=[...S.map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...x.map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],q=k.filter(y=>y.failsStrict).map(y=>Hr(y,Ur(y,!1))),b=k.filter(y=>!y.failsStrict).map(y=>({...Hr(y,Ur(y,!0)),failsStrict:!1})),T=I?er({arkRules:R,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},Ne=T.violations.filter(y=>y.failsStrict).map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,arkruleId:y.arkruleId,arkruleSource:y.arkruleSource,nextAction:`Add a test title or declared symbol covering ${y.arkruleId} (declared in ${y.arkruleSource}), then preflight again.`})),me=T.violations.filter(y=>!y.failsStrict).map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,arkruleId:y.arkruleId,arkruleSource:y.arkruleSource,failsStrict:!1,nextAction:y.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${y.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${y.arkruleId} in ${y.arkruleSource} (advisory / partial).`})),nt=sr(i),ie=ur({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:a(y=>l.get(y)??Q(y,e.contract.config.layers),"layerForFile"),classification:nt}),se=e.contract.config.arkRun?.mode,he=ie.findings.filter(()=>se==="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:y.failsStrict,...y.severity?{severity:y.severity}:{}})),Pe=ie.findings.filter(()=>se!=="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:!1})),Se=hr({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:a(y=>l.get(y)??Q(y,e.contract.config.layers),"layerForFile"),classification:nt}),De=e.contract.config.arkOrder?.mode,rt=Se.findings.filter(()=>De==="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:y.failsStrict,...y.severity?{severity:y.severity}:{}})),un=Se.findings.filter(()=>De!=="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:!1})),v=[...T.partial&&T.coverage.some(y=>y.mode==="enforced"&&y.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...ie.completenessReasons,...Se.completenessReasons],C=Je({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(y=>y.layer).map(y=>y.path),contentViolations:[...zi(e,t,l),...q,...$,...Ne,...he,...rt],edges:c,warnings:[...f,...h.warnings,...b,...me,...Pe,...un],safety:h.report}),m=s==="complete"&&v.length>0?"partial":s,A=m==="complete"?o:[...o,...v].sort((y,Y)=>{let Me=`${y.code}\0${y.file??""}\0${y.message}`,He=`${Y.code}\0${Y.file??""}\0${Y.message}`;return Me<He?-1:Me>He?1:0}),O=C.violations.filter(y=>y.failsStrict!==!1),j=m==="complete"&&O.length===0,ue=j&&C.warnings.every(y=>y.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:m,completenessReasons:A,valid:j,strictValid:ue,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(y=>y.name),edges:c,capabilityUses:t.capabilityUses,violations:C.violations,warnings:C.warnings}}}a(Yt,"analyzeCanonicalResolvedProject");function yt(e){return Yt({contract:e.contract,facts:ye(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}a(yt,"analyzeResolvedProject");var Xt="1.0";var Rt=class extends Error{static{a(this,"ArchitectureChangeMapValidationError")}issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
|
|
13
13
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
14
|
-
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Pt,"isObject");function Lt(e,t,n,r){for(let s of Object.keys(e))t.includes(s)||r.push({path:`${n}.${s}`,message:"unknown field"})}i(Lt,"unknownFields");function Re(e,t,n,r){let s=e[t];if(typeof s=="string"&&s.length>0)return s;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}i(Re,"requiredString");function No(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}i(No,"canonicalProjectPath");function Po(e,t,n="architecture change map"){let r=[];if(!Pt(e))throw new at(n,[{path:"$",message:"must be an object"}]);Lt(e,["$schema","schemaVersion","files","dependencies"],"$",r);let s=Re(e,"$schema","$",r),o=Re(e,"schemaVersion","$",r);o&&o!==Nt&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${Nt}`});let a=new Set(t.layers.map(c=>c.name)),d=[],l=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((c,y)=>{let k=`$.files[${y}]`;if(!Pt(c)){r.push({path:k,message:"must be an object"});return}Lt(c,["path","operation","layer"],k,r);let E=Re(c,"path",k,r),I=Re(c,"operation",k,r),O=Re(c,"layer",k,r),$=E?No(E):void 0;E&&!$&&r.push({path:`${k}.path`,message:"must be a canonical project-relative path"}),I&&!["create","update","delete"].includes(I)&&r.push({path:`${k}.operation`,message:"must be create, update, or delete"}),O&&!a.has(O)&&r.push({path:`${k}.layer`,message:`references unknown layer ${JSON.stringify(O)}`}),$&&l.has($)&&r.push({path:`${k}.path`,message:`duplicates planned path ${$}`}),$&&l.add($);let W=$?Q($,t.layers):void 0;$&&O&&a.has(O)&&W!==O&&r.push({path:`${k}.layer`,message:W?`${$} resolves to ${W}, not ${O}`:`${$} is not assigned to an architecture layer`}),$&&I&&["create","update","delete"].includes(I)&&O&&d.push({path:$,operation:I,layer:O})});let p=[],h=new Map(d.map(c=>[c.path,c.operation])),A=new Set,u=e.dependencies??[];if(Array.isArray(u)?u.forEach((c,y)=>{let k=`$.dependencies[${y}]`;if(!Pt(c)){r.push({path:k,message:"must be an object"});return}Lt(c,["from","to"],k,r);let E=Re(c,"from",k,r),I=Re(c,"to",k,r);E&&!l.has(E)&&r.push({path:`${k}.from`,message:`must reference a planned file path: ${E}`}),I&&!l.has(I)&&r.push({path:`${k}.to`,message:`must reference a planned file path: ${I}`}),E&&h.get(E)==="delete"&&r.push({path:`${k}.from`,message:`cannot depend from deleted file ${E}`}),I&&h.get(I)==="delete"&&r.push({path:`${k}.to`,message:`cannot depend on deleted file ${I}`}),E&&I&&E===I&&r.push({path:k,message:"must not declare a self dependency"});let O=E&&I?`${E}\0${I}`:void 0;O&&A.has(O)&&r.push({path:k,message:`duplicates dependency ${E} -> ${I}`}),O&&A.add(O),E&&I&&p.push({from:E,to:I})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new at(n,r);let f={$schema:s,schemaVersion:Nt,files:d.sort((c,y)=>c.path.localeCompare(y.path)),dependencies:p.sort((c,y)=>c.from.localeCompare(y.from)||c.to.localeCompare(y.to))};return{map:f,hash:j(N(f))}}i(Po,"loadArchitectureChangeMap");function Z(e){return`${e.from}->${e.to}`}i(Z,"dependencyKey");function Ue(e,t,n,r="dependency"){return{id:`${e}:${r}:${Z(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Z(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Z(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Z(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Z(t)} from the candidate, then preflight again.`}:{}}}i(Ue,"dependencyFinding");function je(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),s=new Map(e.changeMap.map.dependencies.map(u=>[Z(u),u])),o=new Map(e.baseDependencies.map(u=>[Z(u),u])),a=new Map(e.candidateDependencies.map(u=>[Z(u),u]));for(let u of[...n.values()].sort((f,c)=>f.path.localeCompare(c.path))){let f=r.get(u.path);f?f.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:f.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${f.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:f.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((f,c)=>f.path.localeCompare(c.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let d=new Set;for(let u of[...s.values()].sort((f,c)=>Z(f).localeCompare(Z(c)))){if(a.has(Z(u))){t.push(Ue("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let f={from:u.to,to:u.from};a.has(Z(f))?(d.add(Z(f)),t.push(Ue("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ue("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let l=new Set([...n.keys(),...r.keys()]);for(let[u,f]of[...a].sort(([c],[y])=>c.localeCompare(y)))o.has(u)||s.has(u)||d.has(u)||!l.has(f.from)&&!l.has(f.to)||t.push({...Ue("unplanned",f,`${f.from} -> ${f.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,f]of[...o].sort(([c],[y])=>c.localeCompare(y)))a.has(u)||p.has(f.from)||p.has(f.to)||!l.has(f.from)&&!l.has(f.to)||t.push({...Ue("unplanned",f,`${f.from} -> ${f.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,f)=>h[u.classification]-h[f.classification]||(u.subject===f.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(f.id));let A={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:A.missing===0&&A.contradictory===0&&A.unplanned===0,behavioralCompletion:"not-evaluated",summary:A,findings:t}}i(je,"analyzeArchitectureConvergence");function we(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(we,"literalText");function Rr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(Rr,"lineOf");function yr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(yr,"isTypeOnlyReference");function Ar(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(Ar,"singleFileChecker");function Dt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Dt,"symbolAt");function Mt(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):Dt(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Mt,"localDeclaration");function Ht(e,t){let n,r=[],s=i((a,d,l,p=!1)=>r.push({specifier:l,kind:d,line:Rr(t,a),typeOnly:p,unresolved:l===void 0,node:a}),"add"),o=i(a=>{if(e.isImportDeclaration(a))s(a,"import",we(e,a.moduleSpecifier),yr(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",we(e,a.moduleSpecifier),yr(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",we(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let d=a.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Mt(e,n??(n=Ar(e,t)),t,a.expression);(d||p)&&s(a,p?"require":"dynamic-import",we(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i(Ht,"extractSemanticDependencies");function Lo(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=we(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(Lo,"staticAccessPath");function Do(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(Do,"runtimeIdentifierReference");function hr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}i(hr,"bestForbiddenMatch");function Kt(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Ar(e,t),o=new Map,a=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let f of u.declarationList.declarations)e.isIdentifier(f.name)&&a.add(f.name.text);let d=i(u=>{let f=Lo(e,u);if(!f)return;let c=Dt(s,f.root),y=c?o.get(c):void 0;return y?[...y,...f.segments.slice(1)]:Mt(e,s,t,f.root)||a.has(f.root.text)?void 0:f.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let f of u.declarationList.declarations){if(!f.initializer||!e.isIdentifier(f.name))continue;let c=d(f.initializer),y=Dt(s,f.name);!c||!y||o.set(y,c)}let l=[],p=new Set,h=i((u,f)=>{let c=Rr(t,f),y=`${u}:${f.getStart(t)}`;p.has(y)||(p.add(y),l.push({name:u,line:c,node:f}))},"flag"),A=i(u=>{let f=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!f){let c=d(u),y=c?hr(r,c):void 0;y&&h(y,u)}else e.isIdentifier(u)&&r.has(u.text)&&Do(e,u)&&!Mt(e,s,t,u)&&h(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let c=d(u.initializer);if(c)for(let y of u.name.elements){if(!e.isIdentifier(y.name))continue;let k=y.propertyName?we(e,y.propertyName)??y.propertyName.text:y.name.text,E=hr(r,[...c,k]);E&&h(E,u.initializer)}}e.forEachChild(u,A)},"visit");return A(t),l}i(Kt,"collectForbiddenCapabilityUses");function Mo(e,t,n){let r=[];for(let s of n?.dependencies??Ht(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Fe(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Kt(e,t,pt)){let o=Pe(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}i(Mo,"collectCapabilityUses");function Ut(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:s,...o}=t;return o})}}i(Ut,"omitLayerDescriptions");function kr(e){let{stewards:t,...n}=Ut(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(kr,"effectiveContractPolicyPayload");var Sr="1.0",Ho="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function C(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Ho}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(C,"addFinding");function B(e){return[...new Set(e??[])].sort()}i(B,"sortedUnique");function ne(e,t,n,r,s){let o=B(n),a=B(r),d=new Set(o),l=new Set(a),p=a.filter(A=>!d.has(A)),h=o.filter(A=>!l.has(A));p.length===0&&h.length===0||(p.length>0&&C(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:a}),h.length>0&&C(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:a}))}i(ne,"compareStringSets");function Ve(e,t,n,r,s,o,a){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:a,before:n,after:r})}i(Ve,"compareBoolean");function it(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}i(it,"keyed");function Ko(e,t,n){let r=it(t,o=>o.name),s=it(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let a=r.values.get(o),d=s.values.get(o),l=`$.layers[${o}]`;if(!a&&d){C(e,{kind:"layer-added",path:l,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:d});continue}if(a&&!d){C(e,{kind:"layer-removed",path:l,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!d)continue;ne(e,`${l}.patterns`,a.patterns,d.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ne(e,`${l}.exclude`,a.exclude,d.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let p=Xe(a),h=Xe(d);ne(e,`${l}.forbiddenGlobals`,p.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ne(e,`${l}.capabilities`,p.atoms,h.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),B(a.intentPrefixes).join("\0")!==B(d.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${l}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:B(a.intentPrefixes),after:B(d.intentPrefixes)}),Ve(e,`${l}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,d.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Ve(e,`${l}.optional`,a.optional===!0,d.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(Ko,"compareLayers");function Uo(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=it(t,r),o=it(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let a of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let d=s.values.get(a),l=o.values.get(a),p=`$.rules[${a}]`;if(!d&&l){l.allowed===!1?C(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:l}):C(e,{kind:"allow-added",path:p,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:l});continue}if(d&&!l){d.allowed===!1&&C(e,{kind:"deny-removed",path:p,classification:"weakening",message:"A denied dependency edge was removed.",before:d});continue}if(!d||!l)continue;d.allowed!==l.allowed&&C(e,{kind:l.allowed?"deny-disabled":"deny-enabled",path:`${p}.allowed`,classification:l.allowed?"weakening":"strengthening",message:l.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:d.allowed,after:l.allowed});let h=d.peerIsolation===!0,A=l.peerIsolation===!0;if(h!==A){let c=d.from===d.to&&l.from===l.to;C(e,{kind:A?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:c?A?"strengthening":"weakening":"judgment-required",message:c?A?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:h,after:A})}B(d.sliceFolders).join("\0")!==B(l.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:B(d.sliceFolders),after:B(l.sliceFolders)});let u=d.sliceIdentity??"path",f=l.sliceIdentity??"path";if(u!==f&&C(e,{kind:"slice-identity-changed",path:`${p}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:u,after:f}),!(!h&&!A)&&(vr(e,`${p}.sharedRoots`,"shared-roots",B(d.sharedRoots),B(l.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),vr(e,`${p}.allowedCrossSlice`,"cross-slice-allowance",B((d.allowedCrossSlice??[]).map(br)),B((l.allowedCrossSlice??[]).map(br)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(d.sharedImportsSlice??null)!==(l.sharedImportsSlice??null))){let c=l.sharedImportsSlice==="deny";C(e,{kind:"shared-imports-slice",path:`${p}.sharedImportsSlice`,classification:c?"strengthening":"weakening",message:c?"A shared root may no longer import a slice.":"A shared root may import a slice again.",before:d.sharedImportsSlice??null,after:l.sharedImportsSlice??null})}}}i(Uo,"compareRules");function br(e){return JSON.stringify([e.from,e.to])}i(br,"crossSliceKey");function vr(e,t,n,r,s,o,a){if(JSON.stringify(r)===JSON.stringify(s))return;let d=s.filter(h=>!r.includes(h)),l=r.filter(h=>!s.includes(h)),p=d.length>0&&l.length>0;C(e,{kind:p?`${n}-changed`:d.length>0?`${n}-added`:`${n}-removed`,path:t,classification:p?"judgment-required":d.length>0?"weakening":"strengthening",message:p?`${o} Entries were added and removed in the same change.`:d.length>0?o:a,before:r,after:s})}i(vr,"compareDeclaredExceptions");function jo(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let a=r[o]??0,d=s[o]??0;a!==d&&C(e,{kind:d>a?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:d>a?"weakening":"strengthening",message:d>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:d})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])Ve(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(jo,"compareSafety");function jt(e){return e.mode==="enforced"?"enforced":"advisory"}i(jt,"arkRunMode");function Vt(e){return e.mode==="enforced"?"enforced":"advisory"}i(Vt,"arkOrderMode");function Vo(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){C(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${Vt(s)}).`,after:s});return}if(r&&!s){C(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let a=Vt(r),d=Vt(s);if(a!==d){let l=a==="advisory"&&d==="enforced";C(e,{kind:l?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:d})}ne(e,`${o}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ne(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(Vo,"compareArkOrder");function Go(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){C(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${jt(s)}).`,after:s});return}if(r&&!s){C(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let a=jt(r),d=jt(s);if(a!==d){let l=a==="advisory"&&d==="enforced";C(e,{kind:l?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:l?"strengthening":"weakening",message:l?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:d})}ne(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ne(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Ve(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Go,"compareArkRun");function Bo(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(Bo,"overallClassification");function Ir(e,t){return`${e}::${t}`}i(Ir,"ruleKey");function Er(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Ir(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Ir(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Er,"indexEffectiveRules");function zo(e,t,n,r,s,o){let a=new Map((o??[]).map(u=>[u.invariantId,u])),d=t.arkRules??{},l=n.arkRules??{},p=[...new Set([...Object.keys(d),...Object.keys(l)])].sort();for(let u of p){let f=d[u],c=l[u],y=`$.arkRules[${u}]`;if(f===void 0&&c!==void 0){C(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:c});continue}if(f!==void 0&&c===void 0){C(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:f});continue}f!==c&&C(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:f,after:c})}let h=Er(r),A=Er(s);for(let u of[...new Set([...h.structure.keys(),...A.structure.keys()])].sort()){let f=h.structure.get(u),c=A.structure.get(u),y=`$.arkRules.structure[${u}]`;if(!f&&c){C(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${c.id} was added (${c.mode}).`,after:c});continue}if(f&&!c){C(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${f.id} was removed.`,before:f});continue}if(!(!f||!c)){if(f.mode!==c.mode){let k=f.mode==="advisory"&&c.mode==="enforced";C(e,{kind:k?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:k?"strengthening":"weakening",message:k?`Structure ArkRule ${c.id} was promoted to enforced.`:`Structure ArkRule ${c.id} was demoted to advisory.`,before:f.mode,after:c.mode})}f.sensor!==c.sensor&&C(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${c.id} changed sensor identity.`,before:f.sensor,after:c.sensor})}}for(let u of[...new Set([...h.invariants.keys(),...A.invariants.keys()])].sort()){let f=h.invariants.get(u),c=A.invariants.get(u),y=`$.arkRules.invariants[${u}]`;if(!f&&c){C(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${c.id} was added (${c.mode}).`,after:c});continue}if(f&&!c){C(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${f.id} was removed.`,before:f});continue}if(!(!f||!c)&&f.mode!==c.mode)if(f.mode==="advisory"&&c.mode==="enforced"){let E=a?.get(c.id),I=Nn(E);I.ok?C(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${c.id} was promoted to enforced (coverage evidence present).`,before:f.mode,after:c.mode}):C(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${c.id} cannot be promoted to enforced: ${I.reason}`,before:f.mode,after:c.mode})}else C(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${c.id} was demoted to advisory.`,before:f.mode,after:c.mode})}}i(zo,"compareArkRules");function Cr(e,t,n){let r=[];ne(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ne(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),ne(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Ve(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},o=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(o!==a){let d=s[a]===s[o]?"judgment-required":s[a]>s[o]?"strengthening":"weakening";C(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:d,message:"The cycle enforcement level changed.",before:o,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Ko(r,e.layers,t.layers),Uo(r,e.rules,t.rules),jo(r,e,t),zo(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Go(r,e,t),Vo(r,e,t),r.sort((d,l)=>d.path.localeCompare(l.path)||d.id.localeCompare(l.id)),{schemaVersion:Sr,classification:Bo(r),findings:r}}i(Cr,"classifyArkPolicyDelta");function wr(e,t){if(!e||e.schemaVersion!==Sr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=B(e.findingIds),r=B(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}i(wr,"policyDeltaAcknowledgementMatches");function Ae(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Ae,"normalizePath");function Or(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(Or,"isIdentifierStart");function lt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(lt,"isIdentifierCharacter");function J(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(J,"skipWhitespace");function Ge(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}i(Ge,"readString");function ee(e,t,n){return e.startsWith(t,n)&&!lt(e[n-1])&&!lt(e[n+t.length])}i(ee,"isWordAt");function xr(e,t){let n=J(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=J(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ee(e,"type",n))return!1;let s=J(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ee(e,"as",s)||!Or(e[s]))return!1;for(n=s;n<e.length&<(e[n]);)n+=1;if(n=J(e,n),ee(e,"as",n)){if(n=J(e,n+2),!Or(e[n]))return!1;for(;n<e.length&<(e[n]);)n+=1}r=!0}return!1}i(xr,"bracedNamedBindingsAreTypeOnly");function Wo(e,t){if(t=J(e,t+6),e[t]==="(")return Ge(e,J(e,t+1));let n=!1;if(ee(e,"type",t)){let s=J(e,t+4);e[s]!==","&&!ee(e,"from",s)&&(n=!0)}else xr(e,t)&&(n=!0);let r=_r(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(Wo,"specifierAfterImport");function qo(e,t){t=t+6;let n=J(e,t),r=!1;if(ee(e,"type",n)){let o=J(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else xr(e,n)&&(r=!0);let s=_r(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}i(qo,"specifierAfterExport");function _r(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ee(e,"from",t))return Ge(e,J(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ge(e,t);if(t>0&&(ee(e,"import",t)||ee(e,"export",t)))return}}i(_r,"specifierInStaticStatement");function Yo(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i(Yo,"skipTemplateLiteral");function Xo(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=J(e,t+7);if(e[r]!=="(")return;r=J(e,r+1);let s=Ge(e,r);return s?{...s,requireCall:!0}:void 0}i(Xo,"specifierAfterRequire");function Zo(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
15
|
-
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let o=e.indexOf("*/",n+2);if(o<0)break;n=o+1;continue}if(r==="`"){n=
|
|
16
|
-
`).length;r.push({file:e.path,symbol:o,capability:
|
|
17
|
-
`).length,d={kind:"import",file:e.path,line:a,excerpt:s.excerpt},l=Jo(e.path,o,t);n.push({from:e.path,specifier:o,to:l?.path??null,resolution:l?"resolved":"unresolved",fromLayer:e.layer,toLayer:l?.layer??null,evidence:d})}return{edges:n,capabilityUses:r}}i($r,"moduleFactsFor");function Jo(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let a=n.get(o);if(a)return a}}i(Jo,"resolveSpecifier");function Tr(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=dn(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}i(Tr,"violationsFor");var Qo={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function ea(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(ea,"hasActiveArkRules");function ta(e,t){return ea(e,t)?j(N(kr({config:e,arkRules:t,warnings:[]}))):j(N(Ut(e)))}i(ta,"policyHashFor");function Gt(e,t,n){let r=typeof e=="string"?ur(e,t):$t(e,t),s=n?.arkRules??De();return{...r,arkRules:s,policyHash:ta(r.config,s)}}i(Gt,"loadContract");function na(e){let t=Gt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Gt(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Cr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(d=>d.classification==="weakening"||d.classification==="judgment-required").map(d=>d.id).sort(),o=s.length>0,a=o&&wr(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:o,acknowledged:a,valid:!o||a}}i(na,"analyzePolicyDelta");function ct(e){let t=e.files.map(A=>{let u=Ae(A.path);return{path:u,content:A.content,contentHash:j(A.content),layer:Q(u,e.contract.config.layers)??null}}).sort((A,u)=>A.path.localeCompare(u.path)),n=new Map(t.map(A=>[A.path,A])),r=[],s=[];for(let A of t){let u=$r(A,n);r.push(...u.edges),s.push(...u.capabilityUses)}let o=Tr(r,e.contract.config),a=new Map(e.contract.config.layers.map(A=>[A.name,A])),d=new Map(e.contract.config.layers.map(A=>[A.name,new Set(Ie(A))]));for(let A of s){let u=n.get(A.file)?.layer;if(!u)continue;let f=a.get(u),c=Ne(A.symbol,f?.forbiddenGlobals??[]);if(c){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${A.symbol}" because it is the import form of forbidden global "${c}".`,symbol:A.symbol,evidence:A.evidence});continue}d.get(u)?.has(A.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${A.capability} capability; found import of "${A.symbol}".`,capability:A.capability,symbol:A.symbol,evidence:A.evidence})}let l=t.length===0?"complete":"partial",p=l==="complete"?[]:[{...Qo}],h={schemaVersion:Qt,policyHash:e.contract.policyHash,compilerOptionsHash:j(N(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(A=>A.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:l,completenessReasons:p,valid:l==="complete"&&o.length===0,ir:h}}i(ct,"analyzeProject");function Bt(e){let t=new Map(e.files.map(n=>[Ae(n.path),n]));for(let n of e.changes){let r=Ae(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return ct({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Bt,"analyzeChange");function ra(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(ra,"explainViolation");function Fr(e){return j(N(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Fr,"analysisTreeHash");function sa(e){let t=ct(e),n=new Map(t.ir.files.map(c=>[c.path,c])),r=[],s=new Set,o=[];for(let c of e.changes){let y=c.path.replace(/\\/g,"/"),k=Ae(c.path);if(!k||k===".."||k.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(k)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}s.add(k),"delete"in c&&c.delete&&!n.has(k)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base tree.`}),r.push("delete"in c&&c.delete?{path:k,delete:!0}:{path:k,content:"content"in c?c.content:""})}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Bt({...e,changes:r}),d=new Map(a.ir.files.map(c=>[c.path,c])),l=a.ir.violations.filter(c=>c.ruleId==="CAPABILITY_VIOLATION"||c.ruleId==="FORBIDDEN_GLOBAL").map(c=>{let y=d.get(c.evidence.file)?.layer;return{ruleId:c.ruleId,file:c.evidence.file,line:c.evidence.line,target:c.symbol,...c.capability?{capability:c.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:c.message}}),p=Ke({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(c=>c.path),contentViolations:l,edges:a.ir.edges.filter(c=>!!c.fromLayer).map(c=>({from:c.from,fromLayer:c.fromLayer,...c.to?{to:c.to}:{},...c.toLayer?{toLayer:c.toLayer}:{},line:c.evidence.line,kind:"import",...c.typeOnly?{typeOnly:!0}:{},...c.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),h=r.map(c=>{let y=Ae(c.path),k=n.get(y),E=d.get(y);return{path:y,operation:"delete"in c&&c.delete?"delete":k?"update":"create",...k?{beforeContentHash:k.contentHash}:{},...E?{candidateContentHash:E.contentHash}:{}}}).sort((c,y)=>c.path.localeCompare(y.path)),A=[...o,...p.violations].map(c=>({...c,nextAction:fe(c)})),u=A.filter(c=>c.failsStrict!==!1),f=e.changeMap?je({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[]),candidateDependencies:a.ir.edges.flatMap(c=>c.to?[{from:c.from,to:c.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:Fr(t.ir.files),candidateTreeHash:Fr(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:h,violations:A,warnings:p.warnings}}i(sa,"preflightChange");function oa(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}i(oa,"canonicalChangePath");function aa(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}i(aa,"identityViolations");function ia(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}i(ia,"preparedChange");function la(e){let t=ye(e.baseFacts),n=ye(e.candidateFacts),r=ot({contract:e.contract,facts:t}),s=ot({contract:e.contract,facts:n}),o=new Map(t.files.map(f=>[f.path,f])),a=new Map(n.files.map(f=>[f.path,f])),d=aa(t,n),l=new Map,p=[];for(let f of e.changes){let c=oa(f.path);if(!c){d.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(l.has(c)){d.push({ruleId:"DUPLICATE_CHANGE_PATH",file:c,line:1,message:`The atomic change set contains more than one operation for ${c}.`});continue}l.set(c,f);let y=o.get(c),k=a.get(c);if("delete"in f&&f.delete)y||d.push({ruleId:"DELETE_TARGET_MISSING",file:c,line:1,message:`Cannot delete ${c} because it is not present in the supplied base facts.`}),k&&d.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:c,line:1,message:`Candidate facts still contain deleted file ${c}.`});else{let E="content"in f?f.content:"",I=j(E);k?k.contentHash!==I&&d.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:c,line:1,expectedContentHash:I,candidateContentHash:k.contentHash,message:`Candidate facts for ${c} do not match the declared content.`}):d.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:c,line:1,message:`Candidate facts do not contain changed file ${c}.`})}p.push(ia(f,c,o,a))}e.changes.length===0&&d.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let f of new Set([...o.keys(),...a.keys()])){if(l.has(f))continue;let c=o.get(f),y=a.get(f);c&&y&&N(c)===N(y)||d.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:f,line:1,message:`Candidate facts change ${f}, but the atomic change set does not declare it.`})}let h=e.changeMap?je({changeMap:e.changeMap,changes:p,baseDependencies:r.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:s.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0,A=[...d,...s.ir.violations].map(f=>({...f,nextAction:fe(f)})),u=A.filter(f=>f.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&u.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:p.sort((f,c)=>f.path<c.path?-1:f.path>c.path?1:0),violations:A,warnings:s.ir.warnings}}i(la,"preflightResolvedChange");var Nr=new WeakSet;function Pr(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))Pr(t);return Object.freeze(e)}i(Pr,"deepFreeze");function sc(e){let t=Pr(qe(e));return Nr.add(t),t}i(sc,"createTrustedResolvedCandidateFacts");function oc(e){if(!Nr.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Ft(e)}i(oc,"analyzeTrustedResolvedProject");export{pt as AMBIENT_CAPABILITY_ENTRIES,ut as CAPABILITY_IDS,Rt as DEFAULT_INTENT_PREFIXES,Jt as RESOLVED_CANDIDATE_FACTS_SCHEMA,be as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ht as SOURCE_POLICY_MESSAGES,gt as ambientCoveredByForbiddenGlobals,je as analyzeArchitectureConvergence,Bt as analyzeChange,na as analyzePolicyDelta,ct as analyzeProject,ot as analyzeResolvedProject,oc as analyzeTrustedResolvedProject,Pe as capabilityForAmbientName,Fe as capabilityForModuleSpecifier,kt as classifyPublishFacts,Tt as collectAnalysisConfigWarnings,Mo as collectCapabilityUses,Kt as collectForbiddenCapabilityUses,qe as createResolvedCandidateFacts,sc as createTrustedResolvedCandidateFacts,fr as detectArchitectureCycles,j as deterministicHash,Ie as effectiveCapabilityDeny,Ke as evaluateArchitectureGraph,ra as explainViolation,Ht as extractSemanticDependencies,Ne as forbiddenGlobalForModuleSpecifier,Po as loadArchitectureChangeMap,Gt as loadContract,ye as loadResolvedCandidateFacts,fn as looksLikeArkIntent,Kr as lowerForbiddenGlobal,Xe as loweredLayerCoverage,sa as preflightChange,la as preflightResolvedChange,At as resolveIntentLayer,We as resolvedFactsEvidenceRequirementsHash,N as stableSerialize};
|
|
14
|
+
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Jt,"isObject");function Zt(e,t,n,r){for(let s of Object.keys(e))t.includes(s)||r.push({path:`${n}.${s}`,message:"unknown field"})}a(Zt,"unknownFields");function be(e,t,n,r){let s=e[t];if(typeof s=="string"&&s.length>0)return s;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}a(be,"requiredString");function qi(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}a(qi,"canonicalProjectPath");function Yi(e,t,n="architecture change map"){let r=[];if(!Jt(e))throw new Rt(n,[{path:"$",message:"must be an object"}]);Zt(e,["$schema","schemaVersion","files","dependencies"],"$",r);let s=be(e,"$schema","$",r),o=be(e,"schemaVersion","$",r);o&&o!==Xt&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${Xt}`});let i=new Set(t.layers.map(d=>d.name)),l=[],c=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((d,g)=>{let k=`$.files[${g}]`;if(!Jt(d)){r.push({path:k,message:"must be an object"});return}Zt(d,["path","operation","layer"],k,r);let I=be(d,"path",k,r),S=be(d,"operation",k,r),x=be(d,"layer",k,r),$=I?qi(I):void 0;I&&!$&&r.push({path:`${k}.path`,message:"must be a canonical project-relative path"}),S&&!["create","update","delete"].includes(S)&&r.push({path:`${k}.operation`,message:"must be create, update, or delete"}),x&&!i.has(x)&&r.push({path:`${k}.layer`,message:`references unknown layer ${JSON.stringify(x)}`}),$&&c.has($)&&r.push({path:`${k}.path`,message:`duplicates planned path ${$}`}),$&&c.add($);let q=$?Q($,t.layers):void 0;$&&x&&i.has(x)&&q!==x&&r.push({path:`${k}.layer`,message:q?`${$} resolves to ${q}, not ${x}`:`${$} is not assigned to an architecture layer`}),$&&S&&["create","update","delete"].includes(S)&&x&&l.push({path:$,operation:S,layer:x})});let f=[],h=new Map(l.map(d=>[d.path,d.operation])),R=new Set,u=e.dependencies??[];if(Array.isArray(u)?u.forEach((d,g)=>{let k=`$.dependencies[${g}]`;if(!Jt(d)){r.push({path:k,message:"must be an object"});return}Zt(d,["from","to"],k,r);let I=be(d,"from",k,r),S=be(d,"to",k,r);I&&!c.has(I)&&r.push({path:`${k}.from`,message:`must reference a planned file path: ${I}`}),S&&!c.has(S)&&r.push({path:`${k}.to`,message:`must reference a planned file path: ${S}`}),I&&h.get(I)==="delete"&&r.push({path:`${k}.from`,message:`cannot depend from deleted file ${I}`}),S&&h.get(S)==="delete"&&r.push({path:`${k}.to`,message:`cannot depend on deleted file ${S}`}),I&&S&&I===S&&r.push({path:k,message:"must not declare a self dependency"});let x=I&&S?`${I}\0${S}`:void 0;x&&R.has(x)&&r.push({path:k,message:`duplicates dependency ${I} -> ${S}`}),x&&R.add(x),I&&S&&f.push({from:I,to:S})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new Rt(n,r);let p={$schema:s,schemaVersion:Xt,files:l.sort((d,g)=>d.path.localeCompare(g.path)),dependencies:f.sort((d,g)=>d.from.localeCompare(g.from)||d.to.localeCompare(g.to))};return{map:p,hash:V(F(p))}}a(Yi,"loadArchitectureChangeMap");function J(e){return`${e.from}->${e.to}`}a(J,"dependencyKey");function Ze(e,t,n,r="dependency"){return{id:`${e}:${r}:${J(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${J(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${J(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${J(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${J(t)} from the candidate, then preflight again.`}:{}}}a(Ze,"dependencyFinding");function Qe(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),s=new Map(e.changeMap.map.dependencies.map(u=>[J(u),u])),o=new Map(e.baseDependencies.map(u=>[J(u),u])),i=new Map(e.candidateDependencies.map(u=>[J(u),u]));for(let u of[...n.values()].sort((p,d)=>p.path.localeCompare(d.path))){let p=r.get(u.path);p?p.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:p.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:p.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((p,d)=>p.path.localeCompare(d.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...s.values()].sort((p,d)=>J(p).localeCompare(J(d)))){if(i.has(J(u))){t.push(Ze("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let p={from:u.to,to:u.from};i.has(J(p))?(l.add(J(p)),t.push(Ze("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ze("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,p]of[...i].sort(([d],[g])=>d.localeCompare(g)))o.has(u)||s.has(u)||l.has(u)||!c.has(p.from)&&!c.has(p.to)||t.push({...Ze("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,p]of[...o].sort(([d],[g])=>d.localeCompare(g)))i.has(u)||f.has(p.from)||f.has(p.to)||!c.has(p.from)&&!c.has(p.to)||t.push({...Ze("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,p)=>h[u.classification]-h[p.classification]||(u.subject===p.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(p.id));let R={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:R.missing===0&&R.contradictory===0&&R.unplanned===0,behavioralCompletion:"not-evaluated",summary:R,findings:t}}a(Qe,"analyzeArchitectureConvergence");function Le(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Le,"literalText");function Gr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(Gr,"lineOf");function jr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}a(jr,"isTypeOnlyReference");function Br(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()}a(Br,"singleFileChecker");function Qt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Qt,"symbolAt");function en(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):Qt(t,r)}catch{o=void 0}return!!o?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(en,"localDeclaration");function tn(e,t){let n,r=[],s=a((i,l,c,f=!1)=>r.push({specifier:c,kind:l,line:Gr(t,i),typeOnly:f,unresolved:c===void 0,node:i}),"add"),o=a(i=>{if(e.isImportDeclaration(i))s(i,"import",Le(e,i.moduleSpecifier),jr(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)s(i,"export",Le(e,i.moduleSpecifier),jr(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))s(i,"require",Le(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!en(e,n??(n=Br(e,t)),t,i.expression);(l||f)&&s(i,f?"require":"dynamic-import",Le(e,i.arguments[0]))}e.forEachChild(i,o)},"visit");return o(t),r}a(tn,"extractSemanticDependencies");function Xi(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=Le(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}}a(Xi,"staticAccessPath");function Ji(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}a(Ji,"runtimeIdentifierReference");function Vr(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}}a(Vr,"bestForbiddenMatch");function nn(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Br(e,t),o=new Map,i=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let p of u.declarationList.declarations)e.isIdentifier(p.name)&&i.add(p.name.text);let l=a(u=>{let p=Xi(e,u);if(!p)return;let d=Qt(s,p.root),g=d?o.get(d):void 0;return g?[...g,...p.segments.slice(1)]:en(e,s,t,p.root)||i.has(p.root.text)?void 0:p.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let p of u.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let d=l(p.initializer),g=Qt(s,p.name);!d||!g||o.set(g,d)}let c=[],f=new Set,h=a((u,p)=>{let d=Gr(t,p),g=`${u}:${p.getStart(t)}`;f.has(g)||(f.add(g),c.push({name:u,line:d,node:p}))},"flag"),R=a(u=>{let p=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!p){let d=l(u),g=d?Vr(r,d):void 0;g&&h(g,u)}else e.isIdentifier(u)&&r.has(u.text)&&Ji(e,u)&&!en(e,s,t,u)&&h(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let d=l(u.initializer);if(d)for(let g of u.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?Le(e,g.propertyName)??g.propertyName.text:g.name.text,I=Vr(r,[...d,k]);I&&h(I,u.initializer)}}e.forEachChild(u,R)},"visit");return R(t),c}a(nn,"collectForbiddenCapabilityUses");function Zi(e,t,n){let r=[];for(let s of n?.dependencies??tn(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Ue(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??nn(e,t,Ct)){let o=je(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}a(Zi,"collectCapabilityUses");function rn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:s,...o}=t;return o})}}a(rn,"omitLayerDescriptions");function Wr(e){let{stewards:t,...n}=rn(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}a(Wr,"effectiveContractPolicyPayload");var ts="1.0",Qi="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function E(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Qi}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}a(E,"addFinding");function P(e){return[...new Set(e??[])].sort()}a(P,"sortedUnique");function re(e,t,n,r,s){let o=P(n),i=P(r),l=new Set(o),c=new Set(i),f=i.filter(R=>!l.has(R)),h=o.filter(R=>!c.has(R));f.length===0&&h.length===0||(f.length>0&&E(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:i}),h.length>0&&E(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:i}))}a(re,"compareStringSets");function et(e,t,n,r,s,o,i){if(n===r)return;E(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:i,before:n,after:r})}a(et,"compareBoolean");function At(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}a(At,"keyed");function ea(e,t,n){let r=At(t,o=>o.name),s=At(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&E(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let i=r.values.get(o),l=s.values.get(o),c=`$.layers[${o}]`;if(!i&&l){E(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){E(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;re(e,`${c}.patterns`,i.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),re(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=at(i),h=at(l);re(e,`${c}.forbiddenGlobals`,f.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),re(e,`${c}.capabilities`,f.atoms,h.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),P(i.intentPrefixes).join("\0")!==P(l.intentPrefixes).join("\0")&&E(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:P(i.intentPrefixes),after:P(l.intentPrefixes)}),et(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),et(e,`${c}.optional`,i.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}a(ea,"compareLayers");function ta(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),s=At(t,r),o=At(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&E(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let i of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let l=s.values.get(i),c=o.values.get(i),f=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?E(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):E(e,{kind:"allow-added",path:f,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&E(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&E(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let h=l.peerIsolation===!0,R=c.peerIsolation===!0;if(h!==R){let d=l.from===l.to&&c.from===c.to;E(e,{kind:R?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.peerIsolation`,classification:d?R?"strengthening":"weakening":"judgment-required",message:d?R?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:h,after:R})}P(l.sliceFolders).join("\0")!==P(c.sliceFolders).join("\0")&&E(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:P(l.sliceFolders),after:P(c.sliceFolders)});let u=l.sliceIdentity??"path",p=c.sliceIdentity??"path";if(u!==p&&E(e,{kind:"slice-identity-changed",path:`${f}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:u,after:p}),!(!h&&!R)){if(ln(e,`${f}.sharedRoots`,"shared-roots",P(l.sharedRoots),P(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),ln(e,`${f}.allowedCrossSlice`,"cross-slice-allowance",P((l.allowedCrossSlice??[]).map(an)),P((c.allowedCrossSlice??[]).map(an)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(l.sharedImportsSlice??null)!==(c.sharedImportsSlice??null)){let d=l.sharedImportsSlice??null,g=c.sharedImportsSlice??null,k=es(g)>es(d);E(e,{kind:"shared-imports-slice",path:`${f}.sharedImportsSlice`,classification:k?"strengthening":"weakening",message:ga(d,g),before:d,after:g})}ra(e,f,l,c)}}}a(ta,"compareRules");function zr(e){let t=e.childSlices;return t?JSON.stringify([P(t.sliceFolders??[]),t.sliceIdentity??"path",P(t.commonFolders??[])]):""}a(zr,"childSliceFoldersKey");function na(e){return P((e??[]).map(t=>kt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(na,"enforceKeys");function qr(e){if(!e.childSlices)return null;let t=e.childSlices.siblings;return t==null||t==="deny"?{mode:"deny",enforce:[]}:t==="advisory"?{mode:"advisory",enforce:[]}:t.default==="deny"?{mode:"deny",enforce:[]}:{mode:"advisory",enforce:na(t.enforce)}}a(qr,"childSliceSiblingPolicy");function ra(e,t,n,r){let s=qr(n),o=qr(r);if(s===null&&o===null)return;if(s===null&&o!==null){E(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:o.mode==="advisory"?"judgment-required":"strengthening",message:o.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(s!==null&&o===null){E(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(zr(n)!==zr(r)){E(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(s===null||o===null)return;if(s.mode!==o.mode){let c=o.mode==="advisory";E(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?o.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:s.mode,after:o.mode})}else s.mode==="advisory"&&sa(e,`${t}.childSlices.siblings.enforce`,s.enforce,o.enforce);let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&E(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:i,after:l}),la(e,t,n,r),aa(e,t,n,r)}a(ra,"compareChildSlices");function sa(e,t,n,r){if(JSON.stringify(n)===JSON.stringify(r))return;let s=r.filter(l=>!n.includes(l)),o=n.filter(l=>!r.includes(l)),i=s.length>0&&o.length>0;E(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":s.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":s.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(sa,"compareSiblingEnforceList");function an(e){return JSON.stringify([e.from,e.to])}a(an,"crossSliceKey");function Yr(e){return P((e.childSlices?.allowedCrossSlice??[]).map(an))}a(Yr,"childCrossSliceKeys");function Fe(e){return kt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Fe,"allowanceSegments");function Xr(e,t){let n=Fe(e),r=Fe(t);if(n.length===0||n.length!==r.length)return!1;let s=!1;for(let o=0;o<n.length;o+=1)if(n[o]!==r[o]){if(n[o]==="*"&&r[o]!=="*"){s=!0;continue}return!1}return s}a(Xr,"patternWidens");function oa(e,t){let n=JSON.parse(e),r=JSON.parse(t),s=Fe(n[0]).join("/")===Fe(r[0]).join("/"),o=Fe(n[1]).join("/")===Fe(r[1]).join("/"),i=Xr(n[0],r[0]),l=Xr(n[1],r[1]);return!(s||i)||!(o||l)?!1:i||l}a(oa,"allowanceWidens");function ia(e){return JSON.stringify([kt(e.from.trim().replace(/\\/g,"/")).toLowerCase(),kt(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(ia,"aliasEntryKey");function Jr(e){return P((e.childSlices?.sliceAliases??[]).map(ia))}a(Jr,"sliceAliasKeys");function aa(e,t,n,r){let s=Jr(n),o=Jr(r);if(JSON.stringify(s)===JSON.stringify(o))return;let i=o.filter(f=>!s.includes(f)),l=s.filter(f=>!o.includes(f)),c=i.length>0&&l.length>0;E(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:s,after:o})}a(aa,"compareSliceAliases");function la(e,t,n,r){let s=Yr(n),o=Yr(r);if(JSON.stringify(s)===JSON.stringify(o))return;let i=o.filter(c=>!s.includes(c)),l=s.filter(c=>!o.includes(c));if(i.length>0&&l.length>0&&l.filter(f=>!i.some(h=>oa(h,f))).length===0){E(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:s,after:o});return}ln(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",s,o,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}a(la,"compareChildCrossSliceAllowances");function ln(e,t,n,r,s,o,i){if(JSON.stringify(r)===JSON.stringify(s))return;let l=s.filter(h=>!r.includes(h)),c=r.filter(h=>!s.includes(h)),f=l.length>0&&c.length>0;E(e,{kind:f?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:f?"judgment-required":l.length>0?"weakening":"strengthening",message:f?`${o} Entries were added and removed in the same change.`:l.length>0?o:i,before:r,after:s})}a(ln,"compareDeclaredExceptions");function ca(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let i=r[o]??0,l=s[o]??0;i!==l&&E(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])et(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(ca,"compareSafety");function sn(e){return e.mode==="enforced"?"enforced":"advisory"}a(sn,"arkRunMode");function on(e){return e.mode==="enforced"?"enforced":"advisory"}a(on,"arkOrderMode");function da(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){E(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${on(s)}).`,after:s});return}if(r&&!s){E(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let i=on(r),l=on(s);if(i!==l){let c=i==="advisory"&&l==="enforced";E(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}re(e,`${o}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),re(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(da,"compareArkOrder");function ua(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){E(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${sn(s)}).`,after:s});return}if(r&&!s){E(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let i=sn(r),l=sn(s);if(i!==l){let c=i==="advisory"&&l==="enforced";E(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}re(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),re(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),et(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(ua,"compareArkRun");function fa(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}a(fa,"overallClassification");function Zr(e,t){return`${e}::${t}`}a(Zr,"ruleKey");function Qr(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Zr(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Zr(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Qr,"indexEffectiveRules");function pa(e,t,n,r,s,o){let i=new Map((o??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},f=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of f){let p=l[u],d=c[u],g=`$.arkRules[${u}]`;if(p===void 0&&d!==void 0){E(e,{kind:"arkrules-ref-added",path:g,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:d});continue}if(p!==void 0&&d===void 0){E(e,{kind:"arkrules-ref-removed",path:g,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:p});continue}p!==d&&E(e,{kind:"arkrules-ref-path-changed",path:g,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:p,after:d})}let h=Qr(r),R=Qr(s);for(let u of[...new Set([...h.structure.keys(),...R.structure.keys()])].sort()){let p=h.structure.get(u),d=R.structure.get(u),g=`$.arkRules.structure[${u}]`;if(!p&&d){E(e,{kind:"arkrule-structure-added",path:g,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(p&&!d){E(e,{kind:"arkrule-structure-removed",path:g,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!d)){if(p.mode!==d.mode){let k=p.mode==="advisory"&&d.mode==="enforced";E(e,{kind:k?"arkrule-promoted":"arkrule-demoted",path:`${g}.mode`,classification:k?"strengthening":"weakening",message:k?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:p.mode,after:d.mode})}p.sensor!==d.sensor&&E(e,{kind:"arkrule-sensor-changed",path:`${g}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:p.sensor,after:d.sensor})}}for(let u of[...new Set([...h.invariants.keys(),...R.invariants.keys()])].sort()){let p=h.invariants.get(u),d=R.invariants.get(u),g=`$.arkRules.invariants[${u}]`;if(!p&&d){E(e,{kind:"arkrule-invariant-added",path:g,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(p&&!d){E(e,{kind:"arkrule-invariant-removed",path:g,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!d)&&p.mode!==d.mode)if(p.mode==="advisory"&&d.mode==="enforced"){let I=i?.get(d.id),S=tr(I);S.ok?E(e,{kind:"arkrule-invariant-promoted",path:`${g}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:d.mode}):E(e,{kind:"arkrule-invariant-promote-refused",path:`${g}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${S.reason}`,before:p.mode,after:d.mode})}else E(e,{kind:"arkrule-invariant-demoted",path:`${g}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:p.mode,after:d.mode})}}a(pa,"compareArkRules");function ns(e,t,n){let r=[];re(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),re(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),re(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),et(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},o=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(o!==i){let l=s[i]===s[o]?"judgment-required":s[i]>s[o]?"strengthening":"weakening";E(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:o,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&E(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),ea(r,e.layers,t.layers),ta(r,e.rules,t.rules),ca(r,e,t),pa(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),ua(r,e,t),da(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:ts,classification:fa(r),findings:r}}a(ns,"classifyArkPolicyDelta");function rs(e,t){if(!e||e.schemaVersion!==ts||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=P(e.findingIds),r=P(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}a(rs,"policyDeltaAcknowledgementMatches");function kt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(kt,"trimTrailingSlashes");function es(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(es,"sharedImportsSliceRank");function ga(e,t){return t==="deny"?"A shared root may no longer import a slice.":e==="deny"&&t==="deny-cross-parent"?"A shared root may import a slice again, except when that hop carries another universe.":e==="deny"?"A shared root may import a slice again.":t==="deny-cross-parent"?"A slice may no longer reach another universe through a shared root. ark-check and CI report that path. The write hook and ESLint see one edge at a time and do not block it.":"A slice may reach another universe through a shared root again."}a(ga,"sharedImportsSliceMessage");function ve(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(ve,"normalizePath");function ss(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(ss,"isIdentifierStart");function bt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(bt,"isIdentifierCharacter");function Z(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(Z,"skipWhitespace");function tt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}a(tt,"readString");function ee(e,t,n){return e.startsWith(t,n)&&!bt(e[n-1])&&!bt(e[n+t.length])}a(ee,"isWordAt");function os(e,t){let n=Z(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=Z(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ee(e,"type",n))return!1;let s=Z(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ee(e,"as",s)||!ss(e[s]))return!1;for(n=s;n<e.length&&bt(e[n]);)n+=1;if(n=Z(e,n),ee(e,"as",n)){if(n=Z(e,n+2),!ss(e[n]))return!1;for(;n<e.length&&bt(e[n]);)n+=1}r=!0}return!1}a(os,"bracedNamedBindingsAreTypeOnly");function ma(e,t){if(t=Z(e,t+6),e[t]==="(")return tt(e,Z(e,t+1));let n=!1;if(ee(e,"type",t)){let s=Z(e,t+4);e[s]!==","&&!ee(e,"from",s)&&(n=!0)}else os(e,t)&&(n=!0);let r=is(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(ma,"specifierAfterImport");function ha(e,t){t=t+6;let n=Z(e,t),r=!1;if(ee(e,"type",n)){let o=Z(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else os(e,n)&&(r=!0);let s=is(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}a(ha,"specifierAfterExport");function is(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ee(e,"from",t))return tt(e,Z(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return tt(e,t);if(t>0&&(ee(e,"import",t)||ee(e,"export",t)))return}}a(is,"specifierInStaticStatement");function ya(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}a(ya,"skipTemplateLiteral");function Ra(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=Z(e,t+7);if(e[r]!=="(")return;r=Z(e,r+1);let s=tt(e,r);return s?{...s,requireCall:!0}:void 0}a(Ra,"specifierAfterRequire");function Aa(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
15
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let o=e.indexOf("*/",n+2);if(o<0)break;n=o+1;continue}if(r==="`"){n=ya(e,n);continue}if(r==="'"||r==='"'){let o=tt(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&ee(e,"import",n)?ma(e,n):r==="e"&&ee(e,"export",n)?ha(e,n):r==="r"&&ee(e,"require",n)?Ra(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}a(Aa,"moduleSpecifiers");function as(e,t){let n=[],r=[];for(let s of Aa(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let f=Ue(o);if(!f)continue;let h=e.content.slice(0,s.offset).split(`
|
|
16
|
+
`).length;r.push({file:e.path,symbol:o,capability:f,evidence:{kind:"import",file:e.path,line:h,excerpt:s.excerpt}});continue}let i=e.content.slice(0,s.offset).split(`
|
|
17
|
+
`).length,l={kind:"import",file:e.path,line:i,excerpt:s.excerpt},c=ka(e.path,o,t);n.push({from:e.path,specifier:o,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}a(as,"moduleFactsFor");function ka(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let i=n.get(o);if(i)return i}}a(ka,"resolveSpecifier");function ls(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=_n(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(ls,"violationsFor");var ba={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function va(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(va,"hasActiveArkRules");function Sa(e,t){return va(e,t)?V(F(Wr({config:e,arkRules:t,warnings:[]}))):V(F(rn(e)))}a(Sa,"policyHashFor");function cn(e,t,n){let r=typeof e=="string"?Pr(e,t):Wt(e,t),s=n?.arkRules??ze();return{...r,arkRules:s,policyHash:Sa(r.config,s)}}a(cn,"loadContract");function Ia(e){let t=cn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=cn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=ns(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),o=s.length>0,i=o&&rs(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:o,acknowledged:i,valid:!o||i}}a(Ia,"analyzePolicyDelta");function vt(e){let t=e.files.map(R=>{let u=ve(R.path);return{path:u,content:R.content,contentHash:V(R.content),layer:Q(u,e.contract.config.layers)??null}}).sort((R,u)=>R.path.localeCompare(u.path)),n=new Map(t.map(R=>[R.path,R])),r=[],s=[];for(let R of t){let u=as(R,n);r.push(...u.edges),s.push(...u.capabilityUses)}let o=ls(r,e.contract.config),i=new Map(e.contract.config.layers.map(R=>[R.name,R])),l=new Map(e.contract.config.layers.map(R=>[R.name,new Set(Ce(R))]));for(let R of s){let u=n.get(R.file)?.layer;if(!u)continue;let p=i.get(u),d=Ke(R.symbol,p?.forbiddenGlobals??[]);if(d){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${R.symbol}" because it is the import form of forbidden global "${d}".`,symbol:R.symbol,evidence:R.evidence});continue}l.get(u)?.has(R.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${R.capability} capability; found import of "${R.symbol}".`,capability:R.capability,symbol:R.symbol,evidence:R.evidence})}let c=t.length===0?"complete":"partial",f=c==="complete"?[]:[{...ba}],h={schemaVersion:Rn,policyHash:e.contract.policyHash,compilerOptionsHash:V(F(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(R=>R.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:f,valid:c==="complete"&&o.length===0,ir:h}}a(vt,"analyzeProject");function dn(e){let t=new Map(e.files.map(n=>[ve(n.path),n]));for(let n of e.changes){let r=ve(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return vt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(dn,"analyzeChange");function Ea(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}a(Ea,"explainViolation");function cs(e){return V(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(cs,"analysisTreeHash");function Ca(e){let t=vt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],s=new Set,o=[];for(let d of e.changes){let g=d.path.replace(/\\/g,"/"),k=ve(d.path);if(!k||k===".."||k.startsWith("../")||g.startsWith("/")||/^[A-Za-z]:\//.test(g)||g.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(k)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}s.add(k),"delete"in d&&d.delete&&!n.has(k)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:k,delete:!0}:{path:k,content:"content"in d?d.content:""})}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=dn({...e,changes:r}),l=new Map(i.ir.files.map(d=>[d.path,d])),c=i.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let g=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...g?{fromLayer:g}:{},edgeKind:"import",message:d.message}}),f=Je({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(d=>d.path),contentViolations:c,edges:i.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),h=r.map(d=>{let g=ve(d.path),k=n.get(g),I=l.get(g);return{path:g,operation:"delete"in d&&d.delete?"delete":k?"update":"create",...k?{beforeContentHash:k.contentHash}:{},...I?{candidateContentHash:I.contentHash}:{}}}).sort((d,g)=>d.path.localeCompare(g.path)),R=[...o,...f.violations].map(d=>({...d,nextAction:pe(d)})),u=R.filter(d=>d.failsStrict!==!1),p=e.changeMap?Qe({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:i.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&u.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:cs(t.ir.files),candidateTreeHash:cs(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:h,violations:R,warnings:f.warnings}}a(Ca,"preflightChange");function wa(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}a(wa,"canonicalChangePath");function xa(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}a(xa,"identityViolations");function Oa(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}a(Oa,"preparedChange");function _a(e){let t=ye(e.baseFacts),n=ye(e.candidateFacts),r=yt({contract:e.contract,facts:t}),s=yt({contract:e.contract,facts:n}),o=new Map(t.files.map(p=>[p.path,p])),i=new Map(n.files.map(p=>[p.path,p])),l=xa(t,n),c=new Map,f=[];for(let p of e.changes){let d=wa(p.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,p);let g=o.get(d),k=i.get(d);if("delete"in p&&p.delete)g||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),k&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let I="content"in p?p.content:"",S=V(I);k?k.contentHash!==S&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:S,candidateContentHash:k.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}f.push(Oa(p,d,o,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...o.keys(),...i.keys()])){if(c.has(p))continue;let d=o.get(p),g=i.get(p);d&&g&&F(d)===F(g)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let h=e.changeMap?Qe({changeMap:e.changeMap,changes:f,baseDependencies:r.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:s.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,R=[...l,...s.ir.violations].map(p=>({...p,nextAction:pe(p)})),u=R.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&u.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:f.sort((p,d)=>p.path<d.path?-1:p.path>d.path?1:0),violations:R,warnings:s.ir.warnings}}a(_a,"preflightResolvedChange");var ds=new WeakSet;function us(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))us(t);return Object.freeze(e)}a(us,"deepFreeze");function Cd(e){let t=us(ot(e));return ds.add(t),t}a(Cd,"createTrustedResolvedCandidateFacts");function wd(e){if(!ds.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Yt(e)}a(wd,"analyzeTrustedResolvedProject");export{Ct as AMBIENT_CAPABILITY_ENTRIES,It as CAPABILITY_IDS,Lt as DEFAULT_INTENT_PREFIXES,yn as RESOLVED_CANDIDATE_FACTS_SCHEMA,Ie as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Tt as SOURCE_POLICY_MESSAGES,wt as ambientCoveredByForbiddenGlobals,Qe as analyzeArchitectureConvergence,dn as analyzeChange,Ia as analyzePolicyDelta,vt as analyzeProject,yt as analyzeResolvedProject,wd as analyzeTrustedResolvedProject,je as capabilityForAmbientName,Ue as capabilityForModuleSpecifier,Nt as classifyPublishFacts,zt as collectAnalysisConfigWarnings,Zi as collectCapabilityUses,nn as collectForbiddenCapabilityUses,ot as createResolvedCandidateFacts,Cd as createTrustedResolvedCandidateFacts,Mr as detectArchitectureCycles,V as deterministicHash,Ce as effectiveCapabilityDeny,Je as evaluateArchitectureGraph,Ea as explainViolation,tn as extractSemanticDependencies,Ke as forbiddenGlobalForModuleSpecifier,Yi as loadArchitectureChangeMap,cn as loadContract,ye as loadResolvedCandidateFacts,Ln as looksLikeArkIntent,hs as lowerForbiddenGlobal,at as loweredLayerCoverage,Ca as preflightChange,_a as preflightResolvedChange,Ft as resolveIntentLayer,st as resolvedFactsEvidenceRequirementsHash,F as stableSerialize};
|