arkgate 4.8.23 → 4.8.24
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 +68 -0
- package/README.md +7 -5
- package/bin/ark-check-runtime.mjs +24 -77
- package/bin/ark-dashboard.mjs +56 -53
- package/bin/ark-layer-match.mjs +596 -112
- package/bin/ark-mcp-runtime.mjs +412 -138
- package/bin/ark-mcp.mjs +68 -4
- package/bin/ark-shared.mjs +39 -0
- package/bin/ark.mjs +65 -97
- package/bin/lib/adapter-contract-types.mjs +5 -0
- package/bin/lib/adapter-contract.mjs +15 -0
- package/bin/lib/agent-projection-command.mjs +5 -1
- package/bin/lib/analysis-engine.mjs +15 -11
- package/bin/lib/architecture-scan.mjs +50 -6
- package/bin/lib/ark-order-doctor.mjs +1 -1
- package/bin/lib/ark-order-facts.mjs +410 -15
- package/bin/lib/ark-order-invariants.mjs +51 -9
- package/bin/lib/ark-order-sensors.mjs +28 -101
- package/bin/lib/ark-order-types.mjs +2 -0
- package/bin/lib/ark-run-doctor.mjs +14 -0
- package/bin/lib/ark-run-facts.mjs +434 -11
- package/bin/lib/ark-run-sensors.mjs +5 -3
- package/bin/lib/arkgate-pins.mjs +91 -0
- package/bin/lib/arkrules-sensors.mjs +50 -249
- package/bin/lib/check-args.mjs +23 -1
- package/bin/lib/ci-and-commands.mjs +16 -6
- package/bin/lib/class-source-scan.mjs +479 -0
- package/bin/lib/codex-home.mjs +4 -2
- package/bin/lib/config-contract-slices.mjs +701 -0
- package/bin/lib/config-contract.mjs +5 -493
- package/bin/lib/config-warnings.mjs +32 -0
- package/bin/lib/dashboard-cli.mjs +62 -0
- package/bin/lib/design-delta.mjs +1 -1
- package/bin/lib/diagnostic-catalog.mjs +16 -9
- package/bin/lib/doctor-advisories.mjs +25 -1
- package/bin/lib/doctor-next-actions.mjs +17 -2
- package/bin/lib/doctor-plan.mjs +6 -8
- package/bin/lib/effective-contract-load.mjs +121 -59
- package/bin/lib/enforcement-profiles.mjs +40 -4
- package/bin/lib/first-run-help.mjs +3 -2
- package/bin/lib/flat-parent-importers.mjs +137 -0
- package/bin/lib/flat-parent-pilot.mjs +40 -100
- package/bin/lib/gate-files.mjs +29 -2
- package/bin/lib/git-change-scope.mjs +109 -0
- package/bin/lib/github-enforcement.mjs +1 -1
- package/bin/lib/hook-templates.mjs +18 -16
- package/bin/lib/host-support-matrix.mjs +3 -1
- package/bin/lib/import-resolve.mjs +13 -1
- package/bin/lib/install-migrate.mjs +50 -73
- package/bin/lib/invariant-coverage.mjs +59 -11
- package/bin/lib/mcp-adoption.mjs +9 -1
- package/bin/lib/mcp-hook-payload.mjs +401 -61
- package/bin/lib/package-manager.mjs +59 -1
- package/bin/lib/passthrough-commands.mjs +83 -0
- package/bin/lib/persistence-write-hint.mjs +81 -0
- package/bin/lib/pin-dependent-gates.mjs +117 -0
- package/bin/lib/policy-delta-io.mjs +168 -10
- package/bin/lib/prepare-change.mjs +120 -6
- package/bin/lib/prepare-write.mjs +1 -0
- package/bin/lib/presets.mjs +3 -5
- package/bin/lib/remediation.mjs +23 -4
- package/bin/lib/resolved-candidate-facts.mjs +315 -55
- package/bin/lib/rules-inventory.mjs +22 -3
- package/bin/lib/rules-under-contract.mjs +179 -5
- package/bin/lib/scan-files.mjs +32 -0
- package/bin/lib/snippet-analysis.mjs +140 -6
- package/bin/lib/source-policy.mjs +34 -0
- package/bin/lib/stable-hash.mjs +90 -0
- package/bin/lib/start-install-recovery.mjs +71 -1
- package/bin/lib/start-preview.mjs +30 -0
- package/bin/lib/status-command.mjs +33 -4
- package/bin/lib/status-manifest.mjs +32 -4
- package/bin/lib/team-parliament-io.mjs +77 -75
- package/bin/lib/team-parliament.mjs +6 -1
- package/bin/lib/write-path-capabilities.mjs +4 -2
- package/dist/chunk-A5EIY3HI.cjs +5 -0
- package/dist/chunk-MBXCFLO4.js +16 -0
- package/dist/chunk-RNQHRDCQ.cjs +16 -0
- package/dist/chunk-SVSQVGFJ.js +5 -0
- package/dist/{configTypes-Bbf_MFGe.d.ts → configTypes-BJbaeoj4.d.cts} +18 -3
- package/dist/configTypes-BJbaeoj4.d.ts +246 -0
- package/dist/eslint/index.cjs +17 -4
- package/dist/eslint/index.d.cts +359 -0
- package/dist/eslint/index.d.ts +130 -156
- package/dist/eslint/index.js +10 -4
- package/dist/index.cjs +35 -34
- package/dist/index.d.cts +5475 -0
- package/dist/index.d.ts +3312 -299
- package/dist/index.js +35 -34
- package/dist/inspectorListen-6DQVJ4DC.js +1 -0
- package/dist/inspectorListen-KGMIQ2TF.cjs +1 -0
- package/dist/nestjs/index.cjs +1 -18
- package/dist/nestjs/index.d.cts +22 -0
- package/dist/nestjs/index.d.ts +1 -3
- package/dist/nestjs/index.js +1 -18
- package/dist/order/index.cjs +1 -1
- package/dist/order/index.d.cts +155 -0
- package/dist/order/index.d.ts +15 -3
- package/dist/order/index.js +1 -1
- package/dist/runtime/index.cjs +13 -30
- package/dist/{diagnosticCatalog-35mrwAHe.d.ts → runtime/index.d.cts} +804 -290
- package/dist/runtime/index.d.ts +2678 -108
- package/dist/runtime/index.js +13 -30
- package/dist/{types-Bdj32QwA.d.ts → types-DRinG-vT.d.cts} +576 -140
- package/dist/types-DRinG-vT.d.ts +1792 -0
- package/docs/README.md +2 -1
- package/docs/agent-guide.md +84 -15
- package/docs/ai-gates.md +160 -26
- package/docs/arkorder.md +32 -15
- package/docs/brownfield-adoption.md +5 -1
- package/docs/configuration.md +196 -26
- package/docs/develop.md +2 -1
- package/docs/diagnostics.md +96 -19
- package/docs/package-surface.md +31 -8
- package/docs/product-voice.md +1 -1
- package/package.json +59 -18
- package/schemas/ark.analysis-result.schema.json +15 -0
- package/schemas/ark.config.schema.json +47 -10
- package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
- package/schemas/ark.status-manifest.schema.json +22 -0
- package/server.json +3 -9
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +4 -1
- package/templates/agent-skills/ark-order/SKILL.md +4 -2
- package/templates/agent-skills/ark-runtime/SKILL.md +6 -1
- package/templates/arkrules/PersistenceAdapters.json +1 -1
- package/templates/arkrules/PresentationAdapters.json +1 -1
- package/templates/skills/ark-adopt.md +4 -1
- package/templates/skills/ark-order.md +4 -2
- package/templates/skills/ark-runtime.md +6 -1
- package/dist/types-Ik_OakcI.d.ts +0 -183
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
// GENERATED from src/kernel/analysis.ts by scripts/generate-analysis-engine.mjs.
|
|
2
2
|
// Do not edit this file directly.
|
|
3
|
-
var fs=Object.defineProperty;var a=(e,t)=>fs(e,"name",{value:t,configurable:!0});function V(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(V,"deterministicHash");function F(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(F).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${F(t[n])}`).join(",")}}`}a(F,"stableSerialize");var Ie="1.2";var pn=["network","filesystem","clock","randomness","environment","process","persistence"];function K(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}a(K,"compareCanonical");function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(B,"sortedUnique");function st(e){let t={schemaVersion:"1.2",include:B(e.include??[]),exclude:B(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:B(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:B(n.patterns??[]),exclude:B(n.exclude??[]),forbiddenGlobals:B(n.forbiddenGlobals??[]),intentPrefixes:B(n.intentPrefixes??[]),capabilityDeny:B(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(K),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:B(e.arkRun.compositionRoots),managedLayers:B(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return V(F(t))}a(st,"resolvedFactsEvidenceRequirementsHash");function ps(e){let t=e.completenessReasons.map(b=>({code:b.code,message:b.message,...b.file?{file:b.file}:{}})).sort(K),n=e.files.map(b=>({...b,typeOnlyExportNames:B(b.typeOnlyExportNames)})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),r=e.dependencies.map(b=>({...b,...b.namedBindings?{namedBindings:B(b.namedBindings)}:{}})).sort(K),s=e.capabilityUses.map(b=>({...b})).sort(K),o=e.ambientUses.map(b=>({...b})).sort(K),i=e.publishCalls.map(b=>({...b})).sort(K),l=e.intentReferences.map(b=>({...b})).sort(K),c=e.safetyUses.map(b=>({...b})).sort(K),f=(e.classShapes??[]).map(b=>({...b,mutatingMethods:[...b.mutatingMethods??[]].map(T=>({...T}))})).sort(K),h=(e.arkRunKernelCalls??[]).map(b=>({...b})).sort(K),R=(e.arkRunManagedNews??[]).map(b=>({...b})).sort(K),u=(e.arkRunCompositionRootHits??[]).map(b=>({...b})).sort(K),p=(e.arkRunDeclarations??[]).map(b=>({...b,uses:B(b.uses),reactsTo:B(b.reactsTo),raises:B(b.raises),sends:B(b.sends)})).sort(K),d=(e.arkOrderPlaneCalls??[]).map(b=>({...b})).sort(K),g=(e.arkOrderGenericUpdates??[]).map(b=>({...b})).sort(K),k=(e.arkOrderRootHits??[]).map(b=>({...b})).sort(K),I=(e.arkOrderXiFieldWrites??[]).map(b=>({...b})).sort(K),S=(e.arkOrderIngestWritesXi??[]).map(b=>({...b})).sort(K),x=(e.arkOrderReleaseKeyCounts??[]).map(b=>({...b})).sort(K),$=e.files.map(({path:b,contentHash:T})=>({path:b,contentHash:T})).sort((b,T)=>b.path<T.path?-1:b.path>T.path?1:0),q=V(F($));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:q,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:s,ambientUses:o,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:f,arkRunKernelCalls:h,arkRunManagedNews:R,arkRunCompositionRootHits:u,arkRunDeclarations:p,arkOrderPlaneCalls:d,arkOrderGenericUpdates:g,arkOrderRootHits:k,arkOrderXiFieldWrites:I,arkOrderIngestWritesXi:S,arkOrderReleaseKeyCounts:x}}a(ps,"canonicalResolvedFactsInput");function gn(e){let t=ps(e);return{...t,factsHash:V(F(t))}}a(gn,"createCanonicalResolvedCandidateFacts");function ot(e){return gn(hn(L(e,"$"),!1))}a(ot,"createResolvedCandidateFacts");function L(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(L,"asRecord");function N(e,t,n){let r=new Set(t),s=Object.keys(e).find(o=>!r.has(o));if(s)throw new Error(`${n}.${s} is not part of schema ${"1.2"}.`)}a(N,"assertOnlyKeys");function _(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}a(_,"requiredText");function ae(e,t,n){if(e[t]!==void 0)return _(e,t,n)}a(ae,"optionalText");function D(e,t,n){let r=_(e,t,n),s=r.replace(/\\/g,"/");if(!s||s.startsWith("/")||/^[A-Za-z]:\//.test(s)||/[\u0000-\u001f\u007f]/.test(s))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let o=[];for(let l of s.split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);o.pop()}else o.push(l);let i=o.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(D,"requiredProjectPath");function M(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(M,"requiredBoolean");function mn(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}a(mn,"requiredInteger");function z(e,t,n){let r=mn(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(z,"requiredPositiveInteger");function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(H,"requiredArray");function le(e,t,n,r){let s=e[t];if(typeof s!="string"||!n.includes(s))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return s}a(le,"enumValue");function Ee(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}a(Ee,"parseStringArray");function gs(e,t,n){let r=new Set;for(let s of e){let o=t(s);if(r.has(o))throw new Error(`${n} must not contain duplicate facts (${o}).`);r.add(o)}}a(gs,"assertUnique");function hn(e,t){N(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=le(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=le(e,"completeness",["complete","partial","unavailable"],"$"),s=H(e,"completenessReasons","$").map((v,C)=>{let m=`$.completenessReasons[${C}]`,A=L(v,m);N(A,["code","message","file"],m);let O=A.file===void 0?void 0:D(A,"file",m);return{code:_(A,"code",m),message:_(A,"message",m),...O?{file:O}:{}}});if(r==="complete"&&s.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&s.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let o=H(e,"files","$").map((v,C)=>{let m=`$.files[${C}]`,A=L(v,m);return N(A,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],m),{path:D(A,"path",m),contentHash:_(A,"contentHash",m),parseStatus:le(A,"parseStatus",["parsed","invalid"],m),parseDiagnosticCount:mn(A,"parseDiagnosticCount",m),exportsOnlyTypes:M(A,"exportsOnlyTypes",m),typeOnlyExportNames:Ee(A.typeOnlyExportNames,`${m}.typeOnlyExportNames`),hasTopLevelSideEffects:M(A,"hasTopLevelSideEffects",m)}}),i=H(e,"dependencies","$").map((v,C)=>{let m=`$.dependencies[${C}]`,A=L(v,m);N(A,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],m);let O=ae(A,"specifier",m),j=ae(A,"target",m),ue=le(A,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],m);if(ue==="resolved-project"&&!j)throw new Error(`${m}.target is required for resolved-project dependencies.`);if(ue!=="resolved-project"&&j)throw new Error(`${m}.target is only allowed for resolved-project dependencies.`);if(ue!=="dynamic"&&!O)throw new Error(`${m}.specifier is required unless resolution is dynamic.`);return{from:D(A,"from",m),...O?{specifier:O}:{},kind:le(A,"kind",["import","export","dynamic-import","require"],m),typeOnly:M(A,"typeOnly",m),line:z(A,"line",m),resolution:ue,...j?{target:D(A,"target",m)}:{},...A.namedBindings!==void 0?{namedBindings:Ee(A.namedBindings,`${m}.namedBindings`)}:{},...A.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:M(A,"targetTypeOnlyExports",m)}:{},...A.sourcePureTypeModule!==void 0?{sourcePureTypeModule:M(A,"sourcePureTypeModule",m)}:{},...A.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:M(A,"namedBindingsTypeOnly",m)}:{},...A.portProofEligible!==void 0?{portProofEligible:M(A,"portProofEligible",m)}:{}}}),l=H(e,"capabilityUses","$").map((v,C)=>{let m=`$.capabilityUses[${C}]`,A=L(v,m);return N(A,["file","line","symbol","capability","source"],m),{file:D(A,"file",m),line:z(A,"line",m),symbol:_(A,"symbol",m),capability:le(A,"capability",pn,m),source:le(A,"source",["ambient-global","import-based"],m)}}),c=H(e,"ambientUses","$").map((v,C)=>{let m=`$.ambientUses[${C}]`,A=L(v,m);return N(A,["file","line","symbol"],m),{file:D(A,"file",m),line:z(A,"line",m),symbol:_(A,"symbol",m)}}),f=H(e,"publishCalls","$").map((v,C)=>{let m=`$.publishCalls[${C}]`,A=L(v,m);N(A,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],m);let O=ae(A,"rawIntentName",m),j=ae(A,"sourceIntent",m);return{file:D(A,"file",m),line:z(A,"line",m),...O?{rawIntentName:O}:{},objectHasIntent:M(A,"objectHasIntent",m),arkPublishCandidate:M(A,"arkPublishCandidate",m),hasSource:M(A,"hasSource",m),...j?{sourceIntent:j}:{}}}),h=H(e,"intentReferences","$").map((v,C)=>{let m=`$.intentReferences[${C}]`,A=L(v,m);return N(A,["file","line","intent"],m),{file:D(A,"file",m),line:z(A,"line",m),intent:_(A,"intent",m)}}),R=H(e,"safetyUses","$").map((v,C)=>{let m=`$.safetyUses[${C}]`,A=L(v,m);N(A,["file","line","kind","symbol"],m);let O=ae(A,"symbol",m),j=le(A,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],m);if(j==="in-memory-store"&&!O)throw new Error(`${m}.symbol is required for in-memory-store facts.`);if(j!=="in-memory-store"&&O)throw new Error(`${m}.symbol is only allowed for in-memory-store facts.`);return{file:D(A,"file",m),line:z(A,"line",m),kind:j,...O?{symbol:O}:{}}});gs(o,v=>v.path,"$.files");let u=new Set(o.map(v=>v.path));for(let v of o){if(v.parseStatus==="parsed"&&v.parseDiagnosticCount!==0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(v.parseStatus==="invalid"&&v.parseDiagnosticCount===0)throw new Error(`$.files[${v.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&o.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of i)if(!u.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:H(e,"arkRunKernelCalls","$")).map((v,C)=>{let m=`$.arkRunKernelCalls[${C}]`,A=L(v,m);N(A,["file","line","kind","callee","viaImport","receiver","nameLiteral"],m);let O=ae(A,"receiver",m),j=ae(A,"nameLiteral",m);return{file:D(A,"file",m),line:z(A,"line",m),kind:le(A,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],m),callee:_(A,"callee",m),viaImport:M(A,"viaImport",m),...O?{receiver:O}:{},...j?{nameLiteral:j}:{}}}),k=(e.arkRunManagedNews===void 0?[]:H(e,"arkRunManagedNews","$")).map((v,C)=>{let m=`$.arkRunManagedNews[${C}]`,A=L(v,m);N(A,["file","line","typeName","importedFrom"],m);let O=ae(A,"importedFrom",m);return{file:D(A,"file",m),line:z(A,"line",m),typeName:_(A,"typeName",m),...O?{importedFrom:O}:{}}}),S=(e.arkRunCompositionRootHits===void 0?[]:H(e,"arkRunCompositionRootHits","$")).map((v,C)=>{let m=`$.arkRunCompositionRootHits[${C}]`,A=L(v,m);return N(A,["file","matchedRoot","hasKernelFactory"],m),{file:D(A,"file",m),matchedRoot:_(A,"matchedRoot",m),hasKernelFactory:M(A,"hasKernelFactory",m)}}),x=e.arkRunDeclarations===void 0?[]:H(e,"arkRunDeclarations","$"),q=(e.arkOrderPlaneCalls===void 0?[]:H(e,"arkOrderPlaneCalls","$")).map((v,C)=>{let m=`$.arkOrderPlaneCalls[${C}]`,A=L(v,m);return N(A,["file","line","callee"],m),{file:D(A,"file",m),line:z(A,"line",m),callee:_(A,"callee",m)}}),T=(e.arkOrderGenericUpdates===void 0?[]:H(e,"arkOrderGenericUpdates","$")).map((v,C)=>{let m=`$.arkOrderGenericUpdates[${C}]`,A=L(v,m);return N(A,["file","line","method"],m),{file:D(A,"file",m),line:z(A,"line",m),method:_(A,"method",m)}}),me=(e.arkOrderRootHits===void 0?[]:H(e,"arkOrderRootHits","$")).map((v,C)=>{let m=`$.arkOrderRootHits[${C}]`,A=L(v,m);return N(A,["file","matchedRoot","hasPlaneFactory"],m),{file:D(A,"file",m),matchedRoot:_(A,"matchedRoot",m),hasPlaneFactory:M(A,"hasPlaneFactory",m)}}),ie=(e.arkOrderXiFieldWrites===void 0?[]:H(e,"arkOrderXiFieldWrites","$")).map((v,C)=>{let m=`$.arkOrderXiFieldWrites[${C}]`,A=L(v,m);return N(A,["file","line","key"],m),{file:D(A,"file",m),line:z(A,"line",m),key:_(A,"key",m)}}),he=(e.arkOrderIngestWritesXi===void 0?[]:H(e,"arkOrderIngestWritesXi","$")).map((v,C)=>{let m=`$.arkOrderIngestWritesXi[${C}]`,A=L(v,m);return N(A,["file","line"],m),{file:D(A,"file",m),line:z(A,"line",m)}}),Se=(e.arkOrderReleaseKeyCounts===void 0?[]:H(e,"arkOrderReleaseKeyCounts","$")).map((v,C)=>{let m=`$.arkOrderReleaseKeyCounts[${C}]`,A=L(v,m);return N(A,["file","line","keyCount"],m),{file:D(A,"file",m),line:z(A,"line",m),keyCount:z(A,"keyCount",m)}}),De=x.map((v,C)=>{let m=`$.arkRunDeclarations[${C}]`,A=L(v,m);return N(A,["file","line","uses","reactsTo","raises","sends"],m),{file:D(A,"file",m),line:z(A,"line",m),uses:Ee(A.uses,`${m}.uses`),reactsTo:Ee(A.reactsTo,`${m}.reactsTo`),raises:Ee(A.raises,`${m}.raises`),sends:Ee(A.sends,`${m}.sends`)}});for(let[v,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",f],["$.intentReferences",h],["$.safetyUses",R],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",k],["$.arkRunCompositionRootHits",S],["$.arkRunDeclarations",De],["$.arkOrderPlaneCalls",q],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",me],["$.arkOrderXiFieldWrites",ie],["$.arkOrderIngestWritesXi",he],["$.arkOrderReleaseKeyCounts",Se]])for(let m of C)if(!u.has(m.file))throw new Error(`${v} references missing file ${m.file}.`);let rt=ae(e,"projectPackageName","$"),fn=(e.classShapes===void 0?[]:H(e,"classShapes","$")).map((v,C)=>{let m=`$.classShapes[${C}]`,A=L(v,m);N(A,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],m);let O=H(A,"mutatingMethods",m).map((j,ue)=>{let y=`${m}.mutatingMethods[${ue}]`,Y=L(j,y);return N(Y,["name","referencesGuardOrPublish"],y),{name:_(Y,"name",y),referencesGuardOrPublish:M(Y,"referencesGuardOrPublish",y)}});return{file:D(A,"file",m),className:_(A,"className",m),exported:M(A,"exported",m),hasPublicMutableFields:M(A,"hasPublicMutableFields",m),hasPublicSetters:M(A,"hasPublicSetters",m),hasPublicConstructor:M(A,"hasPublicConstructor",m),hasStaticFactory:M(A,"hasStaticFactory",m),mutatingMethods:O,...A.dataOnly===void 0?{}:{dataOnly:M(A,"dataOnly",m)}}});return{schemaVersion:n,completeness:r,completenessReasons:s,resolverIdentity:_(e,"resolverIdentity","$"),compilerIdentity:_(e,"compilerIdentity","$"),compilerOptionsHash:_(e,"compilerOptionsHash","$"),tsconfigHash:_(e,"tsconfigHash","$"),evidenceRequirementsHash:_(e,"evidenceRequirementsHash","$"),...rt?{projectPackageName:rt}:{},files:o,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:f,intentReferences:h,safetyUses:R,classShapes:fn,arkRunKernelCalls:d,arkRunManagedNews:k,arkRunCompositionRootHits:S,arkRunDeclarations:De,arkOrderPlaneCalls:q,arkOrderGenericUpdates:T,arkOrderRootHits:me,arkOrderXiFieldWrites:ie,arkOrderIngestWritesXi:he,arkOrderReleaseKeyCounts:Se}}a(hn,"parseResolvedFactsInput");function ye(e){let t=L(e,"$"),n=_(t,"factsHash","$"),r=_(t,"candidateTreeHash","$"),s=gn(hn(t,!0));if(s.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${s.factsHash}).`);if(r!==s.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${s.candidateTreeHash}).`);return s}a(ye,"loadResolvedCandidateFacts");var ms=["network","filesystem","clock","randomness","environment","process","persistence"],w={type:"string",minLength:1},X={type:"integer",minimum:1},U={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},yn={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:w,message:w,file:U}}},resolverIdentity:w,compilerIdentity:w,compilerOptionsHash:w,tsconfigHash:w,candidateTreeHash:w,evidenceRequirementsHash:w,projectPackageName:w,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:U,contentHash:w,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:w},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:U,specifier:w,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:X,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:U,namedBindings:{type:"array",items:w},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:U,line:X,symbol:w,capability:{enum:ms},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:U,line:X,symbol:w}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:U,line:X,rawIntentName:w,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:w}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:U,line:X,intent:w}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:U,line:X,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:w},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:U,className:w,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:w,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:U,line:X,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:w,viaImport:{type:"boolean"},receiver:w,nameLiteral:w}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:U,line:X,typeName:w,importedFrom:w}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:U,matchedRoot:w,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:U,line:X,uses:{type:"array",items:w},reactsTo:{type:"array",items:w},raises:{type:"array",items:w},sends:{type:"array",items:w}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:U,line:X,callee:w}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:U,line:X,method:w}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:U,matchedRoot:w,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:U,line:X,key:w}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:U,line:X}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:U,line:X,keyCount:{type:"integer",minimum:1}}}},factsHash:w},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Rn="1.0";var It=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),it=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ct=Object.freeze(Object.keys(it).sort()),St=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Et=Object.freeze({process:Object.freeze(["process","node:process"])});function Ue(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=St[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=St[r];if(s)return s;let o=e.indexOf("/",n+1);return o<0?null:St[e.slice(0,o)]??null}a(Ue,"capabilityForModuleSpecifier");function Ke(e,t){for(let n of t)if(Et[n]?.includes(e))return n;return null}a(Ke,"forbiddenGlobalForModuleSpecifier");function je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),s=it[r];if(s)return s}return null}a(je,"capabilityForAmbientName");function Ce(e){if(e?.pure===!0)return[...It].sort();let n=(e?.capabilities?.deny??[]).filter(r=>It.includes(r));return[...new Set(n)].sort()}a(Ce,"effectiveCapabilityDeny");function wt(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let s=r.length;s>=1;s-=1)if(n.has(r.slice(0,s).join(".")))return!0;return!1}a(wt,"ambientCoveredByForbiddenGlobals");function at(e){let t=new Set,n=new Set,r=Object.keys(it);for(let s of e?.forbiddenGlobals??[]){let o=r.filter(i=>i===s||i.startsWith(`${s}.`));if(o.length===0)n.add(s);else for(let i of o)t.add(`ambient:${i}`);for(let i of Et[s]??[])t.add(`import-exact:${i}`)}for(let s of Ce(e)){if(t.add(`import:${s}`),s==="process")for(let o of Et.process)t.add(`import-exact:${o}`);for(let o of r)je(o)===s&&t.add(`ambient:${o}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(at,"loweredLayerCoverage");function hs(e){let t=new Set,n=je(e);n&&t.add(n);for(let[r,s]of Object.entries(it))(r===e||r.startsWith(`${e}.`))&&t.add(s);return[...t].sort()}a(hs,"lowerForbiddenGlobal");var An="4.8.22",kn=new Map;function bn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(bn,"escapeLiteral");function dt(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}a(dt,"normalizeGlobSeparators");function ys(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(ys,"bracesBalanced");function oe(e){let t=kn.get(e);if(t)return t;let n=dt(e),r=ys(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=bn(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=bn(c)}let i=new RegExp(`^${s}$`);return kn.set(e,i),i}a(oe,"globToRegExp");function Rs(e){return dt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Rs,"concreteGlobSegments");function Ot(e,t){let n=dt(String(e)),r=Rs(n),s=n.replace(/\*/g,"").length,o=r.length*1e4+s;if(t==null||t==="")return o;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let l=0,c=-1;for(let f of r){let h=-1;for(let R=l;R<i.length;R+=1)if(i[R]===f){h=R;break}if(h<0)return o;c=h,l=h+1}return(c+1)*1e6+r.length*1e4+s}a(Ot,"patternSpecificity");function Q(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let o of t??[])if(!(o.exclude??[]).some(i=>oe(i).test(n))){for(let i of o.patterns??[])if(oe(i).test(n)){let l=Ot(i,n);l>s&&(s=l,r=o.name)}}return r}a(Q,"layerForRelativePath");function _t(e,t,n){if(!t?.length)return;let r=n==="stars"?"stars":"path",s=String(e).split(/[/\\]/).filter(Boolean);if(s.length===0)return;let o=new Set;for(let i of t)if(!(typeof i!="string"||i.length===0)){if(En(i)){let l=As(s,i,r);if(l)return l;continue}!i.includes("/")&&!i.includes("\\")&&!i.includes("*")&&o.add(i.toLowerCase())}return Ss(s,o)}a(_t,"sliceIdForPath");function En(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(En,"isAnchoredSliceEntry");function As(e,t,n){let r=t.split(/[/\\]/).filter(o=>o.length>0).map(o=>o.toLowerCase()),s=wn(e,r[0]??"");for(let o of s){let i=ks(e,r,o,n);if(i)return i}}a(As,"anchoredSliceId");function ks(e,t,n,r="path"){let s=[],o=-1,i=n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="*"){if(i>=e.length-1){for(let f=l;f<t.length;f+=1)if(t[f]!=="*")return;break}s.push(e[i].toLowerCase()),i+=1;continue}if(c==="**"||i>=e.length||e[i].toLowerCase()!==c)return;s.push(e[i].toLowerCase()),o=s.length-1,i+=1}if(s.length!==0)return r==="stars"?o<0?void 0:s.slice(o).join("/"):s.join("/")}a(ks,"bindAnchoredSlice");function Cn(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,s=new Map;for(let o of n.sliceFolders??[]){if(typeof o!="string"||o.length===0)continue;let i=bs(o);if(!i)continue;let l=o.split(/[/\\]/).filter(h=>h.length>0).join("/").toLowerCase(),c=s.get(i)??new Set;if(c.has(l))continue;c.add(l),s.set(i,c);let f=r.get(i)??[];f.push(o),r.set(i,f)}for(let[o,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:o,paths:i,message:vs(n.from,n.to,i,o)})}return t}a(Cn,"sliceIdentityCollisions");function bs(e){if(!En(e))return;let t=e.split(/[/\\]/).filter(s=>s.length>0).map(s=>s.toLowerCase()),n=-1;for(let s=0;s<t.length;s+=1){let o=t[s]??"";if(o==="**")return;o!=="*"&&(n=s)}if(n<0)return;let r=t.slice(n);if(!r.some((s,o)=>o>0&&s!=="*"))return r.join("/")}a(bs,"starsIdentityStem");function vs(e,t,n,r){let s=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${e} \u2192 ${t}: sliceIdentity "stars" gives one slice id to ${s}. They bind as ${r}.`}a(vs,"formatSliceIdentityCollision");function Ss(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}a(Ss,"bareSliceId");function Is(e){let t=new Set;for(let n of e??[]){let s=dt(String(n)).split("/").filter(Boolean);for(let o=0;o<s.length;o+=1){let i=s[o];if((i==="**"||i==="*")&&o>0){let l=s[o-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(Is,"inferSliceFoldersFromPatterns");function $t(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return Is(r?.patterns)}a($t,"resolveSliceFolders");function vn(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(vn,"normalizeSegments");function Be(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Be,"trimTrailingSlashes");var Es=["src","app"];function wn(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Es.includes(n)&&r!==n?[0,1]:[0]}a(wn,"anchorOffsets");function Cs(e){let t=Be(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Cs,"isBlanketRoot");function Ve(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),s=vn(n);for(let o of t){if(typeof o!="string"||o.length===0||Cs(o))continue;if(o.includes("*")){let c=Be(o.toLowerCase());if(oe(c).test(r)||oe(`${c}/**`).test(r))return!0;continue}let i=vn(o);if(i.length===0)continue;let l=wn(s,i[0]??"");for(let c of l){if(c+i.length>s.length)continue;let f=!0;for(let h=0;h<i.length;h+=1)if(s[c+h]!==i[h]){f=!1;break}if(f)return!0}}return!1}a(Ve,"pathUnderSharedRoot");function Sn(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(Sn,"sliceMatchesDeclaration");function ws(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Sn(r.from,t)&&Sn(r.to,n))}a(ws,"crossSliceEdgeAllowed");function xs(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(xs,"peerIsolationDecision");function xn(e){return Be(e.trim().replace(/\\/g,"/")).toLowerCase()}a(xn,"aliasGlobPattern");function Os(e,t){let n=xn(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),s=xt(r),o=oe(n);return o.test(r)||s!==r&&o.test(s)}a(Os,"aliasGlobMatches");function _s(e){let t=xn(e).split("/").filter(Boolean);return t.length<2||t.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:t.slice(0,-1).join("/"),childId:t.join("/")}}a(_s,"splitAliasTarget");function $s(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Os(n.from,e))return _s(n.to);return null}a($s,"firstSliceAlias");function we(e,t,n){if(!e)return{};let r=n??t.sliceFolders,s=_t(e,r?[...r]:void 0,t.sliceIdentity),o=lt(e,s,t.childSlices);if(s||o.childId||o.mismatched)return o.childId?{universeId:s,childId:o.childId}:{universeId:s};let i=$s(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(we,"resolveGovernedSlice");function Ts(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${t.toSlice??"?"} (${t.fromPath??"?"} \u2192 ${t.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.toPath].filter(s=>!!s);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(Ts,"peerIsolationDenyExplanation");function Ls(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Ls,"crossParentExplanation");function Fs(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(Fs,"crossSiblingExplanation");function Ns(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(Ns,"parentImportsChildExplanation");function Ge(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(Ge,"universePairLabel");function Ps(e){return String(e).split(/[/\\]/).filter(Boolean).slice(0,-1)}a(Ps,"directorySegments");function Ds(e,t){if(!t?.length)return!1;let n=new Set;for(let r of t)typeof r=="string"&&r.length>0&&n.add(r.toLowerCase());return n.size===0?!1:Ps(e).some(r=>n.has(r.toLowerCase()))}a(Ds,"pathHasCommonFolder");function lt(e,t,n){if(!e||!n?.sliceFolders?.length)return{};if(Ds(e,n.commonFolders))return{};let r=_t(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let s=r.toLowerCase(),o=t.toLowerCase();return s===o?{}:s.startsWith(`${o}/`)?{childId:r}:{mismatched:{childId:r,universeId:t}}}a(lt,"resolveChildSliceId");function Ms(e){return Be(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ms,"siblingEntryKey");function xt(e){return e.replace(/^(?:src|app)\//,"")}a(xt,"stripSrcOrApp");function Hs(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=xt(t);if(!r)return!1;let s=xt(n);return n===r||n.startsWith(`${r}/`)||s===r||s.startsWith(`${r}/`)}a(Hs,"pathUnderSubtree");function Us(e,t,n){if(!t||!n?.length)return!1;let r=t.toLowerCase();for(let s of n){if(typeof s!="string")continue;let o=Ms(s);if(!(!o||o.includes("*"))&&(r===o||e&&Hs(e,o)))return!0}return!1}a(Us,"importerInEnforcedSubtree");function Ks(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!Us(t,n,e.enforce)}a(Ks,"siblingCrossingAdvisory");function ct(e){if(typeof e!="string")return null;let t=Be(e.trim().replace(/\\/g,"/")).toLowerCase();if(!t.includes("/"))return null;let n=t.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(ct,"childSlicePatternSegments");function In(e,t){let n=ct(e),r=ct(t);if(!n||!r||n.length!==r.length)return!1;for(let s=0;s<n.length;s+=1){let o=n[s];if(o!=="*"&&o!==r[s])return!1}return!0}a(In,"childSlicePatternMatches");function js(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&In(r.from,t)&&In(r.to,n))return!0;return!1}a(js,"childCrossSliceAllowed");function Vs(e,t){let n=ct(e),r=ct(t);if(!n||!r)return!1;let s=n.slice(0,-1),o=r.slice(0,-1);if(s.length!==o.length)return!0;for(let i=0;i<s.length;i+=1){let l=s[i],c=o[i];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(Vs,"childAllowanceSpansUniverses");function Gs(e){let t=xs({fromPath:e.fromPath,toPath:e.toPath,folderCount:e.folderCount,fromSlice:e.fromSlice,toSlice:e.toSlice,fromShared:e.fromShared,toShared:e.toShared,crossSliceAllowed:e.crossSliceAllowed,sharedImportsSlice:e.rule.sharedImportsSlice});if(t.denied){let i=!!e.rule.childSlices&&t.reason==="cross-slice";return{crossing:t.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...i?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:i?Ls(e.fromSlice,e.toSlice):Ts(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??lt(e.fromPath,e.fromSlice,n).childId,s=e.toChild??lt(e.toPath,e.toSlice,n).childId,o={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&s&&r!==s?js(n.allowedCrossSlice,r,s)?o:{crossing:"cross-sibling",decision:Ks(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:Fs(r,s,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&s&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:Ns(s),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:o}a(Gs,"evaluateNestedSliceWall");function ut(e){let t=e.verdict.explanation;if(e.surface==="intent"){let n=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return e.verdict.reasonId&&t?`${n} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${n} ${t}`:e.ruleMessage?t?`${e.ruleMessage} (${t})`:e.ruleMessage:n}if(e.ruleMessage)return t?`${e.ruleMessage} (${t})`:e.ruleMessage;if(t){let n=e.kind??"import";return`${e.fromLayer} must not ${n} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(ut,"composeSliceDenialMessage");function ft(e){if(!e||e.decision==="allow")return{};let t=Ge(e.fromUniverse),n=Ge(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(ft,"sliceFindingExtras");function On(e,t){let n=[],r=!1,s=new Set,o=new Set;for(let i of e??[])if(i?.childSlices&&(r||(r=!0,n.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,message:`childSlices needs an arkgate newer than ${An}. Version ${An} and older reject the key because the rule schema sets additionalProperties: false.`})),!!i.peerIsolation)){for(let l of t){let c=_t(l,i.sliceFolders,i.sliceIdentity),f=lt(l,c,i.childSlices);if(!f.mismatched)continue;let h=`${i.from}\0${i.to}\0${f.mismatched.universeId}\0${f.mismatched.childId}`;s.has(h)||(s.add(h),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:i.from,toLayer:i.to,path:l,message:`${i.from} \u2192 ${i.to}: child id ${f.mismatched.childId} does not extend universe id ${f.mismatched.universeId} (${l}).`}))}for(let l of i.childSlices.allowedCrossSlice??[]){if(!l||typeof l.from!="string"||typeof l.to!="string"||!Vs(l.from,l.to))continue;let c=`${l.from.trim().toLowerCase()}\0${l.to.trim().toLowerCase()}`;o.has(c)||(o.add(c),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`childSlices.allowedCrossSlice ${l.from} \u2192 ${l.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(On,"childSliceConfigFindings");function _n(e,t,n,r){return We(e,t,n,r)?.rule}a(_n,"findDeniedEdgeRule");function We(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let o=r?.fromPath,i=r?.toPath,l=$t(s,t,r?.layers),c=we(o,s,l),f=we(i,s,l),h=c.universeId,R=f.universeId,u=Gs({rule:s,fromPath:o,toPath:i,folderCount:l.length,fromSlice:h,toSlice:R,fromChild:c.childId,toChild:f.childId,fromShared:!h&&Ve(o,s.sharedRoots),toShared:!R&&Ve(i,s.sharedRoots),crossSliceAllowed:ws(s.allowedCrossSlice,h,R)});if(u.decision!=="allow")return{rule:s,peerIsolationReason:u.peerIsolationReason,fromSlice:h,toSlice:R,sliceVerdict:u};continue}if(t!==n)return{rule:s}}}a(We,"findDeniedEdgeDecision");function $n(e,t,n,r){let s=r?.fromPath,o=r?.toPath;if(!(!s||!o))for(let i of e??[]){if(i.from!==t||i.to!==n||i.allowed!==!1||!i.peerIsolation||i.sharedImportsSlice==="deny")continue;let l=$t(i,t,r?.layers),c=we(s,i,l).universeId,f=we(o,i,l).universeId;if(!(c||!f)&&Ve(s,i.sharedRoots))return{fromPath:s,toPath:o,toSlice:f}}}a($n,"findSharedImportsSliceBridge");function Tn(e,t,n){return $t(e,t,n)}a(Tn,"peerSliceFolders");var Tt={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Lt=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Ft(e,t){return t.flatMap((r,s)=>(r.prefixes??r.intentPrefixes??[]).map(o=>({layer:r.name,layerIndex:s,prefix:o.endsWith(".")?o:`${o}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,s)=>s.prefix.length-r.prefix.length||r.layerIndex-s.layerIndex)[0]?.layer}a(Ft,"resolveIntentLayer");function Ln(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(Ln,"looksLikeArkIntent");function Nt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Ln(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Tt.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Tt.PUBLISH_MISSING_SOURCE}),t}a(Nt,"classifyPublishFacts");var Fn="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Bs=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Nn={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ja={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Fn,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:Fn},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...Bs]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Nn,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Nn}}}};function ze(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(ze,"emptyEffectiveArkRules");function Pn(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}a(Pn,"structureFreezeTarget");var Ws=["no-anemic-model"],Kn=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],nl=new RegExp(`\\b(${Kn.join("|")})\\b`),jn="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",rl=new RegExp(`\\bthis\\.${jn}\\.push\\s*\\(`),sl=new RegExp(`^this\\.${jn}\\s*=\\s*\\[\\s*\\]`);var zs="truncatedUntil";function qs(){return`${Kn.join(", ")}, or events-array .push(`}a(qs,"expectedDomainInvariantWordsPhrase");function Pt(e){let t=Object.getOwnPropertyDescriptor(e,zs)?.value;return typeof t=="number"?t:void 0}a(Pt,"shapeTruncatedUntil");function Ys(e){let t=Pt(e);return t==null?"":` shape analysed until character ${t}`}a(Ys,"shapeTruncationSuffix");function Dn(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Dn,"escapeGlobLiteral");function Xs(e){let t="";for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="\\"&&r+1<e.length){let o=e[r+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,r+=1;continue}t+="/";continue}t+=s}let n="";for(let r=0;r<t.length;r+=1){let s=t[r];s==="\\"&&r+1<t.length?(n+=Dn(t[r+1]),r+=1):s==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":s==="?"?n+="[^/]":n+=Dn(s)}return new RegExp(`^${n}$`)}a(Xs,"globToRegExp");function xe(e,t){return!t||t.length===0?!0:t.some(n=>Xs(n).test(e))}a(xe,"matchesAppliesTo");function Vn(e){return Ws.includes(e)}a(Vn,"isTier2");function Gn(e){return e.mode==="enforced"&&!Vn(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Gn,"severityFor");function fe(e,t,n,r=1){let{severity:s,failsStrict:o}=Gn(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:s,sensor:e.sensor,failsStrict:o}}a(fe,"baseViolation");function pt(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(pt,"isInRuleLayer");function gt(e,t,n){return t.filter(r=>!(!r.exported||!xe(r.file,e.appliesTo)||!pt(r.file,e,n)))}a(gt,"shapesForRule");function Js(e,t,n){let r=[];for(let s of gt(e,t,n))(s.hasPublicSetters||s.hasPublicMutableFields)&&r.push(fe(e,s.file,`Exported class ${s.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(Js,"evaluateAggregatePrivateState");function Zs(e,t,n){let r=[];for(let s of gt(e,t,n))if(s.hasPublicConstructor&&!s.hasStaticFactory){if(!(s.hasPublicMutableFields||s.hasPublicSetters||(s.mutatingMethods?.length??0)>0))continue;r.push(fe(e,s.file,`Exported class ${s.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(Zs,"evaluateAlwaysValidFactory");function Qs(e,t,n){let r=[],s=qs();for(let o of gt(e,t,n)){let i=Ys(o);Pt(o)!=null&&r.push(fe(e,o.file,`Exported class ${o.className} shape analysed until character ${Pt(o)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of o.mutatingMethods)l.referencesGuardOrPublish||r.push(fe(e,o.file,`Mutating method ${o.className}.${l.name} does not reference ${s} (sensor domain-event-on-mutation).${i}`))}return r}a(Qs,"evaluateDomainEventOnMutation");function eo(e,t){let n=[];for(let r of t.files)xe(r,e.appliesTo)&&pt(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(fe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(eo,"evaluateOrchestrationOnly");function to(e,t){let n=[];for(let r of t.files)xe(r,e.appliesTo)&&pt(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(fe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(to,"evaluateThinAdapter");function no(e,t){let n=[];for(let r of t.files)xe(r,e.appliesTo)&&pt(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(fe(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}a(no,"evaluateWritesViaAggregate");function ro(e,t,n){let r=[];for(let s of gt(e,t,n))if(s.dataOnly===!0){let o=fe(e,s.file,`Exported type ${s.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...o,severity:"warning",failsStrict:!1})}return r}a(ro,"evaluateNoAnemicModel");function Bn(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Js(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Zs(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Qs(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...eo(n,e));break;case"thin-adapter":t.push(...to(n,e));break;case"writes-via-aggregate":t.push(...no(n,e));break;case"no-anemic-model":t.push(...ro(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}a(Bn,"evaluateArkRuleSensors");function Wn(e,t){let n=[],r=t.map(s=>s.replace(/\\/g,"/"));for(let s of e.structure){if(!s.appliesTo||s.appliesTo.length===0||r.some(c=>xe(c,s.appliesTo)))continue;let{severity:i,failsStrict:l}=Gn(s);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i,sensor:s.sensor,failsStrict:l})}for(let s of e.invariants??[]){if(!s.appliesTo||s.appliesTo.length===0||r.some(l=>xe(l,s.appliesTo)))continue;let i=s.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${s.id}" appliesTo matched zero governed files (patterns: ${s.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:s.provenance.sourceFile,line:1,fromLayer:s.provenance.layer,arkruleId:s.id,arkruleSource:s.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((s,o)=>s.file.localeCompare(o.file)||s.arkruleId.localeCompare(o.arkruleId)||s.message.localeCompare(o.message))}a(Wn,"collectEmptyAppliesToFindings");var Mn=64;function so(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}a(so,"stripTrailingDots");function oo(e){let t=e.trim(),n=t.length>Mn?t.slice(0,Mn):t;return so(n)}a(oo,"normalizeIntentPrefix");function io(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(io,"layerNameLooksDomain");function ao(e){return e.some(t=>{let n=oo(t);return n==="Domain"||n.startsWith("Domain.")})}a(ao,"ownsDomainIntent");function lo(e,t=[]){return io(e)||ao(t)}a(lo,"isDomainRoleLayerName");function zn(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>lo(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let f=typeof c.layer=="string"?c.layer:"";return f.length>0&&n.has(f)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let o=t.find(c=>e.arkRules.byLayer?.[c])??t[0],i=e.arkRules.byLayer?.[o]?.sourceFile??`arkrules/${o}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!Vn(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${o} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${i}.`,file:i,line:1,fromLayer:o,arkruleId:"invariant-catalog",arkruleSource:i,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}a(zn,"collectEmptyInvariantCatalogFindings");var Hn=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,Un=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,co=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function uo(e){return e==="PersistenceAdapters"}a(uo,"isPersistenceDriverLayer");function fo(e,t){if(Hn.test(e)||Un.test(e))return!0;if(!t)return!1;for(let n of t){if(uo(n.layer))return!0;let r=n.specifier;if(!r)continue;let s=`from '${r}'`;if(Hn.test(s)||Un.test(s))return!0}return!1}a(fo,"sourceImportsPersistenceDriver");var po=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,go=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,mo=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,ho=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function yo(e,t,n){if(!t)return null;let r=fo(t,n),s=r&&co.test(t);if(t.length<40)return s?{persistenceWrite:!0}:null;let o=t.match(new RegExp(mo.source,"g"))??[],i=t.match(new RegExp(ho.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,f=o.length>=2||o.length>=1&&i.length>=2||i.length>=3&&l+c>=6,h=po.test(t)||go.test(t),R=o.length>=1||i.length>=2,u=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),p=r&&R||h&&R||r&&u&&(l>=4||o.length>=1)||h&&r;return!f&&!p&&!s?null:{...f?{orchestrationHeavy:!0}:{},...p?{adapterThick:!0}:{},...s?{persistenceWrite:!0}:{}}}a(yo,"deriveArkRuleFileHints");function qn(e,t){let n={};for(let[r,s]of Object.entries(e)){let o=r.replace(/\\/g,"/"),i=yo(r,s,t?.[o]);i&&(n[o]=i)}return n}a(qn,"buildArkRuleFileHints");var Ro="INVARIANT_TESTS_PATH_MISSING",Ao="This project is adopted and has domain invariants, but ark.config.json does not name a real tests path. Add coverage.testGlobs or coverage.coverageRoots pointing at the folder where those tests live, then re-run. Without that path, coverage is an empty checkbox.",ko="INVARIANT_COVERAGE_ROOTS_MISSING",bo="A domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where this project's test runner actually goes. Add coverage.coverageRoots pointing at that folder, then re-run. Without it, coverage can certify a test no runner runs.";function Yn(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let s=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${s}.`}a(Yn,"formatCoverageDiscards");function Zn(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let s=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return s===""||s==="."?!0:n===s||n.startsWith(`${s}/`)})}a(Zn,"isUnderCoverageRoot");function Mt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Mt,"escapeRegExp");function Oe(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Oe,"normalizePath");function Ht(e,t){let n=[],r=0,s=e.length;for(;r<s;){let o=e[r],i=e[r+1];if(o==="/"&&i==="/"){for(;r<s&&e[r]!==`
|
|
4
|
-
|
|
3
|
+
var Oo=Object.defineProperty;var a=(e,t)=>Oo(e,"name",{value:t,configurable:!0});function B(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}a(B,"deterministicHash");function j(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(j).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${j(t[n])}`).join(",")}}`}a(j,"stableSerialize");function fe(e,t){let n=t.hash;for(let r=0;r<e.length;r+=1)n^=e.charCodeAt(r),n=Math.imul(n,16777619);t.hash=n}a(fe,"feedText");function qt(e,t){if(Array.isArray(e)){fe("[",t);for(let o=0;o<e.length;o+=1){if(o>0&&fe(",",t),!(o in e))continue;let s=e[o];if(s!==null&&typeof s=="object")qt(s,t);else{let i=JSON.stringify(s);i!==void 0&&fe(i,t)}}fe("]",t);return}let n=e,r=Object.keys(n).sort();fe("{",t);for(let o=0;o<r.length;o+=1){o>0&&fe(",",t);let s=r[o];fe(`${JSON.stringify(s)}:`,t);let i=n[s];i!==null&&typeof i=="object"?qt(i,t):fe(`${JSON.stringify(i)}`,t)}fe("}",t)}a(qt,"feedStable");function Yt(e){if(e===null||typeof e!="object")return B(j(e));let t={hash:2166136261};return qt(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}a(Yt,"stableHash");var Te="1.2";var Zn=["network","filesystem","clock","randomness","environment","process","persistence"];function H(e){let t=e.map((n,r)=>({key:j(n),index:r}));return t.sort((n,r)=>n.key<r.key?-1:n.key>r.key?1:n.index-r.index),t.map(({index:n})=>e[n])}a(H,"sortCanonical");function z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(z,"sortedUnique");function gt(e){let t={schemaVersion:"1.2",include:z(e.include??[]),exclude:z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:z(e.dynamicImportAllowlist??[]),layers:H(e.layers.map(n=>({name:n.name,patterns:z(n.patterns??[]),exclude:z(n.exclude??[]),forbiddenGlobals:z(n.forbiddenGlobals??[]),intentPrefixes:z(n.intentPrefixes??[]),capabilityDeny:z(n.capabilities?.deny??[]),pure:n.pure===!0}))),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:z(e.arkRun.compositionRoots),managedLayers:z(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return B(j(t))}a(gt,"resolvedFactsEvidenceRequirementsHash");function To(e){let t=H(e.completenessReasons.map(b=>({code:b.code,message:b.message,...b.file?{file:b.file}:{}}))),n=e.files.map(b=>({...b,typeOnlyExportNames:z(b.typeOnlyExportNames)})).sort((b,V)=>b.path<V.path?-1:b.path>V.path?1:0),r=H(e.dependencies.map(b=>({...b,...b.namedBindings?{namedBindings:z(b.namedBindings)}:{}}))),o=H(e.capabilityUses.map(b=>({...b}))),s=H(e.ambientUses.map(b=>({...b}))),i=H(e.publishCalls.map(b=>({...b}))),l=H(e.intentReferences.map(b=>({...b}))),c=H(e.safetyUses.map(b=>({...b}))),f=H((e.classShapes??[]).map(b=>({...b,mutatingMethods:[...b.mutatingMethods??[]].map(V=>({...V}))}))),h=H((e.arkRunKernelCalls??[]).map(b=>({...b}))),y=H((e.arkRunManagedNews??[]).map(b=>({...b}))),p=H((e.arkRunCompositionRootHits??[]).map(b=>({...b}))),R=H((e.arkRunDeclarations??[]).map(b=>({...b,uses:z(b.uses),reactsTo:z(b.reactsTo),raises:z(b.raises),sends:z(b.sends)}))),d=H((e.arkOrderPlaneCalls??[]).map(b=>({...b}))),g=H((e.arkOrderGenericUpdates??[]).map(b=>({...b}))),A=H((e.arkOrderRootHits??[]).map(b=>({...b}))),I=H((e.arkOrderXiFieldWrites??[]).map(b=>({...b}))),S=H((e.arkOrderIngestWritesXi??[]).map(b=>({...b}))),w=H((e.arkOrderReleaseKeyCounts??[]).map(b=>({...b}))),T=H((e.arkOrderXiTtlKeys??[]).map(b=>({...b}))),q=H((e.arkOrderBudgetLeaks??[]).map(b=>({...b}))),Q=e.files.map(({path:b,contentHash:V})=>({path:b,contentHash:V})).sort((b,V)=>b.path<V.path?-1:b.path>V.path?1:0),Y=Yt(Q);return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:Y,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:f,arkRunKernelCalls:h,arkRunManagedNews:y,arkRunCompositionRootHits:p,arkRunDeclarations:R,arkOrderPlaneCalls:d,arkOrderGenericUpdates:g,arkOrderRootHits:A,arkOrderXiFieldWrites:I,arkOrderIngestWritesXi:S,arkOrderReleaseKeyCounts:w,arkOrderXiTtlKeys:T,arkOrderBudgetLeaks:q}}a(To,"canonicalResolvedFactsInput");function Jn(e){let t=To(e);return{...t,factsHash:Yt(t)}}a(Jn,"createCanonicalResolvedCandidateFacts");function ht(e){return Jn(Qn($(e,"$"),!1))}a(ht,"createResolvedCandidateFacts");function $(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a($,"asRecord");function L(e,t,n){let r=Object.keys(e).find(o=>!t.includes(o));if(r)throw new Error(`${n}.${r} is not part of schema ${"1.2"}.`)}a(L,"assertOnlyKeys");function O(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}a(O,"requiredText");function pe(e,t,n){if(e[t]!==void 0)return O(e,t,n)}a(pe,"optionalText");function N(e,t,n){let r=O(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(N,"requiredProjectPath");function K(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(K,"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)}a(Xt,"requiredInteger");function G(e,t,n){let r=Xt(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(G,"requiredPositiveInteger");function P(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(P,"requiredArray");function ge(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}a(ge,"enumValue");function $e(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}a($e,"parseStringArray");function $o(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}a($o,"assertUnique");function Qn(e,t){L(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","arkOrderXiTtlKeys","arkOrderBudgetLeaks",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ge(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ge(e,"completeness",["complete","partial","unavailable"],"$"),o=P(e,"completenessReasons","$").map((v,C)=>{let m=`$.completenessReasons[${C}]`,u=$(v,m);L(u,["code","message","file"],m);let _=u.file===void 0?void 0:N(u,"file",m);return{code:O(u,"code",m),message:O(u,"message",m),..._?{file:_}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=P(e,"files","$").map((v,C)=>{let m=`$.files[${C}]`,u=$(v,m);return L(u,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],m),{path:N(u,"path",m),contentHash:O(u,"contentHash",m),parseStatus:ge(u,"parseStatus",["parsed","invalid"],m),parseDiagnosticCount:Xt(u,"parseDiagnosticCount",m),exportsOnlyTypes:K(u,"exportsOnlyTypes",m),typeOnlyExportNames:$e(u.typeOnlyExportNames,`${m}.typeOnlyExportNames`),hasTopLevelSideEffects:K(u,"hasTopLevelSideEffects",m)}}),i=P(e,"dependencies","$").map((v,C)=>{let m=`$.dependencies[${C}]`,u=$(v,m);L(u,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],m);let _=pe(u,"specifier",m),M=pe(u,"target",m),ee=ge(u,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],m);if(ee==="resolved-project"&&!M)throw new Error(`${m}.target is required for resolved-project dependencies.`);if(ee!=="resolved-project"&&M)throw new Error(`${m}.target is only allowed for resolved-project dependencies.`);if(ee!=="dynamic"&&!_)throw new Error(`${m}.specifier is required unless resolution is dynamic.`);return{from:N(u,"from",m),..._?{specifier:_}:{},kind:ge(u,"kind",["import","export","dynamic-import","require"],m),typeOnly:K(u,"typeOnly",m),line:G(u,"line",m),resolution:ee,...M?{target:N(u,"target",m)}:{},...u.namedBindings!==void 0?{namedBindings:$e(u.namedBindings,`${m}.namedBindings`)}:{},...u.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:K(u,"targetTypeOnlyExports",m)}:{},...u.sourcePureTypeModule!==void 0?{sourcePureTypeModule:K(u,"sourcePureTypeModule",m)}:{},...u.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:K(u,"namedBindingsTypeOnly",m)}:{},...u.portProofEligible!==void 0?{portProofEligible:K(u,"portProofEligible",m)}:{}}}),l=P(e,"capabilityUses","$").map((v,C)=>{let m=`$.capabilityUses[${C}]`,u=$(v,m);return L(u,["file","line","symbol","capability","source"],m),{file:N(u,"file",m),line:G(u,"line",m),symbol:O(u,"symbol",m),capability:ge(u,"capability",Zn,m),source:ge(u,"source",["ambient-global","import-based"],m)}}),c=P(e,"ambientUses","$").map((v,C)=>{let m=`$.ambientUses[${C}]`,u=$(v,m);return L(u,["file","line","symbol"],m),{file:N(u,"file",m),line:G(u,"line",m),symbol:O(u,"symbol",m)}}),f=P(e,"publishCalls","$").map((v,C)=>{let m=`$.publishCalls[${C}]`,u=$(v,m);L(u,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],m);let _=pe(u,"rawIntentName",m),M=pe(u,"sourceIntent",m);return{file:N(u,"file",m),line:G(u,"line",m),..._?{rawIntentName:_}:{},objectHasIntent:K(u,"objectHasIntent",m),arkPublishCandidate:K(u,"arkPublishCandidate",m),hasSource:K(u,"hasSource",m),...M?{sourceIntent:M}:{}}}),h=P(e,"intentReferences","$").map((v,C)=>{let m=`$.intentReferences[${C}]`,u=$(v,m);return L(u,["file","line","intent"],m),{file:N(u,"file",m),line:G(u,"line",m),intent:O(u,"intent",m)}}),y=P(e,"safetyUses","$").map((v,C)=>{let m=`$.safetyUses[${C}]`,u=$(v,m);L(u,["file","line","kind","symbol"],m);let _=pe(u,"symbol",m),M=ge(u,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],m);if(M==="in-memory-store"&&!_)throw new Error(`${m}.symbol is required for in-memory-store facts.`);if(M!=="in-memory-store"&&_)throw new Error(`${m}.symbol is only allowed for in-memory-store facts.`);return{file:N(u,"file",m),line:G(u,"line",m),kind:M,..._?{symbol:_}:{}}});$o(s,v=>v.path,"$.files");let p=new Set(s.map(v=>v.path));for(let v of s){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"&&s.some(v=>v.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let v of i)if(!p.has(v.from))throw new Error(`$.dependencies references missing source file ${v.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:P(e,"arkRunKernelCalls","$")).map((v,C)=>{let m=`$.arkRunKernelCalls[${C}]`,u=$(v,m);L(u,["file","line","kind","callee","viaImport","receiver","nameLiteral"],m);let _=pe(u,"receiver",m),M=pe(u,"nameLiteral",m);return{file:N(u,"file",m),line:G(u,"line",m),kind:ge(u,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],m),callee:O(u,"callee",m),viaImport:K(u,"viaImport",m),..._?{receiver:_}:{},...M?{nameLiteral:M}:{}}}),A=(e.arkRunManagedNews===void 0?[]:P(e,"arkRunManagedNews","$")).map((v,C)=>{let m=`$.arkRunManagedNews[${C}]`,u=$(v,m);L(u,["file","line","typeName","importedFrom"],m);let _=pe(u,"importedFrom",m);return{file:N(u,"file",m),line:G(u,"line",m),typeName:O(u,"typeName",m),..._?{importedFrom:_}:{}}}),S=(e.arkRunCompositionRootHits===void 0?[]:P(e,"arkRunCompositionRootHits","$")).map((v,C)=>{let m=`$.arkRunCompositionRootHits[${C}]`,u=$(v,m);return L(u,["file","matchedRoot","hasKernelFactory"],m),{file:N(u,"file",m),matchedRoot:O(u,"matchedRoot",m),hasKernelFactory:K(u,"hasKernelFactory",m)}}),w=e.arkRunDeclarations===void 0?[]:P(e,"arkRunDeclarations","$"),q=(e.arkOrderPlaneCalls===void 0?[]:P(e,"arkOrderPlaneCalls","$")).map((v,C)=>{let m=`$.arkOrderPlaneCalls[${C}]`,u=$(v,m);return L(u,["file","line","callee"],m),{file:N(u,"file",m),line:G(u,"line",m),callee:O(u,"callee",m)}}),Y=(e.arkOrderGenericUpdates===void 0?[]:P(e,"arkOrderGenericUpdates","$")).map((v,C)=>{let m=`$.arkOrderGenericUpdates[${C}]`,u=$(v,m);return L(u,["file","line","method"],m),{file:N(u,"file",m),line:G(u,"line",m),method:O(u,"method",m)}}),V=(e.arkOrderRootHits===void 0?[]:P(e,"arkOrderRootHits","$")).map((v,C)=>{let m=`$.arkOrderRootHits[${C}]`,u=$(v,m);return L(u,["file","matchedRoot","hasPlaneFactory"],m),{file:N(u,"file",m),matchedRoot:O(u,"matchedRoot",m),hasPlaneFactory:K(u,"hasPlaneFactory",m)}}),de=(e.arkOrderXiFieldWrites===void 0?[]:P(e,"arkOrderXiFieldWrites","$")).map((v,C)=>{let m=`$.arkOrderXiFieldWrites[${C}]`,u=$(v,m);return L(u,["file","line","key"],m),{file:N(u,"file",m),line:G(u,"line",m),key:O(u,"key",m)}}),se=(e.arkOrderIngestWritesXi===void 0?[]:P(e,"arkOrderIngestWritesXi","$")).map((v,C)=>{let m=`$.arkOrderIngestWritesXi[${C}]`,u=$(v,m);return L(u,["file","line"],m),{file:N(u,"file",m),line:G(u,"line",m)}}),ue=(e.arkOrderReleaseKeyCounts===void 0?[]:P(e,"arkOrderReleaseKeyCounts","$")).map((v,C)=>{let m=`$.arkOrderReleaseKeyCounts[${C}]`,u=$(v,m);return L(u,["file","line","keyCount"],m),{file:N(u,"file",m),line:G(u,"line",m),keyCount:G(u,"keyCount",m)}}),ut=(e.arkOrderXiTtlKeys===void 0?[]:P(e,"arkOrderXiTtlKeys","$")).map((v,C)=>{let m=`$.arkOrderXiTtlKeys[${C}]`,u=$(v,m);return L(u,["file","line","key"],m),{file:N(u,"file",m),line:G(u,"line",m),key:O(u,"key",m)}}),Bt=(e.arkOrderBudgetLeaks===void 0?[]:P(e,"arkOrderBudgetLeaks","$")).map((v,C)=>{let m=`$.arkOrderBudgetLeaks[${C}]`,u=$(v,m);return L(u,["file","line","kind"],m),{file:N(u,"file",m),line:G(u,"line",m),kind:O(u,"kind",m)}}),ze=w.map((v,C)=>{let m=`$.arkRunDeclarations[${C}]`,u=$(v,m);return L(u,["file","line","uses","reactsTo","raises","sends"],m),{file:N(u,"file",m),line:G(u,"line",m),uses:$e(u.uses,`${m}.uses`),reactsTo:$e(u.reactsTo,`${m}.reactsTo`),raises:$e(u.raises,`${m}.raises`),sends:$e(u.sends,`${m}.sends`)}});for(let[v,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",f],["$.intentReferences",h],["$.safetyUses",y],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",A],["$.arkRunCompositionRootHits",S],["$.arkRunDeclarations",ze],["$.arkOrderPlaneCalls",q],["$.arkOrderGenericUpdates",Y],["$.arkOrderRootHits",V],["$.arkOrderXiFieldWrites",de],["$.arkOrderIngestWritesXi",se],["$.arkOrderReleaseKeyCounts",ue],["$.arkOrderXiTtlKeys",ut],["$.arkOrderBudgetLeaks",Bt]])for(let m of C)if(!p.has(m.file))throw new Error(`${v} references missing file ${m.file}.`);let ve=pe(e,"projectPackageName","$"),zt=(e.classShapes===void 0?[]:P(e,"classShapes","$")).map((v,C)=>{let m=`$.classShapes[${C}]`,u=$(v,m);L(u,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],m);let _=P(u,"mutatingMethods",m).map((M,ee)=>{let pt=`${m}.mutatingMethods[${ee}]`,Wt=$(M,pt);return L(Wt,["name","referencesGuardOrPublish"],pt),{name:O(Wt,"name",pt),referencesGuardOrPublish:K(Wt,"referencesGuardOrPublish",pt)}});return{file:N(u,"file",m),className:O(u,"className",m),exported:K(u,"exported",m),hasPublicMutableFields:K(u,"hasPublicMutableFields",m),hasPublicSetters:K(u,"hasPublicSetters",m),hasPublicConstructor:K(u,"hasPublicConstructor",m),hasStaticFactory:K(u,"hasStaticFactory",m),mutatingMethods:_,...u.dataOnly===void 0?{}:{dataOnly:K(u,"dataOnly",m)},...u.truncatedUntil===void 0?{}:{truncatedUntil:Xt(u,"truncatedUntil",m)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:O(e,"resolverIdentity","$"),compilerIdentity:O(e,"compilerIdentity","$"),compilerOptionsHash:O(e,"compilerOptionsHash","$"),tsconfigHash:O(e,"tsconfigHash","$"),evidenceRequirementsHash:O(e,"evidenceRequirementsHash","$"),...ve?{projectPackageName:ve}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:f,intentReferences:h,safetyUses:y,classShapes:zt,arkRunKernelCalls:d,arkRunManagedNews:A,arkRunCompositionRootHits:S,arkRunDeclarations:ze,arkOrderPlaneCalls:q,arkOrderGenericUpdates:Y,arkOrderRootHits:V,arkOrderXiFieldWrites:de,arkOrderIngestWritesXi:se,arkOrderReleaseKeyCounts:ue,arkOrderXiTtlKeys:ut,arkOrderBudgetLeaks:Bt}}a(Qn,"parseResolvedFactsInput");function Se(e){let t=$(e,"$"),n=O(t,"factsHash","$"),r=O(t,"candidateTreeHash","$"),o=Jn(Qn(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}a(Se,"loadResolvedCandidateFacts");var Lo=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},W={type:"integer",minimum:1},F={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},er={$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:x,message:x,file:F}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:F,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:F,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:W,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:F,namedBindings:{type:"array",items:x},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:F,line:W,symbol:x,capability:{enum:Lo},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:F,line:W,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:F,line:W,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:F,line:W,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:F,line:W,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:F,className:x,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},truncatedUntil:{type:"integer",minimum:0},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:F,line:W,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:F,line:W,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:F,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:F,line:W,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:F,line:W,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:F,line:W,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:F,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:F,line:W,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:F,line:W}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:F,line:W,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:F,line:W,key:x}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:F,line:W,kind:x}}},factsHash:x},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var tr="1.0";var Jt=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),mt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),en=Object.freeze(Object.keys(mt).sort()),Zt=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"}),Qt=Object.freeze({process:Object.freeze(["process","node:process"])});function We(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Zt[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Zt[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Zt[e.slice(0,s)]??null}a(We,"capabilityForModuleSpecifier");function qe(e,t){for(let n of t)if(Qt[n]?.includes(e))return n;return null}a(qe,"forbiddenGlobalForModuleSpecifier");function Ye(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=mt[r];if(o)return o}return null}a(Ye,"capabilityForAmbientName");function Le(e){if(e?.pure===!0)return[...Jt].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Jt.includes(r));return[...new Set(n)].sort()}a(Le,"effectiveCapabilityDeny");function tn(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}a(tn,"ambientCoveredByForbiddenGlobals");function yt(e){let t=new Set,n=new Set,r=Object.keys(mt);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(i=>i===o||i.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let i of s)t.add(`ambient:${i}`);for(let i of Qt[o]??[])t.add(`import-exact:${i}`)}for(let o of Le(e)){if(t.add(`import:${o}`),o==="process")for(let s of Qt.process)t.add(`import-exact:${s}`);for(let s of r)Ye(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(yt,"loweredLayerCoverage");function No(e){let t=new Set,n=Ye(e);n&&t.add(n);for(let[r,o]of Object.entries(mt))(r===e||r.startsWith(`${e}.`))&&t.add(o);return[...t].sort()}a(No,"lowerForbiddenGlobal");function ye(e){if(e==="deny"||e==="deny-cross-parent")return e;if(e!==null&&typeof e=="object"){let t=e.mode;if(t==="deny-cross-parent")return t}}a(ye,"sharedImportsSliceMode");function vt(e){if(e===null||typeof e!="object")return[];let t=e.stopAt;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}a(vt,"sharedImportsSliceStopAt");var nr=new Map;function rr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(rr,"escapeLiteral");function St(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}a(St,"normalizeGlobSeparators");function Po(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(Po,"bracesBalanced");function oe(e){let t=nr.get(e);if(t)return t;let n=St(e),r=Po(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=rr(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=rr(c)}let i=new RegExp(`^${o}$`);return nr.set(e,i),i}a(oe,"globToRegExp");function Fo(e){return St(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Fo,"concreteGlobSegments");function on(e,t){let n=St(String(e)),r=Fo(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let f of r){let h=-1;for(let y=l;y<i.length;y+=1)if(i[y]===f){h=y;break}if(h<0)return s;c=h,l=h+1}return(c+1)*1e6+r.length*1e4+o}a(on,"patternSpecificity");function te(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>oe(i).test(n))){for(let i of s.patterns??[])if(oe(i).test(n)){let l=on(i,n);l>o&&(o=l,r=s.name)}}return r}a(te,"layerForRelativePath");function Je(e,t,n){return ur(e,t,n==="stars"?"stars":"path")}a(Je,"sliceIdForPath");function rn(e,t){return ur(e,t?[...t]:void 0,dr)}a(rn,"legacyStarsSliceIdForPath");var dr="stars-4.8.23";function ur(e,t,n){if(!t?.length)return;let r=String(e).split(/[/\\]/).filter(Boolean);if(r.length===0)return;let o=new Set;for(let s of t){if(typeof s!="string"||s.length===0)continue;let i=Do(s);if(i.anchored){let l=Ho(r,i.anchored,n);if(l)return l;continue}i.bare!==void 0&&o.add(i.bare)}return Vo(r,o)}a(ur,"sliceIdWithBinding");var Rt=new Map;function Do(e){let t=Rt.get(e);if(t)return t;let n={};return fr(e)?n={anchored:Mo(e)}:!e.includes("/")&&!e.includes("\\")&&!e.includes("*")&&(n={bare:e.toLowerCase()}),Rt.size>=1024&&Rt.clear(),Rt.set(e,n),n}a(Do,"parsedSliceFolder");function fr(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(fr,"isAnchoredSliceEntry");function Mo(e){return e.split(/[/\\]/).filter(t=>t.length>0).map(t=>t.toLowerCase())}a(Mo,"anchoredSlicePattern");function Ho(e,t,n){let r=hr(e,t[0]??"");for(let o of r){let s=Ko(e,t,o,n);if(s)return s}}a(Ho,"anchoredSliceIdFromPattern");function Ko(e,t,n,r="path"){let o=[],s=[],i=-1,l=n;for(let c=0;c<t.length;c+=1){let f=t[c];if(f==="*"){if(l>=e.length-1){for(let h=c;h<t.length;h+=1)if(t[h]!=="*")return;break}o.push(e[l].toLowerCase()),s.push(!0),l+=1;continue}if(f==="**"||l>=e.length||e[l].toLowerCase()!==f)return;o.push(e[l].toLowerCase()),s.push(!1),i=o.length-1,l+=1}if(o.length!==0)return r===dr?i<0?void 0:o.slice(i).join("/"):r==="stars"?i<0?void 0:o.filter((c,f)=>f>=i||s[f]).join("/"):o.join("/")}a(Ko,"bindAnchoredSlice");function pr(e){let t=-1;for(let r=0;r<e.length;r+=1)e[r]!=="*"&&(t=r);if(t<0)return null;let n=[];for(let r=0;r<e.length;r+=1)(r>=t||e[r]==="*")&&n.push(r);return n}a(pr,"starsKeptSegmentIndexes");function gr(e){let t=[];for(let n of e??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let s of n.sliceFolders??[]){if(typeof s!="string"||s.length===0)continue;let i=jo(s);if(!i)continue;let l=s.split(/[/\\]/).filter(h=>h.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let f=r.get(i)??[];f.push(s),r.set(i,f)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:Uo(n.from,n.to,i,s)})}return t}a(gr,"sliceIdentityCollisions");function jo(e){if(!fr(e))return;let t=e.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(t.some(r=>r==="**"))return;let n=pr(t);if(n)return n.map(r=>t[r]).join("/")}a(jo,"starsIdentityStem");function Uo(e,t,n,r){let o=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 ${o}. They bind as ${r}.`}a(Uo,"formatSliceIdentityCollision");function Vo(e,t){if(t.size!==0){for(let n=0;n<e.length-1;n+=1)if(t.has(e[n].toLowerCase())&&!(n+1>=e.length-1))return`${e[n].toLowerCase()}/${e[n+1].toLowerCase()}`}}a(Vo,"bareSliceId");function Go(e){let t=new Set;for(let n of e??[]){let o=St(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let i=o[s];if((i==="**"||i==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(Go,"inferSliceFoldersFromPatterns");function an(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return Go(r?.patterns)}a(an,"resolveSliceFolders");function sr(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(sr,"normalizeSegments");function Qe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Qe,"trimTrailingSlashes");var Bo=["src","app"];function hr(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return Bo.includes(n)&&r!==n?[0,1]:[0]}a(hr,"anchorOffsets");function zo(e){let t=Qe(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(zo,"isBlanketRoot");function Pe(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=sr(n);for(let s of t){if(typeof s!="string"||s.length===0||zo(s))continue;if(s.includes("*")){let c=Qe(s.toLowerCase());if(oe(c).test(r)||oe(`${c}/**`).test(r))return!0;continue}let i=sr(s);if(i.length===0)continue;let l=hr(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let f=!0;for(let h=0;h<i.length;h+=1)if(o[c+h]!==i[h]){f=!1;break}if(f)return!0}}return!1}a(Pe,"pathUnderSharedRoot");function or(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(or,"sliceMatchesDeclaration");function At(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&or(r.from,t)&&or(r.to,n))}a(At,"crossSliceEdgeAllowed");function Wo(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:e.sharedImportsSlice==="deny"&&e.fromShared===!0&&e.toSlice&&!e.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(Wo,"peerIsolationDecision");function mr(e){return Qe(e.trim().replace(/\\/g,"/")).toLowerCase()}a(mr,"aliasGlobPattern");function yr(e,t){let n=mr(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=sn(r),s=oe(n),l=(n.split("/").pop()??"").includes("*")?null:oe(`${n}/**`),c=a(f=>s.test(f)||l!==null&&l.test(f),"hit");return c(r)||o!==r&&c(o)}a(yr,"aliasGlobMatches");function Rr(e,t){return!e||!t?.length?!1:Pe(e,[...t])?!0:t.some(n=>typeof n=="string"&&yr(n,e))}a(Rr,"pathMatchesSharedWalkStop");function ln(e){let t=mr(e).split("/").filter(Boolean);return t.length<2||t.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:t.slice(0,-1).join("/"),childId:t.join("/")}}a(ln,"splitAliasTarget");function Ar(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&yr(n.from,e))return n;return null}a(Ar,"firstSliceAliasEntry");function qo(e,t){let n=Ar(e,t);return n?ln(n.to):null}a(qo,"firstSliceAlias");function Xe(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=Je(e,r?[...r]:void 0,t.sliceIdentity),s=kt(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=qo(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Xe,"resolveGovernedSlice");function Yo(e){let t=[];for(let n of e??[]){if(typeof n!="string"||n.length===0)continue;let r=n.split(/[/\\]/).filter(Boolean).map(l=>l.toLowerCase());if(r.length===1&&r[0]&&!r[0].includes("*")){t.push({literals:[r[0],null],legacy:[r[0],null]});continue}if(r.some(l=>l==="**"||l.includes("*")&&l!=="*"))continue;let o=pr(r);if(!o||!r.includes("*"))continue;let s=a(l=>l==="*"?null:l,"star"),i=o.find(l=>r[l]!=="*")??0;t.push({literals:o.map(l=>s(r[l]??"")),legacy:r.slice(i).map(s)})}return t}a(Yo,"starsUniverseShapes");function ir(e,t){return e.length===t.length&&e.every((n,r)=>n===null||t[r]==="*"||n===t[r])}a(ir,"literalsMatch");function Ne(e,t){let n=t.split("/").filter(Boolean).map(s=>s.toLowerCase()),r=Yo(e);if(n.length===0||r.some(s=>ir(s.literals,n)))return[];let o=new Set;for(let s of r)if(s.legacy.length!==s.literals.length&&ir(s.legacy,n)){let i=[...n],l=s.literals.length-s.legacy.length;o.add([...s.literals.slice(0,l).map(()=>"*"),...i].join("/"))}return[...o].sort()}a(Ne,"legacyStarsIdTargets");function kr(e,t){if(e.sliceIdentity!=="stars")return;let n=ln(t);if(n)return Ne(e.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(kr,"legacyAliasUniverse");function ar(e,t,n){let r=Xe(e,t,n);if(!e||t.sliceIdentity!=="stars")return r;if(r.universeId){let o=Ar(e,t);if(!Je(e,[...n],t.sliceIdentity)&&o&&kr(t,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let i=rn(e,n),l=t.childSlices,c=l?.sliceIdentity==="stars"?rn(e,l.sliceFolders):void 0;return{...r,...i?{legacyUniverse:i}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(ar,"placeForPair");function cn(e,t,n,r){let o=ar(n,e,t),s=ar(r,e,t),i=o.legacyUniverse,l=s.legacyUniverse,c=a((d,g)=>{if(!d.legacyAlias||g.legacyAlias||!g.universeId||g.legacyUniverse?.toLowerCase()!==d.universeId?.toLowerCase())return d;let A=d.childId?.split("/").pop();return{...d,universeId:g.universeId,...A?{childId:`${g.universeId}/${A}`}:{}}},"adopt"),f=c(o,s),h=c(s,o),y=At(e.allowedCrossSlice,f.universeId,h.universeId)||e.sliceIdentity==="stars"&&(i!==f.universeId||l!==h.universeId)&&At(e.allowedCrossSlice,i,l),p=e.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&s.legacyChild!==void 0&&o.legacyChild!==s.legacyChild&&br(e.childSlices.allowedCrossSlice,o.legacyChild,s.legacyChild),R=a(d=>({...d.universeId?{universeId:d.universeId}:{},...d.childId?{childId:d.childId}:{}}),"strip");return{from:R(f),to:R(h),crossSliceAllowed:y,legacyChildAllowed:p}}a(cn,"resolveGovernedSlicePair");function Xo(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(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(Xo,"peerIsolationDenyExplanation");function Zo(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(Zo,"crossParentExplanation");function Jo(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(Jo,"crossSiblingExplanation");function Qo(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(Qo,"parentImportsChildExplanation");function Ze(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(Ze,"universePairLabel");function ei(e,t){if(!e||!t?.length)return!1;let n=e.toLowerCase();return t.some(r=>typeof r=="string"&&r.length>0&&r.toLowerCase()===n)}a(ei,"isCommonFolderName");function kt(e,t,n){if(!e||!n?.sliceFolders?.length)return{};let r=Je(e,n.sliceFolders,n.sliceIdentity);if(!r||!t)return{};let o=r.toLowerCase(),s=t.toLowerCase();if(o===s)return{};if(!o.startsWith(`${s}/`))return{mismatched:{childId:r,universeId:t}};let i=o.slice(s.length+1).split("/")[0];return ei(i,n.commonFolders)?{}:{childId:r}}a(kt,"resolveChildSliceId");function ti(e){return Qe(e.trim().replace(/\\/g,"/")).toLowerCase()}a(ti,"siblingEntryKey");function sn(e){return e.replace(/^(?:src|app)\//,"")}a(sn,"stripSrcOrApp");function ni(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=sn(t);if(!r)return!1;let o=sn(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(ni,"pathUnderSubtree");function ri(e,t,n){if(!t||!n?.length)return!1;let r=t.toLowerCase();for(let o of n){if(typeof o!="string")continue;let s=ti(o);if(!(!s||s.includes("*"))&&(r===s||e&&ni(e,s)))return!0}return!1}a(ri,"importerInEnforcedSubtree");function si(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!ri(t,n,e.enforce)}a(si,"siblingCrossingAdvisory");function bt(e){if(typeof e!="string")return null;let t=Qe(e.trim().replace(/\\/g,"/")).toLowerCase();if(!t.includes("/"))return null;let n=t.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(bt,"childSlicePatternSegments");function lr(e,t){let n=bt(e),r=bt(t);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let s=n[o];if(s!=="*"&&s!==r[o])return!1}return!0}a(lr,"childSlicePatternMatches");function br(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&lr(r.from,t)&&lr(r.to,n))return!0;return!1}a(br,"childCrossSliceAllowed");function oi(e,t){let n=bt(e),r=bt(t);if(!n||!r)return!1;let o=n.slice(0,-1),s=r.slice(0,-1);if(o.length!==s.length)return!0;for(let i=0;i<o.length;i+=1){let l=o[i],c=s[i];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(oi,"childAllowanceSpansUniverses");function ii(e){let t=Wo({fromPath:e.fromPath,toPath:e.toPath,folderCount:e.folderCount,fromSlice:e.fromSlice,toSlice:e.toSlice,fromShared:e.fromShared,toShared:e.toShared,crossSliceAllowed:e.crossSliceAllowed,sharedImportsSlice:ye(e.rule.sharedImportsSlice)});if(t.denied){let i=!!e.rule.childSlices&&t.reason==="cross-slice";return{crossing:t.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...i?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:i?Zo(e.fromSlice,e.toSlice):Xo(t.reason??"missing-path",{fromPath:e.fromPath,toPath:e.toPath,fromSlice:e.fromSlice,toSlice:e.toSlice}),peerIsolationReason:t.reason,fromUniverse:e.fromSlice,toUniverse:e.toSlice}}let n=e.rule.childSlices;if(!n||!e.fromSlice||!e.toSlice||e.fromSlice!==e.toSlice||!e.toPath)return{crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};let r=e.fromChild??kt(e.fromPath,e.fromSlice,n).childId,o=e.toChild??kt(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?e.legacyChildAllowed||br(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:si(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:Jo(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:Qo(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(ii,"evaluateNestedSliceWall");function vr(e){return e?.crossing==="cross-sibling"||e?.crossing==="parent-imports-child"}a(vr,"isChildWallCrossing");function Sr(e,t){return vr(t)?e?.childSlices?.message:e?.message}a(Sr,"sliceConsumerMessage");function It(e){let t=e.verdict.explanation,n=vr(e.verdict),r=n?e.childMessage:e.ruleMessage;if(e.surface==="intent"){let o=e.defaultMessage??`${e.fromLayer} must not reference ${e.toLayer} intent.`;return n&&t?`${e.childMessage??o} ${t}`:e.verdict.reasonId&&t?`${o} ${t}`:t&&e.verdict.peerIsolationReason!=="cross-slice"?`${o} ${t}`:r?t?`${r} (${t})`:r:o}if(r)return t?`${r} (${t})`:r;if(t){let o=e.kind??"import";return`${e.fromLayer} must not ${o} another slice of ${e.toLayer} (${e.fromPath} \u2192 ${e.toPath}): ${t}`}return`${e.fromLayer} must not ${e.kind??"import"} ${e.toLayer}.`}a(It,"composeSliceDenialMessage");function Et(e){if(!e||e.decision==="allow")return{};let t=Ze(e.fromUniverse),n=Ze(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Et,"sliceFindingExtras");function Ir(e,t){let n=[],r=new Set,o=new Set;for(let s of e??[])if(s?.peerIsolation&&s.allowed===!1&&n.push(...ai(s,t)),!!s?.childSlices){if(!s.peerIsolation||s.allowed!==!1){n.push({ruleId:"CONFIG_CHILD_SLICES_INERT",failsStrict:!1,fromLayer:s.from,toLayer:s.to,message:`${s.from} \u2192 ${s.to}: childSlices is inert on this rule and enforces nothing. The child wall runs only inside a universe wall. Add "peerIsolation": true and "allowed": false to the same rule, or remove childSlices.`});continue}for(let i of t){let l=Je(i,s.sliceFolders,s.sliceIdentity),c=kt(i,l,s.childSlices);if(!c.mismatched)continue;let f=`${s.from}\0${s.to}\0${c.mismatched.universeId}\0${c.mismatched.childId}`;r.has(f)||(r.add(f),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:s.from,toLayer:s.to,path:i,message:`${s.from} \u2192 ${s.to}: child id ${c.mismatched.childId} does not extend universe id ${c.mismatched.universeId} (${i}).`}))}for(let i of s.childSlices.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string"||!oi(i.from,i.to))continue;let l=`${i.from.trim().toLowerCase()}\0${i.to.trim().toLowerCase()}`;o.has(l)||(o.add(l),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:s.from,toLayer:s.to,message:`childSlices.allowedCrossSlice ${i.from} \u2192 ${i.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(Ir,"childSliceConfigFindings");function cr(e,t){let n=new Map;if(!e?.length)return n;for(let r of t){if(typeof r!="string")continue;let o=Je(r,[...e],"stars"),s=rn(r,e);if(!o||!s||o===s)continue;let i=n.get(s)??new Set;i.add(o),n.set(s,i)}return n}a(cr,"observedIdsByLegacy");function nn(e,t,n,r){let o=r?`/${r}`:"",s=`${t[0]??e}${o}`,i=[...n.get(e.toLowerCase())??[]].sort().map(l=>`${l}${o}`);return i.length===1?`${i[0]}`:i.length>1?`${s} (one entry per module: ${i.join(", ")})`:s}a(nn,"newIdHint");function ai(e,t){let n=[],r=a(s=>n.push({ruleId:"CONFIG_SLICE_LEGACY_STARS_ID",failsStrict:!1,fromLayer:e.from,toLayer:e.to,message:`${e.from} \u2192 ${e.to}: ${s} It keeps its 4.8.23 meaning for this release only.`}),"push"),o=e.childSlices;if(e.sliceIdentity==="stars"){let s=cr(e.sliceFolders,t);for(let i of o?.sliceAliases??[]){if(!i||typeof i.to!="string")continue;let l=ln(i.to);if(!l||kr(e,i.to)===void 0)continue;let c=Ne(e.sliceFolders,l.universeId),f=l.childId.split("/").pop();r(`sliceAliases to "${i.to}" is a 4.8.23 stars id (the star before the last literal was dropped). The id is now ${nn(l.universeId,c,s,f)}; write that instead.`)}for(let i of e.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string")continue;let l=[i.from,i.to].filter(f=>f.includes("/")&&Ne(e.sliceFolders,f).length>0);if(l.length===0)continue;let c=a(f=>l.includes(f)?nn(f,Ne(e.sliceFolders,f),s):f,"rename");r(`allowedCrossSlice ${i.from} \u2192 ${i.to} names a 4.8.23 stars id. The ids are now ${c(i.from)} \u2192 ${c(i.to)}; write those instead.`)}}if(o?.sliceIdentity==="stars"){let s=cr(o.sliceFolders,t);for(let i of o.allowedCrossSlice??[]){if(!i||typeof i.from!="string"||typeof i.to!="string")continue;let l=[i.from,i.to].filter(f=>Ne(o.sliceFolders,f).length>0);if(l.length===0)continue;let c=a(f=>l.includes(f)?nn(f,Ne(o.sliceFolders,f),s):f,"rename");r(`childSlices.allowedCrossSlice ${i.from} \u2192 ${i.to} names a 4.8.23 stars id. The ids are now ${c(i.from)} \u2192 ${c(i.to)}; write those instead.`)}}return n}a(ai,"legacyStarsIdFindings");function Er(e){if(e!==null&&typeof e=="object"){let t=e.ratchet;if(t===!0)return"always";if(t===!1)return"never"}return"auto"}a(Er,"siblingRatchetMode");function Fe(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,i=r?.toPath,l=an(o,t,r?.layers),c=cn(o,l,s,i),f=c.from,h=c.to,y=f.universeId,p=h.universeId,R=ii({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:y,toSlice:p,fromChild:f.childId,toChild:h.childId,fromShared:!y&&Pe(s,o.sharedRoots),toShared:!p&&Pe(i,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(R.decision!=="allow")return{rule:o,peerIsolationReason:R.peerIsolationReason,fromSlice:y,toSlice:p,sliceVerdict:R};continue}if(t!==n)return{rule:o}}}a(Fe,"findDeniedEdgeDecision");function Cr(e,t,n,r){let o=r?.fromPath,s=r?.toPath;if(!(!o||!s))for(let i of e??[]){if(i.from!==t||i.to!==n||i.allowed!==!1||!i.peerIsolation||ye(i.sharedImportsSlice)==="deny")continue;let l=an(i,t,r?.layers),c=Xe(o,i,l).universeId,f=Xe(s,i,l).universeId;if(!(c||!f)&&Pe(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:f}}}a(Cr,"findSharedImportsSliceBridge");function dn(e,t,n){return an(e,t,n)}a(dn,"peerSliceFolders");var un={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."},Ct=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 fn(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}a(fn,"resolveIntentLayer");function pn(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(pn,"looksLikeArkIntent");function gn(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&pn(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:un.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:un.PUBLISH_MISSING_SOURCE}),t}a(gn,"classifyPublishFacts");var wr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",li=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var xr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Wc={$schema:"https://json-schema.org/draft/2020-12/schema",$id:wr,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:wr},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:[...li]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:xr,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:xr}}}};function et(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(et,"emptyEffectiveArkRules");function _r(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}a(_r,"structureFreezeTarget");var ci=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),di=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),ui=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function fi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(n<0)return!0;let r=e[n];if(/[A-Za-z0-9_$]/.test(r)){let o=n;for(;o>=0&&/[A-Za-z0-9_$]/.test(e[o]);)o-=1;return ui.has(e.slice(o+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:di.has(r)}a(fi,"slashStartsRegex");function pi(e,t){if(!fi(e,t))return t;let n=t+1,r=!1;for(;n<e.length;){let o=e[n];if(o===`
|
|
4
|
+
`||o==="\r")return t;if(o==="\\"){n+=2;continue}if(r)o==="]"&&(r=!1);else if(o==="[")r=!0;else if(o==="/"){for(n+=1;n<e.length&&/[A-Za-z]/.test(e[n]);)n+=1;return n}n+=1}return t}a(pi,"skipRegexLiteral");function Ie(e,t){let n=e[t];if(n==="/"&&e[t+1]==="/"){let r=e.indexOf(`
|
|
5
|
+
`,t);return r===-1?e.length:r}if(n==="/"&&e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}if(n==="/")return pi(e,t);if(n==="'"||n==='"'||n==="`"){let r=t+1;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]===n)return r+1;r+=1}return e.length}return t}a(Ie,"skipStringOrComment");function le(e,t){let n=t;for(;n<e.length;){if(/\s/.test(e[n])){n+=1;continue}if(e[n]==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=Ie(e,n);continue}break}return n}a(le,"skipWsAndComments");function wt(e,t){let n=e[t];if(!n||!/[A-Za-z_$]/.test(n))return null;let r=t+1;for(;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r+=1;return{ident:e.slice(t,r),end:r}}a(wt,"readIdent");function Re(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=Ie(e,s);if(i!==s){s=i;continue}let l=e[s];l===n?o+=1:l===r&&!(r===">"&&e[s-1]==="=")&&(o-=1),s+=1}return o===0?s:null}a(Re,"skipBalanced");function hn(e){let t=[],n=0,r;for(;n<e.length&&(n=le(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let h=wt(e,s);if(!h||!ci.has(h.ident))break;o.push(h.ident),s=le(e,h.end)}if(o.length===1&&o[0]==="static"&&e[s]==="{"){let h=Re(e,s,"{","}");if(h==null){r=e.length;break}n=h;continue}let i=wt(e,s);if(!i){n+=1;continue}if(s=le(e,i.end),e[s]==="<"){let h=Re(e,s,"<",">");if(h==null){r=e.length;break}s=le(e,h)}if(e[s]==="("){let h=Re(e,s,"(",")");if(h==null){r=e.length;break}if(s=le(e,h),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let y=Ie(e,s);if(y!==s){s=y;continue}s+=1}if(e[s]==="{"){let y=Re(e,s,"{","}");if(y==null){r=e.length;break}t.push({name:i.ident,modifiers:o,kind:"method",body:e.slice(s+1,y-1)}),n=y;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,f=0;for(;s<e.length;){let h=Ie(e,s);if(h!==s){s=h;continue}let y=e[s];if(y==="{")l+=1;else if(y==="}"){if(l===0)break;l-=1}else if(y==="(")c+=1;else if(y===")")c-=1;else if(y==="[")f+=1;else if(y==="]")f-=1;else if(y===";"&&l===0&&c===0&&f===0){s+=1;break}s+=1}s>=e.length&&(l>0||c>0||f>0)&&(r=e.length),t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(hn,"scanClassMembers");function Or(e,t){let n=t;for(;n<e.length;){let r=le(e,n);if(r!==n){n=r;continue}let o=e[n];if(o==="{")return n;if(o===";")return null;if(o==="<"||o==="("||o==="["){let i=Re(e,n,o,o==="<"?">":o==="("?")":"]");if(i==null)return null;n=i;continue}if(o==='"'||o==="'"||o==="`"){n=Ie(e,n);continue}n+=1}return null}a(Or,"findClassBodyBrace");function mn(e,t={}){let n=[],r=t.exportedOnly?/\bexport\s+(?:abstract\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*)/g:/(?:\b(export)\s+(?:default\s+)?)?(?:\babstract\s+)?\bclass\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,o=Tr(e),s;for(;(s=r.exec(o))!==null;){let i=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=Or(e,s.index+s[0].length);if(c==null){n.push({name:i,start:s.index,exported:l,bodyStart:null,bodyEnd:null});continue}let f=Re(e,c,"{","}");n.push({name:i,start:s.index,exported:l,bodyStart:c+1,bodyEnd:f==null?null:f-1})}return n}a(mn,"findClassDeclarations");function Tr(e){let t="",n=0;for(;n<e.length;){let r=Ie(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}a(Tr,"maskStringsAndComments");function $r(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=Tr(e),o=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),s=new RegExp(`\\b(?:(namespace|module)\\s+${o}\\s*\\{|(?:const|let|var)\\s+${o}\\s*(?::[^=;]+?)?=(?!=|>)\\s*(class\\b)?)`,"g"),i;for(;(i=s.exec(r))!==null;){let l,c;if(i[1])c="namespace",l=i.index+i[0].length-1;else if(i[2])c="class-expression",l=Or(e,i.index+i[0].length);else{c="object";let h=le(e,i.index+i[0].length);l=e[h]==="{"?h:null}if(l==null)continue;let f=Re(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:f==null?e.length:f-1})}return n}a($r,"findMemberContainers");function Lr(e){let t=[],n=0,r=!0;for(;n<e.length;){let o=Ie(e,n);if(o!==n){n=o,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=Re(e,n,s,s==="{"?"}":s==="("?")":"]")??e.length,r=!1;continue}if(s===","){r=!0,n+=1;continue}if(r&&/[A-Za-z_$]/.test(s)){let i=wt(e,n);for(;i&&(i.ident==="async"||i.ident==="get"||i.ident==="set");){let l=le(e,i.end);e[l]==="*"&&(l=le(e,l+1));let c=wt(e,l);if(!c)break;i=c}if(i){let l=le(e,i.end);("(:,<".includes(e[l]??"")||l>=e.length)&&t.push(i.ident),n=i.end,r=!1;continue}}if(r&&s==="*"){n+=1;continue}/\s/.test(s)||(r=!1),n+=1}return t}a(Lr,"objectLiteralMemberNames");var gi=/\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)/,hi=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,mi=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,yi=["db","tx","client","prisma","prismaClient","drizzle"],Ri="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",Ai="\\bINSERT\\s+INTO\\b|\\bUPDATE\\s+[A-Za-z_][\\w.]*\\s+SET\\b|\\bDELETE\\s+FROM\\b",Nr="\\((?:[^()]|\\([^()]*\\))*\\)",ki=`\\bnew\\s+PrismaClient\\s*${Nr}|\\bdrizzle\\s*${Nr}`,bi=/(?<![\w$])([A-Za-z_$][\w$]*)\s*[?!]?\s*(?::[^=;\n]+)?=(?![=>])\s*(?:await\s+)?(?:new\s+(?:PrismaClient|Pool|Client|MongoClient|Sequelize|Kysely|Knex)\b|(?:drizzle|knex|Knex|postgres)\s*\()/g,vi=/(?<![\w$])([A-Za-z_$][\w$]*)\s*[?!]?\s*:\s*(?:Readonly\s*<\s*)?(?:Prisma\s*\.\s*TransactionClient|PrismaClient|Pool|PoolClient|MongoClient|Sequelize|Kysely|Knex|DataSource|EntityManager|NodePgDatabase|PostgresJsDatabase|BetterSQLite3Database|MySql2Database|LibSQLDatabase)\b/g;function Si(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Si,"escapeRegExp");function xt(e){return gi.test(e)||hi.test(e)}a(xt,"sourceImportsPersistenceDriverText");function Pr(e,t,n){let r=new RegExp(e.source,"g"),o;for(;(o=r.exec(t))!==null;)o[1]&&n.add(o[1])}a(Pr,"collectFirstGroup");function Ii(e){let t=new Set;Pr(bi,e,t),Pr(vi,e,t);let n=new RegExp(mi.source,"g"),r;for(;(r=n.exec(e))!==null;)for(let o of(r[1]??"").split(",")){let s=o.trim().replace(/^type\s+/,"").split(/\s+as\s+/),i=(s[1]??s[0]??"").trim();/^[A-Za-z_$][\w$]*$/.test(i)&&t.add(i)}return[...t].sort()}a(Ii,"persistenceClientBindings");function yn(e){let t=[...yi,...Ii(e)].map(Si).join("|");return new RegExp(`(?:\\b(?:${t})(?![\\w$])|${ki})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${Ri}\\s*\\(|${Ai}`,"i").test(e)}a(yn,"sourceHasPersistenceWrite");var Ei=["no-anemic-model"],Mr=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],sd=new RegExp(`\\b(${Mr.join("|")})\\b`),Hr="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",od=new RegExp(`\\bthis\\.${Hr}\\.push\\s*\\(`),id=new RegExp(`^this\\.${Hr}\\s*=\\s*\\[\\s*\\]`);function Ci(){return`${Mr.join(", ")}, or events-array .push(`}a(Ci,"expectedDomainInvariantWordsPhrase");function Kr(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}a(Kr,"shapeTruncatedUntil");function wi(e){let t=Kr(e);return t==null?"":` shape analysed until character ${t}`}a(wi,"shapeTruncationSuffix");function Fr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Fr,"escapeGlobLiteral");function xi(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=Fr(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Fr(o)}return new RegExp(`^${n}$`)}a(xi,"globToRegExp");function De(e,t){return!t||t.length===0?!0:t.some(n=>xi(n).test(e))}a(De,"matchesAppliesTo");function jr(e){return Ei.includes(e)}a(jr,"isTier2");function Ur(e){return e.mode==="enforced"&&!jr(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Ur,"severityFor");function Ae(e,t,n,r=1){let{severity:o,failsStrict:s}=Ur(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:o,sensor:e.sensor,failsStrict:s}}a(Ae,"baseViolation");function _t(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(_t,"isInRuleLayer");function Ot(e,t,n){return t.filter(r=>!(!r.exported||!De(r.file,e.appliesTo)||!_t(r.file,e,n)))}a(Ot,"shapesForRule");function Rn(e,t,n){let r=Kr(t);if(r!=null)return Ae(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}a(Rn,"truncatedShapeViolation");function _i(e,t,n){let r=[];for(let o of Ot(e,t,n)){let s=Rn(e,o,"members");s&&r.push(s),(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Ae(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}a(_i,"evaluateAggregatePrivateState");function Oi(e,t,n){let r=[];for(let o of Ot(e,t,n)){let s=Rn(e,o,"constructors and factories");if(s&&r.push(s),o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Ae(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}a(Oi,"evaluateAlwaysValidFactory");function Ti(e,t,n){let r=[],o=Ci();for(let s of Ot(e,t,n)){let i=wi(s),l=Rn(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Ae(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(Ti,"evaluateDomainEventOnMutation");function $i(e,t){let n=[];for(let r of t.files)De(r,e.appliesTo)&&_t(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Ae(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a($i,"evaluateOrchestrationOnly");function Li(e,t){let n=[];for(let r of t.files)De(r,e.appliesTo)&&_t(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Ae(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(Li,"evaluateThinAdapter");function Ni(e,t){let n=[];for(let r of t.files)De(r,e.appliesTo)&&_t(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Ae(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}a(Ni,"evaluateWritesViaAggregate");function Pi(e,t,n){let r=[];for(let o of Ot(e,t,n))if(o.dataOnly===!0){let s=Ae(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}a(Pi,"evaluateNoAnemicModel");function Vr(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(..._i(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Oi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Ti(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...$i(n,e));break;case"thin-adapter":t.push(...Li(n,e));break;case"writes-via-aggregate":t.push(...Ni(n,e));break;case"no-anemic-model":t.push(...Pi(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}a(Vr,"evaluateArkRuleSensors");function Gr(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>De(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=Ur(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>De(l,o.appliesTo)))continue;let i=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a(Gr,"collectEmptyAppliesToFindings");var Dr=64;function Fi(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===46;)t-=1;return t===e.length?e:e.slice(0,t)}a(Fi,"stripTrailingDots");function Di(e){let t=e.trim(),n=t.length>Dr?t.slice(0,Dr):t;return Fi(n)}a(Di,"normalizeIntentPrefix");function Mi(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(Mi,"layerNameLooksDomain");function Hi(e){return e.some(t=>{let n=Di(t);return n==="Domain"||n.startsWith("Domain.")})}a(Hi,"ownsDomainIntent");function Ki(e,t=[]){return Mi(e)||Hi(t)}a(Ki,"isDomainRoleLayerName");function Br(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Ki(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let f=typeof c.layer=="string"?c.layer:"";return f.length>0&&n.has(f)}))return[];if((e.arkRules.invariants??[]).filter(c=>n.has(c.provenance.layer)).length>0)return[];let s=t.find(c=>e.arkRules.byLayer?.[c])??t[0],i=e.arkRules.byLayer?.[s]?.sourceFile??`arkrules/${s}.json`,l=(e.arkRules.structure??[]).some(c=>c.mode==="enforced"&&n.has(c.provenance.layer)&&!jr(c.sensor));return[{ruleId:"INVARIANT_CATALOG_EMPTY",code:"invariant-catalog-empty",message:`ArkRules is on and ${s} has code, but invariants[] is empty \u2014 there are no phrases the code must preserve. Add 1\u20132 short phrases in ${i}.`,file:i,line:1,fromLayer:s,arkruleId:"invariant-catalog",arkruleSource:i,severity:l?"error":"warning",sensor:"invariant-coverage",failsStrict:l}]}a(Br,"collectEmptyInvariantCatalogFindings");function ji(e){return e==="PersistenceAdapters"}a(ji,"isPersistenceDriverLayer");function Ui(e,t){if(xt(e))return!0;if(!t)return!1;for(let n of t){if(ji(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(xt(o))return!0}return!1}a(Ui,"sourceImportsPersistenceDriver");var Vi=/\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*=)/,Gi=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Bi=/\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*=/,zi=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Wi(e,t,n){if(!t)return null;let r=Ui(t,n),o=r&&yn(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Bi.source,"g"))??[],i=t.match(new RegExp(zi.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,f=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,h=Vi.test(t)||Gi.test(t),y=s.length>=1||i.length>=2,p=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),R=r&&y||h&&y||r&&p&&(l>=4||s.length>=1)||h&&r;return!f&&!R&&!o?null:{...f?{orchestrationHeavy:!0}:{},...R?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(Wi,"deriveArkRuleFileHints");function zr(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=Wi(r,o,t?.[s]);i&&(n[s]=i)}return n}a(zr,"buildArkRuleFileHints");var qi="INVARIANT_TESTS_PATH_MISSING",Yi="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.",Xi="INVARIANT_COVERAGE_ROOTS_MISSING",Zi="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 Wr(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 o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}a(Wr,"formatCoverageDiscards");function Xr(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}a(Xr,"isUnderCoverageRoot");function kn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(kn,"escapeRegExp");function Me(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(Me,"normalizePath");function bn(e,t){let n=[],r=0,o=e.length;for(;r<o;){let s=e[r],i=e[r+1];if(s==="/"&&i==="/"){for(;r<o&&e[r]!==`
|
|
6
|
+
`;)n.push(" "),r+=1;continue}if(s==="/"&&i==="*"){for(n.push(" "," "),r+=2;r<o&&!(e[r]==="*"&&e[r+1]==="/");)n.push(e[r]===`
|
|
5
7
|
`?`
|
|
6
|
-
`:" "),r+=1;r<
|
|
7
|
-
`?" ":c),r+=1}continue}n.push(
|
|
8
|
+
`:" "),r+=1;r<o&&(n.push(" "," "),r+=2);continue}if(s==='"'||s==="'"||s==="`"){let l=s;for(n.push(t?" ":s),r+=1;r<o;){let c=e[r];if(c==="\\"){let f=e[r+1];t?n.push(" ",f===void 0?"":" "):(n.push("\\"),f!==void 0&&n.push(f)),r+=f===void 0?1:2;continue}if(c===l){n.push(t?" ":c),r+=1;break}n.push(t&&c!==`
|
|
9
|
+
`?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(bn,"maskNonCode");function Ji(e,t){if(!t)return;let n=kn(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(bn(e,!1))?.[2];return s===void 0?void 0:s}a(Ji,"matchTestTitle");function Zr(e,t){if(!t)return;let n=kn(t),r=bn(e,!0),o=[{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 s of o)if(new RegExp(s.source).test(r))return s.shape}a(Zr,"declarationShape");function Qi(e,t,n){let r=a(o=>hn(o).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let o of mn(e))if(!(o.name!==t||o.bodyStart==null)&&r(e.slice(o.bodyStart,o.bodyEnd??e.length)))return"method";for(let o of $r(e,t)){let s=e.slice(o.bodyStart,o.bodyEnd);if(o.kind==="class-expression"&&r(s)||o.kind==="object"&&Lr(s).includes(n))return"method";if(o.kind==="namespace"){let i=Zr(s,n);if(i==="function"||i==="const")return i}}}a(Qi,"classMemberShape");function ea(e,t){let n=e.lastIndexOf(`
|
|
8
10
|
`,t-1)+1,r=e.indexOf(`
|
|
9
|
-
`,t);return e.slice(n,r===-1?e.length:r)}a(
|
|
10
|
-
`;)i(s,"comment"),s+=1;continue}if(l==="/"&&c==="*"){for(i(s,"comment"),i(s+1,"comment"),s+=2;s<o&&!(e[s]==="*"&&e[s+1]==="/");)i(s,"comment"),s+=1;s<o&&(i(s,"comment"),i(s+1,"comment"),s+=2);continue}if(l==='"'||l==="'"||l==="`"){let f=l;for(i(s,"string"),s+=1;s<o;){let h=e[s];if(h==="\\"){i(s,"string"),e[s+1]!==void 0&&i(s+1,"string"),s+=e[s+1]===void 0?1:2;continue}if(h===f){i(s,"string"),s+=1;break}i(s,"string"),s+=1}continue}i(s,"code"),s+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(Xn,"mentionContext");function Qn(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1?t[0]??null:null,name:n}:void 0}a(Qn,"symbolNeedle");function Co(e){return Qn(e.coverage?.symbol)?.name??e.id}a(Co,"declaredLabel");function Jn(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Jn,"sortedContentFiles");function wo(e,t,n=!0){let r=t.testFiles??[],s=new Set(r.map(p=>Oe(p))),o=(t.coverageRoots??[]).filter(p=>typeof p=="string"&&p.length>0),i=e.coverage?.test!==!1&&n,l=Qn(e.coverage?.symbol??void 0),c,f;if(i){for(let p of r){let d=t.fileContents[p];if(!d)continue;let g=vo(d,e.id);if(g!==void 0){if(o.length===0||Zn(p,o)){c={file:p,title:g};break}f??={file:p,title:g}}}c??=f}let h;if(l)for(let p of Jn(t.fileContents)){if(s.has(Oe(p)))continue;let d=t.fileContents[p];if(!d||l.className&&!d.includes(l.className))continue;let g=So(d,l.name);if(g){h={file:p,shape:g};break}}let R;if(!c&&!h){if(i)for(let p of r){let d=t.fileContents[p];if(!d)continue;let g=Xn(d,e.id,!0);if(g){R={file:p,context:g};break}}if(!R&&l)for(let p of Jn(t.fileContents)){if(s.has(Oe(p)))continue;let d=t.fileContents[p];if(!d)continue;let g=Xn(d,l.name,!1);if(g){R={file:p,context:g};break}}}let u=c?{kind:"test-title",file:c.file,title:c.title}:h?{kind:"declaration",file:h.file,shape:h.shape}:R?{kind:"mention-only",file:R.file,context:R.context}:{kind:"none"};return u.kind==="mention-only"&&u.context==="comment"&&l&&xo(t.fileContents,s,l.name,u.file)&&(u={kind:"declaration-miss",symbol:l.name}),{best:u,...c?{testTitle:c}:{},...h?{declaration:h}:{}}}a(wo,"rankCoverage");function xo(e,t,n,r){let s=new RegExp(`(?:^|[^A-Za-z0-9_$])${Mt(n)}(?=$|[^A-Za-z0-9_$])`),o=Oe(r);for(let i of Object.keys(e)){if(t.has(Oe(i))||Oe(i)===o)continue;let l=e[i];if(l&&s.test(Ht(l,!0)))return!0}return!1}a(xo,"symbolInCodeElsewhere");function Oo(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Oo,"countsAsCoverage");function _o(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}a(_o,"mentionWhere");function $o(e,t){switch(t.kind){case"test-title":return`found \`${t.title}\` in a describe/it title in ${t.file}`;case"declaration":return`found \`${t.shape} ${Co(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${_o(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}a($o,"describeCoverage");function er(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,s=e.coverageBudgetExhausted===!0,o=e.coverageStats,i=Yn(o),l=Yn(o,!0),c=o?`coverage file budget exhausted: ${o.filesLoaded} files loaded at the ${o.maxFiles}-file cap, ${o.testFilesRetained} tests retained, ${o.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof o.filesRead=="number"?`; ${o.filesRead} were read`:""})`:"coverage file budget exhausted",f=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),h=f.length>0,R=f.join(", "),u=[],p=[];for(let d of t){let g=d.coverage?.test!==!1,k=d.coverage?.symbol,I=!r&&g,S=wo(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:f},I),x=S.best,$=[];I&&S.testTitle&&$.push("test-title"),S.declaration&&$.push("symbol");let q=Oo(x),b,T;I&&S.testTitle&&(b=S.testTitle.file,h&&(T=!Zn(b,f)));let Ne=S.declaration?.file,me=S.declaration?.shape,ie=(d.coverage?.test===!0||!!k||d.coverage===void 0)&&q||d.coverage?.test===!1&&!k?!0:q,se=r&&g&&!q;if(u.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:ie&&!se,evidence:$,partial:se,description:d.description,...b!==void 0?{testEvidenceFile:b}:{},...Ne!==void 0?{symbolEvidenceFile:Ne}:{},...me!==void 0?{shape:me}:{},...T!==void 0?{outsideDeclaredRoots:T}:{},coverageRootsDeclared:h}),T===!0&&b!==void 0&&p.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${b}, which is outside the declared coverage roots (${R}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:b,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!ie||se){let he=d.mode==="enforced"&&!se,Pe=r||n.length===0?"never-had-tests":"tests-disappeared";p.push({ruleId:"INVARIANT_UNCOVERED",message:(se?s?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:`Invariant ${d.id}: ${$o(d,x)} (${Pe==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(se&&s?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:he?"error":"warning",failsStrict:he,kind:Pe})}}return{coverage:u,violations:p,partial:u.some(d=>d.partial)}}a(er,"evaluateInvariantCoverage");function tr(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a(tr,"canPromoteInvariant");function Dt(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}a(Dt,"nonEmptyPathStrings");function To(e){return!e||typeof e!="object"?[]:[...Dt(e.testGlobs),...Dt(e.coverageRoots)]}a(To,"configuredInvariantTestsPaths");function Lo(e){return To(e).length>0}a(Lo,"hasConfiguredInvariantTestsPath");function Ut(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Ut,"catalogDemandsInvariantTestsPath");function nr(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Ut(e.invariants);return e.adopted!==!0||!t?[]:Lo(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Ro,message:Ao,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(nr,"collectMissingInvariantTestsPathFindings");function Fo(e){return!e||typeof e!="object"?[]:Dt(e.coverageRoots)}a(Fo,"configuredCoverageRoots");function No(e){return Fo(e).length>0}a(No,"hasConfiguredCoverageRoots");function Kt(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Kt,"catalogHasEnforcedInvariant");function rr(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Kt(e.invariants)?No(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:ko,message:bo,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(rr,"collectMissingCoverageRootsFindings");function Po(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}a(Po,"normalizeExtraMergeTeethClassification");function mt(e){let t=Po(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}a(mt,"extraMergeTeethAllowed");function sr(e){let t=e.length,n=0,r=new Set;for(let s of e){let o=typeof s.layer=="string"&&s.layer.length>0?s.layer:null;o&&(n+=1,r.add(o))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(sr,"classifyResolvedLayerCoverage");var Do=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var ul=new Set(Do);function or(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(or,"isArkRunKernelModuleSpecifier");var Mo=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],jt=new Set(Mo);function ir(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(jt.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(jt.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:jt.has(e.slice(0,r))}a(ir,"isArkRunTransportBypassSpecifier");var Ho=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Uo=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ko=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function jo(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),s=String(t?.toLayer??"");return Ho.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Uo.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${s} ${n}`))?"kernel-emit":Ko.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&s==="PersistenceAdapters"?"use-case":"unknown"}a(jo,"classifyLayerImportKind");function Vo(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=jo(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}a(Vo,"layerImportNextAction");function Go(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Go,"arkRunCallSiteName");function Bo(e){let t=Go(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(Bo,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Vo(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"INVARIANT_CATALOG_EMPTY":return typeof e.file=="string"&&e.file.length>0?`Add 1\u20132 short phrases to invariants[] in ${e.file}, then run ark-check --doctor. Starters show the shape.`:"Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json, then run ark-check --doctor. Starters show the shape.";case"INVARIANT_TESTS_PATH_MISSING":return"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.";case"INVARIANT_COVERAGE_ROOTS_MISSING":return"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return Bo(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(pe,"deterministicNextAction");var Wo=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Sl=new Set(Wo);var ar={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},zo="ARKRUN_INTERACTION_NAME_INCOMPLETE";function dr(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}a(dr,"isDomainRoleLayer");function qo(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(qo,"compareFindings");function ce(e,t,n,r,s,o,i){let l=e.mode==="enforced"&&i;return{ruleId:ar[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:ar[t],fromLayer:o?.fromLayer,target:o?.target})}}a(ce,"finding");function Yo(e,t){let n=[],r=[],s=[],o=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),s.push(...i.raises),o.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(s),sends:new Set(o)}}a(Yo,"bagForFile");function lr(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(lr,"emitKinds");function cr(e){return e==="subscribe"||e==="register-handler"}a(cr,"handleKinds");function Xo(e){return e==="resolve"||e==="resolve-singleton"}a(Xo,"dependKinds");function Jo(e,t,n){let r=[],s=e.kernelRoots??e.compositionRoots;if(s.length===0)return r.push(ce(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let o=new Map;for(let i of t){let l=o.get(i.matchedRoot)??[];l.push(i),o.set(i.matchedRoot,l)}for(let i of s){let l=[...o.get(i)??[]].sort((f,h)=>f.file.localeCompare(h.file));if(l.length===0){r.push(ce(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(f=>f.hasKernelFactory))continue;let c=l[0];r.push(ce(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(Jo,"evaluateMissingRoot");function Zo(e,t,n,r,s){let o=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!or(c))continue;let f=r(l.from);f&&dr(f,o.get(f)??[])&&i.push(ce(e,"arkrun-kernel-in-domain",l.from,l.line,`${f} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:f,target:c},s))}return i}a(Zo,"evaluateKernelInDomain");function Qo(e,t,n,r,s,o){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(h=>[h.name,h.intentPrefixes??[]])),c=new Set(r.filter(h=>h.hasKernelFactory).map(h=>h.file)),f=[];for(let h of n){if(c.has(h.file))continue;let R=h.typeName;if(e.ignoreDirectNewForErrors!==!1&&(R.endsWith("Error")||R==="Error")||R.endsWith("DTO")||R.endsWith("VO"))continue;let u=s(h.file);!u||!i.has(u)||dr(u,l.get(u)??[])||f.push(ce(e,"arkrun-direct-new",h.file,h.line,`${u} must not construct ${h.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:h.typeName},o))}return f}a(Qo,"evaluateDirectNew");function ei(e,t,n,r,s){let o=[],i=[];if(e.requireDeclarations!==!0)return{findings:o,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:o,completenessReasons:i};for(let c of t){if(!lr(c.kind)&&!cr(c.kind)&&!Xo(c.kind))continue;let f=r(c.file);if(!f||!l.has(f))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:zo,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let h=Yo(n,c.file);if(lr(c.kind)){if(h.raises.has(c.nameLiteral)||h.sends.has(c.nameLiteral))continue;o.push(ce(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:f,target:c.nameLiteral},s));continue}if(cr(c.kind)){if(h.reactsTo.has(c.nameLiteral))continue;o.push(ce(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:f,target:c.nameLiteral},s));continue}h.uses.has(c.nameLiteral)||o.push(ce(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:f,target:c.nameLiteral},s))}return{findings:o,completenessReasons:i}}a(ei,"evaluateUndeclared");function ti(e,t,n,r){let s=new Set(e.managedLayers);if(s.size===0)return[];let o=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!ir(l))continue;let c=n(i.from);!c||!s.has(c)||o.push(ce(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return o}a(ti,"evaluateTransportBypass");function ur(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=mt(e.classification),r=ei(t,e.kernelCalls,e.declarations,e.layerForFile,n),s=[...Jo(t,e.compositionRootHits,n),...Zo(t,e.layers,e.dependencies,e.layerForFile,n),...Qo(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...ti(t,e.dependencies,e.layerForFile,n)].sort(qo),o=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,f=`${l.code}\0${l.file??""}\0${l.message}`;return c<f?-1:c>f?1:0});return{findings:s,completenessReasons:o}}a(ur,"evaluateArkRunSensors");function fr(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(fr,"isArkOrderModuleSpecifier");var pr=new Map;function gr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(gr,"escapeAppliesToLiteral");function ni(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}a(ni,"normalizeAppliesToGlob");function ri(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(ri,"appliesToBracesBalanced");function si(e){let t=pr.get(e);if(t)return t;let n=ni(e),r=ri(n),s="",o=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(s+=gr(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(s+="(?:.*/)?",l+=2):(s+=".*",l+=1):s+="[^/]*":c==="?"?s+="[^/]":c==="{"&&r?(s+="(?:",o+=1):c==="}"&&r&&o>0?(s+=")",o-=1):c===","&&r&&o>0?s+="|":s+=gr(c)}let i=new RegExp(`^${s}$`);return pr.set(e,i),i}a(si,"globToRegExp");var mr={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function oi(e,t){return!t||t.length===0?!0:t.some(n=>si(n).test(e))}a(oi,"matchesArkOrderAppliesTo");function ii(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let s=r.trim().replace(/\.+$/,"");return s==="Domain"||s.startsWith("Domain.")})}a(ii,"isDomainRoleLayer");function ge(e,t,n,r,s,o,i){let l=e.mode==="enforced"&&i;return{ruleId:mr[t],sensor:t,message:s,file:n,line:r,...o?.fromLayer?{fromLayer:o.fromLayer}:{},...o?.target?{target:o.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:mr[t],fromLayer:o?.fromLayer,target:o?.target})}}a(ge,"finding");function hr(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=mt(e.classification),r=[],s=t.planeRoots;if(t.mode==="enforced"&&s.length===0)r.push(ge(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let f of e.planeRootHits){let h=c.get(f.matchedRoot)??[];h.push(f),c.set(f.matchedRoot,h)}for(let f of s){let h=c.get(f)??[];if(h.length===0){r.push(ge(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(f)} matched no governed files and has no createOrderPlane factory.`,{target:f},n));continue}h.some(R=>R.hasPlaneFactory)||r.push(ge(t,"arkorder-missing-plane",h[0].file,1,`ArkOrder plane root ${JSON.stringify(f)} has no createOrderPlane factory.`,{target:f},n))}}let o=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let f=c.specifier;if(!f||!fr(f))continue;let h=e.layerForFile(c.from);h&&ii(h,o.get(h)??[])&&r.push(ge(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:h,target:f},n))}for(let c of e.genericUpdates)r.push(ge(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(ge(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(ge(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let f=e.layerForFile(c.file);!f||!l.has(f)||oi(c.file,t.appliesTo)&&r.push(ge(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:f,target:c.key},n))}return r.sort((c,f)=>c.file.localeCompare(f.file)||c.ruleId.localeCompare(f.ruleId)||c.line-f.line),{findings:r,completenessReasons:[]}}a(hr,"evaluateArkOrderSensors");var Re={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},yr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Re,default:[]},kernelRoots:{...Re},managedLayers:{...Re,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Rr={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Re,default:[]},managedLayers:{...Re,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Re,default:[]},appliesTo:{...Re,default:[]}}};function qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(qe,"isObject");function Ar(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)qe(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Ar,"declaredLayerNames");function kr(e){if(!qe(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}a(kr,"defaultedArkRun");function br(e){if(!qe(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}a(br,"defaultedArkOrder");function vr(e,t){let n=e.arkRun;if(n===void 0||!qe(n))return;let r=Ar(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(vr,"validateArkRunExtra");function Sr(e,t){let n=e.arkOrder;if(n===void 0||!qe(n))return;let r=Ar(e),s=n.managedLayers;if(Array.isArray(s)&&s.forEach((o,i)=>{typeof o=="string"&&o.length>0&&!r.has(o)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(o)} is not declared in layers[]`})}),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Sr,"validateArkOrderExtra");function ht(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(ht,"normalizeStewardId");function Ir(e){let t=ht(e);return!t||Vt(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Ir,"isGitHubHandle");function ai(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return!t.includes("@")||t.includes(" ")||Vt(t)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}a(ai,"isGitHubEmail");function li(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Ir(t[1])?ht(t[1]):null}a(li,"githubHandleFromEmail");function Er(e){let t=li(e);if(t)return t;let n=ht(e);return!n||Vt(n)?null:Ir(n)||ai(n)?n:null}a(Er,"canonicalStewardId");var ci=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Vt(e){let t=ht(e);return!t||ci.test(t)}a(Vt,"isAutomationAuthor");var te="1.3",di=["public","auth","admin","internal"];function ui(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(ui,"isFutureHouseLayer");function fi(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a(fi,"layerOwnersList");function Tr(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!ui(t)&&!fi(t)).map(t=>t.name)}a(Tr,"layersMissingRequiredOwners");function Lr(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(Lr,"missingLayerOwnersNextAction");var Gt="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Cr=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],pi=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function gi(){let e=[];for(let t of Cr)for(let n of Cr)t===n||pi.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(gi,"createDefaultRules");var Fr=gi(),Bt=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],W={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},wr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Gt,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:Gt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:te,default:te},name:{type:"string",minLength:1},include:{...W,minItems:1,default:["src"]},exclude:{...W,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Fr,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...W,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...W,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...W,minItems:1},exclude:W,intentPrefixes:W,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...di]},owners:{...W,minItems:1},forbiddenGlobals:W,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...W,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...W,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny","deny-cross-parent"],description:"deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. arkgate 4.8.22 and older reject deny-cross-parent."},childSlices:{type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Absent keeps today's universe wall. sliceFolders names children. commonFolders and flat files are universe common. siblings is "deny" (default), "advisory", or { default, enforce }. parentMayImportChild defaults to false. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...W,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...W,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce } so listed subtrees are errors while the default stays advisory. A string-enum build rejects the object at config load (must be one of deny, advisory).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...W}}}]},parentMayImportChild:{type:"boolean"},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A bare name, a universe id alone, an unknown universe, and a wildcard in to are rejected. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each alias as an owed move. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...W,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...W,minItems:1}}},arkRun:yr,arkOrder:Rr}},de=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
11
|
+
`,t);return e.slice(n,r===-1?e.length:r)}a(ea,"lineAt");function ta(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(ta,"isImportLine");function qr(e,t,n){if(!t||!e.includes(t))return;let r=new Set,o=0,s=e.length,i=a((l,c)=>{if(e.startsWith(t,l)){if(c==="comment"){r.add("comment");return}if(c==="string"){r.add("string");return}if(ta(ea(e,l))){r.add("import");return}n&&r.add("test-body")}},"note");for(;o<s;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(;o<s&&e[o]!==`
|
|
12
|
+
`;)i(o,"comment"),o+=1;continue}if(l==="/"&&c==="*"){for(i(o,"comment"),i(o+1,"comment"),o+=2;o<s&&!(e[o]==="*"&&e[o+1]==="/");)i(o,"comment"),o+=1;o<s&&(i(o,"comment"),i(o+1,"comment"),o+=2);continue}if(l==='"'||l==="'"||l==="`"){let f=l;for(i(o,"string"),o+=1;o<s;){let h=e[o];if(h==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(h===f){i(o,"string"),o+=1;break}i(o,"string"),o+=1}continue}i(o,"code"),o+=1}if(r.has("comment"))return"comment";if(r.has("string"))return"string";if(r.has("test-body"))return"test-body";if(r.has("import"))return"import"}a(qr,"mentionContext");function Jr(e){if(!e)return;let t=e.split("."),n=t[t.length-1]??"";return n?{className:t.length>1&&t[t.length-2]||null,name:n}:void 0}a(Jr,"symbolNeedle");function na(e){return Jr(e.coverage?.symbol)?.name??e.id}a(na,"declaredLabel");function Yr(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(Yr,"sortedContentFiles");function ra(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(R=>Me(R))),s=(t.coverageRoots??[]).filter(R=>typeof R=="string"&&R.length>0),i=e.coverage?.test!==!1&&n,l=Jr(e.coverage?.symbol??void 0),c,f;if(i){for(let R of r){let d=t.fileContents[R];if(!d)continue;let g=Ji(d,e.id);if(g!==void 0){if(s.length===0||Xr(R,s)){c={file:R,title:g};break}f??={file:R,title:g}}}c??=f}let h;if(l)for(let R of Yr(t.fileContents)){if(o.has(Me(R)))continue;let d=t.fileContents[R];if(!d)continue;let g=l.className?Qi(d,l.className,l.name):Zr(d,l.name);if(g){h={file:R,shape:g};break}}let y;if(!c&&!h){if(i)for(let R of r){let d=t.fileContents[R];if(!d)continue;let g=qr(d,e.id,!0);if(g){y={file:R,context:g};break}}if(!y&&l)for(let R of Yr(t.fileContents)){if(o.has(Me(R)))continue;let d=t.fileContents[R];if(!d)continue;let g=qr(d,l.name,!1);if(g){y={file:R,context:g};break}}}let p=c?{kind:"test-title",file:c.file,title:c.title}:h?{kind:"declaration",file:h.file,shape:h.shape}:y?{kind:"mention-only",file:y.file,context:y.context}:{kind:"none"};return p.kind==="mention-only"&&p.context==="comment"&&l&&sa(t.fileContents,o,l.name,p.file)&&(p={kind:"declaration-miss",symbol:l.name}),{best:p,...c?{testTitle:c}:{},...h?{declaration:h}:{}}}a(ra,"rankCoverage");function sa(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${kn(n)}(?=$|[^A-Za-z0-9_$])`),s=Me(r);for(let i of Object.keys(e)){if(t.has(Me(i))||Me(i)===s)continue;let l=e[i];if(l&&o.test(bn(l,!0)))return!0}return!1}a(sa,"symbolInCodeElsewhere");function oa(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(oa,"countsAsCoverage");function ia(e){switch(e){case"test-body":return"a test body";case"comment":return"a comment";case"string":return"a string";case"import":return"an import"}}a(ia,"mentionWhere");function aa(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} ${na(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${ia(t.context)} in ${t.file}; put it in a describe/it title`;case"declaration-miss":return`no declaration matched \`${t.symbol}\``;case"none":return"no scanned test names it in a describe/it title and no declared symbol was found"}}a(aa,"describeCoverage");function Qr(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,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,i=Wr(s),l=Wr(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",f=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),h=f.length>0,y=f.join(", "),p=[],R=[];for(let d of t){let g=d.coverage?.test!==!1,A=d.coverage?.symbol,I=!r&&g,S=ra(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:f},I),w=S.best,T=[];I&&S.testTitle&&T.push("test-title"),S.declaration&&T.push("symbol");let q=oa(w),Q,Y;I&&S.testTitle&&(Q=S.testTitle.file,h&&(Y=!Xr(Q,f)));let b=S.declaration?.file,V=S.declaration?.shape,Ge=d.coverage?.test===!0||!!A||d.coverage===void 0,de=d.coverage?.test===!1&&!A,Oe=Ge&&q||de&&d.mode!=="enforced"?!0:q,se=r&&g&&!q;if(p.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:Oe&&!se,evidence:T,partial:se,description:d.description,...Q!==void 0?{testEvidenceFile:Q}:{},...b!==void 0?{symbolEvidenceFile:b}:{},...V!==void 0?{shape:V}:{},...Y!==void 0?{outsideDeclaredRoots:Y}:{},coverageRootsDeclared:h}),Y===!0&&Q!==void 0&&R.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${Q}, which is outside the declared coverage roots (${y}). 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:Q,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!Oe||se){let Be=d.mode==="enforced"&&!se,ue=r||n.length===0?"never-had-tests":"tests-disappeared";R.push({ruleId:"INVARIANT_UNCOVERED",message:(se?o?`Invariant ${d.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${d.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:de?`Invariant ${d.id} is enforced but declares no evidence (coverage.test is false and no coverage.symbol); set coverage.symbol, drop test:false, or keep mode "advisory".`:`Invariant ${d.id}: ${aa(d,w)} (${ue==="tests-disappeared"?"tests-disappeared \u2014 a suite exists":"never-had-tests \u2014 the scan found no tests at all"}). ArkGate matches declared text; it never executes tests.`)+(se&&o?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:Be?"error":"warning",failsStrict:Be,kind:ue})}}return{coverage:p,violations:R,partial:p.some(d=>d.partial)}}a(Qr,"evaluateInvariantCoverage");function es(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?Array.isArray(e.evidence)&&e.evidence.length===0?{ok:!1,reason:`Invariant ${e.invariantId} declares no evidence (coverage.test:false and no symbol); add coverage.symbol or a test title before promoting to enforced.`}:e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:e.coverageRootsDeclared===!1?{ok:!1,reason:`Declare coverage.coverageRoots in ark.config.json before promoting ${e.invariantId} to enforced. Without that, ArkGate cannot tell whether a covering test is one the runner executes.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}a(es,"canPromoteInvariant");function An(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim();r.length>0&&t.push(r)}return t}a(An,"nonEmptyPathStrings");function la(e){return!e||typeof e!="object"?[]:[...An(e.testGlobs),...An(e.coverageRoots)]}a(la,"configuredInvariantTestsPaths");function ca(e){return la(e).length>0}a(ca,"hasConfiguredInvariantTestsPath");function vn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(vn,"catalogDemandsInvariantTestsPath");function ts(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&vn(e.invariants);return e.adopted!==!0||!t?[]:ca(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:qi,message:Yi,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(ts,"collectMissingInvariantTestsPathFindings");function da(e){return!e||typeof e!="object"?[]:An(e.coverageRoots)}a(da,"configuredCoverageRoots");function ua(e){return da(e).length>0}a(ua,"hasConfiguredCoverageRoots");function Sn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Sn,"catalogHasEnforcedInvariant");function ns(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Sn(e.invariants)?ua(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:Xi,message:Zi,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(ns,"collectMissingCoverageRootsFindings");function fa(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}a(fa,"normalizeExtraMergeTeethClassification");function Tt(e){let t=fa(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}a(Tt,"extraMergeTeethAllowed");function rs(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}a(rs,"classifyResolvedLayerCoverage");var pa=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"];var ga=["forRoot","forRootAsync"],ha=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"];var md=new Set(ga),yd=new Set(ha);var Rd=new Set(pa);function ss(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}a(ss,"isArkRunKernelModuleSpecifier");var ma=["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"],In=new Set(ma);function os(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(In.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(In.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:In.has(e.slice(0,r))}a(os,"isArkRunTransportBypassSpecifier");function k(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(k,"entry");var is=Object.freeze([k("LAYER_IMPORT_VIOLATION","layer","This import is not allowed","This file imported a folder it may not reach. The write doesn\u2019t land. The same check fails the pull request.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),k("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),k("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),k("SHARED_IMPORTS_SLICE","layer","A shared root imports a slice",'A declared shared root imports a slice directly. That hop is allowed while sharedImportsSlice is unset or "deny-cross-parent", so this is advisory: the universe wall is direct-only.','Move the code the shared root needs into the shared root, or invert the dependency. Set sharedImportsSlice: "deny" to make these edges errors. With "deny-cross-parent", a slice that reaches another universe through a shared root is reported as LAYER_IMPORT_VIOLATION with reasonId CROSS_PARENT_VIA_SHARED. This warning does not fail the check.',{oftenAdvisory:!0}),k("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),k("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),k("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),k("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),k("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),k("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),k("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),k("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),k("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),k("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),k("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),k("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),k("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),k("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),k("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),k("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),k("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),k("ARKRULE_FILE_UNREFERENCED","arkrules","ArkRules file not referenced","A JSON file under arkrules/ is not referenced by the arkRules map in ark.config.json (or no map exists), so none of its rules are enforced or reported. Drift looks like governance until someone notices.",'Reference the file from arkRules ("<Layer>": "arkrules/<file>.json"), or delete it. Advisory only: it never fails the check.',{oftenAdvisory:!0}),k("INVARIANT_CATALOG_EMPTY","arkrules","Domain invariant catalog is empty","ArkRules is on and a Domain-role layer has code, but invariants[] has no phrases the code must preserve. Empty looks like \u201Cdone\u201D until someone fills the catalog.","Add 1\u20132 short phrases to invariants[] in arkrules/<Domain>.json (or the mapped file). Starters show the shape. Advisory unless a domain structure rule is already enforced \u2014 then --strict-merge can refuse. Do not freeze this finding.",{oftenAdvisory:!0}),k("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),k("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),k("INVARIANT_TESTS_PATH_MISSING","arkrules","Domain-invariant tests path missing under adopted","The project is adopted (required CI or explicit advisory) and has domain invariants that want test evidence, but ark.config.json does not name where those tests live. Green coverage without a real tests path is an empty checkbox.","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. Not freezable."),k("INVARIANT_COVERAGE_ROOTS_MISSING","arkrules","Coverage roots missing while an invariant is enforced","A catalogued domain invariant is enforced, but ark.config.json does not name coverage.coverageRoots \u2014 the folders where the project says its test runner actually goes. Without that declaration, INVARIANT_COVERAGE_OUTSIDE_ROOTS cannot fire and coverage can certify a test no runner runs.","Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. testGlobs alone is not enough. Fail-closed until that path is present. Not freezable."),k("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel, their *FromConfig variants, or ArkModule.forRoot / forRootAsync imported from arkgate/nestjs) was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","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."),k("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, arkgate/nestjs, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),k("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),k("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),k("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call on a receiver traced to the kernel names an intent (string literal or same-file define/defineIntent binding) that is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),k("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call on a receiver traced to the kernel names a component that is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),k("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),k("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","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."),k("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),k("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),k("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),k("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),k("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),k("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),k("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),k("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),k("ARKORDER_UNVALVED_RELEASE","arkorder","Second freeze without the valve","release() already froze the big choice. A later release() with a different value does not land. First freeze is release(); later change is proposeRelease then apply.","Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe."),k("ARKORDER_STALE_PROPOSAL","arkorder","Proposal is not bound to the current Release","apply() got a ProposeResult computed against another Release (another apply landed first), one missing its base binding, or one whose reviewed blast radius is not the transition that would commit. The binding is data, not a capability: a proposal that states the current base and the exact transition applies whoever built it.","Run proposeRelease again against the current Release, review the new blast radius, then apply that proposal. Never mechanical-safe."),k("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),k("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),k("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),k("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),k("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),k("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),k("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),k("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),k("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),k("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),k("WRITE_GATE_UNAVAILABLE","preflight","Write gate could not run","The write gate could not load its own inputs (ark.config.json missing, unreadable, or invalid; a referenced ArkRules file missing or invalid; or the built library missing), so it cannot judge this governed source write (existing files included), or a write would leave ark.config.json or a referenced ArkRules file unloadable. No checker, no write: the hook blocks instead of letting the write through unchecked.","Fix the reported input (repair ark.config.json or the ArkRules file, or run `npm run build` / reinstall arkgate from npm), then retry the same write. Do not remove the hook to get past it."),k("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),k("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),k("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","This check only saw one file, so it cannot fully prove how the import resolves. The result is provisional \u2014 `ark-check` on the project is the authority.","For a complete verdict, run `npx arkgate-check --root . --config ark.config.json` (or ark_prepare_change over MCP with the full candidate batch). Read lexicalValid for the one-file result."),k("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),k("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),k("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),k("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),k("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),k("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),k("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),k("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),k("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),k("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),k("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),k("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),k("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),k("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),k("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),k("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),k("CONFIG_LAYER_MISSING_OWNER","config","Layer missing owner","requireLayerOwners is on and this layer has no owners. Writes to that house fail closed, like a folder with no name on the door.","Add a GitHub handle or email to that layer\u2019s owners in ark.config.json (/ark-adopt), then re-run. Reserved/allowEmpty houses may stay unnamed. Turn the flag off only if you no longer want owners required."),k("CONFIG_SLICE_IDENTITY_COLLISION","config","Starred slice prefixes share one id","sliceIdentity is stars and two different sliceFolders prefixes bind as the same slice id. Parallel trees of one feature do that on purpose; unrelated trees that share the last folder name merge by accident.","Keep stars when those prefixes are one feature. Otherwise use path, or rename the last literal so the prefixes do not bind as the same id. Doctor names both paths.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICES_VERSION","config","Config needs a newer arkgate than a pinned copy",'ark.config.json uses a slice key (childSlices, sharedImportsSlice "deny-cross-parent" or its object form, sliceIdentity, sharedImportsSlice, childSlices.message, siblings.ratchet) that an arkgate pinned in this repo rejects at config load. Emitted only with evidence of that pin: an exact package.json dependency, the installed node_modules/arkgate, package-lock.json, a scripts/*hook* or host hook command, or a CI workflow. Silent otherwise.',"Bump the named file to the version the finding gives (or newer), then run Ark again. This warning does not fail the check.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICE_EXTENDS","config","Child slice id does not extend its universe","A path resolved a child id that is not the universe id plus a further segment. The child wall does not treat that id as a child, so the edge is universe common until the folders line up.","Point childSlices.sliceFolders at children under the same universe id the outer sliceFolders already names. Doctor names the path.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICE_CROSS_UNIVERSE","config","Child slice allowance cannot cross the universe wall","childSlices.allowedCrossSlice names a pattern that can match two universes. That list clears only a sibling crossing inside one universe. The universe wall still denies the edge.","Narrow the pattern so both sides share one universe prefix (features/projects/* to features/projects/d2d-item), or remove the entry. This warning does not fail the check.",{oftenAdvisory:!0}),k("CONFIG_CHILD_SLICES_INERT","config","childSlices on a rule that cannot run it","A rule sets childSlices without peerIsolation: true and allowed: false. The child wall runs only inside a universe wall, so on this rule childSlices enforces nothing. Config load still accepts it (arkgate 4.8.23 did too).",'Add "peerIsolation": true and "allowed": false to the same rule so the child wall runs, or remove childSlices. This warning does not fail the check.',{oftenAdvisory:!0}),k("CONFIG_SLICE_LEGACY_STARS_ID","config","Slice id written in the 4.8.23 stars form",'Under sliceIdentity "stars", a sliceAliases target or an allowedCrossSlice entry names the 4.8.23 stars id, which dropped a star binding before the last literal (modules/*/api/* bound api/v1). The id now keeps that binding (orders/api/v1). For one release the entry keeps its 4.8.23 meaning, so verdicts do not change.',"Rewrite the entry with the new id the warning names (for example orders/api/v1/x instead of api/v1/x). A sliceAliases target that maps to more than one universe shape is rejected at config load. This warning does not fail the check.",{oftenAdvisory:!0}),k("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),k("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),k("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),bd=new Map(is.map(e=>[e.ruleId,e])),vd=Object.freeze(is.map(e=>e.ruleId));var ya=Object.freeze([Object.freeze({reasonId:"CROSS_PARENT_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe slice",why:"This import crosses two universe slices. The child wall cannot allow another universe.",fix:"Keep the import inside one universe, or move the shared code into a folder both universes may use."}),Object.freeze({reasonId:"CROSS_SIBLING_SLICE",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-sibling slice",why:"This import crosses two feature slices inside one universe.",fix:"Import universe-common code, or move the shared piece into the feature that owns it.",advisoryNote:"This crossing is a warning (siblings advisory). With a baseline in use, a new one fails only when the baseline already records an advisory crossing of this rule and the count grows, or when siblings.ratchet is true; ratchet false measures only."}),Object.freeze({reasonId:"CROSS_PARENT_VIA_SHARED",ruleId:"LAYER_IMPORT_VIOLATION",title:"Cross-universe through a shared root",why:"A slice reaches another universe only through a shared root. ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.",fix:"Stop the shared root from importing the other universe, or move that import into the universe that owns it. A shared hop that stays inside one universe is allowed. If the shared hop is a composition root (bootstrap, DI registrations), list it in sharedImportsSlice.stopAt; a path through a stop is not a crossing."})]),Ra=new Map(ya.map(e=>[e.reasonId,e]));function as(e){if(!(typeof e!="string"||e.length===0))return Ra.get(e)}a(as,"sliceReasonHint");var Aa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,ka=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,ba=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function va(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Aa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(ka.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":ba.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(va,"classifyLayerImportKind");function Sa(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}a(Sa,"sliceHintAction");function Ia(e){let t=as(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${Sa(t,e)} Then preflight again.`;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 n=va(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 n==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":n==="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.":n==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}a(Ia,"layerImportNextAction");function Ea(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Ea,"arkRunCallSiteName");function Ca(e){let t=Ea(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(Ca,"arkRunNextAction");function ke(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ia(e);case"CONFIG_CHILD_SLICES_VERSION":return typeof e.nextAction=="string"&&e.nextAction.length>0?e.nextAction:"Bump the pinned arkgate named in the finding to the version it gives, then run Ark again.";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 Ca(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change the choice with proposeRelease then apply. release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}a(ke,"deterministicNextAction");var wa=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Pd=new Set(wa);var ls={"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"},xa="ARKRUN_INTERACTION_NAME_INCOMPLETE";function us(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 o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(us,"isDomainRoleLayer");function _a(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(_a,"compareFindings");function he(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:ls[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:ke({ruleId:ls[t],fromLayer:s?.fromLayer,target:s?.target})}}a(he,"finding");function Oa(e,t){let n=[],r=[],o=[],s=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),o.push(...i.raises),s.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}a(Oa,"bagForFile");function cs(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(cs,"emitKinds");function ds(e){return e==="subscribe"||e==="register-handler"}a(ds,"handleKinds");function Ta(e){return e==="resolve"||e==="resolve-singleton"}a(Ta,"dependKinds");function $a(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(he(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((f,h)=>f.file.localeCompare(h.file));if(l.length===0){r.push(he(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(f=>f.hasKernelFactory))continue;let c=l[0];r.push(he(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no kernel factory (createArkKernel / createStrictArkKernel / createLenientArkKernel / *FromConfig, or ArkModule.forRoot / forRootAsync from arkgate/nestjs).`,{target:i},n))}return r}a($a,"evaluateMissingRoot");function La(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!ss(c))continue;let f=r(l.from);f&&us(f,s.get(f)??[])&&i.push(he(e,"arkrun-kernel-in-domain",l.from,l.line,`${f} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:f,target:c},o))}return i}a(La,"evaluateKernelInDomain");function Na(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(h=>[h.name,h.intentPrefixes??[]])),c=new Set(r.filter(h=>h.hasKernelFactory).map(h=>h.file)),f=[];for(let h of n){if(c.has(h.file))continue;let y=h.typeName;if(e.ignoreDirectNewForErrors!==!1&&(y.endsWith("Error")||y==="Error")||y.endsWith("DTO")||y.endsWith("VO"))continue;let p=o(h.file);!p||!i.has(p)||us(p,l.get(p)??[])||f.push(he(e,"arkrun-direct-new",h.file,h.line,`${p} must not construct ${h.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:h.typeName},s))}return f}a(Na,"evaluateDirectNew");function Pa(e,t,n,r,o){let s=[],i=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:i};for(let c of t){if(!cs(c.kind)&&!ds(c.kind)&&!Ta(c.kind))continue;let f=r(c.file);if(!f||!l.has(f))continue;if(!c.nameLiteral){e.mode==="enforced"&&c.kind!=="publisher"&&i.push({code:xa,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name or same-file define/defineIntent binding; enforced extra cannot prove the declaration.`});continue}let h=Oa(n,c.file);if(cs(c.kind)){if(h.raises.has(c.nameLiteral)||h.sends.has(c.nameLiteral))continue;s.push(he(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:f,target:c.nameLiteral},o));continue}if(ds(c.kind)){if(h.reactsTo.has(c.nameLiteral))continue;s.push(he(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:f,target:c.nameLiteral},o));continue}h.uses.has(c.nameLiteral)||s.push(he(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:f,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(Pa,"evaluateUndeclared");function Fa(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!os(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(he(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}a(Fa,"evaluateTransportBypass");function fs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Tt(e.classification),r=Pa(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...$a(t,e.compositionRootHits,n),...La(t,e.layers,e.dependencies,e.layerForFile,n),...Na(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Fa(t,e.dependencies,e.layerForFile,n)].sort(_a),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,f=`${l.code}\0${l.file??""}\0${l.message}`;return c<f?-1:c>f?1:0});return{findings:o,completenessReasons:s}}a(fs,"evaluateArkRunSensors");var ps=new Map;function gs(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(gs,"escapeAppliesToLiteral");function Da(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}a(Da,"normalizeAppliesToGlob");function Ma(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}a(Ma,"appliesToBracesBalanced");function hs(e){let t=ps.get(e);if(t)return t;let n=Da(e),r=Ma(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=gs(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=gs(c)}let i=new RegExp(`^${o}$`);return ps.set(e,i),i}a(hs,"arkOrderGlobToRegExp");function ms(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(ms,"isArkOrderModuleSpecifier");var ys={"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 Ha(e,t){return!t||t.length===0?!0:t.some(n=>hs(n).test(e))}a(Ha,"matchesArkOrderAppliesTo");function Ka(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}a(Ka,"isDomainRoleLayer");function ce(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:ys[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:ke({ruleId:ys[t],fromLayer:s?.fromLayer,target:s?.target})}}a(ce,"finding");function Rs(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Tt(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(ce(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let f of e.planeRootHits){let h=c.get(f.matchedRoot)??[];h.push(f),c.set(f.matchedRoot,h)}for(let f of o){let h=c.get(f)??[];if(h.length===0){r.push(ce(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(f)} matched no governed files and has no createOrderPlane factory.`,{target:f},n));continue}h.some(y=>y.hasPlaneFactory)||r.push(ce(t,"arkorder-missing-plane",h[0].file,1,`ArkOrder plane root ${JSON.stringify(f)} has no createOrderPlane factory.`,{target:f},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let f=c.specifier;if(!f||!ms(f))continue;let h=e.layerForFile(c.from);h&&Ka(h,s.get(h)??[])&&r.push(ce(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:h,target:f},n))}for(let c of e.genericUpdates)r.push(ce(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let i=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(ce(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(ce(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));for(let c of e.xiTtlKeys??[])r.push(ce(t,"arkorder-xi-ttl",c.file,c.line,`\u03BE key ${JSON.stringify(c.key)} is a freshness field; freshness belongs on \u03C3 (freshUntil), never on \u03BE.`,{target:c.key},n));for(let c of e.budgetLeaks??[])r.push(ce(t,"arkorder-information-budget",c.file,c.line,`Projection allowedKinds lists ${JSON.stringify(c.kind)}, which informationBudget.cannotObserve denies.`,{target:c.kind},n));let l=new Set(t.managedLayers);for(let c of i.length===0?[]:e.xiFieldWrites??[]){let f=e.layerForFile(c.file);!f||!l.has(f)||Ha(c.file,t.appliesTo)&&r.push(ce(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:f,target:c.key},n))}return r.sort((c,f)=>c.file.localeCompare(f.file)||c.ruleId.localeCompare(f.ruleId)||c.line-f.line),{findings:r,completenessReasons:[]}}a(Rs,"evaluateArkOrderSensors");var Ee={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},As={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Ee,default:[]},kernelRoots:{...Ee},managedLayers:{...Ee,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},ks={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Ee,default:[]},managedLayers:{...Ee,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Ee,default:[]},appliesTo:{...Ee,default:[]}}};function tt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(tt,"isObject");function bs(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)tt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(bs,"declaredLayerNames");function vs(e){if(!tt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}a(vs,"defaultedArkRun");function Ss(e){if(!tt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}a(Ss,"defaultedArkOrder");function Is(e,t){let n=e.arkRun;if(n===void 0||!tt(n))return;let r=bs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.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(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Is,"validateArkRunExtra");function Es(e,t){let n=e.arkOrder;if(n===void 0||!tt(n))return;let r=bs(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Es,"validateArkOrderExtra");var Lt={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ts={description:'deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. The object form { mode: "deny-cross-parent", stopAt } names composition roots (bootstrap, DI registrations) the whole-graph walk never starts at or passes through; a stop file must still sit under sharedRoots, and stopAt does not silence the direct SHARED_IMPORTS_SLICE warning. arkgate 4.8.22 and older reject deny-cross-parent. arkgate 4.8.23 and older reject the object form (must be one of deny, deny-cross-parent).',oneOf:[{type:"string",enum:["deny","deny-cross-parent"]},{type:"object",additionalProperties:!1,required:["mode","stopAt"],properties:{mode:{type:"string",enum:["deny-cross-parent"]},stopAt:{...Lt,minItems:1}}}]},$s={type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Runs only on a rule with peerIsolation: true and allowed: false; elsewhere it is inert and ark-check warns CONFIG_CHILD_SLICES_INERT (config load still accepts it, as 4.8.23 did). Absent keeps today's universe wall. sliceFolders names children. Flat files are universe common, and so is a commonFolders directory directly under the universe (a folder of that name inside a child belongs to that child). siblings is "deny" (default), "advisory", or { default, enforce, ratchet }. parentMayImportChild defaults to false. message is the text for inner-wall findings. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...Lt,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...Lt,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce, ratchet } so listed subtrees are errors while the default stays advisory. ratchet absent: a new advisory crossing fails only when the baseline in use already records an advisory crossing of this rule. ratchet true: any unrecorded advisory crossing fails when a baseline is in use. ratchet false: measure only, never fails. A string-enum build rejects the object at config load (must be one of deny, advisory). arkgate 4.8.23 and older reject ratchet (unknown field).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...Lt},ratchet:{type:"boolean"}}}]},parentMayImportChild:{type:"boolean"},message:{type:"string",minLength:1,description:"Text for inner-wall findings (CROSS_SIBLING_SLICE and universe common importing a child). The rule message stays the universe-wall text (CROSS_PARENT_SLICE and fail-closed denies). Absent: ArkGate default text, never the rule message. arkgate 4.8.23 and older reject this field (unknown field)."},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A path without a wildcard also covers everything under it, as sharedRoots does. A bare name, a universe id alone, a target outside every universe shape, and a wildcard in to are rejected. Under stars identity a target written against the 4.8.23 stars id (star bindings before the last literal dropped, e.g. api/v1/x for modules/*/api/*) still loads when it maps to one universe shape, and ark-check warns CONFIG_SLICE_LEGACY_STARS_ID with the new id; it is rejected only when it maps to more than one shape. Config load checks only the shape; doctor reports a target universe no file belongs to. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each alias as an owed move. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}};function ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ne,"isObject");function Nt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Nt,"propertyPath");function be(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(be,"trimTrailingSlashes");function Ls(e,t){Ba(e,t),Wa(e,t),Za(e,t),ul(e,t)}a(Ls,"validateSliceContract");var Cs='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',ws="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function ja(e){return e==="*"||e==="**"}a(ja,"isWildcardSegment");function Ns(e){let t=e.toLowerCase().split("/").filter(o=>o.length>0&&o!==".");(t[0]==="src"||t[0]==="app")&&(t=t.slice(1));let n=t.length;for(;n>0&&ja(t[n-1]??"");)n-=1;let r=t.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(Ns,"coveredFolder");function Ua(e,t){return e.length<=t.length&&e.every((n,r)=>t[r]===n)}a(Ua,"isPrefixOf");function Va(e,t){let n=e.layers;if(!Array.isArray(n))return[];let r=new Set([t.from,t.to].filter(s=>typeof s=="string")),o=[];for(let s of n){if(!ne(s)||typeof s.name!="string"||!r.has(s.name))continue;let i=Array.isArray(s.patterns)?s.patterns:[];for(let l of i){if(typeof l!="string")continue;let c=l.replace(/\\/g,"/").split("/"),f=c.findIndex(p=>p.includes("*")),h=f===-1?c:c.slice(0,f),y=Ns(h.join("/"));y&&o.push(y)}}return o}a(Va,"ruleLayerFolders");function Ga(e,t){let n=be(e.trim().replace(/\\/g,"/"));if(n.length===0)return"must be a non-empty path or glob";let r=n.replace(/^[./]+/,"");if(r===""||r==="*"||r==="**")return ws;for(let s of n.split("/"))if(s.length===0||s==="."||s==="..")return"must be a path or glob without empty, . or .. segments";let o=Ns(n);return o===null?null:o.length===0?ws:t.some(s=>Ua(o,s))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(Ga,"stopAtEntryIssue");function Ba(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ne(r)||r.sharedImportsSlice===void 0)return;let s=r.sharedImportsSlice,i=`$.rules[${o}].sharedImportsSlice`;if(typeof s=="string"){s!=="deny"&&s!=="deny-cross-parent"&&t.push({path:i,message:Cs});return}if(!ne(s)){t.push({path:i,message:Cs});return}for(let h of Object.keys(s))h!=="mode"&&h!=="stopAt"&&t.push({path:Nt(i,h),message:"unknown field"});s.mode===void 0?t.push({path:`${i}.mode`,message:"is required"}):s.mode!=="deny-cross-parent"&&t.push({path:`${i}.mode`,message:'must be deny-cross-parent. stopAt has no meaning for deny; use the string "deny".'});let l=s.stopAt;if(l===void 0){t.push({path:`${i}.stopAt`,message:"is required"});return}if(!Array.isArray(l)||l.length===0){t.push({path:`${i}.stopAt`,message:"must be a non-empty array of paths or globs"});return}let c=new Set,f=Va(e,r);l.forEach((h,y)=>{let p=`${i}.stopAt[${y}]`;if(typeof h!="string"){t.push({path:p,message:"must be a non-empty path or glob"});return}let R=Ga(h,f);if(R){t.push({path:p,message:R});return}let d=be(h.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(d)){t.push({path:p,message:"duplicate stopAt entry"});return}c.add(d)})})}a(Ba,"validateSharedImportsSlice");var za=["deny","advisory"],xs='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function Wa(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ne(r))return;let s=r.childSlices;if(!ne(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){za.includes(i)||t.push({path:l,message:xs});return}if(!ne(i)){t.push({path:l,message:xs});return}for(let f of Object.keys(i))f!=="default"&&f!=="enforce"&&f!=="ratchet"&&t.push({path:Nt(l,f),message:"unknown field"});if(i.ratchet!==void 0&&typeof i.ratchet!="boolean"&&t.push({path:`${l}.ratchet`,message:"must be a boolean"}),i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((f,h)=>{let y=`${l}.enforce[${h}]`;if(typeof f!="string"||f.trim().length===0){t.push({path:y,message:"must be a non-empty child slice id or subtree path"});return}let p=be(f.trim().replace(/\\/g,"/"));if(p.split("/").some(R=>R.length===0||R==="."||R==="..")){t.push({path:y,message:"must be a child slice id or subtree path without . or .."});return}if(p.includes("*")){t.push({path:y,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(p)){t.push({path:y,message:"duplicate enforce entry"});return}c.add(p)})})}a(Wa,"validateChildSliceSiblings");var qa="must be a slice id with a slash. A bare name is ambiguous across universes.",Ya="* matches one whole path segment. ** and a partial segment are not wildcards.";function Xa(e){let t=be(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return qa;let n=t.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return Ya}return null}a(Xa,"childCrossSlicePatternIssue");function _s(e){return be(e.trim().replace(/\\/g,"/")).toLowerCase()}a(_s,"childCrossSlicePatternKey");function Za(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ne(r))return;let s=r.childSlices;if(!ne(s)||s.allowedCrossSlice===void 0)return;let i=s.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((f,h)=>{let y=`${l}[${h}]`;if(!ne(f)){t.push({path:y,message:"must be an object with from and to"});return}for(let R of Object.keys(f))R!=="from"&&R!=="to"&&t.push({path:Nt(y,R),message:"unknown field"});for(let R of["from","to"]){let d=f[R],g=`${y}.${R}`;if(typeof d!="string"||d.trim().length===0){t.push({path:g,message:"must be a non-empty slice id"});continue}let A=Xa(d);A&&t.push({path:g,message:A})}if(typeof f.from!="string"||typeof f.to!="string")return;let p=`${_s(f.from)}\0${_s(f.to)}`;if(!p.startsWith("\0")&&!p.endsWith("\0")){if(c.has(p)){t.push({path:y,message:"duplicate child slice allowance"});return}c.add(p)}})})}a(Za,"validateChildSliceAllowedCrossSlice");var He="must be a child of a universe shape this rule names (its universe sliceFolders shape plus one child segment). A bare name, a universe id alone, a target outside every universe shape, and a wildcard are rejected. Config load checks the shape only; doctor reports a target universe no file belongs to.",Ja="is a 4.8.23 stars id (star bindings before the last literal dropped) that maps to more than one universe shape of this rule. Write the new stars id, which keeps every star binding (e.g. orders/api/v1/x for modules/*/api/*).",Qa="overlaps a slice folder. An alias covers only files outside the slice trees.",el="two slice aliases match the same file";function tl(e){return be(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(tl,"aliasPathSegments");function nl(e){let t=e[e.length-1];return t===void 0||t.includes("*")?[...e]:[...e,"**"]}a(nl,"aliasSegmentsWithSubtree");function Ps(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(Ps,"concreteGlobPrefix");function nt(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}a(nt,"segmentsArePrefix");function rl(e){let t=e.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(t.length<2||t[0]==="*"||t[0]==="**"||!t.some(r=>r==="*"))return null;let n=[];for(let r of t){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(rl,"anchoredSlicePrefix");function sl(e,t){let n=Ps(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return nt(t,n)||nt(t,o)?!0:r?nt(n,t)&&n.length<t.length||nt(n,["src",...t])&&n.length<t.length+1||nt(n,["app",...t])&&n.length<t.length+1:!1}a(sl,"globOverlapsAnchored");function ol(e,t){for(let r=0;r<e.length;r+=1){if(e[r]!==t&&e[r]!=="*")continue;let o=e.slice(r+1);if(o.length>=2||o.some(s=>s==="*"||s==="**"))return!0}let n=Ps(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(ol,"globOverlapsBare");function il(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return ol(e,n[0]);let r=rl(t);return r?sl(e,r):!1}a(il,"globOverlapsSliceEntry");function al(e){let t=be(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty path glob";if(t==="*"||t==="**")return"must not cover the whole tree";for(let n of t.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(al,"aliasGlobIssue");function ll(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let o of e){if(typeof o!="string"||o.length===0)continue;let s=o.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(s.length===1&&s[0]&&!s[0].includes("*")){n.push({literals:[s[0],null]});continue}if(!s.some(i=>i==="**"||i.includes("*")&&i!=="*")&&s.includes("*")){if(r){let i=-1;for(let f=0;f<s.length;f+=1)s[f]!=="*"&&(i=f);if(i<0)continue;let l=s.filter((f,h)=>h>=i||f==="*").map(f=>f==="*"?null:f),c=s.slice(i).map(f=>f==="*"?null:f);n.push(c.length===l.length?{literals:l}:{literals:l,legacy:c});continue}n.push({literals:s.map(i=>i==="*"?null:i)})}}return n}a(ll,"universeShapes");function $t(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a($t,"shapeMatches");function cl(e,t){let n=be(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(s=>s.length===0||s==="."||s==="..")||n.includes("*")||!n.includes("/"))return He;let r=n.split("/").map(s=>s.toLowerCase());if(t.length===0||t.some(s=>$t(s,r)))return He;if(t.some(s=>$t(s,r.slice(0,-1))))return null;let o=new Set(t.filter(s=>s.legacy!==void 0&&!$t({literals:s.legacy},r)&&$t({literals:s.legacy},r.slice(0,-1))).map(s=>s.literals.map(i=>i??"*").join("/")));return o.size===1?null:o.size>1?Ja:He}a(cl,"aliasTargetIssue");function Os(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(Os,"aliasGlobVariants");function dl(e,t){let n=Os(e),r=Os(t);for(let o of n)if(Ce(o,t,0,0,new Map))return!0;for(let o of r)if(Ce(e,o,0,0,new Map))return!0;return!1}a(dl,"aliasesCanMatchSameFile");function Ce(e,t,n,r,o){let s=`${n}:${r}`,i=o.get(s);if(i!==void 0)return i;let l=!1;if(n===e.length&&r===t.length)l=!0;else if(n<e.length&&e[n]==="**")l=Ce(e,t,n+1,r,o)||r<t.length&&Ce(e,t,n,r+1,o);else if(r<t.length&&t[r]==="**")l=Ce(e,t,n,r+1,o)||n<e.length&&Ce(e,t,n+1,r,o);else if(n<e.length&&r<t.length){let c=e[n],f=t[r];(c===f||c==="*"||f==="*")&&(l=Ce(e,t,n+1,r+1,o))}return o.set(s,l),l}a(Ce,"globsCanMatchSame");function ul(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!ne(r))return;let s=r.childSlices;if(!ne(s)||s.sliceAliases===void 0)return;let i=s.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=ll(r.sliceFolders,r.sliceIdentity),f=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(y=>typeof y=="string"&&y.length>0),h=[];i.forEach((y,p)=>{let R=`${l}[${p}]`;if(!ne(y)){t.push({path:R,message:"must be an object with from and to"});return}for(let A of Object.keys(y))A!=="from"&&A!=="to"&&t.push({path:Nt(R,A),message:"unknown field"});let d=y.from,g=y.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${R}.from`,message:"must be a non-empty path glob"});else{let A=al(d);if(A)t.push({path:`${R}.from`,message:A});else{let I=nl(tl(d));f.some(S=>il(I,S))&&t.push({path:`${R}.from`,message:Qa});for(let S of h)if(dl(S,I)){t.push({path:R,message:el});break}h.push(I)}}if(typeof g!="string"||g.trim().length===0)t.push({path:`${R}.to`,message:He});else{let A=cl(g,c);A&&t.push({path:`${R}.to`,message:A})}})})}a(ul,"validateChildSliceAliases");function Pt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(Pt,"normalizeStewardId");function Fs(e){let t=Pt(e);return!t||En(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Fs,"isGitHubHandle");function fl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t.includes("@")||t.includes(" ")||En(t))return!1;let n=t.split("@");if(n.length!==2||!n[0]||/\s/.test(t))return!1;let r=n[1].lastIndexOf(".");return r>0&&r<n[1].length-1}a(fl,"isGitHubEmail");function pl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Fs(t[1])?Pt(t[1]):null}a(pl,"githubHandleFromEmail");function Ds(e){let t=pl(e);if(t)return t;let n=Pt(e);return!n||En(n)?null:Fs(n)||fl(n)?n:null}a(Ds,"canonicalStewardId");var gl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function En(e){let t=Pt(e);return!t||gl.test(t)}a(En,"isAutomationAuthor");var ie="1.3",hl=["public","auth","admin","internal"];function ml(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(ml,"isFutureHouseLayer");function yl(e){let t=e&&typeof e=="object"?e.owners:void 0;if(!Array.isArray(t)||t.length===0)return;let n=t.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a(yl,"layerOwnersList");function Ks(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!ml(t)&&!yl(t)).map(t=>t.name)}a(Ks,"layersMissingRequiredOwners");function js(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(js,"missingLayerOwnersNextAction");var Cn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Ms=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Rl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Al(){let e=[];for(let t of Ms)for(let n of Ms)t===n||Rl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Al,"createDefaultRules");var Us=Al(),wn=[{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},Hs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Cn,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:Cn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ie,default:ie},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:Us,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:[...hl]},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 every star binding (a star before the last literal is kept too), 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:Ts,childSlices:$s}},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:As,arkOrder:ks}},me=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
11
13
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
12
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ne,"isObject");function ke(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(ke,"propertyPath");function _e(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(_e,"valueType");function mi(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(mi,"resolveSchemaRef");function Xe(e,t,n,r,s){if(t.$ref){let o=mi(t.$ref,r);if(!o){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Xe(e,o,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ne(e)){s.push({path:n,message:`must be an object; received ${_e(e)}`});return}let o=t.properties??{};for(let i of t.required??[])e[i]===void 0&&s.push({path:ke(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in o||s.push({path:ke(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in o||Xe(e[l],i,ke(n,l),r,s)}for(let[i,l]of Object.entries(o))e[i]!==void 0&&Xe(e[i],l,ke(n,i),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${_e(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(i=>JSON.stringify(i));new Set(o).size!==o.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,i)=>Xe(o,t.items,`${n}[${i}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${_e(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${_e(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${_e(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}a(Xe,"validateNode");var hi=["deny","advisory"],xr='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"] }';function yi(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,s)=>{if(!ne(r))return;let o=r.childSlices;if(!ne(o)||o.siblings===void 0)return;let i=o.siblings,l=`$.rules[${s}].childSlices.siblings`;if(typeof i=="string"){hi.includes(i)||t.push({path:l,message:xr});return}if(!ne(i)){t.push({path:l,message:xr});return}for(let f of Object.keys(i))f!=="default"&&f!=="enforce"&&t.push({path:ke(l,f),message:"unknown field"});if(i.default===void 0?t.push({path:`${l}.default`,message:"is required"}):i.default!=="deny"&&i.default!=="advisory"&&t.push({path:`${l}.default`,message:"must be deny or advisory"}),i.enforce===void 0)return;if(!Array.isArray(i.enforce)){t.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;i.enforce.forEach((f,h)=>{let R=`${l}.enforce[${h}]`;if(typeof f!="string"||f.trim().length===0){t.push({path:R,message:"must be a non-empty child slice id or subtree path"});return}let u=Te(f.trim().replace(/\\/g,"/"));if(u.split("/").some(p=>p.length===0||p==="."||p==="..")){t.push({path:R,message:"must be a child slice id or subtree path without . or .."});return}if(u.includes("*")){t.push({path:R,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(u)){t.push({path:R,message:"duplicate enforce entry"});return}c.add(u)})})}a(yi,"validateChildSliceSiblings");var Ri="must be a slice id with a slash. A bare name is ambiguous across universes.",Ai="* matches one whole path segment. ** and a partial segment are not wildcards.";function ki(e){let t=Te(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return Ri;let n=t.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return Ai}return null}a(ki,"childCrossSlicePatternIssue");function Or(e){return Te(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Or,"childCrossSlicePatternKey");function bi(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,s)=>{if(!ne(r))return;let o=r.childSlices;if(!ne(o)||o.allowedCrossSlice===void 0)return;let i=o.allowedCrossSlice,l=`$.rules[${s}].childSlices.allowedCrossSlice`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;i.forEach((f,h)=>{let R=`${l}[${h}]`;if(!ne(f)){t.push({path:R,message:"must be an object with from and to"});return}for(let p of Object.keys(f))p!=="from"&&p!=="to"&&t.push({path:ke(R,p),message:"unknown field"});for(let p of["from","to"]){let d=f[p],g=`${R}.${p}`;if(typeof d!="string"||d.trim().length===0){t.push({path:g,message:"must be a non-empty slice id"});continue}let k=ki(d);k&&t.push({path:g,message:k})}if(typeof f.from!="string"||typeof f.to!="string")return;let u=`${Or(f.from)}\0${Or(f.to)}`;if(!u.startsWith("\0")&&!u.endsWith("\0")){if(c.has(u)){t.push({path:R,message:"duplicate child slice allowance"});return}c.add(u)}})})}a(bi,"validateChildSliceAllowedCrossSlice");var $e="must be a child of an existing universe (the universe id this rule already names, plus one child segment). A bare name, a universe id alone, an unknown universe, and a wildcard are rejected.",vi="overlaps a slice folder. An alias covers only files outside the slice trees.",Si="two slice aliases match the same file";function Ii(e){return Te(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Ii,"aliasPathSegments");function Nr(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(Nr,"concreteGlobPrefix");function Ye(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}a(Ye,"segmentsArePrefix");function Ei(e){let t=e.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(t.length<2||t[0]==="*"||t[0]==="**"||!t.some(r=>r==="*"))return null;let n=[];for(let r of t){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(Ei,"anchoredSlicePrefix");function Ci(e,t){let n=Nr(e),r=n.length<e.length,s=n[0]==="src"||n[0]==="app"?n.slice(1):n;return Ye(t,n)||Ye(t,s)?!0:r?Ye(n,t)&&n.length<t.length||Ye(n,["src",...t])&&n.length<t.length+1||Ye(n,["app",...t])&&n.length<t.length+1:!1}a(Ci,"globOverlapsAnchored");function wi(e,t){for(let r=0;r<e.length;r+=1){if(e[r]!==t&&e[r]!=="*")continue;let s=e.slice(r+1);if(s.length>=2||s.some(o=>o==="*"||o==="**"))return!0}let n=Nr(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(wi,"globOverlapsBare");function xi(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(s=>s.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return wi(e,n[0]);let r=Ei(t);return r?Ci(e,r):!1}a(xi,"globOverlapsSliceEntry");function Oi(e){let t=Te(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty path glob";if(t==="*"||t==="**")return"must not cover the whole tree";for(let n of t.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(Oi,"aliasGlobIssue");function _i(e,t){let n=[];if(!Array.isArray(e))return n;let r=t==="stars";for(let s of e){if(typeof s!="string"||s.length===0)continue;let o=s.split(/[/\\]/).filter(Boolean).map(i=>i.toLowerCase());if(o.length===1&&o[0]&&!o[0].includes("*")){n.push({literals:[o[0],null]});continue}if(!o.some(i=>i==="**"||i.includes("*")&&i!=="*")&&o.includes("*")){if(r){let i=-1;for(let l=0;l<o.length;l+=1)o[l]!=="*"&&(i=l);if(i<0)continue;n.push({literals:o.slice(i).map(l=>l==="*"?null:l)});continue}n.push({literals:o.map(i=>i==="*"?null:i)})}}return n}a(_i,"universeShapes");function _r(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(_r,"shapeMatches");function $i(e,t){let n=Te(e.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(s=>s.length===0||s==="."||s==="..")||n.includes("*")||!n.includes("/"))return $e;let r=n.split("/").map(s=>s.toLowerCase());return t.length===0||t.some(s=>_r(s,r))?$e:t.some(s=>_r(s,r.slice(0,-1)))?null:$e}a($i,"aliasTargetIssue");function $r(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a($r,"aliasGlobVariants");function Ti(e,t){let n=$r(e),r=$r(t);for(let s of n)if(Ae(s,t,0,0,new Map))return!0;for(let s of r)if(Ae(e,s,0,0,new Map))return!0;return!1}a(Ti,"aliasesCanMatchSameFile");function Ae(e,t,n,r,s){let o=`${n}:${r}`,i=s.get(o);if(i!==void 0)return i;let l=!1;if(n===e.length&&r===t.length)l=!0;else if(n<e.length&&e[n]==="**")l=Ae(e,t,n+1,r,s)||r<t.length&&Ae(e,t,n,r+1,s);else if(r<t.length&&t[r]==="**")l=Ae(e,t,n,r+1,s)||n<e.length&&Ae(e,t,n+1,r,s);else if(n<e.length&&r<t.length){let c=e[n],f=t[r];(c===f||c==="*"||f==="*")&&(l=Ae(e,t,n+1,r+1,s))}return s.set(o,l),l}a(Ae,"globsCanMatchSame");function Li(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,s)=>{if(!ne(r))return;let o=r.childSlices;if(!ne(o)||o.sliceAliases===void 0)return;let i=o.sliceAliases,l=`$.rules[${s}].childSlices.sliceAliases`;if(!Array.isArray(i)){t.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=_i(r.sliceFolders,r.sliceIdentity),f=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(o.sliceFolders)?o.sliceFolders:[]].filter(R=>typeof R=="string"&&R.length>0),h=[];i.forEach((R,u)=>{let p=`${l}[${u}]`;if(!ne(R)){t.push({path:p,message:"must be an object with from and to"});return}for(let k of Object.keys(R))k!=="from"&&k!=="to"&&t.push({path:ke(p,k),message:"unknown field"});let d=R.from,g=R.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${p}.from`,message:"must be a non-empty path glob"});else{let k=Oi(d);if(k)t.push({path:`${p}.from`,message:k});else{let I=Ii(d);f.some(S=>xi(I,S))&&t.push({path:`${p}.from`,message:vi});for(let S of h)if(Ti(S,I)){t.push({path:p,message:Si});break}h.push(I)}}if(typeof g!="string"||g.trim().length===0)t.push({path:`${p}.to`,message:$e});else{let k=$i(g,c);k&&t.push({path:`${p}.to`,message:k})}})})}a(Li,"validateChildSliceAliases");function Fi(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,s)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let o=r.owners;Array.isArray(o)&&o.forEach((i,l)=>{typeof i=="string"&&(Er(i)||t.push({path:`$.layers[${s}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Fi,"validateLayerOwners");function Ni(e){let t={...e,$schema:e.$schema===void 0?Gt:e.$schema,schemaVersion:e.schemaVersion===void 0?te:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Fr.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=kr(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=br(e.arkOrder)),t}a(Ni,"defaultedConfig");function Pi(e){return e===te?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Pi,"migratedFromOf");function Di(){let e=new Set([te]);for(let t of Bt)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Di,"knownInputVersions");function Mi(e,t="ark.config.json"){if(!ne(e))throw new de(t,[{path:"$",message:`must be an object; received ${_e(e)}`}]);let n=Di(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${te}`}]);if(r!=="unversioned"&&!n.has(r))throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);let s=r,o={...e},i=0;for(;s!==te&&i<Bt.length+1;){i+=1;let l=Bt.find(c=>c.from===s);if(!l)throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${te}`}]);s=l.to,o.schemaVersion=s}if(s!==te)throw new de(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${te}`}]);return{candidate:Ni(o),migratedFrom:Pi(r)}}a(Mi,"migrateArkConfig");function Wt(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Mi(e,t),s=[];if(Xe(n,wr,"$",wr,s),vr(n,s),Sr(n,s),Fi(n,s),yi(n,s),bi(n,s),Li(n,s),s.length>0)throw new de(t,s);return{config:n,migratedFrom:r}}a(Wt,"loadArkConfigContract");function Pr(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new de(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Wt(n,t)}a(Pr,"parseArkConfigJson");function Te(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Te,"trimTrailingSlashes");function G(e,t,n={}){return{ruleId:e,message:t,...n}}a(G,"configWarning");function zt(e){let{config:t,rules:n,files:r,manifest:s}=e,o=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&o.push(G("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))o.push(G("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let g=t.safety[d];g!==void 0&&(!Number.isInteger(g)||g<0)&&o.push(G("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(s?.architecture?.layers)?s.architecture.layers:[],c=new Set([...i.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);i.length===0&&o.push(G("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let f=new Set,h=new Set;for(let d of i){if(!d.name){o.push(G("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}f.has(d.name)&&h.add(d.name),f.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(k=>typeof k!="string"))&&o.push(G("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let g=Array.isArray(d.patterns)?d.patterns:[];if(g.length===0){o.push(G("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let k of g){let I;try{I=oe(k)}catch(x){o.push(G("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${k}": ${x instanceof Error?x.message:String(x)}`,{layer:d.name,pattern:k}));continue}let S=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(x=>I.test(x))&&!S&&o.push(G("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${k}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:k,failsStrict:!1,reserved:!1}))}}for(let d of h)o.push(G("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&o.push(G("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&o.push(G("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let R=new Set;if(i.length>1)for(let d of r){let g=-1,k=[];for(let I of i)for(let S of I.patterns??[]){if(!oe(S).test(d))continue;let x=Ot(S,d);x>g?(g=x,k=[I.name]):x===g&&!k.includes(I.name)&&k.push(I.name)}k.length>1&&R.add([...k].sort().join(" + "))}R.size>0&&o.push(G("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...R].join(", ")}.`,{pairs:[...R]}));let u=r.filter(d=>!Q(d,i));u.length>0&&o.push(G("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)}));for(let d of Cn(n))o.push(G("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));for(let d of On(n,r))o.push(G(d.ruleId,d.message,{failsStrict:!1,...d.path?{file:d.path}:{},...d.fromLayer?{fromLayer:d.fromLayer}:{},...d.toLayer?{toLayer:d.toLayer}:{}}));let p=Tr(t);if(p.length>0){let d=p[0]??"this layer";o.push(G("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:p,nextAction:Lr(d)}))}return o}a(zt,"collectAnalysisConfigWarnings");function Mr(e){let t=0,n=new Map,r=new Map,s=new Set,o=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,o.push(c),s.add(c);for(let R of[...e.get(c)??[]].sort())e.has(R)&&(n.has(R)?s.has(R)&&r.set(c,Math.min(r.get(c)??0,n.get(R)??0)):(l(R),r.set(c,Math.min(r.get(c)??0,r.get(R)??0))));if(r.get(c)!==n.get(c))return;let f=[],h;do{if(h=o.pop(),h===void 0)break;s.delete(h),f.push(h)}while(h!==c);f.length>1&&i.push(f.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(Mr,"detectArchitectureCycles");function Je(e){let t=e.contentViolations.map(o=>({...o})),n=(e.warnings??[]).map(o=>({...o})),r=new Map(e.files.map(o=>[o,new Set]));for(let o of e.edges){if(o.to&&o.to!==o.from&&!o.typeOnly&&r.has(o.from)&&r.get(o.from)?.add(o.to),!o.to||!o.fromLayer||!o.toLayer)continue;let i=We(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});if(!i){let u=$n(e.rules,o.fromLayer,o.toLayer,{fromPath:o.from,toPath:o.to,layers:e.config.layers});u&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:u.fromPath,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:u.toPath,toSlice:u.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${u.fromPath} \u2192 slice ${u.toSlice} (${u.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,f=!c&&!!(o.typeOnly||o.namedBindingsTypeOnly),h=i.sliceVerdict,R=h?ut({surface:"import",verdict:h,fromLayer:o.fromLayer,toLayer:o.toLayer,kind:o.kind,fromPath:o.from,toPath:o.to,ruleMessage:l.message}):l.message??`${o.fromLayer} must not ${o.kind} ${o.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:o.from,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.to,...o.typeOnly?{typeOnly:!0}:{},...o.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...o.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...o.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&o.portProofEligible?{portProofEligible:!0}:{},...o.kind?{edgeKind:o.kind}:{},...c?{peerIsolation:!0}:{},...ft(h),message:f?`${R} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:R,...f?{failsStrict:!1,severity:"warning"}:{}})}t.push(...Ki(e));let s=String(e.config.cyclePolicy??"strict").toLowerCase();if(s!=="off"){let o=Mr(r);s==="soft"||s==="framework-soft"?n.push(...o.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...o)}return{violations:t,warnings:n,safety:e.safety}}a(Je,"evaluateArchitectureGraph");var Hi="CROSS_PARENT_VIA_SHARED",Ui="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function Dr(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&r.sharedImportsSlice==="deny-cross-parent")return r}a(Dr,"denyingCrossParentRule");function qt(e,t,n,r){let s=we(n,e,Tn(e,t,r)).universeId;return s?{kind:"slice",id:s}:Ve(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(qt,"placeFile");function Ki(e){let t=e.rules??[];if(!t.some(o=>o.sharedImportsSlice==="deny-cross-parent"))return[];let n=new Map;for(let o of e.edges){let i=ji(o);if(!i)continue;let l=n.get(i.from);l?l.push(i):n.set(i.from,[i])}for(let o of n.values())o.sort((i,l)=>i.to<l.to?-1:i.to>l.to?1:i.line-l.line);let r=new Map,s=[...n.values()].flat();s.sort((o,i)=>o.from<i.from?-1:o.from>i.from?1:o.to<i.to?-1:o.to>i.to?1:0);for(let o of s){let i=Dr(t,o.fromLayer,o.toLayer);if(!i)continue;let l=qt(i,o.fromLayer,o.from,e.config.layers),c=qt(i,o.fromLayer,o.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared")continue;let f=[{file:o.to,path:[o.from,o.to]}],h=new Set([o.to]);for(;f.length>0;){let R=f.shift();if(!R)break;for(let u of n.get(R.file)??[]){let p=Dr(t,u.fromLayer,u.toLayer);if(!p)continue;let d=qt(p,u.fromLayer,u.to,e.config.layers);if(d.kind==="shared"){if(h.has(u.to))continue;h.add(u.to),f.push({file:u.to,path:[...R.path,u.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase())continue;let g=[...R.path,u.to],k=`${o.from}\0${u.to}`,I={file:o.from,target:u.to,line:o.line,fromLayer:o.fromLayer,toLayer:u.toLayer,fromSlice:l.id,toSlice:d.id,path:g},S=r.get(k);(!S||g.length<S.path.length||g.length===S.path.length&&g.join("\0")<S.path.join("\0"))&&r.set(k,I)}}}return[...r.values()].sort((o,i)=>o.file<i.file?-1:o.file>i.file?1:o.target<i.target?-1:o.target>i.target?1:0).map(o=>{let i=Ge(o.fromSlice),l=Ge(o.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:Hi,file:o.file,line:o.line,fromLayer:o.fromLayer,toLayer:o.toLayer,target:o.target,peerIsolation:!0,...i&&l?{universeFrom:i,universeTo:l}:{},message:`${o.fromLayer} reaches ${o.toLayer} in another universe through a shared root (${o.path.join(" \u2192 ")}): cross-parent via shared ${o.fromSlice} \u2192 ${o.toSlice}. ${Ui}`}})}a(Ki,"crossParentViaSharedViolations");function ji(e){if(!(!e.to||e.to===e.from||!e.fromLayer||!e.toLayer))return{from:e.from,to:e.to,line:e.line,fromLayer:e.fromLayer,toLayer:e.toLayer}}a(ji,"valueHop");function Hr(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",s=e.ruleId==="INVARIANT_CATALOG_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:Pn({sensor:e.sensor,code:e.code})}:{},...r||s?{freezable:!1}:{},nextAction:t}}a(Hr,"toArkRuleEngineViolation");function Vi(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Vi,"arkRulesMapIsOn");function Ur(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}a(Ur,"arkRuleFindingNextAction");function Gi(e,t){return t.some(n=>{try{return oe(n).test(e)}catch{return!1}})}a(Gi,"matchesAny");function Bi(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,s=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,o=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(g=>g.kind==="ts-suppression").map(({file:g,line:k})=>({file:g,line:k})),l=t.safetyUses.filter(g=>g.kind==="any-cast").map(({file:g,line:k})=>({file:g,line:k})),c=t.safetyUses.filter(g=>(g.kind==="dynamic-import"||g.kind==="dynamic-require")&&!Gi(g.file,o)).map(g=>({file:g.file,line:g.line,kind:g.kind==="dynamic-require"?"require":"import"})),f=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(g=>g.kind==="in-memory-store").map(g=>({file:g.file,line:g.line,store:g.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(g=>g.peerIsolation===!1||g.allowed===!1&&!!g.from&&g.from===g.to&&g.peerIsolation!==!0).map(g=>({from:g.from,to:g.to})),R={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:f,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:r,maxAnyCasts:s}},u=[],p=c.filter(g=>g.kind==="import");if(p.length>0){let g=p[0];u.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${p.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(g=>g.kind==="require");if(d.length>0){let g=d[0];u.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let g=i[0];u.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>s){let g=l[0];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${s}).`})}if(f.length>0){let g=f[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:g.file,line:g.line,message:`${f.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return h.length>0&&u.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${h.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:R,warnings:u}}a(Bi,"evaluateSafety");function Wi(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(Wi,"ambientForbiddenGlobal");function Kr(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Ft(e,n.length>0?n:Lt.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Kr,"intentLayer");function zi(e,t,n){let r=[],s=new Map(e.contract.config.layers.map(o=>[o.name,o]));for(let o of t.ambientUses){let i=n.get(o.file);!i||!Wi(o.symbol,s.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:i,target:o.symbol,message:`${i} must not use the ambient global "${o.symbol}".`})}for(let o of t.capabilityUses){let i=n.get(o.file);if(!i)continue;let l=s.get(i),c=l?.forbiddenGlobals??[],f=o.source==="import-based"?t.dependencies.find(h=>h.from===o.file&&h.line===o.line&&h.specifier===o.symbol&&!h.typeOnly)?.kind:void 0;if(!(o.source==="ambient-global"&&wt(o.symbol,c))){if(o.source==="import-based"){let h=Ke(o.symbol,c);if(h){r.push({ruleId:"FORBIDDEN_GLOBAL",file:o.file,line:o.line,fromLayer:i,target:o.symbol,...f?{edgeKind:f}:{},message:`${i} must not use module "${o.symbol}" because it is the import form of forbidden global "${h}".`});continue}}Ce(l).includes(o.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:o.file,line:o.line,fromLayer:i,target:o.symbol,capability:o.capability,...f?{edgeKind:f}:{},message:o.source==="import-based"?`${i} denies the ${o.capability} capability; found import of "${o.symbol}".`:`${i} denies the ${o.capability} capability; found ambient "${o.symbol}".`})}}for(let o of t.publishCalls){let i=n.get(o.file);if(!i)continue;for(let c of Nt({publishCall:!0,rawIntentName:o.rawIntentName,objectHasIntent:o.objectHasIntent,arkPublishCandidate:o.arkPublishCandidate,hasSource:o.hasSource}))r.push({ruleId:c.ruleId,file:o.file,line:o.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:c.message});if(!o.sourceIntent)continue;let l=Kr(o.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:o.file,line:o.line,fromLayer:i,toLayer:l,target:o.sourceIntent,message:`Publish source "${o.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let o of t.intentReferences){let i=n.get(o.file);if(!i)continue;let l=Kr(o.intent,e.contract);if(!l)continue;let c=We(e.contract.config.rules,i,l,{fromPath:o.file,layers:e.contract.config.layers});if(!c)continue;let f=c.sliceVerdict,h=`${i} must not reference ${l} intent ${o.intent}.`,R=f?ut({surface:"intent",verdict:f,fromLayer:i,toLayer:l,fromPath:o.file,ruleMessage:c.rule.message,defaultMessage:h}):c.rule.message??h;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:o.file,line:o.line,fromLayer:i,toLayer:l,target:o.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},...ft(f),message:R})}return r}a(zi,"contentViolations");function Yt(e){let{facts:t}=e,n=st(e.contract.config),r=t.evidenceRequirementsHash===n,s=r?t.completeness:"unavailable",o=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((y,Y)=>{let Me=`${y.code}\0${y.file??""}\0${y.message}`,He=`${Y.code}\0${Y.file??""}\0${Y.message}`;return Me<He?-1:Me>He?1:0}),i=t.files.map(y=>({...y,layer:Q(y.path,e.contract.config.layers)??null})),l=new Map(i.map(y=>[y.path,y.layer])),c=t.dependencies.map(y=>{let Y=y.target?l.get(y.target)??Q(y.target,e.contract.config.layers):void 0;return{from:y.from,fromLayer:l.get(y.from)??null,...y.resolution==="resolved-project"&&y.target?{to:y.target,...Y?{toLayer:Y}:{}}:{},line:y.line,kind:y.kind,typeOnly:y.typeOnly,...y.targetTypeOnlyExports?{targetTypeOnlyExports:y.targetTypeOnlyExports}:{},...y.sourcePureTypeModule?{sourcePureTypeModule:y.sourcePureTypeModule}:{},...y.namedBindingsTypeOnly?{namedBindingsTypeOnly:y.namedBindingsTypeOnly}:{},...y.portProofEligible?{portProofEligible:y.portProofEligible}:{}}}),f=zt({config:e.contract.config,rules:e.contract.config.rules,files:i.map(y=>y.path)}),h=Bi(e,t),R=e.contract.arkRules??ze(),u=i.map(y=>y.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?qn(e.coverageInputs.fileContents):{},...e.fileHints??{}},g=a(y=>l.get(y)??Q(y,e.contract.config.layers),"resolveLayer"),k=[...Bn({arkRules:R,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:g,fileHints:d}),...Wn(R,u),...zn({arkRulesActive:Vi(e.contract.config),arkRules:R,layers:e.contract.config.layers??[],files:u.map(y=>({path:y,layer:g(y)}))})],I=(R.invariants?.length??0)>0,S=rr({hasEnforcedInvariant:Kt(R.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),x=S.length>0?[]:nr({adopted:e.adopted===!0,hasDomainInvariants:Ut(R.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),$=[...S.map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,nextAction:"Add coverage.coverageRoots in ark.config.json pointing at the folder the test runner uses, then re-run. An enforced invariant fails closed until that path is present.",failsStrict:!0,freezable:!1})),...x.map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],q=k.filter(y=>y.failsStrict).map(y=>Hr(y,Ur(y,!1))),b=k.filter(y=>!y.failsStrict).map(y=>({...Hr(y,Ur(y,!0)),failsStrict:!1})),T=I?er({arkRules:R,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},Ne=T.violations.filter(y=>y.failsStrict).map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,arkruleId:y.arkruleId,arkruleSource:y.arkruleSource,nextAction:`Add a test title or declared symbol covering ${y.arkruleId} (declared in ${y.arkruleSource}), then preflight again.`})),me=T.violations.filter(y=>!y.failsStrict).map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,arkruleId:y.arkruleId,arkruleSource:y.arkruleSource,failsStrict:!1,nextAction:y.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${y.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${y.arkruleId} in ${y.arkruleSource} (advisory / partial).`})),nt=sr(i),ie=ur({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:a(y=>l.get(y)??Q(y,e.contract.config.layers),"layerForFile"),classification:nt}),se=e.contract.config.arkRun?.mode,he=ie.findings.filter(()=>se==="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:y.failsStrict,...y.severity?{severity:y.severity}:{}})),Pe=ie.findings.filter(()=>se!=="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:!1})),Se=hr({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:a(y=>l.get(y)??Q(y,e.contract.config.layers),"layerForFile"),classification:nt}),De=e.contract.config.arkOrder?.mode,rt=Se.findings.filter(()=>De==="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:y.failsStrict,...y.severity?{severity:y.severity}:{}})),un=Se.findings.filter(()=>De!=="enforced").map(y=>({ruleId:y.ruleId,file:y.file,line:y.line,message:y.message,fromLayer:y.fromLayer,target:y.target,nextAction:y.nextAction,sensor:y.sensor,failsStrict:!1})),v=[...T.partial&&T.coverage.some(y=>y.mode==="enforced"&&y.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...ie.completenessReasons,...Se.completenessReasons],C=Je({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(y=>y.layer).map(y=>y.path),contentViolations:[...zi(e,t,l),...q,...$,...Ne,...he,...rt],edges:c,warnings:[...f,...h.warnings,...b,...me,...Pe,...un],safety:h.report}),m=s==="complete"&&v.length>0?"partial":s,A=m==="complete"?o:[...o,...v].sort((y,Y)=>{let Me=`${y.code}\0${y.file??""}\0${y.message}`,He=`${Y.code}\0${Y.file??""}\0${Y.message}`;return Me<He?-1:Me>He?1:0}),O=C.violations.filter(y=>y.failsStrict!==!1),j=m==="complete"&&O.length===0,ue=j&&C.warnings.every(y=>y.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:m,completenessReasons:A,valid:j,strictValid:ue,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(y=>y.name),edges:c,capabilityUses:t.capabilityUses,violations:C.violations,warnings:C.warnings}}}a(Yt,"analyzeCanonicalResolvedProject");function yt(e){return Yt({contract:e.contract,facts:ye(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent})}a(yt,"analyzeResolvedProject");var Xt="1.0";var Rt=class extends Error{static{a(this,"ArchitectureChangeMapValidationError")}issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
|
|
14
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Vs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Vs,"isObject");function Ft(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Ft,"propertyPath");function Ke(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(Ke,"valueType");function kl(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(kl,"resolveSchemaRef");function rt(e,t,n,r,o){if(t.$ref){let s=kl(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}rt(e,s,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Vs(e)){o.push({path:n,message:`must be an object; received ${Ke(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Ft(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:Ft(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||rt(e[l],i,Ft(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&rt(e[i],l,Ft(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${Ke(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>rt(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${Ke(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${Ke(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${Ke(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(rt,"validateNode");function bl(e,t){let n=e.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let s=r.owners;Array.isArray(s)&&s.forEach((i,l)=>{typeof i=="string"&&(Ds(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(bl,"validateLayerOwners");function vl(e){let t={...e,$schema:e.$schema===void 0?Cn:e.$schema,schemaVersion:e.schemaVersion===void 0?ie:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Us.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=vs(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Ss(e.arkOrder)),t}a(vl,"defaultedConfig");function Sl(e){return e===ie?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Sl,"migratedFromOf");function Il(){let e=new Set([ie]);for(let t of wn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Il,"knownInputVersions");function El(e,t="ark.config.json"){if(!Vs(e))throw new me(t,[{path:"$",message:`must be an object; received ${Ke(e)}`}]);let n=Il(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new me(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ie}`}]);if(r!=="unversioned"&&!n.has(r))throw new me(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);let o=r,s={...e},i=0;for(;o!==ie&&i<wn.length+1;){i+=1;let l=wn.find(c=>c.from===o);if(!l)throw new me(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ie}`}]);o=l.to,s.schemaVersion=o}if(o!==ie)throw new me(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);return{candidate:vl(s),migratedFrom:Sl(r)}}a(El,"migrateArkConfig");function xn(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=El(e,t),o=[];if(rt(n,Hs,"$",Hs,o),Is(n,o),Es(n,o),bl(n,o),Ls(n,o),o.length>0)throw new me(t,o);return{config:n,migratedFrom:r}}a(xn,"loadArkConfigContract");function Gs(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new me(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return xn(n,t)}a(Gs,"parseArkConfigJson");var _n="4.8.24";function On(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}a(On,"childSlicesOf");var Bs=Object.freeze([{key:"sharedImportsSlice.stopAt",minVersion:_n,uses:a(e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:_n,uses:a(e=>On(e)?.message!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:_n,uses:a(e=>{let t=On(e)?.siblings;return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:a(e=>On(e)!==null,"uses")},{key:'sharedImportsSlice: "deny-cross-parent"',minVersion:"4.8.23",uses:a(e=>e.sharedImportsSlice==="deny-cross-parent","uses")},{key:"sliceIdentity",minVersion:"4.8.21",uses:a(e=>e.sliceIdentity!==void 0,"uses")},{key:"sharedImportsSlice",minVersion:"4.8.20",uses:a(e=>e.sharedImportsSlice==="deny","uses")}]);function we(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}a(we,"versionCore");function st(e,t){let n=we(e),r=we(t);if(!n&&!r)return 0;if(!n)return-1;if(!r)return 1;for(let o=0;o<3;o+=1){let s=n[o]??0,i=r[o]??0;if(s<i)return-1;if(s>i)return 1}return 0}a(st,"compareArkgateVersion");function zs(e,t){return t&&we(t)&&st(t,e)<0?t.replace(/^v/,""):e}a(zs,"effectiveFloor");function Ws(e,t){let n=[],r=null;for(let o of Bs){if(!(e??[]).some(i=>i&&o.uses(i)))continue;n.push(o.key);let s=zs(o.minVersion,t);(!r||st(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}a(Ws,"configVersionFloors");var Cl=/^(?:=\s*)?v?(\d+\.\d+\.\d+)$/,wl=/(?<![\w@/.-])arkgate@v?(\d+\.\d+\.\d+)(?![\w.])/g,xl=/pedroknigge\/arkgate@v?(\d+\.\d+\.\d+)(?![\w.])/g,_l=/pedroknigge\/arkgate@/,Ol=/^\s*version:\s*['"]?v?(\d+\.\d+\.\d+)['"]?\s*$/;function $n(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
|
|
15
|
+
`&&(n+=1);return n}a($n,"lineOfIndex");function Tn(e,t,n=0){let r=e.indexOf(`"${t}"`,n);return r<0?1:$n(e,r)}a(Tn,"lineOfJsonKey");function Tl(e,t){let n=[],r=t.split(`
|
|
16
|
+
`);for(let o=0;o<r.length;o+=1){let s=r[o]??"";if(!_l.test(s))continue;let i=/^(\s*)-\s/.exec(s),l=i?(i[1]??"").length:s.length-s.trimStart().length-2;for(let c=o+1;c<r.length;c+=1){let f=r[c]??"";if(f.trim().length===0)continue;if(f.length-f.trimStart().length<=l)break;let h=Ol.exec(f);h&&n.push({file:e,line:c+1,version:h[1]??"",source:"ci"})}}return n}a(Tl,"actionVersionInputs");function qs(e,t,n){let r=[];for(let o of[wl,xl]){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;)r.push({file:e,line:$n(t,s.index),version:s[1]??"",source:n})}return n==="ci"&&r.push(...Tl(e,t)),r}a(qs,"textPins");function $l(e,t,n){let r;try{r=JSON.parse(t)}catch{return[]}if(r===null||typeof r!="object")return[];let o=r,s=[];if(n==="installed")return o.name==="arkgate"&&typeof o.version=="string"&&we(o.version)&&s.push({file:e,line:Tn(t,"version"),version:o.version.replace(/^v/,""),source:n}),s;if(n==="package-lock"){let c=o.packages?.["node_modules/arkgate"];if(c&&typeof c.version=="string"&&we(c.version)){let f=t.indexOf('"node_modules/arkgate"');s.push({file:e,line:Tn(t,"version",f<0?0:f),version:c.version.replace(/^v/,""),source:n})}return s}if(o.name==="arkgate")return[];for(let l of["dependencies","devDependencies","optionalDependencies"]){let c=o[l],f=c&&typeof c=="object"?c.arkgate:void 0;if(typeof f!="string")continue;let h=Cl.exec(f.trim());if(!h)continue;let y=t.indexOf(`"${l}"`);s.push({file:e,line:Tn(t,"arkgate",y<0?0:y),version:h[1]??"",source:n})}let i=o.scripts;if(i&&typeof i=="object"){let l=t.indexOf('"scripts"');for(let c of qs(e,t.slice(Math.max(l,0)),"package-json"))s.push({...c,line:c.line+(l<0?0:$n(t,l)-1)})}return s}a($l,"jsonPins");function Ll(e,t,n){return typeof t!="string"||t.length===0?[]:(n==="hook"||n==="ci"?qs(e,t,n):$l(e,t,n)).filter(o=>we(o.version)!==null)}a(Ll,"parseArkgatePins");function Ys(e){let t=Ws(e.rules,e.runningVersion);if(!t||!e.pins?.length)return[];let n=e.runningVersion,r=n&&we(n)&&st(n,t.required)>0?n.replace(/^v/,""):t.required,o=a(l=>Bs.filter(c=>t.keys.includes(c.key)&&st(l.version,zs(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,i=[];for(let l of e.pins){if(st(l.version,t.required)>=0)continue;let c=`${l.file}\0${l.line}`;if(s.has(c))continue;s.add(c);let f=o(l);i.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,path:l.file,line:l.line,message:`ark.config.json uses ${f.join(", ")} (needs arkgate ${t.required}+). ${l.file}:${l.line} pins arkgate ${l.version}, which rejects this config at load.`,nextAction:`Bump arkgate in ${l.file} from ${l.version} to ${r}, then run Ark again.`})}return i.sort((l,c)=>l.path.localeCompare(c.path)||l.line-c.line)}a(Ys,"configVersionPinFindings");function U(e,t,n={}){return{ruleId:e,message:t,...n}}a(U,"configWarning");function Ln(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(d=>typeof d!="string"))&&s.push(U("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)))s.push(U("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let d of["maxTsSuppressions","maxAnyCasts"]){let g=t.safety[d];g!==void 0&&(!Number.isInteger(g)||g<0)&&s.push(U("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${d} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(d=>d.name).filter(Boolean),...l.map(d=>d.name).filter(d=>!!d)]);i.length===0&&s.push(U("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let f=new Set,h=new Set;for(let d of i){if(!d.name){s.push(U("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}f.has(d.name)&&h.add(d.name),f.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(A=>typeof A!="string"))&&s.push(U("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${d.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:d.name}));let g=Array.isArray(d.patterns)?d.patterns:[];if(g.length===0){s.push(U("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let A of g){let I;try{I=oe(A)}catch(w){s.push(U("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${A}": ${w instanceof Error?w.message:String(w)}`,{layer:d.name,pattern:A}));continue}let S=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(w=>I.test(w))&&!S&&s.push(U("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${A}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:A,failsStrict:!1,reserved:!1}))}}for(let d of h)s.push(U("CONFIG_DUPLICATE_LAYER",`Layer "${d}" is configured more than once.`,{layer:d}));if(c.size>0)for(let d of n??[])d.from&&!c.has(d.from)&&s.push(U("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${d.from}".`,{fromLayer:d.from,toLayer:d.to})),d.to&&!c.has(d.to)&&s.push(U("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let y=new Set;if(i.length>1)for(let d of r){let g=-1,A=[];for(let I of i)for(let S of I.patterns??[]){if(!oe(S).test(d))continue;let w=on(S,d);w>g?(g=w,A=[I.name]):w===g&&!A.includes(I.name)&&A.push(I.name)}A.length>1&&y.add([...A].sort().join(" + "))}y.size>0&&s.push(U("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...y].join(", ")}.`,{pairs:[...y]}));let p=r.filter(d=>!te(d,i));p.length>0&&s.push(U("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)}));for(let d of gr(n))s.push(U("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));for(let d of Ir(n,r))s.push(U(d.ruleId,d.message,{failsStrict:!1,...d.path?{file:d.path}:{},...d.fromLayer?{fromLayer:d.fromLayer}:{},...d.toLayer?{toLayer:d.toLayer}:{}}));for(let d of Ys({rules:n,pins:e.arkgatePins,runningVersion:e.runningArkgateVersion}))s.push(U(d.ruleId,d.message,{failsStrict:!1,file:d.path,line:d.line,nextAction:d.nextAction}));let R=Ks(t);if(R.length>0){let d=R[0]??"this layer";s.push(U("CONFIG_LAYER_MISSING_OWNER",`${d} has no owner. Add a GitHub handle or email to layers[].owners so this house has a name on the door.`,{layers:R,nextAction:js(d)}))}return s}a(Ln,"collectAnalysisConfigWarnings");function Js(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let y of[...e.get(c)??[]].sort())e.has(y)&&(n.has(y)?o.has(y)&&r.set(c,Math.min(r.get(c)??0,n.get(y)??0)):(l(y),r.set(c,Math.min(r.get(c)??0,r.get(y)??0))));if(r.get(c)!==n.get(c))return;let f=[],h;do{if(h=s.pop(),h===void 0)break;o.delete(h),f.push(h)}while(h!==c);f.length>1&&i.push(f.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}a(Js,"detectArchitectureCycles");function ot(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let i=Fe(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let p=Cr(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});p&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:p.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:p.toPath,toSlice:p.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${p.fromPath} \u2192 slice ${p.toSlice} (${p.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,f=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),h=i.sliceVerdict,y=h?It({surface:"import",verdict:h,fromLayer:s.fromLayer,toLayer:s.toLayer,kind:s.kind,fromPath:s.from,toPath:s.to,ruleMessage:l.message,childMessage:l.childSlices?.message}):l.message??`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},...Et(h),message:f?`${y} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:y,...f?{failsStrict:!1,severity:"warning"}:{}})}t.push(...Fl(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Js(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}a(ot,"evaluateArchitectureGraph");var Nl="CROSS_PARENT_VIA_SHARED",Pl="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function Xs(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&ye(r.sharedImportsSlice)==="deny-cross-parent")return r}a(Xs,"denyingCrossParentRule");function Nn(e,t,n,r){let o=Xe(n,e,dn(e,t,r)).universeId;return o?{kind:"slice",id:o}:Pe(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Nn,"placeFile");function Zs(e,t){return Rr(t,vt(e.sharedImportsSlice))}a(Zs,"isWalkStop");function Fl(e){let t=e.rules??[];if(!t.some(s=>ye(s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=Dl(s);if(!i)continue;let l=n.get(i.from);l?l.push(i):n.set(i.from,[i])}for(let s of n.values())s.sort((i,l)=>i.to<l.to?-1:i.to>l.to?1:i.line-l.line);let r=new Map,o=[...n.values()].flat();o.sort((s,i)=>s.from<i.from?-1:s.from>i.from?1:s.to<i.to?-1:s.to>i.to?1:0);for(let s of o){let i=Xs(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Nn(i,s.fromLayer,s.from,e.config.layers),c=Nn(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||Zs(i,s.to))continue;let f=[{file:s.to,path:[s.from,s.to]}],h=new Set([s.to]);for(;f.length>0;){let y=f.shift();if(!y)break;for(let p of n.get(y.file)??[]){let R=Xs(t,p.fromLayer,p.toLayer);if(!R)continue;let d=Nn(R,p.fromLayer,p.to,e.config.layers);if(d.kind==="shared"){if(h.has(p.to)||Zs(R,p.to))continue;h.add(p.to),f.push({file:p.to,path:[...y.path,p.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase()||At(i.allowedCrossSlice,l.id,d.id))continue;if(i.sliceIdentity==="stars"){let w=cn(i,dn(i,s.fromLayer,e.config.layers),s.from,p.to);if(w.crossSliceAllowed||w.from.universeId&&w.from.universeId===w.to.universeId)continue}let g=[...y.path,p.to],A=`${s.from}\0${p.to}`,I={file:s.from,target:p.to,line:s.line,fromLayer:s.fromLayer,toLayer:p.toLayer,fromSlice:l.id,toSlice:d.id,path:g},S=r.get(A);(!S||g.length<S.path.length||g.length===S.path.length&&g.join("\0")<S.path.join("\0"))&&r.set(A,I)}}}return[...r.values()].sort((s,i)=>s.file<i.file?-1:s.file>i.file?1:s.target<i.target?-1:s.target>i.target?1:0).map(s=>{let i=Ze(s.fromSlice),l=Ze(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:Nl,file:s.file,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.target,peerIsolation:!0,...i&&l?{universeFrom:i,universeTo:l}:{},via:s.path.slice(1,-1),message:`${s.fromLayer} reaches ${s.toLayer} in another universe through a shared root (${s.path.join(" \u2192 ")}): cross-parent via shared ${s.fromSlice} \u2192 ${s.toSlice}. ${Pl}`}})}a(Fl,"crossParentViaSharedViolations");function Dl(e){if(!(!e.to||e.to===e.from||!e.fromLayer||!e.toLayer))return{from:e.from,to:e.to,line:e.line,fromLayer:e.fromLayer,toLayer:e.toLayer}}a(Dl,"valueHop");function Qs(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY",o=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:_r({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(Qs,"toArkRuleEngineViolation");function Ml(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Ml,"arkRulesMapIsOn");function eo(e,t){return e.ruleId==="INVARIANT_CATALOG_EMPTY"?t?`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve (advisory \u2014 does not fail the merge until a domain structure rule is enforced).`:`Add 1\u20132 short phrases to invariants[] in ${e.arkruleSource} so Domain has policies the code must preserve. Empty catalog fails --strict-merge because a domain structure rule is already enforced.`:e.ruleId==="ARKRULE_SCOPE_EMPTY"?t?`Review appliesTo for ${e.arkruleId} in ${e.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Fix appliesTo globs for ${e.arkruleId} in ${e.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:t?`Review ArkRule ${e.arkruleId} in ${e.arkruleSource} (advisory).`:`Fix the structure or invariant for ${e.arkruleId} (declared in ${e.arkruleSource}), then preflight again.`}a(eo,"arkRuleFindingNextAction");function Hl(e,t){return t.some(n=>{try{return oe(n).test(e)}catch{return!1}})}a(Hl,"matchesAny");function Kl(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],i=t.safetyUses.filter(g=>g.kind==="ts-suppression").map(({file:g,line:A})=>({file:g,line:A})),l=t.safetyUses.filter(g=>g.kind==="any-cast").map(({file:g,line:A})=>({file:g,line:A})),c=t.safetyUses.filter(g=>(g.kind==="dynamic-import"||g.kind==="dynamic-require")&&!Hl(g.file,s)).map(g=>({file:g.file,line:g.line,kind:g.kind==="dynamic-require"?"require":"import"})),f=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(g=>g.kind==="in-memory-store").map(g=>({file:g.file,line:g.line,store:g.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(g=>g.peerIsolation===!1||g.allowed===!1&&!!g.from&&g.from===g.to&&g.peerIsolation!==!0).map(g=>({from:g.from,to:g.to})),y={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:f,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],R=c.filter(g=>g.kind==="import");if(R.length>0){let g=R[0];p.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${R.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let d=c.filter(g=>g.kind==="require");if(d.length>0){let g=d[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${d.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let g=i[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let g=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(f.length>0){let g=f[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:g.file,line:g.line,message:`${f.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return h.length>0&&p.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:y,warnings:p}}a(Kl,"evaluateSafety");function jl(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(jl,"ambientForbiddenGlobal");function to(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return fn(e,n.length>0?n:Ct.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(to,"intentLayer");function Ul(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let i=n.get(s.file);!i||!jl(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],f=s.source==="import-based"?t.dependencies.find(h=>h.from===s.file&&h.line===s.line&&h.specifier===s.symbol&&!h.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&tn(s.symbol,c))){if(s.source==="import-based"){let h=qe(s.symbol,c);if(h){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...f?{edgeKind:f}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${h}".`});continue}}Le(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...f?{edgeKind:f}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of gn({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=to(s.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let s of t.intentReferences){let i=n.get(s.file);if(!i)continue;let l=to(s.intent,e.contract);if(!l)continue;let c=Fe(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let f=c.sliceVerdict,h=`${i} must not reference ${l} intent ${s.intent}.`,y=f?It({surface:"intent",verdict:f,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,childMessage:c.rule.childSlices?.message,defaultMessage:h}):c.rule.message??h;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},...Et(f),message:y})}return r}a(Ul,"contentViolations");function je(e){let{facts:t}=e,n=gt(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((u,_)=>{let M=`${u.code}\0${u.file??""}\0${u.message}`,ee=`${_.code}\0${_.file??""}\0${_.message}`;return M<ee?-1:M>ee?1:0}),i=t.files.map(u=>({...u,layer:te(u.path,e.contract.config.layers)??null})),l=new Map(i.map(u=>[u.path,u.layer])),c=t.dependencies.map(u=>{let _=u.target?l.get(u.target)??te(u.target,e.contract.config.layers):void 0;return{from:u.from,fromLayer:l.get(u.from)??null,...u.resolution==="resolved-project"&&u.target?{to:u.target,..._?{toLayer:_}:{}}:{},line:u.line,kind:u.kind,typeOnly:u.typeOnly,...u.targetTypeOnlyExports?{targetTypeOnlyExports:u.targetTypeOnlyExports}:{},...u.sourcePureTypeModule?{sourcePureTypeModule:u.sourcePureTypeModule}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:u.namedBindingsTypeOnly}:{},...u.portProofEligible?{portProofEligible:u.portProofEligible}:{}}}),f=Ln({config:e.contract.config,rules:e.contract.config.rules,files:i.map(u=>u.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),h=Kl(e,t),y=e.contract.arkRules??et(),p=i.map(u=>u.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?zr(e.coverageInputs.fileContents):{},...e.fileHints??{}},g=a(u=>l.get(u)??te(u,e.contract.config.layers),"resolveLayer"),A=[...Vr({arkRules:y,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:g,fileHints:d}),...Gr(y,p),...Br({arkRulesActive:Ml(e.contract.config),arkRules:y,layers:e.contract.config.layers??[],files:p.map(u=>({path:u,layer:g(u)}))})],I=(y.invariants?.length??0)>0,S=ns({hasEnforcedInvariant:Sn(y.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),w=S.length>0?[]:ts({adopted:e.adopted===!0,hasDomainInvariants:vn(y.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),T=[...S.map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.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})),...w.map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.message,nextAction:"Add coverage.testGlobs or coverage.coverageRoots in ark.config.json pointing at a real tests folder, then re-run. Adopted mode fails closed until that path is present.",failsStrict:!0,freezable:!1}))],q=A.filter(u=>u.failsStrict).map(u=>Qs(u,eo(u,!1))),Q=A.filter(u=>!u.failsStrict).map(u=>({...Qs(u,eo(u,!0)),failsStrict:!1})),Y=I?Qr({arkRules:y,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},b=Y.violations.filter(u=>u.failsStrict).map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.message,fromLayer:u.fromLayer,arkruleId:u.arkruleId,arkruleSource:u.arkruleSource,nextAction:`Add a test title or declared symbol covering ${u.arkruleId} (declared in ${u.arkruleSource}), then preflight again.`})),V=Y.violations.filter(u=>!u.failsStrict).map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.message,fromLayer:u.fromLayer,arkruleId:u.arkruleId,arkruleSource:u.arkruleSource,failsStrict:!1,nextAction:u.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${u.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${u.arkruleId} in ${u.arkruleSource} (advisory / partial).`})),Ge=rs(i),de=fs({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:a(u=>l.get(u)??te(u,e.contract.config.layers),"layerForFile"),classification:Ge}),Oe=e.contract.config.arkRun?.mode,se=de.findings.filter(()=>Oe==="enforced").map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.message,fromLayer:u.fromLayer,target:u.target,nextAction:u.nextAction,sensor:u.sensor,failsStrict:u.failsStrict,...u.severity?{severity:u.severity}:{}})),Be=de.findings.filter(()=>Oe!=="enforced").map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.message,fromLayer:u.fromLayer,target:u.target,nextAction:u.nextAction,sensor:u.sensor,failsStrict:!1})),ue=Rs({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,xiTtlKeys:t.arkOrderXiTtlKeys,budgetLeaks:t.arkOrderBudgetLeaks,dependencies:t.dependencies,layerForFile:a(u=>l.get(u)??te(u,e.contract.config.layers),"layerForFile"),classification:Ge}),Gt=e.contract.config.arkOrder?.mode,ut=ue.findings.filter(()=>Gt==="enforced").map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.message,fromLayer:u.fromLayer,target:u.target,nextAction:u.nextAction,sensor:u.sensor,failsStrict:u.failsStrict,...u.severity?{severity:u.severity}:{}})),Xn=ue.findings.filter(()=>Gt!=="enforced").map(u=>({ruleId:u.ruleId,file:u.file,line:u.line,message:u.message,fromLayer:u.fromLayer,target:u.target,nextAction:u.nextAction,sensor:u.sensor,failsStrict:!1})),ze=[...Y.partial&&Y.coverage.some(u=>u.mode==="enforced"&&u.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."}]:[],...de.completenessReasons,...ue.completenessReasons],ve=ot({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(u=>u.layer).map(u=>u.path),contentViolations:[...Ul(e,t,l),...q,...T,...b,...se,...ut],edges:c,warnings:[...f,...h.warnings,...Q,...V,...Be,...Xn],safety:h.report}),ft=o==="complete"&&ze.length>0?"partial":o,zt=ft==="complete"?s:[...s,...ze].sort((u,_)=>{let M=`${u.code}\0${u.file??""}\0${u.message}`,ee=`${_.code}\0${_.file??""}\0${_.message}`;return M<ee?-1:M>ee?1:0}),v=ve.violations.filter(u=>u.failsStrict!==!1),C=ft==="complete"&&v.length===0,m=C&&ve.warnings.every(u=>u.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:ft,completenessReasons:zt,valid:C,strictValid:m,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(u=>u.name),edges:c,capabilityUses:t.capabilityUses,violations:ve.violations,warnings:ve.warnings}}}a(je,"analyzeCanonicalResolvedProject");function Vl(e){return je({contract:e.contract,facts:Se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints,adopted:e.adopted,invariantTestsPathPresent:e.invariantTestsPathPresent,coverageRootsPresent:e.coverageRootsPresent,arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion})}a(Vl,"analyzeResolvedProject");function Z(e){return`${e.from}->${e.to}`}a(Z,"dependencyKey");function it(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.`}:{}}}a(it,"dependencyFinding");function at(e){let t=[],n=new Map(e.changeMap.map.files.map(p=>[p.path,p])),r=new Map(e.changes.map(p=>[p.path,p])),o=new Map(e.changeMap.map.dependencies.map(p=>[Z(p),p])),s=new Map(e.baseDependencies.map(p=>[Z(p),p])),i=new Map(e.candidateDependencies.map(p=>[Z(p),p]));for(let p of[...n.values()].sort((R,d)=>R.path.localeCompare(d.path))){let R=r.get(p.path);R?R.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:R.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${R.operation}.`,nextAction:`Change ${p.path} to the planned ${p.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${p.path}`,classification:"satisfied",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:R.operation,message:`${p.path} matches the planned ${p.operation} operation.`}):t.push({id:`missing:file:${p.path}`,classification:"missing",subject:"file",path:p.path,expectedOperation:p.operation,message:`${p.path} was planned as ${p.operation} but is absent from the actual change.`,nextAction:`${p.operation[0].toUpperCase()}${p.operation.slice(1)} ${p.path} in the complete change set, then preflight again.`})}for(let p of[...r.values()].sort((R,d)=>R.path.localeCompare(d.path)))n.has(p.path)||t.push({id:`unplanned:file:${p.path}`,classification:"unplanned",subject:"file",path:p.path,actualOperation:p.operation,message:`${p.path} has an unplanned ${p.operation} operation.`,nextAction:`Remove ${p.path} from the change set, then preflight again.`});let l=new Set;for(let p of[...o.values()].sort((R,d)=>Z(R).localeCompare(Z(d)))){if(i.has(Z(p))){t.push(it("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let R={from:p.to,to:p.from};i.has(Z(R))?(l.add(Z(R)),t.push(it("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(it("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,R]of[...i].sort(([d],[g])=>d.localeCompare(g)))s.has(p)||o.has(p)||l.has(p)||!c.has(R.from)&&!c.has(R.to)||t.push({...it("unplanned",R,`${R.from} -> ${R.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,R]of[...s].sort(([d],[g])=>d.localeCompare(g)))i.has(p)||f.has(R.from)||f.has(R.to)||!c.has(R.from)&&!c.has(R.to)||t.push({...it("unplanned",R,`${R.from} -> ${R.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((p,R)=>h[p.classification]-h[R.classification]||(p.subject===R.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(R.id));let y={satisfied:t.filter(p=>p.classification==="satisfied").length,missing:t.filter(p=>p.classification==="missing").length,contradictory:t.filter(p=>p.classification==="contradictory").length,unplanned:t.filter(p=>p.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:y.missing===0&&y.contradictory===0&&y.unplanned===0,behavioralCompletion:"not-evaluated",summary:y,findings:t}}a(at,"analyzeArchitectureConvergence");function Gl(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}a(Gl,"canonicalChangePath");function Bl(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,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}a(Bl,"identityViolations");function zl(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}a(zl,"preparedChange");function Dt(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}a(Dt,"isArkRulesPlaneRule");function no(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,e.file??"",t,e.target??e.message].join("|")}a(no,"ratchetKey");function ro(e,t){let n=new Map;for(let r of e){if(!Dt(r.ruleId)||r.failsStrict===!1)continue;let o=no(r);n.set(o,(n.get(o)??0)+1)}return t.map(r=>{if(!Dt(r.ruleId))return r;let o=no(r),s=n.get(o)??0;return s===0?r:(n.set(o,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}a(ro,"ratchetPreExistingArkRules");function Wl(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>Dt(n.ruleId)),warnings:e.ir.warnings.filter(n=>Dt(n.ruleId))}}}a(Wl,"baseAnalysisSummary");function Pn(e){return Fn(e,Se(e.baseFacts),Se(e.candidateFacts))}a(Pn,"preflightResolvedChange");function Fn(e,t,n){let r=Wl(je({...e.baseAnalysisInputs??{},contract:e.contract,facts:t}),e.changeMap!==void 0),o=je({...e.candidateAnalysisInputs??{},contract:e.contract,facts:n}),s=new Map(t.files.map(g=>[g.path,g])),i=new Map(n.files.map(g=>[g.path,g])),l=Bl(t,n),c=new Map,f=[];for(let g of e.changes){let A=Gl(g.path);if(!A){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(A)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:A,line:1,message:`The atomic change set contains more than one operation for ${A}.`});continue}c.set(A,g);let I=s.get(A),S=i.get(A);if("delete"in g&&g.delete)I||l.push({ruleId:"DELETE_TARGET_MISSING",file:A,line:1,message:`Cannot delete ${A} because it is not present in the supplied base facts.`}),S&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:A,line:1,message:`Candidate facts still contain deleted file ${A}.`});else{let w="content"in g?g.content:"",T=B(w);S?S.contentHash!==T&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:A,line:1,expectedContentHash:T,candidateContentHash:S.contentHash,message:`Candidate facts for ${A} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:A,line:1,message:`Candidate facts do not contain changed file ${A}.`})}f.push(zl(g,A,s,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let g of new Set([...s.keys(),...i.keys()])){if(c.has(g))continue;let A=s.get(g),I=i.get(g);A&&I&&j(A)===j(I)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:g,line:1,message:`Candidate facts change ${g}, but the atomic change set does not declare it.`})}let h=e.changeMap?at({changeMap:e.changeMap,changes:f,baseDependencies:r.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[]),candidateDependencies:o.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[])}):void 0,y=ro(r.ir.violations,o.ir.violations),p=ro(r.ir.warnings,o.ir.warnings),R=[...l,...y].map(g=>({...g,nextAction:ke(g)})),d=R.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.completeness==="complete"&&p.every(g=>g.failsStrict===!1)&&d.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:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:f.sort((g,A)=>g.path<A.path?-1:g.path>A.path?1:0),violations:R,warnings:p}}a(Fn,"preflightCanonicalChange");var Dn="1.0";var Mt=class extends Error{static{a(this,"ArchitectureChangeMapValidationError")}issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
|
|
13
17
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
14
|
-
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Jt,"isObject");function Zt(e,t,n,r){for(let s of Object.keys(e))t.includes(s)||r.push({path:`${n}.${s}`,message:"unknown field"})}a(Zt,"unknownFields");function be(e,t,n,r){let s=e[t];if(typeof s=="string"&&s.length>0)return s;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}a(be,"requiredString");function qi(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}a(qi,"canonicalProjectPath");function Yi(e,t,n="architecture change map"){let r=[];if(!Jt(e))throw new Rt(n,[{path:"$",message:"must be an object"}]);Zt(e,["$schema","schemaVersion","files","dependencies"],"$",r);let s=be(e,"$schema","$",r),o=be(e,"schemaVersion","$",r);o&&o!==Xt&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${Xt}`});let i=new Set(t.layers.map(d=>d.name)),l=[],c=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((d,g)=>{let k=`$.files[${g}]`;if(!Jt(d)){r.push({path:k,message:"must be an object"});return}Zt(d,["path","operation","layer"],k,r);let I=be(d,"path",k,r),S=be(d,"operation",k,r),x=be(d,"layer",k,r),$=I?qi(I):void 0;I&&!$&&r.push({path:`${k}.path`,message:"must be a canonical project-relative path"}),S&&!["create","update","delete"].includes(S)&&r.push({path:`${k}.operation`,message:"must be create, update, or delete"}),x&&!i.has(x)&&r.push({path:`${k}.layer`,message:`references unknown layer ${JSON.stringify(x)}`}),$&&c.has($)&&r.push({path:`${k}.path`,message:`duplicates planned path ${$}`}),$&&c.add($);let q=$?Q($,t.layers):void 0;$&&x&&i.has(x)&&q!==x&&r.push({path:`${k}.layer`,message:q?`${$} resolves to ${q}, not ${x}`:`${$} is not assigned to an architecture layer`}),$&&S&&["create","update","delete"].includes(S)&&x&&l.push({path:$,operation:S,layer:x})});let f=[],h=new Map(l.map(d=>[d.path,d.operation])),R=new Set,u=e.dependencies??[];if(Array.isArray(u)?u.forEach((d,g)=>{let k=`$.dependencies[${g}]`;if(!Jt(d)){r.push({path:k,message:"must be an object"});return}Zt(d,["from","to"],k,r);let I=be(d,"from",k,r),S=be(d,"to",k,r);I&&!c.has(I)&&r.push({path:`${k}.from`,message:`must reference a planned file path: ${I}`}),S&&!c.has(S)&&r.push({path:`${k}.to`,message:`must reference a planned file path: ${S}`}),I&&h.get(I)==="delete"&&r.push({path:`${k}.from`,message:`cannot depend from deleted file ${I}`}),S&&h.get(S)==="delete"&&r.push({path:`${k}.to`,message:`cannot depend on deleted file ${S}`}),I&&S&&I===S&&r.push({path:k,message:"must not declare a self dependency"});let x=I&&S?`${I}\0${S}`:void 0;x&&R.has(x)&&r.push({path:k,message:`duplicates dependency ${I} -> ${S}`}),x&&R.add(x),I&&S&&f.push({from:I,to:S})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new Rt(n,r);let p={$schema:s,schemaVersion:Xt,files:l.sort((d,g)=>d.path.localeCompare(g.path)),dependencies:f.sort((d,g)=>d.from.localeCompare(g.from)||d.to.localeCompare(g.to))};return{map:p,hash:V(F(p))}}a(Yi,"loadArchitectureChangeMap");function J(e){return`${e.from}->${e.to}`}a(J,"dependencyKey");function Ze(e,t,n,r="dependency"){return{id:`${e}:${r}:${J(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${J(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${J(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${J(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${J(t)} from the candidate, then preflight again.`}:{}}}a(Ze,"dependencyFinding");function Qe(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),s=new Map(e.changeMap.map.dependencies.map(u=>[J(u),u])),o=new Map(e.baseDependencies.map(u=>[J(u),u])),i=new Map(e.candidateDependencies.map(u=>[J(u),u]));for(let u of[...n.values()].sort((p,d)=>p.path.localeCompare(d.path))){let p=r.get(u.path);p?p.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:p.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${p.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:p.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((p,d)=>p.path.localeCompare(d.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...s.values()].sort((p,d)=>J(p).localeCompare(J(d)))){if(i.has(J(u))){t.push(Ze("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let p={from:u.to,to:u.from};i.has(J(p))?(l.add(J(p)),t.push(Ze("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ze("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,p]of[...i].sort(([d],[g])=>d.localeCompare(g)))o.has(u)||s.has(u)||l.has(u)||!c.has(p.from)&&!c.has(p.to)||t.push({...Ze("unplanned",p,`${p.from} -> ${p.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let f=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,p]of[...o].sort(([d],[g])=>d.localeCompare(g)))i.has(u)||f.has(p.from)||f.has(p.to)||!c.has(p.from)&&!c.has(p.to)||t.push({...Ze("unplanned",p,`${p.from} -> ${p.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,p)=>h[u.classification]-h[p.classification]||(u.subject===p.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(p.id));let R={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:R.missing===0&&R.contradictory===0&&R.unplanned===0,behavioralCompletion:"not-evaluated",summary:R,findings:t}}a(Qe,"analyzeArchitectureConvergence");function Le(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Le,"literalText");function Gr(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(Gr,"lineOf");function jr(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let s=r.namedBindings;return!!(s&&e.isNamedImports(s)&&s.elements.length>0&&s.elements.every(o=>o.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}a(jr,"isTypeOnlyReference");function Br(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=s=>s===t.fileName?t:void 0,r.fileExists=s=>s===t.fileName,r.readFile=s=>s===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}a(Br,"singleFileChecker");function Qt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Qt,"symbolAt");function en(e,t,n,r){let s=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,o;try{o=s?t.getShorthandAssignmentValueSymbol(r.parent):Qt(t,r)}catch{o=void 0}return!!o?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(en,"localDeclaration");function tn(e,t){let n,r=[],s=a((i,l,c,f=!1)=>r.push({specifier:c,kind:l,line:Gr(t,i),typeOnly:f,unresolved:c===void 0,node:i}),"add"),o=a(i=>{if(e.isImportDeclaration(i))s(i,"import",Le(e,i.moduleSpecifier),jr(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)s(i,"export",Le(e,i.moduleSpecifier),jr(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))s(i,"require",Le(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!en(e,n??(n=Br(e,t)),t,i.expression);(l||f)&&s(i,f?"require":"dynamic-import",Le(e,i.arguments[0]))}e.forEachChild(i,o)},"visit");return o(t),r}a(tn,"extractSemanticDependencies");function Xi(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let s=Le(e,r.argumentExpression);if(s===void 0)return;n.unshift(s)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}a(Xi,"staticAccessPath");function Ji(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}a(Ji,"runtimeIdentifierReference");function Vr(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let s=n.slice(0,r).join(".");if(e.has(s))return s}}a(Vr,"bestForbiddenMatch");function nn(e,t,n){if(n.length===0)return[];let r=new Set(n),s=Br(e,t),o=new Map,i=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let p of u.declarationList.declarations)e.isIdentifier(p.name)&&i.add(p.name.text);let l=a(u=>{let p=Xi(e,u);if(!p)return;let d=Qt(s,p.root),g=d?o.get(d):void 0;return g?[...g,...p.segments.slice(1)]:en(e,s,t,p.root)||i.has(p.root.text)?void 0:p.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let p of u.declarationList.declarations){if(!p.initializer||!e.isIdentifier(p.name))continue;let d=l(p.initializer),g=Qt(s,p.name);!d||!g||o.set(g,d)}let c=[],f=new Set,h=a((u,p)=>{let d=Gr(t,p),g=`${u}:${p.getStart(t)}`;f.has(g)||(f.add(g),c.push({name:u,line:d,node:p}))},"flag"),R=a(u=>{let p=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!p){let d=l(u),g=d?Vr(r,d):void 0;g&&h(g,u)}else e.isIdentifier(u)&&r.has(u.text)&&Ji(e,u)&&!en(e,s,t,u)&&h(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let d=l(u.initializer);if(d)for(let g of u.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?Le(e,g.propertyName)??g.propertyName.text:g.name.text,I=Vr(r,[...d,k]);I&&h(I,u.initializer)}}e.forEachChild(u,R)},"visit");return R(t),c}a(nn,"collectForbiddenCapabilityUses");function Zi(e,t,n){let r=[];for(let s of n?.dependencies??tn(e,t)){if(s.typeOnly||!s.specifier)continue;let o=Ue(s.specifier);o&&r.push({capability:o,symbol:s.specifier,line:s.line,source:"import-based"})}for(let s of n?.ambientUses??nn(e,t,Ct)){let o=je(s.name);o&&r.push({capability:o,symbol:s.name,line:s.line,source:"ambient-global"})}return r.sort((s,o)=>s.line-o.line||s.capability.localeCompare(o.capability)||s.symbol.localeCompare(o.symbol))}a(Zi,"collectCapabilityUses");function rn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:s,...o}=t;return o})}}a(rn,"omitLayerDescriptions");function Wr(e){let{stewards:t,...n}=rn(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}a(Wr,"effectiveContractPolicyPayload");var ts="1.0",Qi="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function E(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Qi}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}a(E,"addFinding");function P(e){return[...new Set(e??[])].sort()}a(P,"sortedUnique");function re(e,t,n,r,s){let o=P(n),i=P(r),l=new Set(o),c=new Set(i),f=i.filter(R=>!l.has(R)),h=o.filter(R=>!c.has(R));f.length===0&&h.length===0||(f.length>0&&E(e,{kind:"added",path:t,classification:s.added,message:s.addedMessage,before:o,after:i}),h.length>0&&E(e,{kind:"removed",path:t,classification:s.removed,message:s.removedMessage,before:o,after:i}))}a(re,"compareStringSets");function et(e,t,n,r,s,o,i){if(n===r)return;E(e,{kind:r?"enabled":"disabled",path:t,classification:r?s:s==="strengthening"?"weakening":"strengthening",message:r?o:i,before:n,after:r})}a(et,"compareBoolean");function At(e,t){let n=new Map,r=new Set;for(let s of e){let o=t(s);n.has(o)?r.add(o):n.set(o,s)}return{values:n,duplicates:[...r].sort()}}a(At,"keyed");function ea(e,t,n){let r=At(t,o=>o.name),s=At(n,o=>o.name);(r.duplicates.length>0||s.duplicates.length>0)&&E(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:s.duplicates});for(let o of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let i=r.values.get(o),l=s.values.get(o),c=`$.layers[${o}]`;if(!i&&l){E(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){E(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;re(e,`${c}.patterns`,i.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),re(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=at(i),h=at(l);re(e,`${c}.forbiddenGlobals`,f.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),re(e,`${c}.capabilities`,f.atoms,h.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),P(i.intentPrefixes).join("\0")!==P(l.intentPrefixes).join("\0")&&E(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:P(i.intentPrefixes),after:P(l.intentPrefixes)}),et(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),et(e,`${c}.optional`,i.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}a(ea,"compareLayers");function ta(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),s=At(t,r),o=At(n,r);(s.duplicates.length>0||o.duplicates.length>0)&&E(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:s.duplicates,after:o.duplicates});for(let i of[...new Set([...s.values.keys(),...o.values.keys()])].sort()){let l=s.values.get(i),c=o.values.get(i),f=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?E(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):E(e,{kind:"allow-added",path:f,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&E(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&E(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let h=l.peerIsolation===!0,R=c.peerIsolation===!0;if(h!==R){let d=l.from===l.to&&c.from===c.to;E(e,{kind:R?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.peerIsolation`,classification:d?R?"strengthening":"weakening":"judgment-required",message:d?R?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:h,after:R})}P(l.sliceFolders).join("\0")!==P(c.sliceFolders).join("\0")&&E(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:P(l.sliceFolders),after:P(c.sliceFolders)});let u=l.sliceIdentity??"path",p=c.sliceIdentity??"path";if(u!==p&&E(e,{kind:"slice-identity-changed",path:`${f}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:u,after:p}),!(!h&&!R)){if(ln(e,`${f}.sharedRoots`,"shared-roots",P(l.sharedRoots),P(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),ln(e,`${f}.allowedCrossSlice`,"cross-slice-allowance",P((l.allowedCrossSlice??[]).map(an)),P((c.allowedCrossSlice??[]).map(an)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."),(l.sharedImportsSlice??null)!==(c.sharedImportsSlice??null)){let d=l.sharedImportsSlice??null,g=c.sharedImportsSlice??null,k=es(g)>es(d);E(e,{kind:"shared-imports-slice",path:`${f}.sharedImportsSlice`,classification:k?"strengthening":"weakening",message:ga(d,g),before:d,after:g})}ra(e,f,l,c)}}}a(ta,"compareRules");function zr(e){let t=e.childSlices;return t?JSON.stringify([P(t.sliceFolders??[]),t.sliceIdentity??"path",P(t.commonFolders??[])]):""}a(zr,"childSliceFoldersKey");function na(e){return P((e??[]).map(t=>kt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(na,"enforceKeys");function qr(e){if(!e.childSlices)return null;let t=e.childSlices.siblings;return t==null||t==="deny"?{mode:"deny",enforce:[]}:t==="advisory"?{mode:"advisory",enforce:[]}:t.default==="deny"?{mode:"deny",enforce:[]}:{mode:"advisory",enforce:na(t.enforce)}}a(qr,"childSliceSiblingPolicy");function ra(e,t,n,r){let s=qr(n),o=qr(r);if(s===null&&o===null)return;if(s===null&&o!==null){E(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:o.mode==="advisory"?"judgment-required":"strengthening",message:o.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(s!==null&&o===null){E(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(zr(n)!==zr(r)){E(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(s===null||o===null)return;if(s.mode!==o.mode){let c=o.mode==="advisory";E(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?o.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:s.mode,after:o.mode})}else s.mode==="advisory"&&sa(e,`${t}.childSlices.siblings.enforce`,s.enforce,o.enforce);let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&E(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:i,after:l}),la(e,t,n,r),aa(e,t,n,r)}a(ra,"compareChildSlices");function sa(e,t,n,r){if(JSON.stringify(n)===JSON.stringify(r))return;let s=r.filter(l=>!n.includes(l)),o=n.filter(l=>!r.includes(l)),i=s.length>0&&o.length>0;E(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":s.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":s.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(sa,"compareSiblingEnforceList");function an(e){return JSON.stringify([e.from,e.to])}a(an,"crossSliceKey");function Yr(e){return P((e.childSlices?.allowedCrossSlice??[]).map(an))}a(Yr,"childCrossSliceKeys");function Fe(e){return kt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Fe,"allowanceSegments");function Xr(e,t){let n=Fe(e),r=Fe(t);if(n.length===0||n.length!==r.length)return!1;let s=!1;for(let o=0;o<n.length;o+=1)if(n[o]!==r[o]){if(n[o]==="*"&&r[o]!=="*"){s=!0;continue}return!1}return s}a(Xr,"patternWidens");function oa(e,t){let n=JSON.parse(e),r=JSON.parse(t),s=Fe(n[0]).join("/")===Fe(r[0]).join("/"),o=Fe(n[1]).join("/")===Fe(r[1]).join("/"),i=Xr(n[0],r[0]),l=Xr(n[1],r[1]);return!(s||i)||!(o||l)?!1:i||l}a(oa,"allowanceWidens");function ia(e){return JSON.stringify([kt(e.from.trim().replace(/\\/g,"/")).toLowerCase(),kt(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(ia,"aliasEntryKey");function Jr(e){return P((e.childSlices?.sliceAliases??[]).map(ia))}a(Jr,"sliceAliasKeys");function aa(e,t,n,r){let s=Jr(n),o=Jr(r);if(JSON.stringify(s)===JSON.stringify(o))return;let i=o.filter(f=>!s.includes(f)),l=s.filter(f=>!o.includes(f)),c=i.length>0&&l.length>0;E(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:s,after:o})}a(aa,"compareSliceAliases");function la(e,t,n,r){let s=Yr(n),o=Yr(r);if(JSON.stringify(s)===JSON.stringify(o))return;let i=o.filter(c=>!s.includes(c)),l=s.filter(c=>!o.includes(c));if(i.length>0&&l.length>0&&l.filter(f=>!i.some(h=>oa(h,f))).length===0){E(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:s,after:o});return}ln(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",s,o,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}a(la,"compareChildCrossSliceAllowances");function ln(e,t,n,r,s,o,i){if(JSON.stringify(r)===JSON.stringify(s))return;let l=s.filter(h=>!r.includes(h)),c=r.filter(h=>!s.includes(h)),f=l.length>0&&c.length>0;E(e,{kind:f?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:f?"judgment-required":l.length>0?"weakening":"strengthening",message:f?`${o} Entries were added and removed in the same change.`:l.length>0?o:i,before:r,after:s})}a(ln,"compareDeclaredExceptions");function ca(e,t,n){let r=t.safety??{},s=n.safety??{};for(let o of["maxTsSuppressions","maxAnyCasts"]){let i=r[o]??0,l=s[o]??0;i!==l&&E(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${o}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let o of["allowInMemory","allowDisabledPeerIsolation"])et(e,`$.safety.${o}`,r[o]===!0,s[o]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(ca,"compareSafety");function sn(e){return e.mode==="enforced"?"enforced":"advisory"}a(sn,"arkRunMode");function on(e){return e.mode==="enforced"?"enforced":"advisory"}a(on,"arkOrderMode");function da(e,t,n){let r=t.arkOrder,s=n.arkOrder,o="$.arkOrder";if(!r&&!s)return;if(!r&&s){E(e,{kind:"arkorder-added",path:o,classification:"strengthening",message:`ArkOrder extra was added (${on(s)}).`,after:s});return}if(r&&!s){E(e,{kind:"arkorder-removed",path:o,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!s)return;let i=on(r),l=on(s);if(i!==l){let c=i==="advisory"&&l==="enforced";E(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}re(e,`${o}.planeRoots`,r.planeRoots,s.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),re(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(da,"compareArkOrder");function ua(e,t,n){let r=t.arkRun,s=n.arkRun,o="$.arkRun";if(!r&&!s)return;if(!r&&s){E(e,{kind:"arkrun-added",path:o,classification:"strengthening",message:`ArkRun extra was added (${sn(s)}).`,after:s});return}if(r&&!s){E(e,{kind:"arkrun-removed",path:o,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!s)return;let i=sn(r),l=sn(s);if(i!==l){let c=i==="advisory"&&l==="enforced";E(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${o}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}re(e,`${o}.compositionRoots`,r.compositionRoots,s.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),re(e,`${o}.managedLayers`,r.managedLayers,s.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),et(e,`${o}.requireDeclarations`,r.requireDeclarations!==!1,s.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(ua,"compareArkRun");function fa(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}a(fa,"overallClassification");function Zr(e,t){return`${e}::${t}`}a(Zr,"ruleKey");function Qr(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Zr(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Zr(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Qr,"indexEffectiveRules");function pa(e,t,n,r,s,o){let i=new Map((o??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},f=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of f){let p=l[u],d=c[u],g=`$.arkRules[${u}]`;if(p===void 0&&d!==void 0){E(e,{kind:"arkrules-ref-added",path:g,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:d});continue}if(p!==void 0&&d===void 0){E(e,{kind:"arkrules-ref-removed",path:g,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:p});continue}p!==d&&E(e,{kind:"arkrules-ref-path-changed",path:g,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:p,after:d})}let h=Qr(r),R=Qr(s);for(let u of[...new Set([...h.structure.keys(),...R.structure.keys()])].sort()){let p=h.structure.get(u),d=R.structure.get(u),g=`$.arkRules.structure[${u}]`;if(!p&&d){E(e,{kind:"arkrule-structure-added",path:g,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(p&&!d){E(e,{kind:"arkrule-structure-removed",path:g,classification:"weakening",message:`Structure ArkRule ${p.id} was removed.`,before:p});continue}if(!(!p||!d)){if(p.mode!==d.mode){let k=p.mode==="advisory"&&d.mode==="enforced";E(e,{kind:k?"arkrule-promoted":"arkrule-demoted",path:`${g}.mode`,classification:k?"strengthening":"weakening",message:k?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:p.mode,after:d.mode})}p.sensor!==d.sensor&&E(e,{kind:"arkrule-sensor-changed",path:`${g}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:p.sensor,after:d.sensor})}}for(let u of[...new Set([...h.invariants.keys(),...R.invariants.keys()])].sort()){let p=h.invariants.get(u),d=R.invariants.get(u),g=`$.arkRules.invariants[${u}]`;if(!p&&d){E(e,{kind:"arkrule-invariant-added",path:g,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(p&&!d){E(e,{kind:"arkrule-invariant-removed",path:g,classification:"weakening",message:`Invariant ${p.id} was removed.`,before:p});continue}if(!(!p||!d)&&p.mode!==d.mode)if(p.mode==="advisory"&&d.mode==="enforced"){let I=i?.get(d.id),S=tr(I);S.ok?E(e,{kind:"arkrule-invariant-promoted",path:`${g}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:p.mode,after:d.mode}):E(e,{kind:"arkrule-invariant-promote-refused",path:`${g}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${S.reason}`,before:p.mode,after:d.mode})}else E(e,{kind:"arkrule-invariant-demoted",path:`${g}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:p.mode,after:d.mode})}}a(pa,"compareArkRules");function ns(e,t,n){let r=[];re(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),re(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),re(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),et(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},o=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(o!==i){let l=s[i]===s[o]?"judgment-required":s[i]>s[o]?"strengthening":"weakening";E(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:o,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&E(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),ea(r,e.layers,t.layers),ta(r,e.rules,t.rules),ca(r,e,t),pa(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),ua(r,e,t),da(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:ts,classification:fa(r),findings:r}}a(ns,"classifyArkPolicyDelta");function rs(e,t){if(!e||e.schemaVersion!==ts||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(s=>typeof s!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=P(e.findingIds),r=P(t.findingIds);return n.length===r.length&&n.every((s,o)=>s===r[o])}a(rs,"policyDeltaAcknowledgementMatches");function kt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(kt,"trimTrailingSlashes");function es(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(es,"sharedImportsSliceRank");function ga(e,t){return t==="deny"?"A shared root may no longer import a slice.":e==="deny"&&t==="deny-cross-parent"?"A shared root may import a slice again, except when that hop carries another universe.":e==="deny"?"A shared root may import a slice again.":t==="deny-cross-parent"?"A slice may no longer reach another universe through a shared root. ark-check and CI report that path. The write hook and ESLint see one edge at a time and do not block it.":"A slice may reach another universe through a shared root again."}a(ga,"sharedImportsSliceMessage");function ve(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(ve,"normalizePath");function ss(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(ss,"isIdentifierStart");function bt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(bt,"isIdentifierCharacter");function Z(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(Z,"skipWhitespace");function tt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,s="";for(t+=1;t<e.length;t+=1){let o=e[t];if(o===n)return{value:s,offset:r,excerpt:e.slice(r,t+1)};o==="\\"&&t+1<e.length?(s+=e[t+1],t+=1):s+=o}}a(tt,"readString");function ee(e,t,n){return e.startsWith(t,n)&&!bt(e[n-1])&&!bt(e[n+t.length])}a(ee,"isWordAt");function os(e,t){let n=Z(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=Z(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ee(e,"type",n))return!1;let s=Z(e,n+4);if(s>=e.length||e[s]===","||e[s]==="}"||ee(e,"as",s)||!ss(e[s]))return!1;for(n=s;n<e.length&&bt(e[n]);)n+=1;if(n=Z(e,n),ee(e,"as",n)){if(n=Z(e,n+2),!ss(e[n]))return!1;for(;n<e.length&&bt(e[n]);)n+=1}r=!0}return!1}a(os,"bracedNamedBindingsAreTypeOnly");function ma(e,t){if(t=Z(e,t+6),e[t]==="(")return tt(e,Z(e,t+1));let n=!1;if(ee(e,"type",t)){let s=Z(e,t+4);e[s]!==","&&!ee(e,"from",s)&&(n=!0)}else os(e,t)&&(n=!0);let r=is(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(ma,"specifierAfterImport");function ha(e,t){t=t+6;let n=Z(e,t),r=!1;if(ee(e,"type",n)){let o=Z(e,n+4);(e[o]==="{"||e[o]==="*")&&(r=!0)}else os(e,n)&&(r=!0);let s=is(e,t,!1);return s&&r?{...s,typeOnly:!0}:s}a(ha,"specifierAfterExport");function is(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ee(e,"from",t))return tt(e,Z(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return tt(e,t);if(t>0&&(ee(e,"import",t)||ee(e,"export",t)))return}}a(is,"specifierInStaticStatement");function ya(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}a(ya,"skipTemplateLiteral");function Ra(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=Z(e,t+7);if(e[r]!=="(")return;r=Z(e,r+1);let s=tt(e,r);return s?{...s,requireCall:!0}:void 0}a(Ra,"specifierAfterRequire");function Aa(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
15
|
-
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let
|
|
16
|
-
`).length;r.push({file:e.path,symbol:
|
|
17
|
-
`).length,l={kind:"import",file:e.path,line:i,excerpt:s.excerpt},c=ka(e.path,o,t);n.push({from:e.path,specifier:o,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}a(as,"moduleFactsFor");function ka(e,t,n){let r=e.split("/");r.pop();for(let o of t.split("/"))o==="."||o===""||(o===".."?r.pop():r.push(o));let s=r.join("/");for(let o of[s,`${s}.ts`,`${s}.tsx`,`${s}.mts`,`${s}.cts`,`${s}/index.ts`,`${s}/index.tsx`]){let i=n.get(o);if(i)return i}}a(ka,"resolveSpecifier");function ls(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let s=_n(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});s&&n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:s.message??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(ls,"violationsFor");var ba={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function va(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(va,"hasActiveArkRules");function Sa(e,t){return va(e,t)?V(F(Wr({config:e,arkRules:t,warnings:[]}))):V(F(rn(e)))}a(Sa,"policyHashFor");function cn(e,t,n){let r=typeof e=="string"?Pr(e,t):Wt(e,t),s=n?.arkRules??ze();return{...r,arkRules:s,policyHash:Sa(r.config,s)}}a(cn,"loadContract");function Ia(e){let t=cn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=cn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=ns(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),s=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),o=s.length>0,i=o&&rs(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:s});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:s,requiresAcknowledgement:o,acknowledged:i,valid:!o||i}}a(Ia,"analyzePolicyDelta");function vt(e){let t=e.files.map(R=>{let u=ve(R.path);return{path:u,content:R.content,contentHash:V(R.content),layer:Q(u,e.contract.config.layers)??null}}).sort((R,u)=>R.path.localeCompare(u.path)),n=new Map(t.map(R=>[R.path,R])),r=[],s=[];for(let R of t){let u=as(R,n);r.push(...u.edges),s.push(...u.capabilityUses)}let o=ls(r,e.contract.config),i=new Map(e.contract.config.layers.map(R=>[R.name,R])),l=new Map(e.contract.config.layers.map(R=>[R.name,new Set(Ce(R))]));for(let R of s){let u=n.get(R.file)?.layer;if(!u)continue;let p=i.get(u),d=Ke(R.symbol,p?.forbiddenGlobals??[]);if(d){o.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${R.symbol}" because it is the import form of forbidden global "${d}".`,symbol:R.symbol,evidence:R.evidence});continue}l.get(u)?.has(R.capability)&&o.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${R.capability} capability; found import of "${R.symbol}".`,capability:R.capability,symbol:R.symbol,evidence:R.evidence})}let c=t.length===0?"complete":"partial",f=c==="complete"?[]:[{...ba}],h={schemaVersion:Rn,policyHash:e.contract.policyHash,compilerOptionsHash:V(F(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(R=>R.name),edges:r,capabilityUses:s,violations:o};return{mode:"lexical-compatibility",completeness:c,completenessReasons:f,valid:c==="complete"&&o.length===0,ir:h}}a(vt,"analyzeProject");function dn(e){let t=new Map(e.files.map(n=>[ve(n.path),n]));for(let n of e.changes){let r=ve(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return vt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(dn,"analyzeChange");function Ea(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}a(Ea,"explainViolation");function cs(e){return V(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(cs,"analysisTreeHash");function Ca(e){let t=vt(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],s=new Set,o=[];for(let d of e.changes){let g=d.path.replace(/\\/g,"/"),k=ve(d.path);if(!k||k===".."||k.startsWith("../")||g.startsWith("/")||/^[A-Za-z]:\//.test(g)||g.includes("\0")){o.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(s.has(k)){o.push({ruleId:"DUPLICATE_CHANGE_PATH",file:k,line:1,message:`The atomic change set contains more than one operation for ${k}.`});continue}s.add(k),"delete"in d&&d.delete&&!n.has(k)&&o.push({ruleId:"DELETE_TARGET_MISSING",file:k,line:1,message:`Cannot delete ${k} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:k,delete:!0}:{path:k,content:"content"in d?d.content:""})}e.changes.length===0&&o.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=dn({...e,changes:r}),l=new Map(i.ir.files.map(d=>[d.path,d])),c=i.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let g=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...g?{fromLayer:g}:{},edgeKind:"import",message:d.message}}),f=Je({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(d=>d.path),contentViolations:c,edges:i.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),h=r.map(d=>{let g=ve(d.path),k=n.get(g),I=l.get(g);return{path:g,operation:"delete"in d&&d.delete?"delete":k?"update":"create",...k?{beforeContentHash:k.contentHash}:{},...I?{candidateContentHash:I.contentHash}:{}}}).sort((d,g)=>d.path.localeCompare(g.path)),R=[...o,...f.violations].map(d=>({...d,nextAction:pe(d)})),u=R.filter(d=>d.failsStrict!==!1),p=e.changeMap?Qe({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:i.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&u.length===0&&(p?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:cs(t.ir.files),candidateTreeHash:cs(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...p?{convergence:p}:{},changes:h,violations:R,warnings:f.warnings}}a(Ca,"preflightChange");function wa(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let s of t.split("/"))if(!(!s||s==="."))if(s===".."){if(n.length===0)return;n.pop()}else n.push(s);let r=n.join("/");return r&&r===t?r:void 0}a(wa,"canonicalChangePath");function xa(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,s])=>r!==s).map(([r,s,o])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:s,candidate:o,message:`Base and candidate facts must use the same ${r}.`}))}a(xa,"identityViolations");function Oa(e,t,n,r){let s=n.get(t),o=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":s?"update":"create",...s?{beforeContentHash:s.contentHash}:{},...o?{candidateContentHash:o.contentHash}:{}}}a(Oa,"preparedChange");function _a(e){let t=ye(e.baseFacts),n=ye(e.candidateFacts),r=yt({contract:e.contract,facts:t}),s=yt({contract:e.contract,facts:n}),o=new Map(t.files.map(p=>[p.path,p])),i=new Map(n.files.map(p=>[p.path,p])),l=xa(t,n),c=new Map,f=[];for(let p of e.changes){let d=wa(p.path);if(!d){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(d)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}c.set(d,p);let g=o.get(d),k=i.get(d);if("delete"in p&&p.delete)g||l.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base facts.`}),k&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:d,line:1,message:`Candidate facts still contain deleted file ${d}.`});else{let I="content"in p?p.content:"",S=V(I);k?k.contentHash!==S&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:d,line:1,expectedContentHash:S,candidateContentHash:k.contentHash,message:`Candidate facts for ${d} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:d,line:1,message:`Candidate facts do not contain changed file ${d}.`})}f.push(Oa(p,d,o,i))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let p of new Set([...o.keys(),...i.keys()])){if(c.has(p))continue;let d=o.get(p),g=i.get(p);d&&g&&F(d)===F(g)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:p,line:1,message:`Candidate facts change ${p}, but the atomic change set does not declare it.`})}let h=e.changeMap?Qe({changeMap:e.changeMap,changes:f,baseDependencies:r.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[]),candidateDependencies:s.ir.edges.flatMap(p=>p.to?[{from:p.from,to:p.to}]:[])}):void 0,R=[...l,...s.ir.violations].map(p=>({...p,nextAction:pe(p)})),u=R.filter(p=>p.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&s.strictValid&&u.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:s.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:s.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:f.sort((p,d)=>p.path<d.path?-1:p.path>d.path?1:0),violations:R,warnings:s.ir.warnings}}a(_a,"preflightResolvedChange");var ds=new WeakSet;function us(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))us(t);return Object.freeze(e)}a(us,"deepFreeze");function Cd(e){let t=us(ot(e));return ds.add(t),t}a(Cd,"createTrustedResolvedCandidateFacts");function wd(e){if(!ds.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Yt(e)}a(wd,"analyzeTrustedResolvedProject");export{Ct as AMBIENT_CAPABILITY_ENTRIES,It as CAPABILITY_IDS,Lt as DEFAULT_INTENT_PREFIXES,yn as RESOLVED_CANDIDATE_FACTS_SCHEMA,Ie as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Tt as SOURCE_POLICY_MESSAGES,wt as ambientCoveredByForbiddenGlobals,Qe as analyzeArchitectureConvergence,dn as analyzeChange,Ia as analyzePolicyDelta,vt as analyzeProject,yt as analyzeResolvedProject,wd as analyzeTrustedResolvedProject,je as capabilityForAmbientName,Ue as capabilityForModuleSpecifier,Nt as classifyPublishFacts,zt as collectAnalysisConfigWarnings,Zi as collectCapabilityUses,nn as collectForbiddenCapabilityUses,ot as createResolvedCandidateFacts,Cd as createTrustedResolvedCandidateFacts,Mr as detectArchitectureCycles,V as deterministicHash,Ce as effectiveCapabilityDeny,Je as evaluateArchitectureGraph,Ea as explainViolation,tn as extractSemanticDependencies,Ke as forbiddenGlobalForModuleSpecifier,Yi as loadArchitectureChangeMap,cn as loadContract,ye as loadResolvedCandidateFacts,Ln as looksLikeArkIntent,hs as lowerForbiddenGlobal,at as loweredLayerCoverage,Ca as preflightChange,_a as preflightResolvedChange,Ft as resolveIntentLayer,st as resolvedFactsEvidenceRequirementsHash,F as stableSerialize};
|
|
18
|
+
`)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Mn,"isObject");function Hn(e,t,n,r){for(let o of Object.keys(e))t.includes(o)||r.push({path:`${n}.${o}`,message:"unknown field"})}a(Hn,"unknownFields");function xe(e,t,n,r){let o=e[t];if(typeof o=="string"&&o.length>0)return o;r.push({path:`${n}.${t}`,message:"must be a non-empty string"})}a(xe,"requiredString");function ql(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}a(ql,"canonicalProjectPath");function Yl(e,t,n="architecture change map"){let r=[];if(!Mn(e))throw new Mt(n,[{path:"$",message:"must be an object"}]);Hn(e,["$schema","schemaVersion","files","dependencies"],"$",r);let o=xe(e,"$schema","$",r),s=xe(e,"schemaVersion","$",r);s&&s!==Dn&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${Dn}`});let i=new Set(t.layers.map(d=>d.name)),l=[],c=new Set;!Array.isArray(e.files)||e.files.length===0?r.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((d,g)=>{let A=`$.files[${g}]`;if(!Mn(d)){r.push({path:A,message:"must be an object"});return}Hn(d,["path","operation","layer"],A,r);let I=xe(d,"path",A,r),S=xe(d,"operation",A,r),w=xe(d,"layer",A,r),T=I?ql(I):void 0;I&&!T&&r.push({path:`${A}.path`,message:"must be a canonical project-relative path"}),S&&!["create","update","delete"].includes(S)&&r.push({path:`${A}.operation`,message:"must be create, update, or delete"}),w&&!i.has(w)&&r.push({path:`${A}.layer`,message:`references unknown layer ${JSON.stringify(w)}`}),T&&c.has(T)&&r.push({path:`${A}.path`,message:`duplicates planned path ${T}`}),T&&c.add(T);let q=T?te(T,t.layers):void 0;T&&w&&i.has(w)&&q!==w&&r.push({path:`${A}.layer`,message:q?`${T} resolves to ${q}, not ${w}`:`${T} is not assigned to an architecture layer`}),T&&S&&["create","update","delete"].includes(S)&&w&&l.push({path:T,operation:S,layer:w})});let f=[],h=new Map(l.map(d=>[d.path,d.operation])),y=new Set,p=e.dependencies??[];if(Array.isArray(p)?p.forEach((d,g)=>{let A=`$.dependencies[${g}]`;if(!Mn(d)){r.push({path:A,message:"must be an object"});return}Hn(d,["from","to"],A,r);let I=xe(d,"from",A,r),S=xe(d,"to",A,r);I&&!c.has(I)&&r.push({path:`${A}.from`,message:`must reference a planned file path: ${I}`}),S&&!c.has(S)&&r.push({path:`${A}.to`,message:`must reference a planned file path: ${S}`}),I&&h.get(I)==="delete"&&r.push({path:`${A}.from`,message:`cannot depend from deleted file ${I}`}),S&&h.get(S)==="delete"&&r.push({path:`${A}.to`,message:`cannot depend on deleted file ${S}`}),I&&S&&I===S&&r.push({path:A,message:"must not declare a self dependency"});let w=I&&S?`${I}\0${S}`:void 0;w&&y.has(w)&&r.push({path:A,message:`duplicates dependency ${I} -> ${S}`}),w&&y.add(w),I&&S&&f.push({from:I,to:S})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new Mt(n,r);let R={$schema:o,schemaVersion:Dn,files:l.sort((d,g)=>d.path.localeCompare(g.path)),dependencies:f.sort((d,g)=>d.from.localeCompare(g.from)||d.to.localeCompare(g.to))};return{map:R,hash:B(j(R))}}a(Yl,"loadArchitectureChangeMap");function Ue(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(Ue,"literalText");function io(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(io,"lineOf");function so(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}a(so,"isTypeOnlyReference");function ao(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}a(ao,"singleFileChecker");function Kn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Kn,"symbolAt");function jn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Kn(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(jn,"localDeclaration");function Un(e,t){let n,r=[],o=a((i,l,c,f=!1)=>r.push({specifier:c,kind:l,line:io(t,i),typeOnly:f,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",Ue(e,i.moduleSpecifier),so(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",Ue(e,i.moduleSpecifier),so(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",Ue(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,f=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!jn(e,n??(n=ao(e,t)),t,i.expression);(l||f)&&o(i,f?"require":"dynamic-import",Ue(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(Un,"extractSemanticDependencies");function Xl(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=Ue(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}a(Xl,"staticAccessPath");function Zl(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}a(Zl,"runtimeIdentifierReference");function oo(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}a(oo,"bestForbiddenMatch");function Vn(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ao(e,t),s=new Map,i=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let R of p.declarationList.declarations)e.isIdentifier(R.name)&&i.add(R.name.text);let l=a(p=>{let R=Xl(e,p);if(!R)return;let d=Kn(o,R.root),g=d?s.get(d):void 0;return g?[...g,...R.segments.slice(1)]:jn(e,o,t,R.root)||i.has(R.root.text)?void 0:R.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let R of p.declarationList.declarations){if(!R.initializer||!e.isIdentifier(R.name))continue;let d=l(R.initializer),g=Kn(o,R.name);!d||!g||s.set(g,d)}let c=[],f=new Set,h=a((p,R)=>{let d=io(t,R),g=`${p}:${R.getStart(t)}`;f.has(g)||(f.add(g),c.push({name:p,line:d,node:R}))},"flag"),y=a(p=>{let R=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!R){let d=l(p),g=d?oo(r,d):void 0;g&&h(g,p)}else e.isIdentifier(p)&&r.has(p.text)&&Zl(e,p)&&!jn(e,o,t,p)&&h(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let d=l(p.initializer);if(d)for(let g of p.name.elements){if(!e.isIdentifier(g.name))continue;let A=g.propertyName?Ue(e,g.propertyName)??g.propertyName.text:g.name.text,I=oo(r,[...d,A]);I&&h(I,p.initializer)}}e.forEachChild(p,y)},"visit");return y(t),c}a(Vn,"collectForbiddenCapabilityUses");function Jl(e,t,n){let r=[];for(let o of n?.dependencies??Un(e,t)){if(o.typeOnly||!o.specifier)continue;let s=We(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Vn(e,t,en)){let s=Ye(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}a(Jl,"collectCapabilityUses");function Gn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(Gn,"omitLayerDescriptions");function lo(e){let{stewards:t,...n}=Gn(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}a(lo,"effectiveContractPolicyPayload");var ko="1.0",Ql="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function E(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${Ql}`:void 0,r=t.nextAction??n;e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...r?{nextAction:r}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}a(E,"addFinding");function D(e){return[...new Set(e??[])].sort()}a(D,"sortedUnique");function ae(e,t,n,r,o){let s=D(n),i=D(r),l=new Set(s),c=new Set(i),f=i.filter(y=>!l.has(y)),h=s.filter(y=>!c.has(y));f.length===0&&h.length===0||(f.length>0&&E(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),h.length>0&&E(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(ae,"compareStringSets");function lt(e,t,n,r,o,s,i){if(n===r)return;E(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(lt,"compareBoolean");function Kt(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}a(Kt,"keyed");function ec(e,t,n){let r=Kt(t,s=>s.name),o=Kt(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&E(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){E(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new layer and put that file path in --policy-ack as adrPath.",after:l});continue}if(i&&!l){E(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;ae(e,`${c}.patterns`,i.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),ae(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let f=yt(i),h=yt(l);ae(e,`${c}.forbiddenGlobals`,f.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ae(e,`${c}.capabilities`,f.atoms,h.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),D(i.intentPrefixes).join("\0")!==D(l.intentPrefixes).join("\0")&&E(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:D(i.intentPrefixes),after:D(l.intentPrefixes)}),lt(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),lt(e,`${c}.optional`,i.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}a(ec,"compareLayers");function tc(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=Kt(t,r),s=Kt(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&E(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),f=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?E(e,{kind:"deny-added",path:f,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):E(e,{kind:"allow-added",path:f,classification:"judgment-required",message:"A new import edge was added; confirm this house should import that one.",nextAction:"Write a short note under docs/adr/ (or docs/decisions/) for this new import edge and put that file path in --policy-ack as adrPath.",after:c});continue}if(l&&!c){l.allowed===!1&&E(e,{kind:"deny-removed",path:f,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&E(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${f}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let h=l.peerIsolation===!0,y=c.peerIsolation===!0;if(h!==y){let A=l.from===l.to&&c.from===c.to;E(e,{kind:y?"peer-isolation-enabled":"peer-isolation-disabled",path:`${f}.peerIsolation`,classification:A?y?"strengthening":"weakening":"judgment-required",message:A?y?"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:y})}D(l.sliceFolders).join("\0")!==D(c.sliceFolders).join("\0")&&E(e,{kind:"slice-folders-changed",path:`${f}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:D(l.sliceFolders),after:D(c.sliceFolders)});let p=l.sliceIdentity??"path",R=c.sliceIdentity??"path";if(p!==R&&E(e,{kind:"slice-identity-changed",path:`${f}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:p,after:R}),!h&&!y)continue;Ht(e,`${f}.sharedRoots`,"shared-roots",D(l.sharedRoots),D(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Ht(e,`${f}.allowedCrossSlice`,"cross-slice-allowance",D((l.allowedCrossSlice??[]).map(Wn)),D((c.allowedCrossSlice??[]).map(Wn)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let d=ye(l.sharedImportsSlice)??null,g=ye(c.sharedImportsSlice)??null;if(d!==g){let A=Ao(g)>Ao(d);E(e,{kind:"shared-imports-slice",path:`${f}.sharedImportsSlice`,classification:A?"strengthening":"weakening",message:gc(d,g),before:d,after:g})}else g==="deny-cross-parent"&&Ht(e,`${f}.sharedImportsSlice.stopAt`,"shared-walk-stop",uo(l.sharedImportsSlice),uo(c.sharedImportsSlice),"Composition roots now stop the cross-parent walk. Paths through them are no longer reported.","Composition roots no longer stop the cross-parent walk. Paths through them are reported again.");rc(e,f,l,c)}}a(tc,"compareRules");function co(e){let t=e.childSlices;return t?JSON.stringify([D(t.sliceFolders??[]),t.sliceIdentity??"path",D(t.commonFolders??[])]):""}a(co,"childSliceFoldersKey");function uo(e){return D(vt(e).map(t=>ct(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(uo,"stopAtKeys");function fo(e){return e==="always"?2:e==="auto"?1:0}a(fo,"siblingRatchetRank");function nc(e){return D((e??[]).map(t=>ct(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(nc,"enforceKeys");function po(e){if(!e.childSlices)return null;let t=e.childSlices.siblings;return t==null||t==="deny"?{mode:"deny",enforce:[],ratchet:"auto"}:t==="advisory"?{mode:"advisory",enforce:[],ratchet:"auto"}:t.default==="deny"?{mode:"deny",enforce:[],ratchet:"auto"}:{mode:"advisory",enforce:nc(t.enforce),ratchet:Er(t)}}a(po,"childSliceSiblingPolicy");function rc(e,t,n,r){let o=po(n),s=po(r);if(o===null&&s===null)return;if(o===null&&s!==null){E(e,{kind:"child-slices-added",path:`${t}.childSlices`,classification:s.mode==="advisory"?"judgment-required":"strengthening",message:s.mode==="advisory"?"A child slice wall was added with advisory sibling crossings.":"A child slice wall was added. Sibling crossings inside a universe are now denied.",after:r.childSlices});return}if(o!==null&&s===null){E(e,{kind:"child-slices-removed",path:`${t}.childSlices`,classification:"weakening",message:"The child slice wall was removed. Sibling crossings inside a universe are allowed again.",before:n.childSlices});return}if(co(n)!==co(r)){E(e,{kind:"child-slices-changed",path:`${t}.childSlices`,classification:"judgment-required",message:"Child slice folders changed and can reclassify edges inside a universe.",before:n.childSlices,after:r.childSlices});return}if(o===null||s===null)return;if(o.mode!==s.mode){let c=s.mode==="advisory";E(e,{kind:"child-slices-siblings",path:`${t}.childSlices.siblings`,classification:c?"weakening":"strengthening",message:c?s.enforce.length>0?"Sibling crossings outside the enforce list are now advisory.":"Sibling crossings inside a universe are now advisory.":"Sibling crossings inside a universe are now denied.",before:o.mode,after:s.mode})}else if(o.mode==="advisory"&&(sc(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce),o.ratchet!==s.ratchet)){let c=fo(s.ratchet)>fo(o.ratchet);E(e,{kind:"child-slices-siblings-ratchet",path:`${t}.childSlices.siblings.ratchet`,classification:c?"strengthening":"weakening",message:c?"New advisory sibling crossings past the baseline fail in more cases.":s.ratchet==="never"?"Advisory sibling crossings are measured only and never fail.":"New advisory sibling crossings past the baseline fail in fewer cases.",before:o.ratchet,after:s.ratchet})}let i=n.childSlices?.parentMayImportChild===!0,l=r.childSlices?.parentMayImportChild===!0;i!==l&&E(e,{kind:"child-slices-parent-import",path:`${t}.childSlices.parentMayImportChild`,classification:l?"weakening":"strengthening",message:l?"Universe common may now import a child slice.":"Universe common may no longer import a child slice.",before:i,after:l}),lc(e,t,n,r),ac(e,t,n,r)}a(rc,"compareChildSlices");function sc(e,t,n,r){if(JSON.stringify(n)===JSON.stringify(r))return;let o=r.filter(l=>!n.includes(l)),s=n.filter(l=>!r.includes(l)),i=o.length>0&&s.length>0;E(e,{kind:i?"child-slices-siblings-enforce-changed":"child-slices-siblings-enforce",path:t,classification:i?"judgment-required":o.length>0?"strengthening":"weakening",message:i?"Enforced sibling subtrees were added and removed in the same change.":o.length>0?"Sibling crossings from these subtrees are now errors.":"Sibling crossings from these subtrees are advisory again.",before:n,after:r})}a(sc,"compareSiblingEnforceList");function Wn(e){return JSON.stringify([e.from,e.to])}a(Wn,"crossSliceKey");function go(e){return D((e.childSlices?.allowedCrossSlice??[]).map(Wn))}a(go,"childCrossSliceKeys");function Ve(e){return ct(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(Ve,"allowanceSegments");function ho(e,t){let n=Ve(e),r=Ve(t);if(n.length===0||n.length!==r.length)return!1;let o=!1;for(let s=0;s<n.length;s+=1)if(n[s]!==r[s]){if(n[s]==="*"&&r[s]!=="*"){o=!0;continue}return!1}return o}a(ho,"patternWidens");function oc(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=Ve(n[0]).join("/")===Ve(r[0]).join("/"),s=Ve(n[1]).join("/")===Ve(r[1]).join("/"),i=ho(n[0],r[0]),l=ho(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(oc,"allowanceWidens");function ic(e){return JSON.stringify([ct(e.from.trim().replace(/\\/g,"/")).toLowerCase(),ct(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(ic,"aliasEntryKey");function mo(e){return D((e.childSlices?.sliceAliases??[]).map(ic))}a(mo,"sliceAliasKeys");function ac(e,t,n,r){let o=mo(n),s=mo(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(f=>!o.includes(f)),l=o.filter(f=>!s.includes(f)),c=i.length>0&&l.length>0;E(e,{kind:c?"slice-aliases-changed":i.length>0?"slice-aliases-added":"slice-aliases-removed",path:`${t}.childSlices.sliceAliases`,classification:c?"judgment-required":i.length>0?"strengthening":"weakening",message:c?"Slice aliases were added and removed in the same change.":i.length>0?"Unclassified files are now under the slice walls.":"Aliased files leave the slice walls.",before:o,after:s})}a(ac,"compareSliceAliases");function lc(e,t,n,r){let o=go(n),s=go(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(c=>!o.includes(c)),l=o.filter(c=>!s.includes(c));if(i.length>0&&l.length>0&&l.filter(f=>!i.some(h=>oc(h,f))).length===0){E(e,{kind:"child-slices-cross-slice-allowance-added",path:`${t}.childSlices.allowedCrossSlice`,classification:"weakening",message:"A wildcard widened a declared sibling allowance.",before:o,after:s});return}Ht(e,`${t}.childSlices.allowedCrossSlice`,"child-slices-cross-slice-allowance",o,s,"Sibling crossings inside a universe are now allowed by declaration.","Declared sibling crossings inside a universe deny again.")}a(lc,"compareChildCrossSliceAllowances");function Ht(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(h=>!r.includes(h)),c=r.filter(h=>!o.includes(h)),f=l.length>0&&c.length>0;E(e,{kind:f?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:f?"judgment-required":l.length>0?"weakening":"strengthening",message:f?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(Ht,"compareDeclaredExceptions");function cc(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&E(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])lt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(cc,"compareSafety");function Bn(e){return e.mode==="enforced"?"enforced":"advisory"}a(Bn,"arkRunMode");function zn(e){return e.mode==="enforced"?"enforced":"advisory"}a(zn,"arkOrderMode");function dc(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){E(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${zn(o)}).`,after:o});return}if(r&&!o){E(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=zn(r),l=zn(o);if(i!==l){let c=i==="advisory"&&l==="enforced";E(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:i,after:l})}ae(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}a(dc,"compareArkOrder");function uc(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){E(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Bn(o)}).`,after:o});return}if(r&&!o){E(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Bn(r),l=Bn(o);if(i!==l){let c=i==="advisory"&&l==="enforced";E(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:i,after:l})}ae(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),ae(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),lt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(uc,"compareArkRun");function fc(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}a(fc,"overallClassification");function yo(e,t){return`${e}::${t}`}a(yo,"ruleKey");function Ro(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(yo(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(yo(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Ro,"indexEffectiveRules");function pc(e,t,n,r,o,s){let i=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},f=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of f){let R=l[p],d=c[p],g=`$.arkRules[${p}]`;if(R===void 0&&d!==void 0){E(e,{kind:"arkrules-ref-added",path:g,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:d});continue}if(R!==void 0&&d===void 0){E(e,{kind:"arkrules-ref-removed",path:g,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:R});continue}R!==d&&E(e,{kind:"arkrules-ref-path-changed",path:g,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:R,after:d})}let h=Ro(r),y=Ro(o);for(let p of[...new Set([...h.structure.keys(),...y.structure.keys()])].sort()){let R=h.structure.get(p),d=y.structure.get(p),g=`$.arkRules.structure[${p}]`;if(!R&&d){E(e,{kind:"arkrule-structure-added",path:g,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(R&&!d){E(e,{kind:"arkrule-structure-removed",path:g,classification:"weakening",message:`Structure ArkRule ${R.id} was removed.`,before:R});continue}if(!(!R||!d)){if(R.mode!==d.mode){let A=R.mode==="advisory"&&d.mode==="enforced";E(e,{kind:A?"arkrule-promoted":"arkrule-demoted",path:`${g}.mode`,classification:A?"strengthening":"weakening",message:A?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:R.mode,after:d.mode})}R.sensor!==d.sensor&&E(e,{kind:"arkrule-sensor-changed",path:`${g}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:R.sensor,after:d.sensor})}}for(let p of[...new Set([...h.invariants.keys(),...y.invariants.keys()])].sort()){let R=h.invariants.get(p),d=y.invariants.get(p),g=`$.arkRules.invariants[${p}]`;if(!R&&d){E(e,{kind:"arkrule-invariant-added",path:g,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(R&&!d){E(e,{kind:"arkrule-invariant-removed",path:g,classification:"weakening",message:`Invariant ${R.id} was removed.`,before:R});continue}if(!(!R||!d)&&R.mode!==d.mode)if(R.mode==="advisory"&&d.mode==="enforced"){let I=i?.get(d.id),S=es(I);S.ok?E(e,{kind:"arkrule-invariant-promoted",path:`${g}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:R.mode,after:d.mode}):E(e,{kind:"arkrule-invariant-promote-refused",path:`${g}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${S.reason}`,before:R.mode,after:d.mode})}else E(e,{kind:"arkrule-invariant-demoted",path:`${g}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:R.mode,after:d.mode})}}a(pc,"compareArkRules");function bo(e,t,n){let r=[];ae(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ae(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."}),ae(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."}),lt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";E(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&E(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),ec(r,e.layers,t.layers),tc(r,e.rules,t.rules),cc(r,e,t),pc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),uc(r,e,t),dc(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:ko,classification:fc(r),findings:r}}a(bo,"classifyArkPolicyDelta");function vo(e,t){if(!e||e.schemaVersion!==ko||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=D(e.findingIds),r=D(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}a(vo,"policyDeltaAcknowledgementMatches");function ct(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(ct,"trimTrailingSlashes");function Ao(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(Ao,"sharedImportsSliceRank");function gc(e,t){return t==="deny"?"A shared root may no longer import a slice.":e==="deny"&&t==="deny-cross-parent"?"A shared root may import a slice again, except when that hop carries another universe.":e==="deny"?"A shared root may import a slice again.":t==="deny-cross-parent"?"A slice may no longer reach another universe through a shared root. ark-check and CI report that path. The write hook and ESLint see one edge at a time and do not block it.":"A slice may reach another universe through a shared root again."}a(gc,"sharedImportsSliceMessage");function _e(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}a(_e,"normalizePath");function So(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(So,"isIdentifierStart");function jt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(jt,"isIdentifierCharacter");function J(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(J,"skipWhitespace");function dt(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}a(dt,"readString");function re(e,t,n){return e.startsWith(t,n)&&!jt(e[n-1])&&!jt(e[n+t.length])}a(re,"isWordAt");function Io(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(!re(e,"type",n))return!1;let o=J(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||re(e,"as",o)||!So(e[o]))return!1;for(n=o;n<e.length&&jt(e[n]);)n+=1;if(n=J(e,n),re(e,"as",n)){if(n=J(e,n+2),!So(e[n]))return!1;for(;n<e.length&&jt(e[n]);)n+=1}r=!0}return!1}a(Io,"bracedNamedBindingsAreTypeOnly");function hc(e,t){if(t=J(e,t+6),e[t]==="(")return dt(e,J(e,t+1));let n=!1;if(re(e,"type",t)){let o=J(e,t+4);e[o]!==","&&!re(e,"from",o)&&(n=!0)}else Io(e,t)&&(n=!0);let r=Eo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(hc,"specifierAfterImport");function mc(e,t){t=t+6;let n=J(e,t),r=!1;if(re(e,"type",n)){let s=J(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Io(e,n)&&(r=!0);let o=Eo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(mc,"specifierAfterExport");function Eo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(re(e,"from",t))return dt(e,J(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return dt(e,t);if(t>0&&(re(e,"import",t)||re(e,"export",t)))return}}a(Eo,"specifierInStaticStatement");function yc(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}a(yc,"skipTemplateLiteral");function Rc(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 o=dt(e,r);return o?{...o,requireCall:!0}:void 0}a(Rc,"specifierAfterRequire");function Ac(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(`
|
|
19
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=yc(e,n);continue}if(r==="'"||r==='"'){let s=dt(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&re(e,"import",n)?hc(e,n):r==="e"&&re(e,"export",n)?mc(e,n):r==="r"&&re(e,"require",n)?Rc(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(Ac,"moduleSpecifiers");function Co(e,t){let n=[],r=[];for(let o of Ac(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let f=We(s);if(!f)continue;let h=e.content.slice(0,o.offset).split(`
|
|
20
|
+
`).length;r.push({file:e.path,symbol:s,capability:f,evidence:{kind:"import",file:e.path,line:h,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
|
|
21
|
+
`).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=kc(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}a(Co,"moduleFactsFor");function kc(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let i=n.get(s);if(i)return i}}a(kc,"resolveSpecifier");function wo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=Fe(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});if(!o)continue;let s=o.rule;n.push({ruleId:`layer-dependency:${s.from}->${s.to}`,message:Sr(s,o.sliceVerdict)??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(wo,"violationsFor");var bc={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 vc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(vc,"hasActiveArkRules");function Sc(e,t){return vc(e,t)?B(j(lo({config:e,arkRules:t,warnings:[]}))):B(j(Gn(e)))}a(Sc,"policyHashFor");function qn(e,t,n){let r=typeof e=="string"?Gs(e,t):xn(e,t),o=n?.arkRules??et();return{...r,arkRules:o,policyHash:Sc(r.config,o)}}a(qn,"loadContract");function Ic(e){let t=qn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=qn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=bo(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,i=s&&vo(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:i,valid:!s||i}}a(Ic,"analyzePolicyDelta");function Ut(e){let t=e.files.map(y=>{let p=_e(y.path);return{path:p,content:y.content,contentHash:B(y.content),layer:te(p,e.contract.config.layers)??null}}).sort((y,p)=>y.path.localeCompare(p.path)),n=new Map(t.map(y=>[y.path,y])),r=[],o=[];for(let y of t){let p=Co(y,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=wo(r,e.contract.config),i=new Map(e.contract.config.layers.map(y=>[y.name,y])),l=new Map(e.contract.config.layers.map(y=>[y.name,new Set(Le(y))]));for(let y of o){let p=n.get(y.file)?.layer;if(!p)continue;let R=i.get(p),d=qe(y.symbol,R?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${y.symbol}" because it is the import form of forbidden global "${d}".`,symbol:y.symbol,evidence:y.evidence});continue}l.get(p)?.has(y.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} denies the ${y.capability} capability; found import of "${y.symbol}".`,capability:y.capability,symbol:y.symbol,evidence:y.evidence})}let c=t.length===0?"complete":"partial",f=c==="complete"?[]:[{...bc}],h={schemaVersion:tr,policyHash:e.contract.policyHash,compilerOptionsHash:B(j(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(y=>y.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:f,valid:c==="complete"&&s.length===0,ir:h}}a(Ut,"analyzeProject");function Yn(e){let t=new Map(e.files.map(n=>[_e(n.path),n]));for(let n of e.changes){let r=_e(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Ut({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(Yn,"analyzeChange");function Ec(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}a(Ec,"explainViolation");function xo(e){return B(j(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(xo,"analysisTreeHash");function Cc(e){let t=Ut(e),n=new Map(t.ir.files.map(d=>[d.path,d])),r=[],o=new Set,s=[];for(let d of e.changes){let g=d.path.replace(/\\/g,"/"),A=_e(d.path);if(!A||A===".."||A.startsWith("../")||g.startsWith("/")||/^[A-Za-z]:\//.test(g)||g.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(A)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:A,line:1,message:`The atomic change set contains more than one operation for ${A}.`});continue}o.add(A),"delete"in d&&d.delete&&!n.has(A)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:A,line:1,message:`Cannot delete ${A} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:A,delete:!0}:{path:A,content:"content"in d?d.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let i=Yn({...e,changes:r}),l=new Map(i.ir.files.map(d=>[d.path,d])),c=i.ir.violations.filter(d=>d.ruleId==="CAPABILITY_VIOLATION"||d.ruleId==="FORBIDDEN_GLOBAL").map(d=>{let g=l.get(d.evidence.file)?.layer;return{ruleId:d.ruleId,file:d.evidence.file,line:d.evidence.line,target:d.symbol,...d.capability?{capability:d.capability}:{},...g?{fromLayer:g}:{},edgeKind:"import",message:d.message}}),f=ot({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(d=>d.path),contentViolations:c,edges:i.ir.edges.filter(d=>!!d.fromLayer).map(d=>({from:d.from,fromLayer:d.fromLayer,...d.to?{to:d.to}:{},...d.toLayer?{toLayer:d.toLayer}:{},line:d.evidence.line,kind:"import",...d.typeOnly?{typeOnly:!0}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),h=r.map(d=>{let g=_e(d.path),A=n.get(g),I=l.get(g);return{path:g,operation:"delete"in d&&d.delete?"delete":A?"update":"create",...A?{beforeContentHash:A.contentHash}:{},...I?{candidateContentHash:I.contentHash}:{}}}).sort((d,g)=>d.path.localeCompare(g.path)),y=[...s,...f.violations].map(d=>({...d,nextAction:ke(d)})),p=y.filter(d=>d.failsStrict!==!1),R=e.changeMap?at({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[]),candidateDependencies:i.ir.edges.flatMap(d=>d.to?[{from:d.from,to:d.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&p.length===0&&(R?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:xo(t.ir.files),candidateTreeHash:xo(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...R?{convergence:R}:{},changes:h,violations:y,warnings:f.warnings}}a(Cc,"preflightChange");var Vt=new WeakSet;function _o(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))_o(t);return Object.freeze(e)}a(_o,"deepFreeze");function ep(e){let t=_o(ht(e));return Vt.add(t),t}a(ep,"createTrustedResolvedCandidateFacts");function tp(e){if(!Vt.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return je(e)}a(tp,"analyzeTrustedResolvedProject");function np(e){let t=e.baseFacts,n=e.candidateFacts;return!Vt.has(t)||!Vt.has(n)?Pn(e):Fn(e,t,n)}a(np,"preflightTrustedResolvedChange");export{en as AMBIENT_CAPABILITY_ENTRIES,Jt as CAPABILITY_IDS,Ct as DEFAULT_INTENT_PREFIXES,er as RESOLVED_CANDIDATE_FACTS_SCHEMA,Te as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,un as SOURCE_POLICY_MESSAGES,tn as ambientCoveredByForbiddenGlobals,at as analyzeArchitectureConvergence,Yn as analyzeChange,Ic as analyzePolicyDelta,Ut as analyzeProject,Vl as analyzeResolvedProject,tp as analyzeTrustedResolvedProject,Ye as capabilityForAmbientName,We as capabilityForModuleSpecifier,gn as classifyPublishFacts,Ln as collectAnalysisConfigWarnings,Jl as collectCapabilityUses,Vn as collectForbiddenCapabilityUses,Ws as configVersionFloors,ht as createResolvedCandidateFacts,ep as createTrustedResolvedCandidateFacts,Js as detectArchitectureCycles,B as deterministicHash,Le as effectiveCapabilityDeny,ot as evaluateArchitectureGraph,Ec as explainViolation,Un as extractSemanticDependencies,qe as forbiddenGlobalForModuleSpecifier,Yl as loadArchitectureChangeMap,qn as loadContract,Se as loadResolvedCandidateFacts,pn as looksLikeArkIntent,No as lowerForbiddenGlobal,yt as loweredLayerCoverage,Ll as parseArkgatePins,Cc as preflightChange,Pn as preflightResolvedChange,np as preflightTrustedResolvedChange,fn as resolveIntentLayer,gt as resolvedFactsEvidenceRequirementsHash,j as stableSerialize};
|