arkgate 4.8.21 → 4.8.22
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 +48 -0
- package/README.md +2 -2
- package/bin/lib/analysis-engine.mjs +8 -8
- package/bin/lib/invariant-coverage.mjs +27 -3
- package/dist/{diagnosticCatalog-B7BXlet6.d.ts → diagnosticCatalog-WD2TPSwZ.d.ts} +8 -3
- package/dist/index.cjs +29 -29
- package/dist/index.d.ts +2 -2
- package/dist/index.js +30 -30
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +19 -19
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +19 -19
- package/docs/README.md +2 -1
- package/docs/product-voice.md +1 -1
- package/package.json +2 -1
- 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 zt=["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 ze(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(ze,"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 Wt(e){let t=Dr(e);return{...t,factsHash:j(N(t))}}i(Wt,"createCanonicalResolvedCandidateFacts");function We(e){return Wt(Yt(F(e,"$"),!1))}i(We,"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 qt(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(qt,"requiredInteger");function z(e,t,n){let r=qt(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 Yt(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:qt(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",zt,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)}}),xe=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",xe],["$.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 Be=oe(e,"projectPackageName","$"),Bt=(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","$"),...Be?{projectPackageName:Be}:{},files:o,dependencies:a,capabilityUses:d,ambientUses:l,publishCalls:p,intentReferences:h,safetyUses:A,classShapes:Bt,arkRunKernelCalls:c,arkRunManagedNews:k,arkRunCompositionRootHits:I,arkRunDeclarations:xe,arkOrderPlaneCalls:W,arkOrderGenericUpdates:T,arkOrderRootHits:ge,arkOrderXiFieldWrites:se,arkOrderIngestWritesXi:me,arkOrderReleaseKeyCounts:ke}}i(Yt,"parseResolvedFactsInput");function ye(e){let t=F(e,"$"),n=_(t,"factsHash","$"),r=_(t,"candidateTreeHash","$"),s=Wt(Yt(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])(?!.*\\/$).+$"},Xt={$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 Zt="1.0";var dt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),qe=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),ft=Object.freeze(Object.keys(qe).sort()),ct=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),ut=Object.freeze({process:Object.freeze(["process","node:process"])});function Te(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=ct[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=ct[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:ct[e.slice(0,o)]??null}i(Te,"capabilityForModuleSpecifier");function Fe(e,t){for(let n of t)if(ut[n]?.includes(e))return n;return null}i(Fe,"forbiddenGlobalForModuleSpecifier");function Ne(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=qe[r];if(s)return s}return null}i(Ne,"capabilityForAmbientName");function Ie(e){if(e?.pure===!0)return[...dt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>dt.includes(r));return[...new Set(n)].sort()}i(Ie,"effectiveCapabilityDeny");function pt(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(pt,"ambientCoveredByForbiddenGlobals");function Ye(e){let t=new Set,n=new Set,r=Object.keys(qe);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 ut[s]??[])t.add(`import-exact:${a}`)}for(let s of Ie(e)){if(t.add(`import:${s}`),s==="process")for(let o of ut.process)t.add(`import-exact:${o}`);for(let o of r)Ne(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Ye,"loweredLayerCoverage");function Kr(e){let t=new Set,n=Ne(e);n&&t.add(n);for(let[r,s]of Object.entries(qe))(r===e||r.startsWith(`${e}.`))&&t.add(s);return[...t].sort()}i(Kr,"lowerForbiddenGlobal");var Jt=new Map;function Qt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Qt,"escapeLiteral");function Ze(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(Ze,"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=Jt.get(e);if(t)return t;let n=Ze(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+=Qt(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+=Qt(l)}let a=new RegExp(`^${s}$`);return Jt.set(e,a),a}i(ie,"globToRegExp");function jr(e){return Ze(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(jr,"concreteGlobSegments");function mt(e,t){let n=Ze(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(mt,"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=mt(a,n);d>s&&(s=d,r=o.name)}}return r}i(Q,"layerForRelativePath");function Xe(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(nn(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(Xe,"sliceIdForPath");function nn(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}i(nn,"isAnchoredSliceEntry");function Vr(e,t,n){let r=t.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),s=an(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 rn(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(rn,"sliceIdentityCollisions");function Br(e){if(!nn(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=Ze(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 sn(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(sn,"resolveSliceFolders");function en(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(en,"normalizeSegments");function on(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(on,"trimTrailingSlashes");var Yr=["src","app"];function an(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Yr.includes(n)&&r!==n?[0,1]:[0]}i(an,"anchorOffsets");function Xr(e){let t=on(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(Xr,"isBlanketRoot");function gt(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=en(n);for(let o of t){if(typeof o!="string"||o.length===0||Xr(o))continue;if(o.includes("*")){let l=on(o.toLowerCase());if(ie(l).test(r)||ie(`${l}/**`).test(r))return!0;continue}let a=en(o);if(a.length===0)continue;let d=an(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(gt,"pathUnderSharedRoot");function tn(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(tn,"sliceMatchesDeclaration");function Zr(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&tn(r.from,t)&&tn(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 Je(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(Je,"peerIsolationDenyExplanation");function ln(e,t,n,r){return Pe(e,t,n,r)?.rule}i(ln,"findDeniedEdgeRule");function Pe(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=sn(s,t,r?.layers),l=o?Xe(o,d,s.sliceIdentity):void 0,p=a?Xe(a,d,s.sliceIdentity):void 0,h=Jr({fromPath:o,toPath:a,folderCount:d.length,fromSlice:l,toSlice:p,fromShared:!l&>(o,s.sharedRoots),toShared:!p&>(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(Pe,"findDeniedEdgeDecision");function cn(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=sn(a,t,r?.layers),l=Xe(s,d,a.sliceIdentity),p=Xe(o,d,a.sliceIdentity);if(!(l||!p)&>(s,a.sharedRoots))return{fromPath:s,toPath:o,toSlice:p}}}i(cn,"findSharedImportsSliceBridge");var yt={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."},ht=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Rt(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(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(Rt,"resolveIntentLayer");function dn(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(dn,"looksLikeArkIntent");function At(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&dn(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:yt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:yt.PUBLISH_MISSING_SOURCE}),t}i(At,"classifyPublishFacts");var un="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 fn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Oa={$schema:"https://json-schema.org/draft/2020-12/schema",$id:un,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:un},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:fn,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:fn}}}};function Le(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Le,"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}i(pn,"structureFreezeTarget");var es=["no-anemic-model"],Rn=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Fa=new RegExp(`\\b(${Rn.join("|")})\\b`),An="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",Na=new RegExp(`\\bthis\\.${An}\\.push\\s*\\(`),Pa=new RegExp(`^this\\.${An}\\s*=\\s*\\[\\s*\\]`);var ts="truncatedUntil";function ns(){return`${Rn.join(", ")}, or events-array .push(`}i(ns,"expectedDomainInvariantWordsPhrase");function kt(e){let t=Object.getOwnPropertyDescriptor(e,ts)?.value;return typeof t=="number"?t:void 0}i(kt,"shapeTruncatedUntil");function rs(e){let t=kt(e);return t==null?"":` shape analysed until character ${t}`}i(rs,"shapeTruncationSuffix");function gn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(gn,"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+=gn(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=gn(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 kn(e){return es.includes(e)}i(kn,"isTier2");function bn(e){return e.mode==="enforced"&&!kn(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(bn,"severityFor");function ue(e,t,n,r=1){let{severity:s,failsStrict:o}=bn(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 Qe(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Qe,"isInRuleLayer");function et(e,t,n){return t.filter(r=>!(!r.exported||!Ee(r.file,e.appliesTo)||!Qe(r.file,e,n)))}i(et,"shapesForRule");function os(e,t,n){let r=[];for(let s of et(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 et(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 et(e,t,n)){let a=rs(o);kt(o)!=null&&r.push(ue(e,o.file,`Exported class ${o.className} shape analysed until character ${kt(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)&&Qe(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)&&Qe(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)&&Qe(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 et(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 vn(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(vn,"evaluateArkRuleSensors");function In(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}=bn(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(In,"collectEmptyAppliesToFindings");var mn=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>mn?t.slice(0,mn):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 En(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)&&!kn(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(En,"collectEmptyInvariantCatalogFindings");var yn=/\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)/,hn=/\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(yn.test(e)||hn.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(yn.test(s)||hn.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 Sn(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(Sn,"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 Cn(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(Cn,"formatCoverageDiscards");function xn(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(xn,"isUnderCoverageRoot");function _n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(_n,"escapeRegExp");function bt(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}i(bt,"normalizePath");function $n(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]!==`
|
|
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
4
|
`;)n.push(" "),r+=1;continue}if(o==="/"&&a==="*"){for(n.push(" "," "),r+=2;r<s&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
|
|
5
5
|
`?`
|
|
6
6
|
`:" "),r+=1;r<s&&(n.push(" "," "),r+=2);continue}if(o==='"'||o==="'"||o==="`"){let d=o;for(n.push(t?" ":o),r+=1;r<s;){let l=e[r];if(l==="\\"){let p=e[r+1];t?n.push(" ",p===void 0?"":" "):(n.push("\\"),p!==void 0&&n.push(p)),r+=p===void 0?1:2;continue}if(l===d){n.push(t?" ":l),r+=1;break}n.push(t&&l!==`
|
|
7
|
-
`?" ":l),r+=1}continue}n.push(o),r+=1}return n.join("")}i(
|
|
7
|
+
`?" ":l),r+=1}continue}n.push(o),r+=1}return n.join("")}i(Et,"maskNonCode");function xs(e,t){if(!t)return;let n=It(t),o=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(Et(e,!1))?.[2];return o===void 0?void 0:o}i(xs,"matchTestTitle");function _s(e,t){if(!t)return;let n=It(t),r=Et(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}i(_s,"declarationShape");function $s(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)}i($s,"lineAt");function Ts(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}i(Ts,"isImportLine");function
|
|
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(wn,"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 On(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}i(On,"sortedContentFiles");function Ns(e,t,n=!0){let r=t.testFiles??[],s=new Set(r.map(f=>bt(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||xn(f,o)){l={file:f,title:y};break}p??={file:f,title:y}}}l??=p}let h;if(d)for(let f of On(t.fileContents)){if(s.has(bt(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=wn(c,e.id,!0);if(y){A={file:f,context:y};break}}if(!A&&d)for(let f of On(t.fileContents)){if(s.has(bt(f)))continue;let c=t.fileContents[f];if(!c)continue;let y=wn(c,d.name,!1);if(y){A={file:f,context:y};break}}}return{best: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"},...l?{testTitle:l}:{},...h?{declaration:h}:{}}}i(Ns,"rankCoverage");function Ps(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"none":return!1}}i(Ps,"countsAsCoverage");function Ls(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(Ls,"mentionWhere");function Ds(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 ${Ls(t.context)} in ${t.file}; put it in a describe/it title`;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}i(Ds,"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=Cn(o),d=Cn(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=Ps(O),b,T;E&&I.testTitle&&(b=I.testTitle.file,h&&(T=!xn(b,p)));let we=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}:{},...we!==void 0?{symbolEvidenceFile:we}:{},...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,Oe=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}: ${Ds(c,O)} (${Oe==="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:Oe})}}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 Ms(e){return!e||typeof e!="object"?[]:[...vt(e.testGlobs),...vt(e.coverageRoots)]}i(Ms,"configuredInvariantTestsPaths");function Hs(e){return Ms(e).length>0}i(Hs,"hasConfiguredInvariantTestsPath");function It(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}i(It,"catalogDemandsInvariantTestsPath");function Pn(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&It(e.invariants);return e.adopted!==!0||!t?[]:Hs(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 Ks(e){return!e||typeof e!="object"?[]:vt(e.coverageRoots)}i(Ks,"configuredCoverageRoots");function Us(e){return Ks(e).length>0}i(Us,"hasConfiguredCoverageRoots");function Et(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}i(Et,"catalogHasEnforcedInvariant");function Ln(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Et(e.invariants)?Us(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 js(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(js,"normalizeExtraMergeTeethClassification");function tt(e){let t=js(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(tt,"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 Vs=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var ja=new Set(Vs);function Mn(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(Mn,"isArkRunKernelModuleSpecifier");var Gs=["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"],St=new Set(Gs);function Hn(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(St.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(St.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:St.has(e.slice(0,r))}i(Hn,"isArkRunTransportBypassSpecifier");var Bs=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,zs=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ws=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function qs(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Bs.test(n)?"pure-shared":r==="PersistenceAdapters"&&(zs.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Ws.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}i(qs,"classifyLayerImportKind");function Ys(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=qs(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(Ys,"layerImportNextAction");function Xs(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(Xs,"arkRunCallSiteName");function Zs(e){let t=Xs(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(Zs,"arkRunNextAction");function fe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ys(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 Zs(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 Js=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],ei=new Set(Js);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"},Qs="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 eo(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(eo,"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 to(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(to,"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 no(e){return e==="resolve"||e==="resolve-singleton"}i(no,"dependKinds");function ro(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(ro,"evaluateMissingRoot");function so(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(so,"evaluateKernelInDomain");function oo(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(oo,"evaluateDirectNew");function ao(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)&&!no(l.kind))continue;let p=r(l.file);if(!p||!d.has(p))continue;if(!l.nameLiteral){e.mode==="enforced"&&a.push({code:Qs,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=to(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(ao,"evaluateUndeclared");function io(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(io,"evaluateTransportBypass");function Gn(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=tt(e.classification),r=ao(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...ro(t,e.compositionRootHits,n),...so(t,e.layers,e.dependencies,e.layerForFile,n),...oo(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...io(t,e.dependencies,e.layerForFile,n)].sort(eo),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 lo(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(lo,"normalizeAppliesToGlob");function co(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(co,"appliesToBracesBalanced");function uo(e){let t=zn.get(e);if(t)return t;let n=lo(e),r=co(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(uo,"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 fo(e,t){return!t||t.length===0?!0:t.some(n=>uo(n).test(e))}i(fo,"matchesArkOrderAppliesTo");function po(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(po,"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=tt(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&&po(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)||fo(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 De(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(De,"isObject");function Jn(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)De(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}i(Jn,"declaredLayerNames");function Qn(e){if(!De(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(!De(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||!De(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||!De(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 nt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}i(nt,"normalizeStewardId");function rr(e){let t=nt(e);return!t||Ct(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}i(rr,"isGitHubHandle");function go(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Ct(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}i(go,"isGitHubEmail");function mo(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&rr(t[1])?nt(t[1]):null}i(mo,"githubHandleFromEmail");function sr(e){let t=mo(e);if(t)return t;let n=nt(e);return!n||Ct(n)?null:rr(n)||go(n)?n:null}i(sr,"canonicalStewardId");var yo=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Ct(e){let t=nt(e);return!t||yo.test(t)}i(Ct,"isAutomationAuthor");var te="1.3",ho=["public","auth","admin","internal"];function Ro(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}i(Ro,"isFutureHouseLayer");function Ao(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(Ao,"layerOwnersList");function ir(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ro(t)&&!Ao(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 wt="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",or=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],ko=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function bo(){let e=[];for(let t of or)for(let n of or)t===n||ko.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}i(bo,"createDefaultRules");var cr=bo(),Ot=[{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:wt,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:wt,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:[...ho]},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)}i($s,"lineAt");function Ts(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}i(Ts,"isImportLine");function xn(e,t,n){if(!t||!e.includes(t))return;let r=new Set,s=0,o=e.length,a=i((d,l)=>{if(e.startsWith(t,d)){if(l==="comment"){r.add("comment");return}if(l==="string"){r.add("string");return}if(Ts($s(e,d))){r.add("import");return}n&&r.add("test-body")}},"note");for(;s<o;){let d=e[s],l=e[s+1];if(d==="/"&&l==="/"){for(;s<o&&e[s]!==`
|
|
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}):
|
|
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 rt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}i(rt,"propertyPath");function Se(e){return e===null?"null":Array.isArray(e)?"array":typeof e}i(Se,"valueType");function vo(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}i(vo,"resolveSchemaRef");function Me(e,t,n,r,s){if(t.$ref){let o=vo(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Me(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 ${Se(e)}`});return}let o=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:rt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in o||s.push({path:rt(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||Me(e[d],a,rt(n,d),r,s)}for(let[a,d]of Object.entries(o))e[a]!==void 0&&Me(e[a],d,rt(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${Se(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let 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)=>Me(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 ${Se(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${Se(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${Se(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}i(Me,"validateNode");function Io(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(Io,"validateLayerOwners");function Eo(e){let t={...e,$schema:e.$schema===void 0?wt: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(Eo,"defaultedConfig");function So(e){return e===te?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}i(So,"migratedFromOf");function Co(){let e=new Set([te]);for(let t of Ot)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}i(Co,"knownInputVersions");function wo(e,t="ark.config.json"){if(!dr(e))throw new ce(t,[{path:"$",message:`must be an object; received ${Se(e)}`}]);let n=Co(),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<Ot.length+1;){a+=1;let d=Ot.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:Eo(o),migratedFrom:So(r)}}i(wo,"migrateArkConfig");function xt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=wo(e,t),s=[];if(Me(n,ar,"$",ar,s),tr(n,s),nr(n,s),Io(n,s),s.length>0)throw new ce(t,s);return{config:n,migratedFrom:r}}i(xt,"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 xt(n,t)}i(ur,"parseArkConfigJson");function G(e,t,n={}){return{ruleId:e,message:t,...n}}i(G,"configWarning");function _t(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=mt(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 rn(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(_t,"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 He(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=Pe(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!a){let u=cn(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?Je(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(He,"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:pn({sensor:e.sensor,code:e.code})}:{},...r||s?{freezable:!1}:{},nextAction:t}}i(pr,"toArkRuleEngineViolation");function Oo(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}i(Oo,"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 xo(e,t){return t.some(n=>{try{return ie(n).test(e)}catch{return!1}})}i(xo,"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")&&!xo(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 $o(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i($o,"ambientForbiddenGlobal");function mr(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Rt(e,n.length>0?n:ht.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(mr,"intentLayer");function To(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||!$o(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"&&pt(o.symbol,l))){if(o.source==="import-based"){let h=Fe(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 At({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=Pe(e.contract.config.rules,a,d,{fromPath:o.file,layers:e.contract.config.layers});if(!l)continue;let p=l.rule.peerIsolation?Je(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(To,"contentViolations");function $t(e){let{facts:t}=e,n=ze(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}`,$e=`${q.code}\0${q.file??""}\0${q.message}`;return _e<$e?-1:_e>$e?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=_t({config:e.contract.config,rules:e.contract.config.rules,files:a.map(m=>m.path)}),h=_o(e,t),A=e.contract.arkRules??Le(),u=a.map(m=>m.path),c={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Sn(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=i(m=>d.get(m)??Q(m,e.contract.config.layers),"resolveLayer"),k=[...vn({arkRules:A,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:y,fileHints:c}),...In(A,u),...En({arkRulesActive:Oo(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:Et(A.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),O=I.length>0?[]:Pn({adopted:e.adopted===!0,hasDomainInvariants:It(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},we=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).`})),Ge=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:Ge}),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}:{}})),Oe=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:Ge}),xe=e.contract.config.arkOrder?.mode,Be=ke.findings.filter(()=>xe==="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}:{}})),Gt=ke.findings.filter(()=>xe!=="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=He({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(m=>m.layer).map(m=>m.path),contentViolations:[...To(e,t,d),...W,...$,...we,...me,...Be],edges:l,warnings:[...p,...h.warnings,...b,...ge,...Oe,...Gt],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}`,$e=`${q.code}\0${q.file??""}\0${q.message}`;return _e<$e?-1:_e>$e?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($t,"analyzeCanonicalResolvedProject");function st(e){return $t({contract:e.contract,facts:ye(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}i(st,"analyzeResolvedProject");var Tt="1.0";var ot=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 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}):
|
|
13
13
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
14
|
-
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}i(Ft,"isObject");function Nt(e,t,n,r){for(let s of Object.keys(e))t.includes(s)||r.push({path:`${n}.${s}`,message:"unknown field"})}i(Nt,"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 Fo(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(Fo,"canonicalProjectPath");function No(e,t,n="architecture change map"){let r=[];if(!Ft(e))throw new ot(n,[{path:"$",message:"must be an object"}]);Nt(e,["$schema","schemaVersion","files","dependencies"],"$",r);let s=Re(e,"$schema","$",r),o=Re(e,"schemaVersion","$",r);o&&o!==Tt&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${Tt}`});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(!Ft(c)){r.push({path:k,message:"must be an object"});return}Nt(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?Fo(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(!Ft(c)){r.push({path:k,message:"must be an object"});return}Nt(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 ot(n,r);let f={$schema:s,schemaVersion:Tt,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(No,"loadArchitectureChangeMap");function Z(e){return`${e.from}->${e.to}`}i(Z,"dependencyKey");function Ke(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(Ke,"dependencyFinding");function Ue(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(Ke("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(Ke("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ke("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({...Ke("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({...Ke("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(Ue,"analyzeArchitectureConvergence");function Ce(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Ce,"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 Pt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(Pt,"symbolAt");function Lt(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):Pt(t,r)}catch{o=void 0}return!!o?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Lt,"localDeclaration");function Dt(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",Ce(e,a.moduleSpecifier),yr(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)s(a,"export",Ce(e,a.moduleSpecifier),yr(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))s(a,"require",Ce(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"&&!Lt(e,n??(n=Ar(e,t)),t,a.expression);(d||p)&&s(a,p?"require":"dynamic-import",Ce(e,a.arguments[0]))}e.forEachChild(a,o)},"visit");return o(t),r}i(Dt,"extractSemanticDependencies");function Po(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=Ce(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(Po,"staticAccessPath");function Lo(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(Lo,"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 Mt(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=Po(e,u);if(!f)return;let c=Pt(s,f.root),y=c?o.get(c):void 0;return y?[...y,...f.segments.slice(1)]:Lt(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=Pt(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)&&Lo(e,u)&&!Lt(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?Ce(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(Mt,"collectForbiddenCapabilityUses");function Do(e,t,n){let r=[];for(let s of n?.dependencies??Dt(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Te(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??Mt(e,t,ft)){let o=Ne(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(Do,"collectCapabilityUses");function Ht(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:s,...o}=t;return o})}}i(Ht,"omitLayerDescriptions");function kr(e){let{stewards:t,...n}=Ht(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",Mo="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 ${Mo}`: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 je(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(je,"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()}}i(at,"keyed");function Ho(e,t,n){let r=at(t,o=>o.name),s=at(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=Ye(a),h=Ye(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)}),je(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."),je(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(Ho,"compareLayers");function Ko(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),s=at(t,r),o=at(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(Ko,"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 Uo(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"])je(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Uo,"compareSafety");function Kt(e){return e.mode==="enforced"?"enforced":"advisory"}i(Kt,"arkRunMode");function Ut(e){return e.mode==="enforced"?"enforced":"advisory"}i(Ut,"arkOrderMode");function jo(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 (${Ut(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=Ut(r),d=Ut(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(jo,"compareArkOrder");function Vo(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 (${Kt(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=Kt(r),d=Kt(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."}),je(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Vo,"compareArkRun");function Go(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(Go,"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 Bo(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(Bo,"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."}),je(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}),Ho(r,e.layers,t.layers),Ko(r,e.rules,t.rules),Uo(r,e,t),Bo(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Vo(r,e,t),jo(r,e,t),r.sort((d,l)=>d.path.localeCompare(l.path)||d.id.localeCompare(l.id)),{schemaVersion:Sr,classification:Go(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 it(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(it,"isIdentifierCharacter");function J(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(J,"skipWhitespace");function Ve(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(Ve,"readString");function ee(e,t,n){return e.startsWith(t,n)&&!it(e[n-1])&&!it(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&&it(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&&it(e[n]);)n+=1}r=!0}return!1}i(xr,"bracedNamedBindingsAreTypeOnly");function zo(e,t){if(t=J(e,t+6),e[t]==="(")return Ve(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(zo,"specifierAfterImport");function Wo(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(Wo,"specifierAfterExport");function _r(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ee(e,"from",t))return Ve(e,J(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ve(e,t);if(t>0&&(ee(e,"import",t)||ee(e,"export",t)))return}}i(_r,"specifierInStaticStatement");function qo(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(qo,"skipTemplateLiteral");function Yo(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=Ve(e,r);return s?{...s,requireCall:!0}:void 0}i(Yo,"specifierAfterRequire");function Xo(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=
|
|
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=Yo(e,n);continue}if(r==="'"||r==='"'){let o=Ge(e,n);o&&(n=o.offset+o.excerpt.length-1);continue}let s=r==="i"&&ee(e,"import",n)?Wo(e,n):r==="e"&&ee(e,"export",n)?qo(e,n):r==="r"&&ee(e,"require",n)?Xo(e,n):void 0;s&&(t.push(s),n=s.offset+s.excerpt.length-1)}return t}i(Zo,"moduleSpecifiers");function $r(e,t){let n=[],r=[];for(let s of Zo(e.content)){let o=s.value;if(!o.startsWith(".")){if(s.typeOnly)continue;let p=Fe(o);if(!p)continue;let h=e.content.slice(0,s.offset).split(`
|
|
16
16
|
`).length;r.push({file:e.path,symbol:o,capability:p,evidence:{kind:"import",file:e.path,line:h,excerpt:s.excerpt}});continue}let a=e.content.slice(0,s.offset).split(`
|
|
17
|
-
`).length,d={kind:"import",file:e.path,line:a,excerpt:s.excerpt},l=Zo(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 Zo(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(Zo,"resolveSpecifier");function Tr(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=ln(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 Jo={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 Qo(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(Qo,"hasActiveArkRules");function ea(e,t){return Qo(e,t)?j(N(kr({config:e,arkRules:t,warnings:[]}))):j(N(Ht(e)))}i(ea,"policyHashFor");function jt(e,t,n){let r=typeof e=="string"?ur(e,t):xt(e,t),s=n?.arkRules??Le();return{...r,arkRules:s,policyHash:ea(r.config,s)}}i(jt,"loadContract");function ta(e){let t=jt(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=jt(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(ta,"analyzePolicyDelta");function lt(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=Fe(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"?[]:[{...Jo}],h={schemaVersion:Zt,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(lt,"analyzeProject");function Vt(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 lt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Vt,"analyzeChange");function na(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(na,"explainViolation");function Fr(e){return j(N(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(Fr,"analysisTreeHash");function ra(e){let t=lt(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=Vt({...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=He({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?Ue({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(ra,"preflightChange");function sa(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(sa,"canonicalChangePath");function oa(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(oa,"identityViolations");function aa(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(aa,"preparedChange");function ia(e){let t=ye(e.baseFacts),n=ye(e.candidateFacts),r=st({contract:e.contract,facts:t}),s=st({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=oa(t,n),l=new Map,p=[];for(let f of e.changes){let c=sa(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(aa(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?Ue({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(ia,"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 rc(e){let t=Pr(We(e));return Nr.add(t),t}i(rc,"createTrustedResolvedCandidateFacts");function sc(e){if(!Nr.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return $t(e)}i(sc,"analyzeTrustedResolvedProject");export{ft as AMBIENT_CAPABILITY_ENTRIES,dt as CAPABILITY_IDS,ht as DEFAULT_INTENT_PREFIXES,Xt as RESOLVED_CANDIDATE_FACTS_SCHEMA,be as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,yt as SOURCE_POLICY_MESSAGES,pt as ambientCoveredByForbiddenGlobals,Ue as analyzeArchitectureConvergence,Vt as analyzeChange,ta as analyzePolicyDelta,lt as analyzeProject,st as analyzeResolvedProject,sc as analyzeTrustedResolvedProject,Ne as capabilityForAmbientName,Te as capabilityForModuleSpecifier,At as classifyPublishFacts,_t as collectAnalysisConfigWarnings,Do as collectCapabilityUses,Mt as collectForbiddenCapabilityUses,We as createResolvedCandidateFacts,rc as createTrustedResolvedCandidateFacts,fr as detectArchitectureCycles,j as deterministicHash,Ie as effectiveCapabilityDeny,He as evaluateArchitectureGraph,na as explainViolation,Dt as extractSemanticDependencies,Fe as forbiddenGlobalForModuleSpecifier,No as loadArchitectureChangeMap,jt as loadContract,ye as loadResolvedCandidateFacts,dn as looksLikeArkIntent,Kr as lowerForbiddenGlobal,Ye as loweredLayerCoverage,ra as preflightChange,ia as preflightResolvedChange,Rt as resolveIntentLayer,ze as resolvedFactsEvidenceRequirementsHash,N as stableSerialize};
|
|
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};
|