arkgate 4.8.26 → 4.8.27

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +2 -2
  3. package/bin/ark-layer-match.mjs +23 -0
  4. package/bin/ark-mcp-runtime.mjs +45 -4
  5. package/bin/ark-mcp.mjs +9 -3
  6. package/bin/ark.mjs +27 -1
  7. package/bin/lib/analysis-engine.mjs +10 -10
  8. package/bin/lib/arkrules-sensors.mjs +9 -4
  9. package/bin/lib/class-source-scan.mjs +1 -1
  10. package/bin/lib/config-contract.mjs +5 -0
  11. package/bin/lib/prepare-change.mjs +10 -6
  12. package/bin/lib/prepare-write.mjs +7 -0
  13. package/bin/lib/remediation.mjs +84 -0
  14. package/bin/lib/resolved-candidate-facts.mjs +19 -2
  15. package/bin/lib/snippet-analysis.mjs +82 -1
  16. package/dist/chunk-A5EIY3HI.cjs +3 -3
  17. package/dist/chunk-H5I3GARV.js +16 -0
  18. package/dist/chunk-QQ4SJEJ7.cjs +16 -0
  19. package/dist/chunk-SVSQVGFJ.js +3 -3
  20. package/dist/{configTypes-GPvvdleM.d.cts → configTypes-D1oxws6x.d.cts} +6 -0
  21. package/dist/{configTypes-GPvvdleM.d.ts → configTypes-D1oxws6x.d.ts} +6 -0
  22. package/dist/eslint/index.cjs +11 -12
  23. package/dist/eslint/index.d.cts +7 -1
  24. package/dist/eslint/index.d.ts +7 -1
  25. package/dist/eslint/index.js +11 -11
  26. package/dist/index.cjs +32 -32
  27. package/dist/index.d.cts +13 -2
  28. package/dist/index.d.ts +13 -2
  29. package/dist/index.js +32 -32
  30. package/dist/inspectorListen-6DQVJ4DC.js +2 -1
  31. package/dist/inspectorListen-KGMIQ2TF.cjs +2 -1
  32. package/dist/nestjs/index.cjs +1 -1
  33. package/dist/nestjs/index.d.cts +1 -1
  34. package/dist/nestjs/index.d.ts +1 -1
  35. package/dist/nestjs/index.js +1 -1
  36. package/dist/order/index.cjs +1 -1
  37. package/dist/order/index.js +1 -1
  38. package/dist/runtime/index.cjs +10 -10
  39. package/dist/runtime/index.d.cts +4 -3
  40. package/dist/runtime/index.d.ts +4 -3
  41. package/dist/runtime/index.js +10 -10
  42. package/dist/{types-CnauMQQL.d.cts → types-DBiqlOWZ.d.cts} +6 -0
  43. package/dist/{types-CnauMQQL.d.ts → types-DBiqlOWZ.d.ts} +6 -0
  44. package/docs/README.md +2 -1
  45. package/docs/agent-guide.md +3 -2
  46. package/docs/ai-gates.md +1 -1
  47. package/docs/configuration.md +11 -0
  48. package/docs/package-surface.md +2 -1
  49. package/docs/product-voice.md +1 -1
  50. package/package.json +1 -1
  51. package/schemas/ark.config.schema.json +10 -0
  52. package/server.json +2 -2
  53. package/templates/agent-skills/README.md +1 -1
  54. package/templates/agent-skills/ark-adopt/SKILL.md +6 -0
  55. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  56. package/templates/agent-skills/ark-place/SKILL.md +4 -0
  57. package/templates/skills/ark-adopt.md +6 -0
  58. package/templates/skills/ark-autopilot.md +1 -1
  59. package/templates/skills/ark-place.md +4 -0
  60. package/dist/chunk-G3JRBJGH.js +0 -16
  61. package/dist/chunk-R3AJ5RSZ.cjs +0 -16
@@ -1,21 +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 Uo=Object.defineProperty;var a=(e,t)=>Uo(e,"name",{value:t,configurable:!0});function G(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(G,"deterministicHash");function K(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(K).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${K(t[n])}`).join(",")}}`}a(K,"stableSerialize");function ce(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(ce,"feedText");function Zt(e,t){if(Array.isArray(e)){ce("[",t);for(let o=0;o<e.length;o+=1){if(o>0&&ce(",",t),!(o in e))continue;let s=e[o];if(s!==null&&typeof s=="object")Zt(s,t);else{let i=JSON.stringify(s);i!==void 0&&ce(i,t)}}ce("]",t);return}let n=e,r=Object.keys(n).sort();ce("{",t);for(let o=0;o<r.length;o+=1){o>0&&ce(",",t);let s=r[o];ce(`${JSON.stringify(s)}:`,t);let i=n[s];i!==null&&typeof i=="object"?Zt(i,t):ce(`${JSON.stringify(i)}`,t)}ce("}",t)}a(Zt,"feedStable");function Jt(e){if(e===null||typeof e!="object")return G(K(e));let t={hash:2166136261};return Zt(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}a(Jt,"stableHash");var $e="1.2",tr=["network","filesystem","clock","randomness","environment","process","persistence"];function M(e){let t=e.map((n,r)=>({key:K(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(M,"sortCanonical");function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(B,"sortedUnique");function At(e){let t={schemaVersion:"1.2",include:B(e.include??[]),exclude:B(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:B(e.dynamicImportAllowlist??[]),layers:M(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}))),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 G(K(t))}a(At,"resolvedFactsEvidenceRequirementsHash");function jo(e){let t=M(e.completenessReasons.map(v=>({code:v.code,message:v.message,...v.file?{file:v.file}:{}}))),n=e.files.map(v=>({...v,typeOnlyExportNames:B(v.typeOnlyExportNames)})).sort((v,j)=>v.path<j.path?-1:v.path>j.path?1:0),r=M(e.dependencies.map(v=>({...v,...v.namedBindings?{namedBindings:B(v.namedBindings)}:{}}))),o=M(e.capabilityUses.map(v=>({...v}))),s=M(e.ambientUses.map(v=>({...v}))),i=M(e.publishCalls.map(v=>({...v}))),l=M(e.intentReferences.map(v=>({...v}))),c=M(e.safetyUses.map(v=>({...v}))),u=M((e.classShapes??[]).map(v=>({...v,mutatingMethods:[...v.mutatingMethods??[]].map(j=>({...j}))}))),p=M((e.arkRunKernelCalls??[]).map(v=>({...v}))),m=M((e.arkRunManagedNews??[]).map(v=>({...v}))),f=M((e.arkRunCompositionRootHits??[]).map(v=>({...v}))),y=M((e.arkRunDeclarations??[]).map(v=>({...v,uses:B(v.uses),reactsTo:B(v.reactsTo),raises:B(v.raises),sends:B(v.sends)}))),d=M((e.arkOrderPlaneCalls??[]).map(v=>({...v}))),g=M((e.arkOrderGenericUpdates??[]).map(v=>({...v}))),b=M((e.arkOrderRootHits??[]).map(v=>({...v}))),I=M((e.arkOrderXiFieldWrites??[]).map(v=>({...v}))),E=M((e.arkOrderIngestWritesXi??[]).map(v=>({...v}))),C=M((e.arkOrderReleaseKeyCounts??[]).map(v=>({...v}))),_=M((e.arkOrderXiTtlKeys??[]).map(v=>({...v}))),q=M((e.arkOrderBudgetLeaks??[]).map(v=>({...v}))),te=e.files.map(({path:v,contentHash:j})=>({path:v,contentHash:j})).sort((v,j)=>v.path<j.path?-1:v.path>j.path?1:0),Y=Jt(te);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:u,arkRunKernelCalls:p,arkRunManagedNews:m,arkRunCompositionRootHits:f,arkRunDeclarations:y,arkOrderPlaneCalls:d,arkOrderGenericUpdates:g,arkOrderRootHits:b,arkOrderXiFieldWrites:I,arkOrderIngestWritesXi:E,arkOrderReleaseKeyCounts:C,arkOrderXiTtlKeys:_,arkOrderBudgetLeaks:q}}a(jo,"canonicalResolvedFactsInput");function nr(e){let t=jo(e);return{...t,factsHash:Jt(t)}}a(nr,"createCanonicalResolvedCandidateFacts");function bt(e){return nr(rr(N(e,"$"),!1))}a(bt,"createResolvedCandidateFacts");function N(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(N,"asRecord");function P(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(P,"assertOnlyKeys");function T(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(T,"requiredText");function de(e,t,n){if(e[t]!==void 0)return T(e,t,n)}a(de,"optionalText");function $(e,t,n){let r=T(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($,"requiredProjectPath");function H(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(H,"requiredBoolean");function Qt(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}a(Qt,"requiredInteger");function V(e,t,n){let r=Qt(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(V,"requiredPositiveInteger");function L(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(L,"requiredArray");function ue(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(ue,"enumValue");function Le(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(Le,"parseStringArray");function Vo(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(Vo,"assertUnique");function rr(e,t){P(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts","arkOrderXiTtlKeys","arkOrderBudgetLeaks",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=ue(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ue(e,"completeness",["complete","partial","unavailable"],"$"),o=L(e,"completenessReasons","$").map((S,A)=>{let h=`$.completenessReasons[${A}]`,R=N(S,h);P(R,["code","message","file"],h);let O=R.file===void 0?void 0:$(R,"file",h);return{code:T(R,"code",h),message:T(R,"message",h),...O?{file:O}:{}}});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=L(e,"files","$").map((S,A)=>{let h=`$.files[${A}]`,R=N(S,h);return P(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:$(R,"path",h),contentHash:T(R,"contentHash",h),parseStatus:ue(R,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Qt(R,"parseDiagnosticCount",h),exportsOnlyTypes:H(R,"exportsOnlyTypes",h),typeOnlyExportNames:Le(R.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:H(R,"hasTopLevelSideEffects",h)}}),i=L(e,"dependencies","$").map((S,A)=>{let h=`$.dependencies[${A}]`,R=N(S,h);P(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let O=de(R,"specifier",h),W=de(R,"target",h),Pe=ue(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(Pe==="resolved-project"&&!W)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(Pe!=="resolved-project"&&W)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(Pe!=="dynamic"&&!O)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:$(R,"from",h),...O?{specifier:O}:{},kind:ue(R,"kind",["import","export","dynamic-import","require"],h),typeOnly:H(R,"typeOnly",h),line:V(R,"line",h),resolution:Pe,...W?{target:$(R,"target",h)}:{},...R.namedBindings!==void 0?{namedBindings:Le(R.namedBindings,`${h}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:H(R,"targetTypeOnlyExports",h)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:H(R,"sourcePureTypeModule",h)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:H(R,"namedBindingsTypeOnly",h)}:{},...R.portProofEligible!==void 0?{portProofEligible:H(R,"portProofEligible",h)}:{}}}),l=L(e,"capabilityUses","$").map((S,A)=>{let h=`$.capabilityUses[${A}]`,R=N(S,h);return P(R,["file","line","symbol","capability","source"],h),{file:$(R,"file",h),line:V(R,"line",h),symbol:T(R,"symbol",h),capability:ue(R,"capability",tr,h),source:ue(R,"source",["ambient-global","import-based"],h)}}),c=L(e,"ambientUses","$").map((S,A)=>{let h=`$.ambientUses[${A}]`,R=N(S,h);return P(R,["file","line","symbol"],h),{file:$(R,"file",h),line:V(R,"line",h),symbol:T(R,"symbol",h)}}),u=L(e,"publishCalls","$").map((S,A)=>{let h=`$.publishCalls[${A}]`,R=N(S,h);P(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let O=de(R,"rawIntentName",h),W=de(R,"sourceIntent",h);return{file:$(R,"file",h),line:V(R,"line",h),...O?{rawIntentName:O}:{},objectHasIntent:H(R,"objectHasIntent",h),arkPublishCandidate:H(R,"arkPublishCandidate",h),hasSource:H(R,"hasSource",h),...W?{sourceIntent:W}:{}}}),p=L(e,"intentReferences","$").map((S,A)=>{let h=`$.intentReferences[${A}]`,R=N(S,h);return P(R,["file","line","intent"],h),{file:$(R,"file",h),line:V(R,"line",h),intent:T(R,"intent",h)}}),m=L(e,"safetyUses","$").map((S,A)=>{let h=`$.safetyUses[${A}]`,R=N(S,h);P(R,["file","line","kind","symbol"],h);let O=de(R,"symbol",h),W=ue(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(W==="in-memory-store"&&!O)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(W!=="in-memory-store"&&O)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:$(R,"file",h),line:V(R,"line",h),kind:W,...O?{symbol:O}:{}}});Vo(s,S=>S.path,"$.files");let f=new Set(s.map(S=>S.path));for(let S of s){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of i)if(!f.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:L(e,"arkRunKernelCalls","$")).map((S,A)=>{let h=`$.arkRunKernelCalls[${A}]`,R=N(S,h);P(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let O=de(R,"receiver",h),W=de(R,"nameLiteral",h);return{file:$(R,"file",h),line:V(R,"line",h),kind:ue(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:T(R,"callee",h),viaImport:H(R,"viaImport",h),...O?{receiver:O}:{},...W?{nameLiteral:W}:{}}}),b=(e.arkRunManagedNews===void 0?[]:L(e,"arkRunManagedNews","$")).map((S,A)=>{let h=`$.arkRunManagedNews[${A}]`,R=N(S,h);P(R,["file","line","typeName","importedFrom"],h);let O=de(R,"importedFrom",h);return{file:$(R,"file",h),line:V(R,"line",h),typeName:T(R,"typeName",h),...O?{importedFrom:O}:{}}}),E=(e.arkRunCompositionRootHits===void 0?[]:L(e,"arkRunCompositionRootHits","$")).map((S,A)=>{let h=`$.arkRunCompositionRootHits[${A}]`,R=N(S,h);return P(R,["file","matchedRoot","hasKernelFactory"],h),{file:$(R,"file",h),matchedRoot:T(R,"matchedRoot",h),hasKernelFactory:H(R,"hasKernelFactory",h)}}),C=e.arkRunDeclarations===void 0?[]:L(e,"arkRunDeclarations","$"),q=(e.arkOrderPlaneCalls===void 0?[]:L(e,"arkOrderPlaneCalls","$")).map((S,A)=>{let h=`$.arkOrderPlaneCalls[${A}]`,R=N(S,h);return P(R,["file","line","callee"],h),{file:$(R,"file",h),line:V(R,"line",h),callee:T(R,"callee",h)}}),Y=(e.arkOrderGenericUpdates===void 0?[]:L(e,"arkOrderGenericUpdates","$")).map((S,A)=>{let h=`$.arkOrderGenericUpdates[${A}]`,R=N(S,h);return P(R,["file","line","method"],h),{file:$(R,"file",h),line:V(R,"line",h),method:T(R,"method",h)}}),j=(e.arkOrderRootHits===void 0?[]:L(e,"arkOrderRootHits","$")).map((S,A)=>{let h=`$.arkOrderRootHits[${A}]`,R=N(S,h);return P(R,["file","matchedRoot","hasPlaneFactory"],h),{file:$(R,"file",h),matchedRoot:T(R,"matchedRoot",h),hasPlaneFactory:H(R,"hasPlaneFactory",h)}}),ge=(e.arkOrderXiFieldWrites===void 0?[]:L(e,"arkOrderXiFieldWrites","$")).map((S,A)=>{let h=`$.arkOrderXiFieldWrites[${A}]`,R=N(S,h);return P(R,["file","line","key"],h),{file:$(R,"file",h),line:V(R,"line",h),key:T(R,"key",h)}}),se=(e.arkOrderIngestWritesXi===void 0?[]:L(e,"arkOrderIngestWritesXi","$")).map((S,A)=>{let h=`$.arkOrderIngestWritesXi[${A}]`,R=N(S,h);return P(R,["file","line"],h),{file:$(R,"file",h),line:V(R,"line",h)}}),ke=(e.arkOrderReleaseKeyCounts===void 0?[]:L(e,"arkOrderReleaseKeyCounts","$")).map((S,A)=>{let h=`$.arkOrderReleaseKeyCounts[${A}]`,R=N(S,h);return P(R,["file","line","keyCount"],h),{file:$(R,"file",h),line:V(R,"line",h),keyCount:V(R,"keyCount",h)}}),qt=(e.arkOrderXiTtlKeys===void 0?[]:L(e,"arkOrderXiTtlKeys","$")).map((S,A)=>{let h=`$.arkOrderXiTtlKeys[${A}]`,R=N(S,h);return P(R,["file","line","key"],h),{file:$(R,"file",h),line:V(R,"line",h),key:T(R,"key",h)}}),ve=(e.arkOrderBudgetLeaks===void 0?[]:L(e,"arkOrderBudgetLeaks","$")).map((S,A)=>{let h=`$.arkOrderBudgetLeaks[${A}]`,R=N(S,h);return P(R,["file","line","kind"],h),{file:$(R,"file",h),line:V(R,"line",h),kind:T(R,"kind",h)}}),Ne=C.map((S,A)=>{let h=`$.arkRunDeclarations[${A}]`,R=N(S,h);return P(R,["file","line","uses","reactsTo","raises","sends"],h),{file:$(R,"file",h),line:V(R,"line",h),uses:Le(R.uses,`${h}.uses`),reactsTo:Le(R.reactsTo,`${h}.reactsTo`),raises:Le(R.raises,`${h}.raises`),sends:Le(R.sends,`${h}.sends`)}});for(let[S,A]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",m],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",E],["$.arkRunDeclarations",Ne],["$.arkOrderPlaneCalls",q],["$.arkOrderGenericUpdates",Y],["$.arkOrderRootHits",j],["$.arkOrderXiFieldWrites",ge],["$.arkOrderIngestWritesXi",se],["$.arkOrderReleaseKeyCounts",ke],["$.arkOrderXiTtlKeys",qt],["$.arkOrderBudgetLeaks",ve]])for(let h of A)if(!f.has(h.file))throw new Error(`${S} references missing file ${h.file}.`);let mt=de(e,"projectPackageName","$"),yt=(e.classShapes===void 0?[]:L(e,"classShapes","$")).map((S,A)=>{let h=`$.classShapes[${A}]`,R=N(S,h);P(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],h);let O=L(R,"mutatingMethods",h).map((W,Pe)=>{let Rt=`${h}.mutatingMethods[${Pe}]`,Xt=N(W,Rt);return P(Xt,["name","referencesGuardOrPublish"],Rt),{name:T(Xt,"name",Rt),referencesGuardOrPublish:H(Xt,"referencesGuardOrPublish",Rt)}});return{file:$(R,"file",h),className:T(R,"className",h),exported:H(R,"exported",h),hasPublicMutableFields:H(R,"hasPublicMutableFields",h),hasPublicSetters:H(R,"hasPublicSetters",h),hasPublicConstructor:H(R,"hasPublicConstructor",h),hasStaticFactory:H(R,"hasStaticFactory",h),mutatingMethods:O,...R.dataOnly===void 0?{}:{dataOnly:H(R,"dataOnly",h)},...R.truncatedUntil===void 0?{}:{truncatedUntil:Qt(R,"truncatedUntil",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:T(e,"resolverIdentity","$"),compilerIdentity:T(e,"compilerIdentity","$"),compilerOptionsHash:T(e,"compilerOptionsHash","$"),tsconfigHash:T(e,"tsconfigHash","$"),evidenceRequirementsHash:T(e,"evidenceRequirementsHash","$"),...mt?{projectPackageName:mt}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:p,safetyUses:m,classShapes:yt,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:E,arkRunDeclarations:Ne,arkOrderPlaneCalls:q,arkOrderGenericUpdates:Y,arkOrderRootHits:j,arkOrderXiFieldWrites:ge,arkOrderIngestWritesXi:se,arkOrderReleaseKeyCounts:ke,arkOrderXiTtlKeys:qt,arkOrderBudgetLeaks:ve}}a(rr,"parseResolvedFactsInput");function Se(e){let t=N(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=nr(rr(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 Go=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},z={type:"integer",minimum:1},F={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},sr={$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:z,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:z,symbol:x,capability:{enum:Go},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:F,line:z,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:F,line:z,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:z,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:F,line:z,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:z,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:z,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:z,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:z,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:F,line:z,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:z,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:F,line:z}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:F,line:z,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:F,line:z,key:x}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:F,line:z,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 or="1.0";var tn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),kt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),rn=Object.freeze(Object.keys(kt).sort()),en=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"}),nn=Object.freeze({process:Object.freeze(["process","node:process"])});function Xe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=en[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=en[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:en[e.slice(0,s)]??null}a(Xe,"capabilityForModuleSpecifier");function Ze(e,t){for(let n of t)if(nn[n]?.includes(e))return n;return null}a(Ze,"forbiddenGlobalForModuleSpecifier");function Je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=kt[r];if(o)return o}return null}a(Je,"capabilityForAmbientName");function Fe(e){if(e?.pure===!0)return[...tn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>tn.includes(r));return[...new Set(n)].sort()}a(Fe,"effectiveCapabilityDeny");function sn(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(sn,"ambientCoveredByForbiddenGlobals");function vt(e){let t=new Set,n=new Set,r=Object.keys(kt);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 nn[o]??[])t.add(`import-exact:${i}`)}for(let o of Fe(e)){if(t.add(`import:${o}`),o==="process")for(let s of nn.process)t.add(`import-exact:${s}`);for(let s of r)Je(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(vt,"loweredLayerCoverage");function Bo(e){let t=new Set,n=Je(e);n&&t.add(n);for(let[r,o]of Object.entries(kt))(r===e||r.startsWith(`${e}.`))&&t.add(o);return[...t].sort()}a(Bo,"lowerForbiddenGlobal");function he(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(he,"sharedImportsSliceMode");function Ct(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(Ct,"sharedImportsSliceStopAt");var ir=new Map;function ar(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(ar,"escapeLiteral");function xt(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(xt,"normalizeGlobSeparators");function zo(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(zo,"bracesBalanced");function Z(e){let t=ir.get(e);if(t)return t;let n=xt(e),r=zo(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=ar(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+=ar(c)}let i=new RegExp(`^${o}$`);return ir.set(e,i),i}a(Z,"globToRegExp");function Wo(e){return xt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Wo,"concreteGlobSegments");function cn(e,t){let n=xt(String(e)),r=Wo(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 u of r){let p=-1;for(let m=l;m<i.length;m+=1)if(i[m]===u){p=m;break}if(p<0)return s;c=p,l=p+1}return(c+1)*1e6+r.length*1e4+o}a(cn,"patternSpecificity");function ne(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>Z(i).test(n))){for(let i of s.patterns??[])if(Z(i).test(n)){let l=cn(i,n);l>o&&(o=l,r=s.name)}}return r}a(ne,"layerForRelativePath");function tt(e,t,n){return hr(e,t,n==="stars"?"stars":"path")}a(tt,"sliceIdForPath");function an(e,t){return hr(e,t?[...t]:void 0,gr)}a(an,"legacyStarsSliceIdForPath");var gr="stars-4.8.23";function hr(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=qo(s);if(i.anchored){let l=Xo(r,i.anchored,n);if(l)return l;continue}i.bare!==void 0&&o.add(i.bare)}return ei(r,o)}a(hr,"sliceIdWithBinding");var St=new Map;function qo(e){let t=St.get(e);if(t)return t;let n={};return mr(e)?n={anchored:Yo(e)}:!e.includes("/")&&!e.includes("\\")&&!e.includes("*")&&(n={bare:e.toLowerCase()}),St.size>=1024&&St.clear(),St.set(e,n),n}a(qo,"parsedSliceFolder");function mr(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(mr,"isAnchoredSliceEntry");function Yo(e){return e.split(/[/\\]/).filter(t=>t.length>0).map(t=>t.toLowerCase())}a(Yo,"anchoredSlicePattern");function Xo(e,t,n){let r=Ar(e,t[0]??"");for(let o of r){let s=Zo(e,t,o,n);if(s)return s}}a(Xo,"anchoredSliceIdFromPattern");function Zo(e,t,n,r="path"){let o=[],s=[],i=-1,l=n;for(let c=0;c<t.length;c+=1){let u=t[c];if(u==="*"){if(l>=e.length-1){for(let p=c;p<t.length;p+=1)if(t[p]!=="*")return;break}o.push(e[l].toLowerCase()),s.push(!0),l+=1;continue}if(u==="**"||l>=e.length||e[l].toLowerCase()!==u)return;o.push(e[l].toLowerCase()),s.push(!1),i=o.length-1,l+=1}if(o.length!==0)return r===gr?i<0?void 0:o.slice(i).join("/"):r==="stars"?i<0?void 0:o.filter((c,u)=>u>=i||s[u]).join("/"):o.join("/")}a(Zo,"bindAnchoredSlice");function yr(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(yr,"starsKeptSegmentIndexes");function Rr(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(p=>p.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let u=r.get(i)??[];u.push(s),r.set(i,u)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:Qo(n.from,n.to,i,s)})}return t}a(Rr,"sliceIdentityCollisions");function Jo(e){if(!mr(e))return;let t=e.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(t.some(r=>r==="**"))return;let n=yr(t);if(n)return n.map(r=>t[r]).join("/")}a(Jo,"starsIdentityStem");function Qo(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(Qo,"formatSliceIdentityCollision");function ei(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(ei,"bareSliceId");function ti(e){let t=new Set;for(let n of e??[]){let o=xt(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(ti,"inferSliceFoldersFromPatterns");function dn(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 ti(r?.patterns)}a(dn,"resolveSliceFolders");function lr(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(lr,"normalizeSegments");function nt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(nt,"trimTrailingSlashes");var ni=["src","app"];function Ar(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return ni.includes(n)&&r!==n?[0,1]:[0]}a(Ar,"anchorOffsets");function ri(e){let t=nt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(ri,"isBlanketRoot");function Me(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=lr(n);for(let s of t){if(typeof s!="string"||s.length===0||ri(s))continue;if(s.includes("*")){let c=nt(s.toLowerCase());if(Z(c).test(r)||Z(`${c}/**`).test(r))return!0;continue}let i=lr(s);if(i.length===0)continue;let l=Ar(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let u=!0;for(let p=0;p<i.length;p+=1)if(o[c+p]!==i[p]){u=!1;break}if(u)return!0}}return!1}a(Me,"pathUnderSharedRoot");function cr(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(cr,"sliceMatchesDeclaration");function It(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&cr(r.from,t)&&cr(r.to,n))}a(It,"crossSliceEdgeAllowed");function si(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(si,"peerIsolationDecision");function br(e){return nt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(br,"aliasGlobPattern");function kr(e,t){let n=br(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=ln(r),s=Z(n),l=(n.split("/").pop()??"").includes("*")?null:Z(`${n}/**`),c=a(u=>s.test(u)||l!==null&&l.test(u),"hit");return c(r)||o!==r&&c(o)}a(kr,"aliasGlobMatches");function vr(e,t){return!e||!t?.length?!1:Me(e,[...t])?!0:t.some(n=>typeof n=="string"&&kr(n,e))}a(vr,"pathMatchesSharedWalkStop");function un(e){let t=br(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(un,"splitAliasTarget");function Sr(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&kr(n.from,e))return n;return null}a(Sr,"firstSliceAliasEntry");function oi(e,t){let n=Sr(e,t);return n?un(n.to):null}a(oi,"firstSliceAlias");function Qe(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=tt(e,r?[...r]:void 0,t.sliceIdentity),s=Et(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=oi(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Qe,"resolveGovernedSlice");function ii(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=yr(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(ii,"starsUniverseShapes");function dr(e,t){return e.length===t.length&&e.every((n,r)=>n===null||t[r]==="*"||n===t[r])}a(dr,"literalsMatch");function De(e,t){let n=t.split("/").filter(Boolean).map(s=>s.toLowerCase()),r=ii(e);if(n.length===0||r.some(s=>dr(s.literals,n)))return[];let o=new Set;for(let s of r)if(s.legacy.length!==s.literals.length&&dr(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(De,"legacyStarsIdTargets");function Ir(e,t){if(e.sliceIdentity!=="stars")return;let n=un(t);if(n)return De(e.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(Ir,"legacyAliasUniverse");function ur(e,t,n){let r=Qe(e,t,n);if(!e||t.sliceIdentity!=="stars")return r;if(r.universeId){let o=Sr(e,t);if(!tt(e,[...n],t.sliceIdentity)&&o&&Ir(t,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let i=an(e,n),l=t.childSlices,c=l?.sliceIdentity==="stars"?an(e,l.sliceFolders):void 0;return{...r,...i?{legacyUniverse:i}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(ur,"placeForPair");function fn(e,t,n,r){let o=ur(n,e,t),s=ur(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 b=d.childId?.split("/").pop();return{...d,universeId:g.universeId,...b?{childId:`${g.universeId}/${b}`}:{}}},"adopt"),u=c(o,s),p=c(s,o),m=It(e.allowedCrossSlice,u.universeId,p.universeId)||e.sliceIdentity==="stars"&&(i!==u.universeId||l!==p.universeId)&&It(e.allowedCrossSlice,i,l),f=e.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&s.legacyChild!==void 0&&o.legacyChild!==s.legacyChild&&Er(e.childSlices.allowedCrossSlice,o.legacyChild,s.legacyChild),y=a(d=>({...d.universeId?{universeId:d.universeId}:{},...d.childId?{childId:d.childId}:{}}),"strip");return{from:y(u),to:y(p),crossSliceAllowed:m,legacyChildAllowed:f}}a(fn,"resolveGovernedSlicePair");function ai(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(ai,"peerIsolationDenyExplanation");function li(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(li,"crossParentExplanation");function ci(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(ci,"crossSiblingExplanation");function di(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(di,"parentImportsChildExplanation");function et(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(et,"universePairLabel");function ui(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(ui,"isCommonFolderName");function Et(e,t,n){if(!e||!n?.sliceFolders?.length)return{};let r=tt(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 ui(i,n.commonFolders)?{}:{childId:r}}a(Et,"resolveChildSliceId");function fi(e){return nt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(fi,"siblingEntryKey");function ln(e){return e.replace(/^(?:src|app)\//,"")}a(ln,"stripSrcOrApp");function pi(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=ln(t);if(!r)return!1;let o=ln(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(pi,"pathUnderSubtree");function gi(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=fi(o);if(!(!s||s.includes("*"))&&(r===s||e&&pi(e,s)))return!0}return!1}a(gi,"importerInEnforcedSubtree");function hi(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!gi(t,n,e.enforce)}a(hi,"siblingCrossingAdvisory");function wt(e){if(typeof e!="string")return null;let t=nt(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(wt,"childSlicePatternSegments");function fr(e,t){let n=wt(e),r=wt(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(fr,"childSlicePatternMatches");function Er(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&fr(r.from,t)&&fr(r.to,n))return!0;return!1}a(Er,"childCrossSliceAllowed");function mi(e,t){let n=wt(e),r=wt(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(mi,"childAllowanceSpansUniverses");function yi(e){let t=si({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:he(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?li(e.fromSlice,e.toSlice):ai(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??Et(e.fromPath,e.fromSlice,n).childId,o=e.toChild??Et(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?e.legacyChildAllowed||Er(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:hi(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:ci(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:di(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(yi,"evaluateNestedSliceWall");function wr(e){return e?.crossing==="cross-sibling"||e?.crossing==="parent-imports-child"}a(wr,"isChildWallCrossing");function Cr(e,t){return wr(t)?e?.childSlices?.message:e?.message}a(Cr,"sliceConsumerMessage");function _t(e){let t=e.verdict.explanation,n=wr(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(_t,"composeSliceDenialMessage");function Ot(e){if(!e||e.decision==="allow")return{};let t=et(e.fromUniverse),n=et(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Ot,"sliceFindingExtras");function xr(e,t){let n=[],r=new Set,o=new Set;for(let s of e??[])if(s?.peerIsolation&&s.allowed===!1&&n.push(...Ri(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=tt(i,s.sliceFolders,s.sliceIdentity),c=Et(i,l,s.childSlices);if(!c.mismatched)continue;let u=`${s.from}\0${s.to}\0${c.mismatched.universeId}\0${c.mismatched.childId}`;r.has(u)||(r.add(u),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"||!mi(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(xr,"childSliceConfigFindings");function pr(e,t){let n=new Map;if(!e?.length)return n;for(let r of t){if(typeof r!="string")continue;let o=tt(r,[...e],"stars"),s=an(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(pr,"observedIdsByLegacy");function on(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(on,"newIdHint");function Ri(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=pr(e.sliceFolders,t);for(let i of o?.sliceAliases??[]){if(!i||typeof i.to!="string")continue;let l=un(i.to);if(!l||Ir(e,i.to)===void 0)continue;let c=De(e.sliceFolders,l.universeId),u=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 ${on(l.universeId,c,s,u)}; 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(u=>u.includes("/")&&De(e.sliceFolders,u).length>0);if(l.length===0)continue;let c=a(u=>l.includes(u)?on(u,De(e.sliceFolders,u),s):u,"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=pr(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(u=>De(o.sliceFolders,u).length>0);if(l.length===0)continue;let c=a(u=>l.includes(u)?on(u,De(o.sliceFolders,u),s):u,"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(Ri,"legacyStarsIdFindings");function _r(e){if(e!==null&&typeof e=="object"){let t=e.ratchet;if(t===!0)return"always";if(t===!1)return"never"}return"auto"}a(_r,"siblingRatchetMode");function He(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=dn(o,t,r?.layers),c=fn(o,l,s,i),u=c.from,p=c.to,m=u.universeId,f=p.universeId,y=yi({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:m,toSlice:f,fromChild:u.childId,toChild:p.childId,fromShared:!m&&Me(s,o.sharedRoots),toShared:!f&&Me(i,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(y.decision!=="allow")return{rule:o,peerIsolationReason:y.peerIsolationReason,fromSlice:m,toSlice:f,sliceVerdict:y};continue}if(t!==n)return{rule:o}}}a(He,"findDeniedEdgeDecision");function Or(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||he(i.sharedImportsSlice)==="deny")continue;let l=dn(i,t,r?.layers),c=Qe(o,i,l).universeId,u=Qe(s,i,l).universeId;if(!(c||!u)&&Me(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}a(Or,"findSharedImportsSliceBridge");function pn(e,t,n){return dn(e,t,n)}a(pn,"peerSliceFolders");var gn={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."},Tt=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 hn(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(hn,"resolveIntentLayer");function mn(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(mn,"looksLikeArkIntent");function yn(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&mn(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:gn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:gn.PUBLISH_MISSING_SOURCE}),t}a(yn,"classifyPublishFacts");function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(rt,"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 me(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(me,"valueType");function Ai(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Ai,"resolveSchemaRef");function Ie(e,t,n,r,o){if(t.$ref){let s=Ai(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ie(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(!rt(e)){o.push({path:n,message:`must be an object; received ${me(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Ke(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.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 s||Ie(e[l],i,Ke(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Ie(e[i],l,Ke(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${me(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)=>Ie(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 ${me(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 ${me(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${me(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(Ie,"validateSchemaNode");var Rn="1.0",Tr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",bi=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Nr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},dd={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Tr,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:Tr},schemaVersion:{type:"string",const:Rn,default:Rn},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:[...bi]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Nr,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:Nr}}}};function st(){return{schemaVersion:Rn,byLayer:{},structure:[],invariants:[]}}a(st,"emptyEffectiveArkRules");function Pr(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(Pr,"structureFreezeTarget");var ki=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),vi=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),Si=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function Ii(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 Si.has(e.slice(o+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:vi.has(r)}a(Ii,"slashStartsRegex");function Ei(e,t){if(!Ii(e,t))return t;let n=t+1,r=!1;for(;n<e.length;){let o=e[n];if(o===`
3
+ var Uo=Object.defineProperty;var a=(e,t)=>Uo(e,"name",{value:t,configurable:!0});function G(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(G,"deterministicHash");function U(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(U).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${U(t[n])}`).join(",")}}`}a(U,"stableSerialize");function ce(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(ce,"feedText");function Zt(e,t){if(Array.isArray(e)){ce("[",t);for(let o=0;o<e.length;o+=1){if(o>0&&ce(",",t),!(o in e))continue;let s=e[o];if(s!==null&&typeof s=="object")Zt(s,t);else{let i=JSON.stringify(s);i!==void 0&&ce(i,t)}}ce("]",t);return}let n=e,r=Object.keys(n).sort();ce("{",t);for(let o=0;o<r.length;o+=1){o>0&&ce(",",t);let s=r[o];ce(`${JSON.stringify(s)}:`,t);let i=n[s];i!==null&&typeof i=="object"?Zt(i,t):ce(`${JSON.stringify(i)}`,t)}ce("}",t)}a(Zt,"feedStable");function Jt(e){if(e===null||typeof e!="object")return G(U(e));let t={hash:2166136261};return Zt(e,t),`fnv1a-${(t.hash>>>0).toString(16).padStart(8,"0")}`}a(Jt,"stableHash");var $e="1.2",nr=["network","filesystem","clock","randomness","environment","process","persistence"];function M(e){let t=e.map((n,r)=>({key:U(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(M,"sortCanonical");function B(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(B,"sortedUnique");function At(e){let t={schemaVersion:"1.2",include:B(e.include??[]),exclude:B(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:B(e.dynamicImportAllowlist??[]),layers:M(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}))),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 G(U(t))}a(At,"resolvedFactsEvidenceRequirementsHash");function jo(e){let t=M(e.completenessReasons.map(S=>({code:S.code,message:S.message,...S.file?{file:S.file}:{}}))),n=e.files.map(S=>({...S,typeOnlyExportNames:B(S.typeOnlyExportNames)})).sort((S,j)=>S.path<j.path?-1:S.path>j.path?1:0),r=M(e.dependencies.map(S=>({...S,...S.namedBindings?{namedBindings:B(S.namedBindings)}:{}}))),o=M(e.capabilityUses.map(S=>({...S}))),s=M(e.ambientUses.map(S=>({...S}))),i=M(e.publishCalls.map(S=>({...S}))),l=M(e.intentReferences.map(S=>({...S}))),c=M(e.safetyUses.map(S=>({...S}))),u=M((e.classShapes??[]).map(S=>({...S,mutatingMethods:[...S.mutatingMethods??[]].map(j=>({...j}))}))),p=M((e.arkRunKernelCalls??[]).map(S=>({...S}))),m=M((e.arkRunManagedNews??[]).map(S=>({...S}))),f=M((e.arkRunCompositionRootHits??[]).map(S=>({...S}))),y=M((e.arkRunDeclarations??[]).map(S=>({...S,uses:B(S.uses),reactsTo:B(S.reactsTo),raises:B(S.raises),sends:B(S.sends)}))),d=M((e.arkOrderPlaneCalls??[]).map(S=>({...S}))),g=M((e.arkOrderGenericUpdates??[]).map(S=>({...S}))),b=M((e.arkOrderRootHits??[]).map(S=>({...S}))),v=M((e.arkOrderXiFieldWrites??[]).map(S=>({...S}))),I=M((e.arkOrderIngestWritesXi??[]).map(S=>({...S}))),C=M((e.arkOrderReleaseKeyCounts??[]).map(S=>({...S}))),x=M((e.arkOrderXiTtlKeys??[]).map(S=>({...S}))),Y=M((e.arkOrderBudgetLeaks??[]).map(S=>({...S}))),te=e.files.map(({path:S,contentHash:j})=>({path:S,contentHash:j})).sort((S,j)=>S.path<j.path?-1:S.path>j.path?1:0),X=Jt(te);return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:X,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:u,arkRunKernelCalls:p,arkRunManagedNews:m,arkRunCompositionRootHits:f,arkRunDeclarations:y,arkOrderPlaneCalls:d,arkOrderGenericUpdates:g,arkOrderRootHits:b,arkOrderXiFieldWrites:v,arkOrderIngestWritesXi:I,arkOrderReleaseKeyCounts:C,arkOrderXiTtlKeys:x,arkOrderBudgetLeaks:Y}}a(jo,"canonicalResolvedFactsInput");function rr(e){let t=jo(e);return{...t,factsHash:Jt(t)}}a(rr,"createCanonicalResolvedCandidateFacts");function bt(e){return rr(sr(N(e,"$"),!1))}a(bt,"createResolvedCandidateFacts");function N(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(N,"asRecord");function $(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($,"assertOnlyKeys");function T(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(T,"requiredText");function de(e,t,n){if(e[t]!==void 0)return T(e,t,n)}a(de,"optionalText");function L(e,t,n){let r=T(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(L,"requiredProjectPath");function H(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(H,"requiredBoolean");function Qt(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}a(Qt,"requiredInteger");function V(e,t,n){let r=Qt(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(V,"requiredPositiveInteger");function F(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(F,"requiredArray");function ue(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(ue,"enumValue");function Le(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(Le,"parseStringArray");function Vo(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(Vo,"assertUnique");function sr(e,t){$(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=ue(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=ue(e,"completeness",["complete","partial","unavailable"],"$"),o=F(e,"completenessReasons","$").map((E,A)=>{let h=`$.completenessReasons[${A}]`,R=N(E,h);$(R,["code","message","file"],h);let O=R.file===void 0?void 0:L(R,"file",h);return{code:T(R,"code",h),message:T(R,"message",h),...O?{file:O}:{}}});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=F(e,"files","$").map((E,A)=>{let h=`$.files[${A}]`,R=N(E,h);return $(R,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],h),{path:L(R,"path",h),contentHash:T(R,"contentHash",h),parseStatus:ue(R,"parseStatus",["parsed","invalid"],h),parseDiagnosticCount:Qt(R,"parseDiagnosticCount",h),exportsOnlyTypes:H(R,"exportsOnlyTypes",h),typeOnlyExportNames:Le(R.typeOnlyExportNames,`${h}.typeOnlyExportNames`),hasTopLevelSideEffects:H(R,"hasTopLevelSideEffects",h)}}),i=F(e,"dependencies","$").map((E,A)=>{let h=`$.dependencies[${A}]`,R=N(E,h);$(R,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],h);let O=de(R,"specifier",h),W=de(R,"target",h),Pe=ue(R,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],h);if(Pe==="resolved-project"&&!W)throw new Error(`${h}.target is required for resolved-project dependencies.`);if(Pe!=="resolved-project"&&W)throw new Error(`${h}.target is only allowed for resolved-project dependencies.`);if(Pe!=="dynamic"&&!O)throw new Error(`${h}.specifier is required unless resolution is dynamic.`);return{from:L(R,"from",h),...O?{specifier:O}:{},kind:ue(R,"kind",["import","export","dynamic-import","require"],h),typeOnly:H(R,"typeOnly",h),line:V(R,"line",h),resolution:Pe,...W?{target:L(R,"target",h)}:{},...R.namedBindings!==void 0?{namedBindings:Le(R.namedBindings,`${h}.namedBindings`)}:{},...R.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:H(R,"targetTypeOnlyExports",h)}:{},...R.sourcePureTypeModule!==void 0?{sourcePureTypeModule:H(R,"sourcePureTypeModule",h)}:{},...R.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:H(R,"namedBindingsTypeOnly",h)}:{},...R.portProofEligible!==void 0?{portProofEligible:H(R,"portProofEligible",h)}:{}}}),l=F(e,"capabilityUses","$").map((E,A)=>{let h=`$.capabilityUses[${A}]`,R=N(E,h);return $(R,["file","line","symbol","capability","source"],h),{file:L(R,"file",h),line:V(R,"line",h),symbol:T(R,"symbol",h),capability:ue(R,"capability",nr,h),source:ue(R,"source",["ambient-global","import-based"],h)}}),c=F(e,"ambientUses","$").map((E,A)=>{let h=`$.ambientUses[${A}]`,R=N(E,h);return $(R,["file","line","symbol"],h),{file:L(R,"file",h),line:V(R,"line",h),symbol:T(R,"symbol",h)}}),u=F(e,"publishCalls","$").map((E,A)=>{let h=`$.publishCalls[${A}]`,R=N(E,h);$(R,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],h);let O=de(R,"rawIntentName",h),W=de(R,"sourceIntent",h);return{file:L(R,"file",h),line:V(R,"line",h),...O?{rawIntentName:O}:{},objectHasIntent:H(R,"objectHasIntent",h),arkPublishCandidate:H(R,"arkPublishCandidate",h),hasSource:H(R,"hasSource",h),...W?{sourceIntent:W}:{}}}),p=F(e,"intentReferences","$").map((E,A)=>{let h=`$.intentReferences[${A}]`,R=N(E,h);return $(R,["file","line","intent"],h),{file:L(R,"file",h),line:V(R,"line",h),intent:T(R,"intent",h)}}),m=F(e,"safetyUses","$").map((E,A)=>{let h=`$.safetyUses[${A}]`,R=N(E,h);$(R,["file","line","kind","symbol"],h);let O=de(R,"symbol",h),W=ue(R,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],h);if(W==="in-memory-store"&&!O)throw new Error(`${h}.symbol is required for in-memory-store facts.`);if(W!=="in-memory-store"&&O)throw new Error(`${h}.symbol is only allowed for in-memory-store facts.`);return{file:L(R,"file",h),line:V(R,"line",h),kind:W,...O?{symbol:O}:{}}});Vo(s,E=>E.path,"$.files");let f=new Set(s.map(E=>E.path));for(let E of s){if(E.parseStatus==="parsed"&&E.parseDiagnosticCount!==0)throw new Error(`$.files[${E.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(E.parseStatus==="invalid"&&E.parseDiagnosticCount===0)throw new Error(`$.files[${E.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(E=>E.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let E of i)if(!f.has(E.from))throw new Error(`$.dependencies references missing source file ${E.from}.`);let d=(e.arkRunKernelCalls===void 0?[]:F(e,"arkRunKernelCalls","$")).map((E,A)=>{let h=`$.arkRunKernelCalls[${A}]`,R=N(E,h);$(R,["file","line","kind","callee","viaImport","receiver","nameLiteral"],h);let O=de(R,"receiver",h),W=de(R,"nameLiteral",h);return{file:L(R,"file",h),line:V(R,"line",h),kind:ue(R,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],h),callee:T(R,"callee",h),viaImport:H(R,"viaImport",h),...O?{receiver:O}:{},...W?{nameLiteral:W}:{}}}),b=(e.arkRunManagedNews===void 0?[]:F(e,"arkRunManagedNews","$")).map((E,A)=>{let h=`$.arkRunManagedNews[${A}]`,R=N(E,h);$(R,["file","line","typeName","importedFrom"],h);let O=de(R,"importedFrom",h);return{file:L(R,"file",h),line:V(R,"line",h),typeName:T(R,"typeName",h),...O?{importedFrom:O}:{}}}),I=(e.arkRunCompositionRootHits===void 0?[]:F(e,"arkRunCompositionRootHits","$")).map((E,A)=>{let h=`$.arkRunCompositionRootHits[${A}]`,R=N(E,h);return $(R,["file","matchedRoot","hasKernelFactory"],h),{file:L(R,"file",h),matchedRoot:T(R,"matchedRoot",h),hasKernelFactory:H(R,"hasKernelFactory",h)}}),C=e.arkRunDeclarations===void 0?[]:F(e,"arkRunDeclarations","$"),Y=(e.arkOrderPlaneCalls===void 0?[]:F(e,"arkOrderPlaneCalls","$")).map((E,A)=>{let h=`$.arkOrderPlaneCalls[${A}]`,R=N(E,h);return $(R,["file","line","callee"],h),{file:L(R,"file",h),line:V(R,"line",h),callee:T(R,"callee",h)}}),X=(e.arkOrderGenericUpdates===void 0?[]:F(e,"arkOrderGenericUpdates","$")).map((E,A)=>{let h=`$.arkOrderGenericUpdates[${A}]`,R=N(E,h);return $(R,["file","line","method"],h),{file:L(R,"file",h),line:V(R,"line",h),method:T(R,"method",h)}}),j=(e.arkOrderRootHits===void 0?[]:F(e,"arkOrderRootHits","$")).map((E,A)=>{let h=`$.arkOrderRootHits[${A}]`,R=N(E,h);return $(R,["file","matchedRoot","hasPlaneFactory"],h),{file:L(R,"file",h),matchedRoot:T(R,"matchedRoot",h),hasPlaneFactory:H(R,"hasPlaneFactory",h)}}),ge=(e.arkOrderXiFieldWrites===void 0?[]:F(e,"arkOrderXiFieldWrites","$")).map((E,A)=>{let h=`$.arkOrderXiFieldWrites[${A}]`,R=N(E,h);return $(R,["file","line","key"],h),{file:L(R,"file",h),line:V(R,"line",h),key:T(R,"key",h)}}),oe=(e.arkOrderIngestWritesXi===void 0?[]:F(e,"arkOrderIngestWritesXi","$")).map((E,A)=>{let h=`$.arkOrderIngestWritesXi[${A}]`,R=N(E,h);return $(R,["file","line"],h),{file:L(R,"file",h),line:V(R,"line",h)}}),ke=(e.arkOrderReleaseKeyCounts===void 0?[]:F(e,"arkOrderReleaseKeyCounts","$")).map((E,A)=>{let h=`$.arkOrderReleaseKeyCounts[${A}]`,R=N(E,h);return $(R,["file","line","keyCount"],h),{file:L(R,"file",h),line:V(R,"line",h),keyCount:V(R,"keyCount",h)}}),qt=(e.arkOrderXiTtlKeys===void 0?[]:F(e,"arkOrderXiTtlKeys","$")).map((E,A)=>{let h=`$.arkOrderXiTtlKeys[${A}]`,R=N(E,h);return $(R,["file","line","key"],h),{file:L(R,"file",h),line:V(R,"line",h),key:T(R,"key",h)}}),ve=(e.arkOrderBudgetLeaks===void 0?[]:F(e,"arkOrderBudgetLeaks","$")).map((E,A)=>{let h=`$.arkOrderBudgetLeaks[${A}]`,R=N(E,h);return $(R,["file","line","kind"],h),{file:L(R,"file",h),line:V(R,"line",h),kind:T(R,"kind",h)}}),Ne=C.map((E,A)=>{let h=`$.arkRunDeclarations[${A}]`,R=N(E,h);return $(R,["file","line","uses","reactsTo","raises","sends"],h),{file:L(R,"file",h),line:V(R,"line",h),uses:Le(R.uses,`${h}.uses`),reactsTo:Le(R.reactsTo,`${h}.reactsTo`),raises:Le(R.raises,`${h}.raises`),sends:Le(R.sends,`${h}.sends`)}});for(let[E,A]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",u],["$.intentReferences",p],["$.safetyUses",m],["$.arkRunKernelCalls",d],["$.arkRunManagedNews",b],["$.arkRunCompositionRootHits",I],["$.arkRunDeclarations",Ne],["$.arkOrderPlaneCalls",Y],["$.arkOrderGenericUpdates",X],["$.arkOrderRootHits",j],["$.arkOrderXiFieldWrites",ge],["$.arkOrderIngestWritesXi",oe],["$.arkOrderReleaseKeyCounts",ke],["$.arkOrderXiTtlKeys",qt],["$.arkOrderBudgetLeaks",ve]])for(let h of A)if(!f.has(h.file))throw new Error(`${E} references missing file ${h.file}.`);let mt=de(e,"projectPackageName","$"),yt=(e.classShapes===void 0?[]:F(e,"classShapes","$")).map((E,A)=>{let h=`$.classShapes[${A}]`,R=N(E,h);$(R,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly","truncatedUntil"],h);let O=F(R,"mutatingMethods",h).map((W,Pe)=>{let Rt=`${h}.mutatingMethods[${Pe}]`,Xt=N(W,Rt);return $(Xt,["name","referencesGuardOrPublish"],Rt),{name:T(Xt,"name",Rt),referencesGuardOrPublish:H(Xt,"referencesGuardOrPublish",Rt)}});return{file:L(R,"file",h),className:T(R,"className",h),exported:H(R,"exported",h),hasPublicMutableFields:H(R,"hasPublicMutableFields",h),hasPublicSetters:H(R,"hasPublicSetters",h),hasPublicConstructor:H(R,"hasPublicConstructor",h),hasStaticFactory:H(R,"hasStaticFactory",h),mutatingMethods:O,...R.dataOnly===void 0?{}:{dataOnly:H(R,"dataOnly",h)},...R.truncatedUntil===void 0?{}:{truncatedUntil:Qt(R,"truncatedUntil",h)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:T(e,"resolverIdentity","$"),compilerIdentity:T(e,"compilerIdentity","$"),compilerOptionsHash:T(e,"compilerOptionsHash","$"),tsconfigHash:T(e,"tsconfigHash","$"),evidenceRequirementsHash:T(e,"evidenceRequirementsHash","$"),...mt?{projectPackageName:mt}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:u,intentReferences:p,safetyUses:m,classShapes:yt,arkRunKernelCalls:d,arkRunManagedNews:b,arkRunCompositionRootHits:I,arkRunDeclarations:Ne,arkOrderPlaneCalls:Y,arkOrderGenericUpdates:X,arkOrderRootHits:j,arkOrderXiFieldWrites:ge,arkOrderIngestWritesXi:oe,arkOrderReleaseKeyCounts:ke,arkOrderXiTtlKeys:qt,arkOrderBudgetLeaks:ve}}a(sr,"parseResolvedFactsInput");function Se(e){let t=N(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=rr(sr(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 Go=["network","filesystem","clock","randomness","environment","process","persistence"],_={type:"string",minLength:1},z={type:"integer",minimum:1},D={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},or={$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:_,message:_,file:D}}},resolverIdentity:_,compilerIdentity:_,compilerOptionsHash:_,tsconfigHash:_,candidateTreeHash:_,evidenceRequirementsHash:_,projectPackageName:_,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:D,contentHash:_,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:_},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:D,specifier:_,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:z,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:D,namedBindings:{type:"array",items:_},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:D,line:z,symbol:_,capability:{enum:Go},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:D,line:z,symbol:_}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:D,line:z,rawIntentName:_,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:_}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:D,line:z,intent:_}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:D,line:z,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:_},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:D,className:_,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:_,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:D,line:z,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:_,viaImport:{type:"boolean"},receiver:_,nameLiteral:_}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:D,line:z,typeName:_,importedFrom:_}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:D,matchedRoot:_,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:D,line:z,uses:{type:"array",items:_},reactsTo:{type:"array",items:_},raises:{type:"array",items:_},sends:{type:"array",items:_}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:D,line:z,callee:_}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:D,line:z,method:_}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:D,matchedRoot:_,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:D,line:z,key:_}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:D,line:z}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:D,line:z,keyCount:{type:"integer",minimum:1}}}},arkOrderXiTtlKeys:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:D,line:z,key:_}}},arkOrderBudgetLeaks:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:D,line:z,kind:_}}},factsHash:_},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 ir="1.0";var tn=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),kt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),rn=Object.freeze(Object.keys(kt).sort()),en=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"}),nn=Object.freeze({process:Object.freeze(["process","node:process"])});function Xe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=en[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=en[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:en[e.slice(0,s)]??null}a(Xe,"capabilityForModuleSpecifier");function Ze(e,t){for(let n of t)if(nn[n]?.includes(e))return n;return null}a(Ze,"forbiddenGlobalForModuleSpecifier");function Je(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=kt[r];if(o)return o}return null}a(Je,"capabilityForAmbientName");function Fe(e){if(e?.pure===!0)return[...tn].sort();let n=(e?.capabilities?.deny??[]).filter(r=>tn.includes(r));return[...new Set(n)].sort()}a(Fe,"effectiveCapabilityDeny");function sn(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(sn,"ambientCoveredByForbiddenGlobals");function vt(e){let t=new Set,n=new Set,r=Object.keys(kt);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 nn[o]??[])t.add(`import-exact:${i}`)}for(let o of Fe(e)){if(t.add(`import:${o}`),o==="process")for(let s of nn.process)t.add(`import-exact:${s}`);for(let s of r)Je(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(vt,"loweredLayerCoverage");function Bo(e){let t=new Set,n=Je(e);n&&t.add(n);for(let[r,o]of Object.entries(kt))(r===e||r.startsWith(`${e}.`))&&t.add(o);return[...t].sort()}a(Bo,"lowerForbiddenGlobal");function he(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(he,"sharedImportsSliceMode");function Ct(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(Ct,"sharedImportsSliceStopAt");var ar=new Map;function lr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(lr,"escapeLiteral");function xt(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(xt,"normalizeGlobSeparators");function zo(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(zo,"bracesBalanced");function q(e){let t=ar.get(e);if(t)return t;let n=xt(e),r=zo(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=lr(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+=lr(c)}let i=new RegExp(`^${o}$`);return ar.set(e,i),i}a(q,"globToRegExp");function Wo(e){return xt(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Wo,"concreteGlobSegments");function cn(e,t){let n=xt(String(e)),r=Wo(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 u of r){let p=-1;for(let m=l;m<i.length;m+=1)if(i[m]===u){p=m;break}if(p<0)return s;c=p,l=p+1}return(c+1)*1e6+r.length*1e4+o}a(cn,"patternSpecificity");function ne(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>q(i).test(n))){for(let i of s.patterns??[])if(q(i).test(n)){let l=cn(i,n);l>o&&(o=l,r=s.name)}}return r}a(ne,"layerForRelativePath");function tt(e,t,n){return mr(e,t,n==="stars"?"stars":"path")}a(tt,"sliceIdForPath");function an(e,t){return mr(e,t?[...t]:void 0,hr)}a(an,"legacyStarsSliceIdForPath");var hr="stars-4.8.23";function mr(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=qo(s);if(i.anchored){let l=Xo(r,i.anchored,n);if(l)return l;continue}i.bare!==void 0&&o.add(i.bare)}return ei(r,o)}a(mr,"sliceIdWithBinding");var St=new Map;function qo(e){let t=St.get(e);if(t)return t;let n={};return yr(e)?n={anchored:Yo(e)}:!e.includes("/")&&!e.includes("\\")&&!e.includes("*")&&(n={bare:e.toLowerCase()}),St.size>=1024&&St.clear(),St.set(e,n),n}a(qo,"parsedSliceFolder");function yr(e){let t=e.split(/[/\\]/).filter(n=>n.length>0);return t.length<2||t[0]==="*"||t[0]==="**"?!1:t.some(n=>n==="*")}a(yr,"isAnchoredSliceEntry");function Yo(e){return e.split(/[/\\]/).filter(t=>t.length>0).map(t=>t.toLowerCase())}a(Yo,"anchoredSlicePattern");function Xo(e,t,n){let r=br(e,t[0]??"");for(let o of r){let s=Zo(e,t,o,n);if(s)return s}}a(Xo,"anchoredSliceIdFromPattern");function Zo(e,t,n,r="path"){let o=[],s=[],i=-1,l=n;for(let c=0;c<t.length;c+=1){let u=t[c];if(u==="*"){if(l>=e.length-1){for(let p=c;p<t.length;p+=1)if(t[p]!=="*")return;break}o.push(e[l].toLowerCase()),s.push(!0),l+=1;continue}if(u==="**"||l>=e.length||e[l].toLowerCase()!==u)return;o.push(e[l].toLowerCase()),s.push(!1),i=o.length-1,l+=1}if(o.length!==0)return r===hr?i<0?void 0:o.slice(i).join("/"):r==="stars"?i<0?void 0:o.filter((c,u)=>u>=i||s[u]).join("/"):o.join("/")}a(Zo,"bindAnchoredSlice");function Rr(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(Rr,"starsKeptSegmentIndexes");function Ar(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(p=>p.length>0).join("/").toLowerCase(),c=o.get(i)??new Set;if(c.has(l))continue;c.add(l),o.set(i,c);let u=r.get(i)??[];u.push(s),r.set(i,u)}for(let[s,i]of r)i.length<2||t.push({from:n.from,to:n.to,stem:s,paths:i,message:Qo(n.from,n.to,i,s)})}return t}a(Ar,"sliceIdentityCollisions");function Jo(e){if(!yr(e))return;let t=e.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(t.some(r=>r==="**"))return;let n=Rr(t);if(n)return n.map(r=>t[r]).join("/")}a(Jo,"starsIdentityStem");function Qo(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(Qo,"formatSliceIdentityCollision");function ei(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(ei,"bareSliceId");function ti(e){let t=new Set;for(let n of e??[]){let o=xt(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(ti,"inferSliceFoldersFromPatterns");function dn(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 ti(r?.patterns)}a(dn,"resolveSliceFolders");function cr(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(cr,"normalizeSegments");function nt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(nt,"trimTrailingSlashes");var ni=["src","app"];function br(e,t){let n=(e[0]??"").toLowerCase(),r=t.toLowerCase();return ni.includes(n)&&r!==n?[0,1]:[0]}a(br,"anchorOffsets");function ri(e){let t=nt(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(ri,"isBlanketRoot");function Me(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=cr(n);for(let s of t){if(typeof s!="string"||s.length===0||ri(s))continue;if(s.includes("*")){let c=nt(s.toLowerCase());if(q(c).test(r)||q(`${c}/**`).test(r))return!0;continue}let i=cr(s);if(i.length===0)continue;let l=br(o,i[0]??"");for(let c of l){if(c+i.length>o.length)continue;let u=!0;for(let p=0;p<i.length;p+=1)if(o[c+p]!==i[p]){u=!1;break}if(u)return!0}}return!1}a(Me,"pathUnderSharedRoot");function dr(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(dr,"sliceMatchesDeclaration");function It(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&dr(r.from,t)&&dr(r.to,n))}a(It,"crossSliceEdgeAllowed");function si(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(si,"peerIsolationDecision");function kr(e){return nt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(kr,"aliasGlobPattern");function vr(e,t){let n=kr(e);if(!n||n==="*"||n==="**")return!1;let r=String(t).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=ln(r),s=q(n),l=(n.split("/").pop()??"").includes("*")?null:q(`${n}/**`),c=a(u=>s.test(u)||l!==null&&l.test(u),"hit");return c(r)||o!==r&&c(o)}a(vr,"aliasGlobMatches");function Sr(e,t){return!e||!t?.length?!1:Me(e,[...t])?!0:t.some(n=>typeof n=="string"&&vr(n,e))}a(Sr,"pathMatchesSharedWalkStop");function un(e){let t=kr(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(un,"splitAliasTarget");function Ir(e,t){for(let n of t.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&vr(n.from,e))return n;return null}a(Ir,"firstSliceAliasEntry");function oi(e,t){let n=Ir(e,t);return n?un(n.to):null}a(oi,"firstSliceAlias");function Qe(e,t,n){if(!e)return{};let r=n??t.sliceFolders,o=tt(e,r?[...r]:void 0,t.sliceIdentity),s=Et(e,o,t.childSlices);if(o||s.childId||s.mismatched)return s.childId?{universeId:o,childId:s.childId}:{universeId:o};let i=oi(e,t);return i?{universeId:i.universeId,childId:i.childId}:{}}a(Qe,"resolveGovernedSlice");function ii(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=Rr(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(ii,"starsUniverseShapes");function ur(e,t){return e.length===t.length&&e.every((n,r)=>n===null||t[r]==="*"||n===t[r])}a(ur,"literalsMatch");function De(e,t){let n=t.split("/").filter(Boolean).map(s=>s.toLowerCase()),r=ii(e);if(n.length===0||r.some(s=>ur(s.literals,n)))return[];let o=new Set;for(let s of r)if(s.legacy.length!==s.literals.length&&ur(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(De,"legacyStarsIdTargets");function Er(e,t){if(e.sliceIdentity!=="stars")return;let n=un(t);if(n)return De(e.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(Er,"legacyAliasUniverse");function fr(e,t,n){let r=Qe(e,t,n);if(!e||t.sliceIdentity!=="stars")return r;if(r.universeId){let o=Ir(e,t);if(!tt(e,[...n],t.sliceIdentity)&&o&&Er(t,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let i=an(e,n),l=t.childSlices,c=l?.sliceIdentity==="stars"?an(e,l.sliceFolders):void 0;return{...r,...i?{legacyUniverse:i}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(fr,"placeForPair");function fn(e,t,n,r){let o=fr(n,e,t),s=fr(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 b=d.childId?.split("/").pop();return{...d,universeId:g.universeId,...b?{childId:`${g.universeId}/${b}`}:{}}},"adopt"),u=c(o,s),p=c(s,o),m=It(e.allowedCrossSlice,u.universeId,p.universeId)||e.sliceIdentity==="stars"&&(i!==u.universeId||l!==p.universeId)&&It(e.allowedCrossSlice,i,l),f=e.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&s.legacyChild!==void 0&&o.legacyChild!==s.legacyChild&&wr(e.childSlices.allowedCrossSlice,o.legacyChild,s.legacyChild),y=a(d=>({...d.universeId?{universeId:d.universeId}:{},...d.childId?{childId:d.childId}:{}}),"strip");return{from:y(u),to:y(p),crossSliceAllowed:m,legacyChildAllowed:f}}a(fn,"resolveGovernedSlicePair");function ai(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(ai,"peerIsolationDenyExplanation");function li(e,t){return`cross-parent slice ${e??"?"} \u2192 ${t??"?"}. The child wall cannot allow another universe.`}a(li,"crossParentExplanation");function ci(e,t,n){return`cross-sibling slice ${e} \u2192 ${t} inside ${n}.`}a(ci,"crossSiblingExplanation");function di(e){return`universe common imports child ${e}. parentMayImportChild is off.`}a(di,"parentImportsChildExplanation");function et(e){if(!e)return;let t=e.split("/").filter(Boolean);return t.length>0?t[t.length-1]:void 0}a(et,"universePairLabel");function ui(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(ui,"isCommonFolderName");function Et(e,t,n){if(!e||!n?.sliceFolders?.length)return{};let r=tt(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 ui(i,n.commonFolders)?{}:{childId:r}}a(Et,"resolveChildSliceId");function fi(e){return nt(e.trim().replace(/\\/g,"/")).toLowerCase()}a(fi,"siblingEntryKey");function ln(e){return e.replace(/^(?:src|app)\//,"")}a(ln,"stripSrcOrApp");function pi(e,t){let n=e.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=ln(t);if(!r)return!1;let o=ln(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(pi,"pathUnderSubtree");function gi(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=fi(o);if(!(!s||s.includes("*"))&&(r===s||e&&pi(e,s)))return!0}return!1}a(gi,"importerInEnforcedSubtree");function hi(e,t,n){return e==null||e==="deny"?!1:e==="advisory"?!0:e.default==="deny"?!1:!gi(t,n,e.enforce)}a(hi,"siblingCrossingAdvisory");function wt(e){if(typeof e!="string")return null;let t=nt(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(wt,"childSlicePatternSegments");function pr(e,t){let n=wt(e),r=wt(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(pr,"childSlicePatternMatches");function wr(e,t,n){if(!e?.length)return!1;for(let r of e)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&pr(r.from,t)&&pr(r.to,n))return!0;return!1}a(wr,"childCrossSliceAllowed");function mi(e,t){let n=wt(e),r=wt(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(mi,"childAllowanceSpansUniverses");function yi(e){let t=si({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:he(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?li(e.fromSlice,e.toSlice):ai(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??Et(e.fromPath,e.fromSlice,n).childId,o=e.toChild??Et(e.toPath,e.toSlice,n).childId,s={crossing:"none",decision:"allow",fromUniverse:e.fromSlice,toUniverse:e.toSlice};return r&&o&&r!==o?e.legacyChildAllowed||wr(n.allowedCrossSlice,r,o)?s:{crossing:"cross-sibling",decision:hi(n.siblings,e.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:ci(r,o,e.fromSlice),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:di(o),fromUniverse:e.fromSlice,toUniverse:e.toSlice}:s}a(yi,"evaluateNestedSliceWall");function Cr(e){return e?.crossing==="cross-sibling"||e?.crossing==="parent-imports-child"}a(Cr,"isChildWallCrossing");function xr(e,t){return Cr(t)?e?.childSlices?.message:e?.message}a(xr,"sliceConsumerMessage");function _t(e){let t=e.verdict.explanation,n=Cr(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(_t,"composeSliceDenialMessage");function Ot(e){if(!e||e.decision==="allow")return{};let t=et(e.fromUniverse),n=et(e.toUniverse);return{...e.reasonId?{reasonId:e.reasonId}:{},...e.reasonId&&t&&n?{universeFrom:t,universeTo:n}:{},...e.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Ot,"sliceFindingExtras");function _r(e,t){let n=[],r=new Set,o=new Set;for(let s of e??[])if(s?.peerIsolation&&s.allowed===!1&&n.push(...Ri(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=tt(i,s.sliceFolders,s.sliceIdentity),c=Et(i,l,s.childSlices);if(!c.mismatched)continue;let u=`${s.from}\0${s.to}\0${c.mismatched.universeId}\0${c.mismatched.childId}`;r.has(u)||(r.add(u),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"||!mi(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(_r,"childSliceConfigFindings");function gr(e,t){let n=new Map;if(!e?.length)return n;for(let r of t){if(typeof r!="string")continue;let o=tt(r,[...e],"stars"),s=an(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(gr,"observedIdsByLegacy");function on(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(on,"newIdHint");function Ri(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=gr(e.sliceFolders,t);for(let i of o?.sliceAliases??[]){if(!i||typeof i.to!="string")continue;let l=un(i.to);if(!l||Er(e,i.to)===void 0)continue;let c=De(e.sliceFolders,l.universeId),u=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 ${on(l.universeId,c,s,u)}; 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(u=>u.includes("/")&&De(e.sliceFolders,u).length>0);if(l.length===0)continue;let c=a(u=>l.includes(u)?on(u,De(e.sliceFolders,u),s):u,"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=gr(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(u=>De(o.sliceFolders,u).length>0);if(l.length===0)continue;let c=a(u=>l.includes(u)?on(u,De(o.sliceFolders,u),s):u,"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(Ri,"legacyStarsIdFindings");function Or(e){if(e!==null&&typeof e=="object"){let t=e.ratchet;if(t===!0)return"always";if(t===!1)return"never"}return"auto"}a(Or,"siblingRatchetMode");function He(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=dn(o,t,r?.layers),c=fn(o,l,s,i),u=c.from,p=c.to,m=u.universeId,f=p.universeId,y=yi({rule:o,fromPath:s,toPath:i,folderCount:l.length,fromSlice:m,toSlice:f,fromChild:u.childId,toChild:p.childId,fromShared:!m&&Me(s,o.sharedRoots),toShared:!f&&Me(i,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(y.decision!=="allow")return{rule:o,peerIsolationReason:y.peerIsolationReason,fromSlice:m,toSlice:f,sliceVerdict:y};continue}if(t!==n)return{rule:o}}if(t!==n&&typeof r?.toPath=="string"&&r.toPath.length>0&&Array.isArray(r?.layers)){let o=r.layers.find(i=>i.name===n),s=Array.isArray(o?.entrypoints)?o.entrypoints.filter(i=>typeof i=="string"&&i.length>0):[];if(s.length>0){let i=String(r.toPath).split(/[/\\]/).join("/");if(!s.some(c=>q(c).test(i)))return{rule:{from:t,to:n,allowed:!1,message:`${t} may only import ${n} via its declared entrypoints (${s.join(", ")}); deep import "${i}" bypasses the public surface.`}}}}}a(He,"findDeniedEdgeDecision");function Tr(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||he(i.sharedImportsSlice)==="deny")continue;let l=dn(i,t,r?.layers),c=Qe(o,i,l).universeId,u=Qe(s,i,l).universeId;if(!(c||!u)&&Me(o,i.sharedRoots))return{fromPath:o,toPath:s,toSlice:u}}}a(Tr,"findSharedImportsSliceBridge");function pn(e,t,n){return dn(e,t,n)}a(pn,"peerSliceFolders");var gn={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."},Tt=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 hn(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(hn,"resolveIntentLayer");function mn(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(mn,"looksLikeArkIntent");function yn(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&mn(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:gn.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:gn.PUBLISH_MISSING_SOURCE}),t}a(yn,"classifyPublishFacts");function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(rt,"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 me(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(me,"valueType");function Ai(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(Ai,"resolveSchemaRef");function Ie(e,t,n,r,o){if(t.$ref){let s=Ai(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ie(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(!rt(e)){o.push({path:n,message:`must be an object; received ${me(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:Ke(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.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 s||Ie(e[l],i,Ke(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&&Ie(e[i],l,Ke(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${me(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)=>Ie(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 ${me(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 ${me(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${me(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(Ie,"validateSchemaNode");var Rn="1.0",Nr="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",bi=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Pr={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},dd={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Nr,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:Nr},schemaVersion:{type:"string",const:Rn,default:Rn},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:[...bi]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Pr,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:Pr}}}};function st(){return{schemaVersion:Rn,byLayer:{},structure:[],invariants:[]}}a(st,"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 ki=new Set(["public","private","protected","static","async","readonly","abstract","override","declare","get","set"]),vi=new Set(["(",",","=",":","[","!","&","|","?","{","}",";","+","-","*","%","<",">","~","^"]),Si=new Set(["return","typeof","case","do","else","in","of","new","delete","void","throw","instanceof","yield","await"]);function Ii(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 Si.has(e.slice(o+1,n+1))}return r==="/"&&e[n-1]==="*"?!1:vi.has(r)}a(Ii,"slashStartsRegex");function Ei(e,t){if(!Ii(e,t))return t;let n=t+1,r=!1;for(;n<e.length;){let o=e[n];if(o===`
4
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(Ei,"skipRegexLiteral");function Ee(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 Ei(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(Ee,"skipStringOrComment");function ae(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=Ee(e,n);continue}break}return n}a(ae,"skipWsAndComments");function Nt(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(Nt,"readIdent");function ye(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=Ee(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(ye,"skipBalanced");function An(e){let t=[],n=0,r;for(;n<e.length&&(n=ae(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=Nt(e,s);if(!p||!ki.has(p.ident))break;o.push(p.ident),s=ae(e,p.end)}if(o.length===1&&o[0]==="static"&&e[s]==="{"){let p=ye(e,s,"{","}");if(p==null){r=e.length;break}n=p;continue}let i=Nt(e,s);if(!i){n+=1;continue}if(s=ae(e,i.end),e[s]==="<"){let p=ye(e,s,"<",">");if(p==null){r=e.length;break}s=ae(e,p)}if(e[s]==="("){let p=ye(e,s,"(",")");if(p==null){r=e.length;break}if(s=ae(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let m=Ee(e,s);if(m!==s){s=m;continue}s+=1}if(e[s]==="{"){let m=ye(e,s,"{","}");if(m==null){r=e.length;break}t.push({name:i.ident,modifiers:o,kind:"method",body:e.slice(s+1,m-1)}),n=m;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,u=0;for(;s<e.length;){let p=Ee(e,s);if(p!==s){s=p;continue}let m=e[s];if(m==="{")l+=1;else if(m==="}"){if(l===0)break;l-=1}else if(m==="(")c+=1;else if(m===")")c-=1;else if(m==="[")u+=1;else if(m==="]")u-=1;else if(m===";"&&l===0&&c===0&&u===0){s+=1;break}s+=1}s>=e.length&&(l>0||c>0||u>0)&&(r=e.length),t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(An,"scanClassMembers");function $r(e,t){let n=t;for(;n<e.length;){let r=ae(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=ye(e,n,o,o==="<"?">":o==="("?")":"]");if(i==null)return null;n=i;continue}if(o==='"'||o==="'"||o==="`"){n=Ee(e,n);continue}n+=1}return null}a($r,"findClassBodyBrace");function bn(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=Lr(e),s;for(;(s=r.exec(o))!==null;){let i=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=$r(e,s.index+s[0].length);if(c==null){n.push({name:i,start:s.index,exported:l,bodyStart:null,bodyEnd:null});continue}let u=ye(e,c,"{","}");n.push({name:i,start:s.index,exported:l,bodyStart:c+1,bodyEnd:u==null?null:u-1})}return n}a(bn,"findClassDeclarations");function Lr(e){let t="",n=0;for(;n<e.length;){let r=Ee(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}a(Lr,"maskStringsAndComments");function Fr(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=Lr(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=$r(e,i.index+i[0].length);else{c="object";let p=ae(e,i.index+i[0].length);l=e[p]==="{"?p:null}if(l==null)continue;let u=ye(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:u==null?e.length:u-1})}return n}a(Fr,"findMemberContainers");function Dr(e){let t=[],n=0,r=!0;for(;n<e.length;){let o=Ee(e,n);if(o!==n){n=o,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=ye(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=Nt(e,n);for(;i&&(i.ident==="async"||i.ident==="get"||i.ident==="set");){let l=ae(e,i.end);e[l]==="*"&&(l=ae(e,l+1));let c=Nt(e,l);if(!c)break;i=c}if(i){let l=ae(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(Dr,"objectLiteralMemberNames");var wi=/\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)/,Ci=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,xi=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,_i=["db","tx","client","prisma","prismaClient","drizzle"],Oi="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",Ur=/\b(?:INSERT\s+INTO|(?<!\b(?:FOR(?:\s+NO\s+KEY)?|DO)\s)UPDATE(?:\s+ONLY)?(?!\s+(?:OF|SET)\b)|DELETE\s+FROM(?:\s+ONLY)?|MERGE\s+INTO|TRUNCATE(?:\s+TABLE)?(?:\s+ONLY)?)\s+(?:(?:(?:"[^"]*"|[A-Za-z_][\w$]*)\s*\.\s*)?(?:"[^"]*"|[A-Za-z_][\w$]*)|\$\{[^}]+\})/i,Ti=/^(?:await|return|throw|yield|new|typeof|void|delete|if|else|case|of|in|instanceof|async|function|class|const|let|var|import|export|from|as|default|type)$/,Mr=/(^|[^\w$])([A-Za-z_$][\w$]*)\s*`((?:[^`\\]|\\[\s\S])*)`/g,Ni=/\bINSERT\s+INTO\b[\s\S]*?\bON\s+CONFLICT\b[\s\S]*?\bDO\s+UPDATE\s+SET\b[^;`]*/gi,Hr="\\((?:[^()]|\\([^()]*\\))*\\)",Pi=`\\bnew\\s+PrismaClient\\s*${Hr}|\\bdrizzle\\s*${Hr}`,$i=/(?<![\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,Li=/(?<![\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 Fi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Fi,"escapeRegExp");function Pt(e){return wi.test(e)||Ci.test(e)}a(Pt,"sourceImportsPersistenceDriverText");function Kr(e,t,n){let r=new RegExp(e.source,"g"),o;for(;(o=r.exec(t))!==null;)o[1]&&n.add(o[1])}a(Kr,"collectFirstGroup");function Di(e){let t=new Set;Kr($i,e,t),Kr(Li,e,t);let n=new RegExp(xi.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(Di,"persistenceClientBindings");function jr(e){return e.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|`(?:[^`\\]|\\[\s\S])*`|'(?:[^'\\]|\\[\s\S])*'|"(?:[^"\\]|\\[\s\S])*"/g,t=>t.charCodeAt(0)===47?t.replace(/[^\n]/g," "):t.charCodeAt(0)===96?t.replace(/--[^\n`]*/g,n=>" ".repeat(n.length)):t)}a(jr,"blankPersistenceComments");function Vr(e){let t=jr(e);Mr.lastIndex=0;let n;for(;(n=Mr.exec(t))!==null;)if(!Ti.test(n[2]??"")&&Ur.test((n[3]??"").replace(Ni," ")))return!0;return!1}a(Vr,"sourceHasTaggedSqlWrite");function kn(e){let t=jr(e),n=[..._i,...Di(t)].map(Fi).join("|");return new RegExp(`(?:\\b(?:${n})(?![\\w$])|${Pi})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${Oi}\\s*\\(`,"i").test(t)?!0:Ur.test(t)}a(kn,"sourceHasPersistenceWrite");var Mi=["no-anemic-model"],zr=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],kd=new RegExp(`\\b(${zr.join("|")})\\b`),Wr="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",vd=new RegExp(`\\bthis\\.${Wr}\\.push\\s*\\(`),Sd=new RegExp(`^this\\.${Wr}\\s*=\\s*\\[\\s*\\]`);function Hi(){return`${zr.join(", ")}, or events-array .push(`}a(Hi,"expectedDomainInvariantWordsPhrase");function qr(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}a(qr,"shapeTruncatedUntil");function Ki(e){let t=qr(e);return t==null?"":` shape analysed until character ${t}`}a(Ki,"shapeTruncationSuffix");function Gr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Gr,"escapeGlobLiteral");function Ui(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+=Gr(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Gr(o)}return new RegExp(`^${n}$`)}a(Ui,"globToRegExp");function Ue(e,t){return!t||t.length===0?!0:t.some(n=>Ui(n).test(e))}a(Ue,"matchesAppliesTo");function Yr(e){return Mi.includes(e)}a(Yr,"isTier2");function Xr(e){return e.mode==="enforced"&&!Yr(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Xr,"severityFor");function Re(e,t,n,r=1){let{severity:o,failsStrict:s}=Xr(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(Re,"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 Lt(e,t,n){return t.filter(r=>!(!r.exported||!Ue(r.file,e.appliesTo)||!$t(r.file,e,n)))}a(Lt,"shapesForRule");function vn(e,t,n){let r=qr(t);if(r!=null)return Re(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}a(vn,"truncatedShapeViolation");function ji(e,t,n){let r=[];for(let o of Lt(e,t,n)){let s=vn(e,o,"members");s&&r.push(s),(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Re(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}a(ji,"evaluateAggregatePrivateState");function Vi(e,t,n){let r=[];for(let o of Lt(e,t,n)){let s=vn(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(Re(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}a(Vi,"evaluateAlwaysValidFactory");function Gi(e,t,n){let r=[],o=Hi();for(let s of Lt(e,t,n)){let i=Ki(s),l=vn(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Re(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(Gi,"evaluateDomainEventOnMutation");function Bi(e,t){let n=[];for(let r of t.files)Ue(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Re(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(Bi,"evaluateOrchestrationOnly");function zi(e,t){let n=[];for(let r of t.files)Ue(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Re(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(zi,"evaluateThinAdapter");function Wi(e,t){let n=[];for(let r of t.files)Ue(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Re(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(Wi,"evaluateWritesViaAggregate");function qi(e,t,n){let r=[];for(let o of Lt(e,t,n))if(o.dataOnly===!0){let s=Re(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(qi,"evaluateNoAnemicModel");function Zr(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(...ji(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Vi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Gi(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Bi(n,e));break;case"thin-adapter":t.push(...zi(n,e));break;case"writes-via-aggregate":t.push(...Wi(n,e));break;case"no-anemic-model":t.push(...qi(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(Zr,"evaluateArkRuleSensors");function Jr(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=>Ue(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=Xr(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=>Ue(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(Jr,"collectEmptyAppliesToFindings");var Br=64;function Yi(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(Yi,"stripTrailingDots");function Xi(e){let t=e.trim(),n=t.length>Br?t.slice(0,Br):t;return Yi(n)}a(Xi,"normalizeIntentPrefix");function Zi(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(Zi,"layerNameLooksDomain");function Ji(e){return e.some(t=>{let n=Xi(t);return n==="Domain"||n.startsWith("Domain.")})}a(Ji,"ownsDomainIntent");function Qi(e,t=[]){return Zi(e)||Ji(t)}a(Qi,"isDomainRoleLayerName");function Qr(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Qi(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))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)&&!Yr(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(Qr,"collectEmptyInvariantCatalogFindings");function ea(e){return e==="PersistenceAdapters"}a(ea,"isPersistenceDriverLayer");function ta(e,t){if(Pt(e))return!0;if(!t)return!1;for(let n of t){if(ea(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Pt(o))return!0}return!1}a(ta,"sourceImportsPersistenceDriver");var na=/\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*=)/,ra=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,sa=/\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*=/,oa=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function ia(e,t,n){if(!t)return null;let r=ta(t,n),o=r&&kn(t)||Vr(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(sa.source,"g"))??[],i=t.match(new RegExp(oa.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,p=na.test(t)||ra.test(t),m=s.length>=1||i.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),y=r&&m||p&&m||r&&f&&(l>=4||s.length>=1)||p&&r;return!u&&!y&&!o?null:{...u?{orchestrationHeavy:!0}:{},...y?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(ia,"deriveArkRuleFileHints");function es(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=ia(r,o,t?.[s]);i&&(n[s]=i)}return n}a(es,"buildArkRuleFileHints");function ts(e){return e==="survived"||e==="not-reached"}a(ts,"verdictRefusesPromotion");function aa(e){switch(e.operator){case"negate-guard":return"the guard is negated";case"drop-throw":return"the throw is removed";case"flip-comparison":return`\`${e.original}\` becomes \`${e.replacement}\``;case"boundary-shift":return`the boundary moves (\`${e.original}\` becomes \`${e.replacement}\`)`;case"const-shift":return`\`${e.original}\` becomes \`${e.replacement}\``}}a(aa,"changeText");function ns(e,t){if(t.verdict==="not-reached")return`Invariant ${e}: the covering tests load the file but never call the declared symbol (mutation probe: not reached); add a test that calls it and re-run --probe-invariants --write before promoting.`;let n=t.survivors[0],r=n?` (${aa(n)} at line ${n.line})`:"";return`Invariant ${e}: the mutation probe shows the covering tests do not pin it${r}; strengthen the test and re-run --probe-invariants --write before promoting.`}a(ns,"probeRefusalReason");var la="INVARIANT_TESTS_PATH_MISSING",ca="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.",da="INVARIANT_COVERAGE_ROOTS_MISSING",ua="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 rs(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(rs,"formatCoverageDiscards");function is(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(is,"isUnderCoverageRoot");function In(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(In,"escapeRegExp");function je(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(je,"normalizePath");function En(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]!==`
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 Ei(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(Ee,"skipStringOrComment");function ae(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=Ee(e,n);continue}break}return n}a(ae,"skipWsAndComments");function Nt(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(Nt,"readIdent");function ye(e,t,n,r){if(e[t]!==n)return null;let o=1,s=t+1;for(;s<e.length&&o>0;){let i=Ee(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(ye,"skipBalanced");function An(e){let t=[],n=0,r;for(;n<e.length&&(n=ae(e,n),!(n>=e.length));){if(e[n]===";"){n+=1;continue}let o=[],s=n;for(;;){let p=Nt(e,s);if(!p||!ki.has(p.ident))break;o.push(p.ident),s=ae(e,p.end)}if(o.length===1&&o[0]==="static"&&e[s]==="{"){let p=ye(e,s,"{","}");if(p==null){r=e.length;break}n=p;continue}let i=Nt(e,s);if(!i){n+=1;continue}if(s=ae(e,i.end),e[s]==="<"){let p=ye(e,s,"<",">");if(p==null){r=e.length;break}s=ae(e,p)}if(e[s]==="("){let p=ye(e,s,"(",")");if(p==null){r=e.length;break}if(s=ae(e,p),e[s]===":")for(s+=1;s<e.length&&e[s]!=="{"&&e[s]!==";";){let m=Ee(e,s);if(m!==s){s=m;continue}s+=1}if(e[s]==="{"){let m=ye(e,s,"{","}");if(m==null){r=e.length;break}t.push({name:i.ident,modifiers:o,kind:"method",body:e.slice(s+1,m-1)}),n=m;continue}if(e[s]===";"){n=s+1;continue}n=s+1;continue}let l=0,c=0,u=0;for(;s<e.length;){let p=Ee(e,s);if(p!==s){s=p;continue}let m=e[s];if(m==="{")l+=1;else if(m==="}"){if(l===0)break;l-=1}else if(m==="(")c+=1;else if(m===")")c-=1;else if(m==="[")u+=1;else if(m==="]")u-=1;else if(m===";"&&l===0&&c===0&&u===0){s+=1;break}s+=1}s>=e.length&&(l>0||c>0||u>0)&&(r=e.length),t.push({name:i.ident,modifiers:o,kind:"field",body:""}),n=s}return{members:t,truncatedAt:r}}a(An,"scanClassMembers");function Lr(e,t){let n=t;for(;n<e.length;){let r=ae(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=ye(e,n,o,o==="<"?">":o==="("?")":"]");if(i==null)return null;n=i;continue}if(o==='"'||o==="'"||o==="`"){n=Ee(e,n);continue}n+=1}return null}a(Lr,"findClassBodyBrace");function bn(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=kn(e),s;for(;(s=r.exec(o))!==null;){let i=t.exportedOnly?s[1]:s[2],l=t.exportedOnly===!0||s[1]==="export",c=Lr(e,s.index+s[0].length);if(c==null){n.push({name:i,start:s.index,exported:l,bodyStart:null,bodyEnd:null});continue}let u=ye(e,c,"{","}");n.push({name:i,start:s.index,exported:l,bodyStart:c+1,bodyEnd:u==null?null:u-1})}return n}a(bn,"findClassDeclarations");function kn(e){let t="",n=0;for(;n<e.length;){let r=Ee(e,n);if(r!==n){t+=e.slice(n,r).replace(/[^\n]/g," "),n=r;continue}t+=e[n],n+=1}return t}a(kn,"maskStringsAndComments");function Fr(e,t){let n=[];if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))return n;let r=kn(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=Lr(e,i.index+i[0].length);else{c="object";let p=ae(e,i.index+i[0].length);l=e[p]==="{"?p:null}if(l==null)continue;let u=ye(e,l,"{","}");n.push({kind:c,bodyStart:l+1,bodyEnd:u==null?e.length:u-1})}return n}a(Fr,"findMemberContainers");function Dr(e){let t=[],n=0,r=!0;for(;n<e.length;){let o=Ee(e,n);if(o!==n){n=o,r=!1;continue}let s=e[n];if(s==="{"||s==="("||s==="["){n=ye(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=Nt(e,n);for(;i&&(i.ident==="async"||i.ident==="get"||i.ident==="set");){let l=ae(e,i.end);e[l]==="*"&&(l=ae(e,l+1));let c=Nt(e,l);if(!c)break;i=c}if(i){let l=ae(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(Dr,"objectLiteralMemberNames");var wi=/\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)/,Ci=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)/,xi=/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle|orm)(?:\.[cm]?[jt]sx?)?['"]/g,_i=["db","tx","client","prisma","prismaClient","drizzle"],Oi="(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))",Ur=/\b(?:INSERT\s+INTO|(?<!\b(?:FOR(?:\s+NO\s+KEY)?|DO)\s)UPDATE(?:\s+ONLY)?(?!\s+(?:OF|SET)\b)|DELETE\s+FROM(?:\s+ONLY)?|MERGE\s+INTO|TRUNCATE(?:\s+TABLE)?(?:\s+ONLY)?)\s+(?:(?:(?:"[^"]*"|[A-Za-z_][\w$]*)\s*\.\s*)?(?:"[^"]*"|[A-Za-z_][\w$]*)|\$\{[^}]+\})/i,Ti=/^(?:await|return|throw|yield|new|typeof|void|delete|if|else|case|of|in|instanceof|async|function|class|const|let|var|import|export|from|as|default|type)$/,Mr=/(^|[^\w$])([A-Za-z_$][\w$]*)\s*`((?:[^`\\]|\\[\s\S])*)`/g,Ni=/\bINSERT\s+INTO\b[\s\S]*?\bON\s+CONFLICT\b[\s\S]*?\bDO\s+UPDATE\s+SET\b[^;`]*/gi,Hr="\\((?:[^()]|\\([^()]*\\))*\\)",Pi=`\\bnew\\s+PrismaClient\\s*${Hr}|\\bdrizzle\\s*${Hr}`,$i=/(?<![\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,Li=/(?<![\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 Fi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Fi,"escapeRegExp");function Pt(e){return wi.test(e)||Ci.test(e)}a(Pt,"sourceImportsPersistenceDriverText");function Kr(e,t,n){let r=new RegExp(e.source,"g"),o;for(;(o=r.exec(t))!==null;)o[1]&&n.add(o[1])}a(Kr,"collectFirstGroup");function Di(e){let t=new Set;Kr($i,e,t),Kr(Li,e,t);let n=new RegExp(xi.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(Di,"persistenceClientBindings");function jr(e){return e.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|`(?:[^`\\]|\\[\s\S])*`|'(?:[^'\\]|\\[\s\S])*'|"(?:[^"\\]|\\[\s\S])*"/g,t=>t.charCodeAt(0)===47?t.replace(/[^\n]/g," "):t.charCodeAt(0)===96?t.replace(/--[^\n`]*/g,n=>" ".repeat(n.length)):t)}a(jr,"blankPersistenceComments");function Vr(e){let t=jr(e);Mr.lastIndex=0;let n;for(;(n=Mr.exec(t))!==null;)if(!Ti.test(n[2]??"")&&Ur.test((n[3]??"").replace(Ni," ")))return!0;return!1}a(Vr,"sourceHasTaggedSqlWrite");function vn(e){let t=jr(e),n=[..._i,...Di(t)].map(Fi).join("|");return new RegExp(`(?:\\b(?:${n})(?![\\w$])|${Pi})(?:\\s*\\.\\s*[A-Za-z_]\\w*)*\\s*\\.\\s*${Oi}\\s*\\(`,"i").test(t)?!0:Ur.test(t)}a(vn,"sourceHasPersistenceWrite");var Mi=["no-anemic-model"],zr=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],kd=new RegExp(`\\b(${zr.join("|")})\\b`),Wr="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",vd=new RegExp(`\\bthis\\.${Wr}\\.push\\s*\\(`);var Sd=new RegExp(`^this\\.${Wr}\\s*=\\s*\\[\\s*\\]`);function Hi(){return`${zr.join(", ")}, or events-array .push(`}a(Hi,"expectedDomainInvariantWordsPhrase");function qr(e){return typeof e.truncatedUntil=="number"?e.truncatedUntil:void 0}a(qr,"shapeTruncatedUntil");function Ki(e){let t=qr(e);return t==null?"":` shape analysed until character ${t}`}a(Ki,"shapeTruncationSuffix");function Gr(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Gr,"escapeGlobLiteral");function Ui(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+=Gr(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Gr(o)}return new RegExp(`^${n}$`)}a(Ui,"globToRegExp");function Ue(e,t){return!t||t.length===0?!0:t.some(n=>Ui(n).test(e))}a(Ue,"matchesAppliesTo");function Yr(e){return Mi.includes(e)}a(Yr,"isTier2");function Xr(e){return e.mode==="enforced"&&!Yr(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Xr,"severityFor");function Re(e,t,n,r=1){let{severity:o,failsStrict:s}=Xr(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(Re,"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 Lt(e,t,n){return t.filter(r=>!(!r.exported||!Ue(r.file,e.appliesTo)||!$t(r.file,e,n)))}a(Lt,"shapesForRule");function Sn(e,t,n){let r=qr(t);if(r!=null)return Re(e,t.file,`Exported class ${t.className} shape analysed until character ${r}; later ${n} may be invisible (sensor ${e.sensor}).`)}a(Sn,"truncatedShapeViolation");function ji(e,t,n){let r=[];for(let o of Lt(e,t,n)){let s=Sn(e,o,"members");s&&r.push(s),(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Re(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`))}return r}a(ji,"evaluateAggregatePrivateState");function Vi(e,t,n){let r=[];for(let o of Lt(e,t,n)){let s=Sn(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(Re(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}}return r}a(Vi,"evaluateAlwaysValidFactory");function Gi(e,t,n){let r=[],o=Hi();for(let s of Lt(e,t,n)){let i=Ki(s),l=Sn(e,s,"methods");l&&r.push(l);for(let c of s.mutatingMethods)c.referencesGuardOrPublish||r.push(Re(e,s.file,`Mutating method ${s.className}.${c.name} does not reference ${o} (sensor domain-event-on-mutation).${i}`))}return r}a(Gi,"evaluateDomainEventOnMutation");function Bi(e,t){let n=[];for(let r of t.files)Ue(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Re(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(Bi,"evaluateOrchestrationOnly");function zi(e,t){let n=[];for(let r of t.files)Ue(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Re(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(zi,"evaluateThinAdapter");function Wi(e,t){let n=[];for(let r of t.files)Ue(r,e.appliesTo)&&$t(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Re(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(Wi,"evaluateWritesViaAggregate");function qi(e,t,n){let r=[];for(let o of Lt(e,t,n))if(o.dataOnly===!0){let s=Re(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(qi,"evaluateNoAnemicModel");function Zr(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(...ji(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Vi(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Gi(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Bi(n,e));break;case"thin-adapter":t.push(...zi(n,e));break;case"writes-via-aggregate":t.push(...Wi(n,e));break;case"no-anemic-model":t.push(...qi(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(Zr,"evaluateArkRuleSensors");function Jr(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=>Ue(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=Xr(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=>Ue(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(Jr,"collectEmptyAppliesToFindings");var Br=64;function Yi(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(Yi,"stripTrailingDots");function Xi(e){let t=e.trim(),n=t.length>Br?t.slice(0,Br):t;return Yi(n)}a(Xi,"normalizeIntentPrefix");function Zi(e){let t=e.toLowerCase();return t.includes("domain")||t.includes("entity")||t.includes("aggregate")||t.includes("model")}a(Zi,"layerNameLooksDomain");function Ji(e){return e.some(t=>{let n=Xi(t);return n==="Domain"||n.startsWith("Domain.")})}a(Ji,"ownsDomainIntent");function Qi(e,t=[]){return Zi(e)||Ji(t)}a(Qi,"isDomainRoleLayerName");function Qr(e){if(e.arkRulesActive!==!0)return[];let t=(e.layers??[]).filter(c=>Qi(c.name,c.intentPrefixes??[])).map(c=>c.name);if(t.length===0)return[];let n=new Set(t);if(!(e.files??[]).some(c=>{let u=typeof c.layer=="string"?c.layer:"";return u.length>0&&n.has(u)}))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)&&!Yr(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(Qr,"collectEmptyInvariantCatalogFindings");function ea(e){return e==="PersistenceAdapters"}a(ea,"isPersistenceDriverLayer");function ta(e,t){if(Pt(e))return!0;if(!t)return!1;for(let n of t){if(ea(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Pt(o))return!0}return!1}a(ta,"sourceImportsPersistenceDriver");var na=/\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*=)/,ra=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,sa=/\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*=/,oa=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function ia(e,t,n){if(!t)return null;let r=ta(t,n),o=r&&vn(t)||Vr(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(sa.source,"g"))??[],i=t.match(new RegExp(oa.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,u=s.length>=2||s.length>=1&&i.length>=2||i.length>=3&&l+c>=6,p=na.test(t)||ra.test(t),m=s.length>=1||i.length>=2,f=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),y=r&&m||p&&m||r&&f&&(l>=4||s.length>=1)||p&&r;return!u&&!y&&!o?null:{...u?{orchestrationHeavy:!0}:{},...y?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}a(ia,"deriveArkRuleFileHints");function es(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),i=ia(r,o,t?.[s]);i&&(n[s]=i)}return n}a(es,"buildArkRuleFileHints");function ts(e){return e==="survived"||e==="not-reached"}a(ts,"verdictRefusesPromotion");function aa(e){switch(e.operator){case"negate-guard":return"the guard is negated";case"drop-throw":return"the throw is removed";case"flip-comparison":return`\`${e.original}\` becomes \`${e.replacement}\``;case"boundary-shift":return`the boundary moves (\`${e.original}\` becomes \`${e.replacement}\`)`;case"const-shift":return`\`${e.original}\` becomes \`${e.replacement}\``}}a(aa,"changeText");function ns(e,t){if(t.verdict==="not-reached")return`Invariant ${e}: the covering tests load the file but never call the declared symbol (mutation probe: not reached); add a test that calls it and re-run --probe-invariants --write before promoting.`;let n=t.survivors[0],r=n?` (${aa(n)} at line ${n.line})`:"";return`Invariant ${e}: the mutation probe shows the covering tests do not pin it${r}; strengthen the test and re-run --probe-invariants --write before promoting.`}a(ns,"probeRefusalReason");var la="INVARIANT_TESTS_PATH_MISSING",ca="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.",da="INVARIANT_COVERAGE_ROOTS_MISSING",ua="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 rs(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(rs,"formatCoverageDiscards");function is(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(is,"isUnderCoverageRoot");function En(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(En,"escapeRegExp");function je(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}a(je,"normalizePath");function wn(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
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]===`
7
7
  `?`
8
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 u=e[r+1];t?n.push(" ",u===void 0?"":" "):(n.push("\\"),u!==void 0&&n.push(u)),r+=u===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(En,"maskNonCode");function fa(e,t){if(!t)return;let n=In(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(En(e,!1))?.[2];return s===void 0?void 0:s}a(fa,"matchTestTitle");function as(e,t){if(!t)return;let n=In(t),r=En(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(as,"declarationShape");function pa(e,t,n){let r=a(o=>An(o).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let o of bn(e))if(!(o.name!==t||o.bodyStart==null)&&r(e.slice(o.bodyStart,o.bodyEnd??e.length)))return"method";for(let o of Fr(e,t)){let s=e.slice(o.bodyStart,o.bodyEnd);if(o.kind==="class-expression"&&r(s)||o.kind==="object"&&Dr(s).includes(n))return"method";if(o.kind==="namespace"){let i=as(s,n);if(i==="function"||i==="const")return i}}}a(pa,"classMemberShape");function ga(e,t){let n=e.lastIndexOf(`
9
+ `?" ":c),r+=1}continue}n.push(s),r+=1}return n.join("")}a(wn,"maskNonCode");function fa(e,t){if(!t)return;let n=En(t),s=new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*(['"\`])((?:(?!\\1)[^\\\\]|\\\\.)*?${n}(?:(?!\\1)[^\\\\]|\\\\.)*?)\\1`,"i").exec(wn(e,!1))?.[2];return s===void 0?void 0:s}a(fa,"matchTestTitle");function as(e,t){if(!t)return;let n=En(t),r=wn(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(as,"declarationShape");function pa(e,t,n){let r=a(o=>An(o).members.some(s=>s.kind==="method"&&s.name===n),"hasClassMethod");for(let o of bn(e))if(!(o.name!==t||o.bodyStart==null)&&r(e.slice(o.bodyStart,o.bodyEnd??e.length)))return"method";for(let o of Fr(e,t)){let s=e.slice(o.bodyStart,o.bodyEnd);if(o.kind==="class-expression"&&r(s)||o.kind==="object"&&Dr(s).includes(n))return"method";if(o.kind==="namespace"){let i=as(s,n);if(i==="function"||i==="const")return i}}}a(pa,"classMemberShape");function ga(e,t){let n=e.lastIndexOf(`
10
10
  `,t-1)+1,r=e.indexOf(`
11
11
  `,t);return e.slice(n,r===-1?e.length:r)}a(ga,"lineAt");function ha(e){let t=e.trim();return/^import\b/.test(t)||/^export\s+/.test(t)&&/\bfrom\b/.test(t)?!0:/\brequire\s*\(/.test(t)}a(ha,"isImportLine");function ss(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(ha(ga(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 u=l;for(i(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===u){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(ss,"mentionContext");function ls(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(ls,"symbolNeedle");function ma(e){return ls(e.coverage?.symbol)?.name??e.id}a(ma,"declaredLabel");function os(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(os,"sortedContentFiles");function ya(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(y=>je(y))),s=(t.coverageRoots??[]).filter(y=>typeof y=="string"&&y.length>0),i=e.coverage?.test!==!1&&n,l=ls(e.coverage?.symbol??void 0),c,u;if(i){for(let y of r){let d=t.fileContents[y];if(!d)continue;let g=fa(d,e.id);if(g!==void 0){if(s.length===0||is(y,s)){c={file:y,title:g};break}u??={file:y,title:g}}}c??=u}let p;if(l)for(let y of os(t.fileContents)){if(o.has(je(y)))continue;let d=t.fileContents[y];if(!d)continue;let g=l.className?pa(d,l.className,l.name):as(d,l.name);if(g){p={file:y,shape:g};break}}let m;if(!c&&!p){if(i)for(let y of r){let d=t.fileContents[y];if(!d)continue;let g=ss(d,e.id,!0);if(g){m={file:y,context:g};break}}if(!m&&l)for(let y of os(t.fileContents)){if(o.has(je(y)))continue;let d=t.fileContents[y];if(!d)continue;let g=ss(d,l.name,!1);if(g){m={file:y,context:g};break}}}let f=c?{kind:"test-title",file:c.file,title:c.title}:p?{kind:"declaration",file:p.file,shape:p.shape}:m?{kind:"mention-only",file:m.file,context:m.context}:{kind:"none"};return f.kind==="mention-only"&&f.context==="comment"&&l&&Ra(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...p?{declaration:p}:{}}}a(ya,"rankCoverage");function Ra(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${In(n)}(?=$|[^A-Za-z0-9_$])`),s=je(r);for(let i of Object.keys(e)){if(t.has(je(i))||je(i)===s)continue;let l=e[i];if(l&&o.test(En(l,!0)))return!0}return!1}a(Ra,"symbolInCodeElsewhere");function Aa(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Aa,"countsAsCoverage");function ba(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(ba,"mentionWhere");function ka(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} ${ma(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${ba(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(ka,"describeCoverage");function cs(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=rs(s),l=rs(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",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,m=u.join(", "),f=[],y=[];for(let d of t){let g=d.coverage?.test!==!1,b=d.coverage?.symbol,I=!r&&g,E=ya(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},I),C=E.best,_=[];I&&E.testTitle&&_.push("test-title"),E.declaration&&_.push("symbol");let q=Aa(C),te,Y;I&&E.testTitle&&(te=E.testTitle.file,p&&(Y=!is(te,u)));let v=E.declaration?.file,j=E.declaration?.shape,qe=d.coverage?.test===!0||!!b||d.coverage===void 0,ge=d.coverage?.test===!1&&!b,Ye=qe&&q||ge&&d.mode!=="enforced"?!0:q,se=r&&g&&!q;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:Ye&&!se,evidence:_,partial:se,description:d.description,...te!==void 0?{testEvidenceFile:te}:{},...v!==void 0?{symbolEvidenceFile:v}:{},...j!==void 0?{shape:j}:{},...Y!==void 0?{outsideDeclaredRoots:Y}:{},coverageRootsDeclared:p}),Y===!0&&te!==void 0&&y.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${te}, which is outside the declared coverage roots (${m}). 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:te,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!Ye||se){let Te=d.mode==="enforced"&&!se,ke=r||n.length===0?"never-had-tests":"tests-disappeared";y.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).`:ge?`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}: ${ka(d,C)} (${ke==="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:Te?"error":"warning",failsStrict:Te,kind:ke})}}return{coverage:f,violations:y,partial:f.some(d=>d.partial)}}a(cs,"evaluateInvariantCoverage");function ds(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.`}:e.probe?.fresh===!0&&ts(e.probe.verdict)?{ok:!1,reason:ns(e.invariantId,e.probe),blocker:"probe-survived"}:{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(ds,"canPromoteInvariant");function Sn(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(Sn,"nonEmptyPathStrings");function va(e){return!e||typeof e!="object"?[]:[...Sn(e.testGlobs),...Sn(e.coverageRoots)]}a(va,"configuredInvariantTestsPaths");function Sa(e){return va(e).length>0}a(Sa,"hasConfiguredInvariantTestsPath");function wn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(wn,"catalogDemandsInvariantTestsPath");function us(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&wn(e.invariants);return e.adopted!==!0||!t?[]:Sa(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:la,message:ca,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(us,"collectMissingInvariantTestsPathFindings");function Ia(e){return!e||typeof e!="object"?[]:Sn(e.coverageRoots)}a(Ia,"configuredCoverageRoots");function Ea(e){return Ia(e).length>0}a(Ea,"hasConfiguredCoverageRoots");function Cn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(Cn,"catalogHasEnforcedInvariant");function fs(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&Cn(e.invariants)?Ea(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:da,message:ua,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(fs,"collectMissingCoverageRootsFindings");function wa(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(wa,"normalizeExtraMergeTeethClassification");function Ft(e){let t=wa(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(Ft,"extraMergeTeethAllowed");function ps(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(ps,"classifyResolvedLayerCoverage");var Ca=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"];var xa=["forRoot","forRootAsync"],_a=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"];var Fd=new Set(xa),Dd=new Set(_a);var Md=new Set(Ca);function gs(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}a(gs,"isArkRunKernelModuleSpecifier");var Oa=["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"],xn=new Set(Oa);function hs(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(xn.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(xn.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:xn.has(e.slice(0,r))}a(hs,"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 ms=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("CROSS_WALL_DUPLICATE","layer","Code copied across a wall","Near-identical code sits on two sides of a slice wall (or in two layers that may not import each other). The wall would deny the import, so the code was copied instead. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; they never enter the check, so the verdict does not change. Same-slice copies are counted, never listed.","Move one copy to a shared home the wall allows \u2014 a declared shared root, the universe common folder, or a layer both sides may import \u2014 then import it from both sides. One move at a time, through the write gate (/ark-place names the destination). Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),k("CROSS_LAYER_DUPLICATE","layer","Code copied in two layers","Near-identical code sits in two layers, and at least one of them may import the other. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; the verdict does not change.","Keep one copy in the lower layer both sides may import, and import it from the other. One move at a time, through the write gate. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),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/, or a slice file named arkrules.<Layer>.json beside governed code, is not in the effective catalog, so none of its rules are enforced. Drift looks like governance until someone notices.","Reference a central file from arkRules, set childSlices.arkRulesFile so a slice file is discovered, or delete it. Advisory only: it never fails the check.",{oftenAdvisory:!0}),k("ARKRULE_DUPLICATE_ID","arkrules","ArkRule id declared more than once","Two ArkRules files in one layer declare the same effective id. Central ids stay bare. A slice file is namespaced as <childId>#<localId>, so the same local id in two slices is not a duplicate.","Rename one id, or split the files onto different slices. Config load fails closed. The catalog is not enforced until the id is unique."),k("ARKRULE_SCOPE_ESCAPES_SLICE","arkrules","Slice ArkRule appliesTo leaves its slice","A file discovered from childSlices.arkRulesFile set appliesTo to a glob that can match outside that child slice. The default, when appliesTo is omitted, is the slice directory.","Narrow appliesTo to the slice directory, or omit it. Config load fails closed. The escaping rule is not enforced."),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_PROBE_SURVIVED","arkrules","Covering tests do not pin the invariant","The committed invariant probe (.ark/invariant-probe.json, written by arkgate-check --probe-invariants --write) shows, for files that have not changed since, that the covering tests still pass with the invariant's symbol broken on purpose (survived) or never call it (not reached). The test names the rule but does not pin it. A status and inventory line only: it never enters the check, so the verdict does not change.","Add a test case that fails when the rule is broken (the line names the change that went unnoticed), then re-run arkgate-check --probe-invariants --write and commit the file. Promotion to enforced refuses while the fresh artifact says survived or not reached; a stale, killed, inconclusive or missing result changes nothing.",{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("ORPHAN_MODULE","drift","File nothing imports","No governed file, test or entry point imports this module. It is the leftover an agent leaves when a rewrite lands next to the old file. Status reads it from the import facts the check already resolved, so it never changes the verdict. When a dynamic import, an unresolved import or an unmapped entry could reach the file, the item says so (maybe-dynamic, maybe-unresolved) and the list is partial.","Delete the file through the write gate, one file at a time. If a framework, a script or a runtime loader uses it, add a glob with a reason to .ark/entry-points.json (optional reviewBy) instead. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),k("UNUSED_EXPORT","drift","Export nothing imports by name","An export no governed file or test imports by name. Listed only in status details (`--doctor --all`) and the report. Default, namespace, star, dynamic and require use count as using every export, so those files are skipped.","Drop the export keyword (or the code) if nothing outside the file needs it, or keep it when it is public API an entry point exposes. Advisory only \u2014 it never fails a run.",{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.")]),Ud=new Map(ms.map(e=>[e.ruleId,e])),jd=Object.freeze(ms.map(e=>e.ruleId));var Ta=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."})]),Na=new Map(Ta.map(e=>[e.reasonId,e]));function ys(e){if(!(typeof e!="string"||e.length===0))return Na.get(e)}a(ys,"sliceReasonHint");var Pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,$a=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,La=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Fa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&($a.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":La.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(Fa,"classifyLayerImportKind");function Da(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}a(Da,"sliceHintAction");function Ma(e){let t=ys(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${Da(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=Fa(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(Ma,"layerImportNextAction");function Ha(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Ha,"arkRunCallSiteName");function Ka(e){let t=Ha(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(Ka,"arkRunNextAction");function Ae(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ma(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 Ka(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(Ae,"deterministicNextAction");var Ua=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],tu=new Set(Ua);var Rs={"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"},ja="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ks(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(ks,"isDomainRoleLayer");function Va(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Va,"compareFindings");function fe(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Rs[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:Ae({ruleId:Rs[t],fromLayer:s?.fromLayer,target:s?.target})}}a(fe,"finding");function Ga(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(Ga,"bagForFile");function As(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(As,"emitKinds");function bs(e){return e==="subscribe"||e==="register-handler"}a(bs,"handleKinds");function Ba(e){return e==="resolve"||e==="resolve-singleton"}a(Ba,"dependKinds");function za(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(fe(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((u,p)=>u.file.localeCompare(p.file));if(l.length===0){r.push(fe(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(u=>u.hasKernelFactory))continue;let c=l[0];r.push(fe(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(za,"evaluateMissingRoot");function Wa(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||!gs(c))continue;let u=r(l.from);u&&ks(u,s.get(u)??[])&&i.push(fe(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return i}a(Wa,"evaluateKernelInDomain");function qa(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),c=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(c.has(p.file))continue;let m=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(m.endsWith("Error")||m==="Error")||m.endsWith("DTO")||m.endsWith("VO"))continue;let f=o(p.file);!f||!i.has(f)||ks(f,l.get(f)??[])||u.push(fe(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}a(qa,"evaluateDirectNew");function Ya(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(!As(c.kind)&&!bs(c.kind)&&!Ba(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&c.kind!=="publisher"&&i.push({code:ja,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 p=Ga(n,c.file);if(As(c.kind)){if(p.raises.has(c.nameLiteral)||p.sends.has(c.nameLiteral))continue;s.push(fe(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},o));continue}if(bs(c.kind)){if(p.reactsTo.has(c.nameLiteral))continue;s.push(fe(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},o));continue}p.uses.has(c.nameLiteral)||s.push(fe(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(Ya,"evaluateUndeclared");function Xa(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||!hs(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(fe(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(Xa,"evaluateTransportBypass");function vs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Ft(e.classification),r=Ya(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...za(t,e.compositionRootHits,n),...Wa(t,e.layers,e.dependencies,e.layerForFile,n),...qa(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Xa(t,e.dependencies,e.layerForFile,n)].sort(Va),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}a(vs,"evaluateArkRunSensors");function Ss(e){return Z(e)}a(Ss,"arkOrderGlobToRegExp");function Is(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Is,"isArkOrderModuleSpecifier");var Es={"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 Za(e,t){return!t||t.length===0?!0:t.some(n=>Ss(n).test(e))}a(Za,"matchesArkOrderAppliesTo");function Ja(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(Ja,"isDomainRoleLayer");function le(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Es[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:Ae({ruleId:Es[t],fromLayer:s?.fromLayer,target:s?.target})}}a(le,"finding");function ws(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Ft(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(le(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 u of e.planeRootHits){let p=c.get(u.matchedRoot)??[];p.push(u),c.set(u.matchedRoot,p)}for(let u of o){let p=c.get(u)??[];if(p.length===0){r.push(le(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}p.some(m=>m.hasPlaneFactory)||r.push(le(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!Is(u))continue;let p=e.layerForFile(c.from);p&&Ja(p,s.get(p)??[])&&r.push(le(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let c of e.genericUpdates)r.push(le(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(le(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(le(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(le(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(le(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 u=e.layerForFile(c.file);!u||!l.has(u)||Za(c.file,t.appliesTo)&&r.push(le(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:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}a(ws,"evaluateArkOrderSensors");var we={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Cs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...we,default:[]},kernelRoots:{...we},managedLayers:{...we,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},xs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...we,default:[]},managedLayers:{...we,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...we,default:[]},appliesTo:{...we,default:[]}}};function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ot,"isObject");function Qa(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)ot(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Qa,"declaredLayerNames");function _s(e){if(!ot(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(_s,"defaultedArkRun");function Os(e){if(!ot(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(Os,"defaultedArkOrder");function Ts(e,t,n,r){if(!Array.isArray(t))return;let o=Qa(e);t.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!o.has(s)&&r.push({path:`$.${n}.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})})}a(Ts,"validateManagedLayersDeclared");function Ns(e,t){let n=e.arkRun;if(n===void 0||!ot(n))return;let r=n.managedLayers;if(Ts(e,r,"arkRun",t),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(r)||r.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Ns,"validateArkRunExtra");function Ps(e,t){let n=e.arkOrder;if(n===void 0||!ot(n))return;let r=n.managedLayers;if(Ts(e,r,"arkOrder",t),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(r)||r.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Ps,"validateArkOrderExtra");var Mt={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ks={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:{...Mt,minItems:1}}}]},Us={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:{...Mt,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...Mt,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:{...Mt},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)."},arkRulesFile:{type:"string",minLength:1,description:"Filename read at each child slice root this wall already resolved. The only token is <Layer>, replaced with a declared layer name (arkrules.<Layer>.json). No slash and no wildcard. A discovered file that omits appliesTo is scoped to that slice directory. Explicit appliesTo outside the slice fails config load (ARKRULE_SCOPE_ESCAPES_SLICE). The effective id is <childId>#<localId>. A build that rejects unknown childSlices fields fails at config load (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 unpinned alias as an owed move. pinned true lists the alias separately and does not count it as debt. reason is a doctor label and does not pin by itself. 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},pinned:{type:"boolean",description:"True when a framework forces the path to stay. The alias is not an owed move and does not clear other honesty debt."},reason:{type:"string",minLength:1,description:"Doctor label, such as framework-route. A label alone does not pin."}}}},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 X(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(X,"isObject");function Ht(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Ht,"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 js(e,t){sl(e,t),il(e,t),dl(e,t),El(e,t),Il(e,t)}a(js,"validateSliceContract");var $s='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',Ls="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function el(e){return e==="*"||e==="**"}a(el,"isWildcardSegment");function Vs(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&&el(t[n-1]??"");)n-=1;let r=t.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(Vs,"coveredFolder");function tl(e,t){return e.length<=t.length&&e.every((n,r)=>t[r]===n)}a(tl,"isPrefixOf");function nl(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(!X(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("/"),u=c.findIndex(f=>f.includes("*")),p=u===-1?c:c.slice(0,u),m=Vs(p.join("/"));m&&o.push(m)}}return o}a(nl,"ruleLayerFolders");function rl(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 Ls;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=Vs(n);return o===null?null:o.length===0?Ls:t.some(s=>tl(o,s))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(rl,"stopAtEntryIssue");function sl(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!X(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:$s});return}if(!X(s)){t.push({path:i,message:$s});return}for(let p of Object.keys(s))p!=="mode"&&p!=="stopAt"&&t.push({path:Ht(i,p),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,u=nl(e,r);l.forEach((p,m)=>{let f=`${i}.stopAt[${m}]`;if(typeof p!="string"){t.push({path:f,message:"must be a non-empty path or glob"});return}let y=rl(p,u);if(y){t.push({path:f,message:y});return}let d=be(p.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(d)){t.push({path:f,message:"duplicate stopAt entry"});return}c.add(d)})})}a(sl,"validateSharedImportsSlice");var ol=["deny","advisory"],Fs='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function il(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!X(r))return;let s=r.childSlices;if(!X(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){ol.includes(i)||t.push({path:l,message:Fs});return}if(!X(i)){t.push({path:l,message:Fs});return}for(let u of Object.keys(i))u!=="default"&&u!=="enforce"&&u!=="ratchet"&&t.push({path:Ht(l,u),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((u,p)=>{let m=`${l}.enforce[${p}]`;if(typeof u!="string"||u.trim().length===0){t.push({path:m,message:"must be a non-empty child slice id or subtree path"});return}let f=be(u.trim().replace(/\\/g,"/"));if(f.split("/").some(y=>y.length===0||y==="."||y==="..")){t.push({path:m,message:"must be a child slice id or subtree path without . or .."});return}if(f.includes("*")){t.push({path:m,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(f)){t.push({path:m,message:"duplicate enforce entry"});return}c.add(f)})})}a(il,"validateChildSliceSiblings");var al="must be a slice id with a slash. A bare name is ambiguous across universes.",ll="* matches one whole path segment. ** and a partial segment are not wildcards.";function cl(e){let t=be(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return al;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 ll}return null}a(cl,"childCrossSlicePatternIssue");function Ds(e){return be(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ds,"childCrossSlicePatternKey");function dl(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!X(r))return;let s=r.childSlices;if(!X(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((u,p)=>{let m=`${l}[${p}]`;if(!X(u)){t.push({path:m,message:"must be an object with from and to"});return}for(let y of Object.keys(u))y!=="from"&&y!=="to"&&t.push({path:Ht(m,y),message:"unknown field"});for(let y of["from","to"]){let d=u[y],g=`${m}.${y}`;if(typeof d!="string"||d.trim().length===0){t.push({path:g,message:"must be a non-empty slice id"});continue}let b=cl(d);b&&t.push({path:g,message:b})}if(typeof u.from!="string"||typeof u.to!="string")return;let f=`${Ds(u.from)}\0${Ds(u.to)}`;if(!f.startsWith("\0")&&!f.endsWith("\0")){if(c.has(f)){t.push({path:m,message:"duplicate child slice allowance"});return}c.add(f)}})})}a(dl,"validateChildSliceAllowedCrossSlice");var Ve="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.",ul="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/*).",fl="overlaps a slice folder. An alias covers only files outside the slice trees.",pl="two slice aliases match the same file";function gl(e){return be(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(gl,"aliasPathSegments");function hl(e){let t=e[e.length-1];return t===void 0||t.includes("*")?[...e]:[...e,"**"]}a(hl,"aliasSegmentsWithSubtree");function Gs(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(Gs,"concreteGlobPrefix");function it(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(it,"segmentsArePrefix");function ml(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(ml,"anchoredSlicePrefix");function yl(e,t){let n=Gs(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return it(t,n)||it(t,o)?!0:r?it(n,t)&&n.length<t.length||it(n,["src",...t])&&n.length<t.length+1||it(n,["app",...t])&&n.length<t.length+1:!1}a(yl,"globOverlapsAnchored");function Rl(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=Gs(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(Rl,"globOverlapsBare");function Al(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return Rl(e,n[0]);let r=ml(t);return r?yl(e,r):!1}a(Al,"globOverlapsSliceEntry");function bl(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(bl,"aliasGlobIssue");function kl(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 u=0;u<s.length;u+=1)s[u]!=="*"&&(i=u);if(i<0)continue;let l=s.filter((u,p)=>p>=i||u==="*").map(u=>u==="*"?null:u),c=s.slice(i).map(u=>u==="*"?null:u);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(kl,"universeShapes");function Dt(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(Dt,"shapeMatches");function vl(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 Ve;let r=n.split("/").map(s=>s.toLowerCase());if(t.length===0||t.some(s=>Dt(s,r)))return Ve;if(t.some(s=>Dt(s,r.slice(0,-1))))return null;let o=new Set(t.filter(s=>s.legacy!==void 0&&!Dt({literals:s.legacy},r)&&Dt({literals:s.legacy},r.slice(0,-1))).map(s=>s.literals.map(i=>i??"*").join("/")));return o.size===1?null:o.size>1?ul:Ve}a(vl,"aliasTargetIssue");function Ms(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(Ms,"aliasGlobVariants");function Sl(e,t){let n=Ms(e),r=Ms(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(Sl,"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],u=t[r];(c===u||c==="*"||u==="*")&&(l=Ce(e,t,n+1,r+1,o))}return o.set(s,l),l}a(Ce,"globsCanMatchSame");var Hs="must be a filename with exactly one <Layer> token and no slash or wildcard (arkrules.<Layer>.json)";function Il(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!X(r))return;let s=r.childSlices;if(!X(s)||s.arkRulesFile===void 0)return;let i=`$.rules[${o}].childSlices.arkRulesFile`,l=s.arkRulesFile;if(typeof l!="string"||l.length===0){t.push({path:i,message:Hs});return}(l.split("<Layer>").length!==2||/[*\\/]/.test(l)||l.includes(".."))&&t.push({path:i,message:Hs})})}a(Il,"validateChildSliceArkRulesFile");function El(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!X(r))return;let s=r.childSlices;if(!X(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=kl(r.sliceFolders,r.sliceIdentity),u=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(m=>typeof m=="string"&&m.length>0),p=[];i.forEach((m,f)=>{let y=`${l}[${f}]`;if(!X(m)){t.push({path:y,message:"must be an object with from and to"});return}for(let b of Object.keys(m))b!=="from"&&b!=="to"&&b!=="pinned"&&b!=="reason"&&t.push({path:Ht(y,b),message:"unknown field"});let d=m.from,g=m.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${y}.from`,message:"must be a non-empty path glob"});else{let b=bl(d);if(b)t.push({path:`${y}.from`,message:b});else{let I=hl(gl(d));u.some(E=>Al(I,E))&&t.push({path:`${y}.from`,message:fl});for(let E of p)if(Sl(E,I)){t.push({path:y,message:pl});break}p.push(I)}}if(typeof g!="string"||g.trim().length===0)t.push({path:`${y}.to`,message:Ve});else{let b=vl(g,c);b&&t.push({path:`${y}.to`,message:b})}})})}a(El,"validateChildSliceAliases");function Kt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(Kt,"normalizeStewardId");function Bs(e){let t=Kt(e);return!t||_n(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Bs,"isGitHubHandle");function wl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t.includes("@")||t.includes(" ")||_n(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(wl,"isGitHubEmail");function Cl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Bs(t[1])?Kt(t[1]):null}a(Cl,"githubHandleFromEmail");function zs(e){let t=Cl(e);if(t)return t;let n=Kt(e);return!n||_n(n)?null:Bs(n)||wl(n)?n:null}a(zs,"canonicalStewardId");var xl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function _n(e){let t=Kt(e);return!t||xl.test(t)}a(_n,"isAutomationAuthor");var oe="1.3",_l=["public","auth","admin","internal"];function Ol(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(Ol,"isFutureHouseLayer");function Tl(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(Tl,"layerOwnersList");function Ys(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ol(t)&&!Tl(t)).map(t=>t.name)}a(Ys,"layersMissingRequiredOwners");function Xs(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(Xs,"missingLayerOwnersNextAction");var On="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Ws=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Nl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Pl(){let e=[];for(let t of Ws)for(let n of Ws)t===n||Nl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Pl,"createDefaultRules");var Zs=Pl(),Tn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],J={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:On,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:On,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:oe,default:oe},name:{type:"string",minLength:1},include:{...J,minItems:1,default:["src"]},exclude:{...J,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Zs,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...J,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{description:"A project-relative ArkRules path, or a list of paths merged into one catalog for this layer. A string keeps today's behaviour. An older build that types this value as a string rejects an array at config load.",oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1}}]},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...J,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...J,minItems:1},exclude:J,intentPrefixes:J,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[..._l]},owners:{...J,minItems:1},forbiddenGlobals:J,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},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:{...J,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:{...J,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:Ks,childSlices:Us}},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:{...J,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:{...J,minItems:1}}},arkRun:Cs,arkOrder:xs}},pe=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
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 u=l;for(i(o,"string"),o+=1;o<s;){let p=e[o];if(p==="\\"){i(o,"string"),e[o+1]!==void 0&&i(o+1,"string"),o+=e[o+1]===void 0?1:2;continue}if(p===u){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(ss,"mentionContext");function ls(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(ls,"symbolNeedle");function ma(e){return ls(e.coverage?.symbol)?.name??e.id}a(ma,"declaredLabel");function os(e){return Object.keys(e).sort((t,n)=>t<n?-1:t>n?1:0)}a(os,"sortedContentFiles");function ya(e,t,n=!0){let r=t.testFiles??[],o=new Set(r.map(y=>je(y))),s=(t.coverageRoots??[]).filter(y=>typeof y=="string"&&y.length>0),i=e.coverage?.test!==!1&&n,l=ls(e.coverage?.symbol??void 0),c,u;if(i){for(let y of r){let d=t.fileContents[y];if(!d)continue;let g=fa(d,e.id);if(g!==void 0){if(s.length===0||is(y,s)){c={file:y,title:g};break}u??={file:y,title:g}}}c??=u}let p;if(l)for(let y of os(t.fileContents)){if(o.has(je(y)))continue;let d=t.fileContents[y];if(!d)continue;let g=l.className?pa(d,l.className,l.name):as(d,l.name);if(g){p={file:y,shape:g};break}}let m;if(!c&&!p){if(i)for(let y of r){let d=t.fileContents[y];if(!d)continue;let g=ss(d,e.id,!0);if(g){m={file:y,context:g};break}}if(!m&&l)for(let y of os(t.fileContents)){if(o.has(je(y)))continue;let d=t.fileContents[y];if(!d)continue;let g=ss(d,l.name,!1);if(g){m={file:y,context:g};break}}}let f=c?{kind:"test-title",file:c.file,title:c.title}:p?{kind:"declaration",file:p.file,shape:p.shape}:m?{kind:"mention-only",file:m.file,context:m.context}:{kind:"none"};return f.kind==="mention-only"&&f.context==="comment"&&l&&Ra(t.fileContents,o,l.name,f.file)&&(f={kind:"declaration-miss",symbol:l.name}),{best:f,...c?{testTitle:c}:{},...p?{declaration:p}:{}}}a(ya,"rankCoverage");function Ra(e,t,n,r){let o=new RegExp(`(?:^|[^A-Za-z0-9_$])${En(n)}(?=$|[^A-Za-z0-9_$])`),s=je(r);for(let i of Object.keys(e)){if(t.has(je(i))||je(i)===s)continue;let l=e[i];if(l&&o.test(wn(l,!0)))return!0}return!1}a(Ra,"symbolInCodeElsewhere");function Aa(e){switch(e.kind){case"test-title":case"declaration":return!0;case"mention-only":case"declaration-miss":case"none":return!1}}a(Aa,"countsAsCoverage");function ba(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(ba,"mentionWhere");function ka(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} ${ma(e)}\` in ${t.file}`;case"mention-only":return`${e.id} appears only in ${ba(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(ka,"describeCoverage");function cs(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=rs(s),l=rs(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",u=(e.coverageRoots??[]).filter(d=>typeof d=="string"&&d.length>0),p=u.length>0,m=u.join(", "),f=[],y=[];for(let d of t){let g=d.coverage?.test!==!1,b=d.coverage?.symbol,v=!r&&g,I=ya(d,{fileContents:e.fileContents,testFiles:n,coverageRoots:u},v),C=I.best,x=[];v&&I.testTitle&&x.push("test-title"),I.declaration&&x.push("symbol");let Y=Aa(C),te,X;v&&I.testTitle&&(te=I.testTitle.file,p&&(X=!is(te,u)));let S=I.declaration?.file,j=I.declaration?.shape,qe=d.coverage?.test===!0||!!b||d.coverage===void 0,ge=d.coverage?.test===!1&&!b,Ye=qe&&Y||ge&&d.mode!=="enforced"?!0:Y,oe=r&&g&&!Y;if(f.push({invariantId:d.id,layer:d.provenance.layer,sourceFile:d.provenance.sourceFile,mode:d.mode,covered:Ye&&!oe,evidence:x,partial:oe,description:d.description,...te!==void 0?{testEvidenceFile:te}:{},...S!==void 0?{symbolEvidenceFile:S}:{},...j!==void 0?{shape:j}:{},...X!==void 0?{outsideDeclaredRoots:X}:{},coverageRootsDeclared:p}),X===!0&&te!==void 0&&y.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${d.id} is covered only by ${te}, which is outside the declared coverage roots (${m}). 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:te,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:"warning",failsStrict:!1}),!Ye||oe){let Te=d.mode==="enforced"&&!oe,ke=r||n.length===0?"never-had-tests":"tests-disappeared";y.push({ruleId:"INVARIANT_UNCOVERED",message:(oe?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).`:ge?`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}: ${ka(d,C)} (${ke==="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.`)+(oe&&o?l:i),file:d.provenance.sourceFile,line:1,arkruleId:d.id,arkruleSource:d.provenance.sourceFile,fromLayer:d.provenance.layer,severity:Te?"error":"warning",failsStrict:Te,kind:ke})}}return{coverage:f,violations:y,partial:f.some(d=>d.partial)}}a(cs,"evaluateInvariantCoverage");function ds(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.`}:e.probe?.fresh===!0&&ts(e.probe.verdict)?{ok:!1,reason:ns(e.invariantId,e.probe),blocker:"probe-survived"}:{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(ds,"canPromoteInvariant");function In(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(In,"nonEmptyPathStrings");function va(e){return!e||typeof e!="object"?[]:[...In(e.testGlobs),...In(e.coverageRoots)]}a(va,"configuredInvariantTestsPaths");function Sa(e){return va(e).length>0}a(Sa,"hasConfiguredInvariantTestsPath");function Cn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.coverage?.test!==!1)}a(Cn,"catalogDemandsInvariantTestsPath");function us(e){let t=e.hasDomainInvariants===!0||e.hasDomainInvariants!==!1&&Cn(e.invariants);return e.adopted!==!0||!t?[]:Sa(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:la,message:ca,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]}a(us,"collectMissingInvariantTestsPathFindings");function Ia(e){return!e||typeof e!="object"?[]:In(e.coverageRoots)}a(Ia,"configuredCoverageRoots");function Ea(e){return Ia(e).length>0}a(Ea,"hasConfiguredCoverageRoots");function xn(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>t!=null&&t.mode==="enforced")}a(xn,"catalogHasEnforcedInvariant");function fs(e){return e.hasEnforcedInvariant===!0||e.hasEnforcedInvariant!==!1&&xn(e.invariants)?Ea(e.coverage)&&e.declaredPathPresent!==!1?[]:[{ruleId:da,message:ua,file:"ark.config.json",line:1,severity:"error",failsStrict:!0,freezable:!1}]:[]}a(fs,"collectMissingCoverageRootsFindings");function wa(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(wa,"normalizeExtraMergeTeethClassification");function Ft(e){let t=wa(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(Ft,"extraMergeTeethAllowed");function ps(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(ps,"classifyResolvedLayerCoverage");var Ca=["createArkKernel","createStrictArkKernel","createLenientArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig","createLenientArkKernelFromConfig"];var xa=["forRoot","forRootAsync"],_a=["ArkKernel","EventBus","EventPublisher","ArkRunPublisher"];var Fd=new Set(xa),Dd=new Set(_a);var Md=new Set(Ca);function gs(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")||e==="arkgate/nestjs"||e.startsWith("arkgate/nestjs/")}a(gs,"isArkRunKernelModuleSpecifier");var Oa=["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"],_n=new Set(Oa);function hs(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(_n.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(_n.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:_n.has(e.slice(0,r))}a(hs,"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 ms=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("CROSS_WALL_DUPLICATE","layer","Code copied across a wall","Near-identical code sits on two sides of a slice wall (or in two layers that may not import each other). The wall would deny the import, so the code was copied instead. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; they never enter the check, so the verdict does not change. Same-slice copies are counted, never listed.","Move one copy to a shared home the wall allows \u2014 a declared shared root, the universe common folder, or a layer both sides may import \u2014 then import it from both sides. One move at a time, through the write gate (/ark-place names the destination). Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),k("CROSS_LAYER_DUPLICATE","layer","Code copied in two layers","Near-identical code sits in two layers, and at least one of them may import the other. Status details (`--doctor --all`) and the report list it from token fingerprints taken at status time; the verdict does not change.","Keep one copy in the lower layer both sides may import, and import it from the other. One move at a time, through the write gate. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),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/, or a slice file named arkrules.<Layer>.json beside governed code, is not in the effective catalog, so none of its rules are enforced. Drift looks like governance until someone notices.","Reference a central file from arkRules, set childSlices.arkRulesFile so a slice file is discovered, or delete it. Advisory only: it never fails the check.",{oftenAdvisory:!0}),k("ARKRULE_DUPLICATE_ID","arkrules","ArkRule id declared more than once","Two ArkRules files in one layer declare the same effective id. Central ids stay bare. A slice file is namespaced as <childId>#<localId>, so the same local id in two slices is not a duplicate.","Rename one id, or split the files onto different slices. Config load fails closed. The catalog is not enforced until the id is unique."),k("ARKRULE_SCOPE_ESCAPES_SLICE","arkrules","Slice ArkRule appliesTo leaves its slice","A file discovered from childSlices.arkRulesFile set appliesTo to a glob that can match outside that child slice. The default, when appliesTo is omitted, is the slice directory.","Narrow appliesTo to the slice directory, or omit it. Config load fails closed. The escaping rule is not enforced."),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_PROBE_SURVIVED","arkrules","Covering tests do not pin the invariant","The committed invariant probe (.ark/invariant-probe.json, written by arkgate-check --probe-invariants --write) shows, for files that have not changed since, that the covering tests still pass with the invariant's symbol broken on purpose (survived) or never call it (not reached). The test names the rule but does not pin it. A status and inventory line only: it never enters the check, so the verdict does not change.","Add a test case that fails when the rule is broken (the line names the change that went unnoticed), then re-run arkgate-check --probe-invariants --write and commit the file. Promotion to enforced refuses while the fresh artifact says survived or not reached; a stale, killed, inconclusive or missing result changes nothing.",{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("ORPHAN_MODULE","drift","File nothing imports","No governed file, test or entry point imports this module. It is the leftover an agent leaves when a rewrite lands next to the old file. Status reads it from the import facts the check already resolved, so it never changes the verdict. When a dynamic import, an unresolved import or an unmapped entry could reach the file, the item says so (maybe-dynamic, maybe-unresolved) and the list is partial.","Delete the file through the write gate, one file at a time. If a framework, a script or a runtime loader uses it, add a glob with a reason to .ark/entry-points.json (optional reviewBy) instead. Advisory only \u2014 it never fails a run.",{oftenAdvisory:!0}),k("UNUSED_EXPORT","drift","Export nothing imports by name","An export no governed file or test imports by name. Listed only in status details (`--doctor --all`) and the report. Default, namespace, star, dynamic and require use count as using every export, so those files are skipped.","Drop the export keyword (or the code) if nothing outside the file needs it, or keep it when it is public API an entry point exposes. Advisory only \u2014 it never fails a run.",{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.")]),Ud=new Map(ms.map(e=>[e.ruleId,e])),jd=Object.freeze(ms.map(e=>e.ruleId));var Ta=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."})]),Na=new Map(Ta.map(e=>[e.reasonId,e]));function ys(e){if(!(typeof e!="string"||e.length===0))return Na.get(e)}a(ys,"sliceReasonHint");var Pa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,$a=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,La=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function Fa(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Pa.test(n)?"pure-shared":r==="PersistenceAdapters"&&($a.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":La.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(Fa,"classifyLayerImportKind");function Da(e,t){return t.failsStrict===!1&&e.advisoryNote?`${e.fix} ${e.advisoryNote}`:e.fix}a(Da,"sliceHintAction");function Ma(e){let t=ys(typeof e.reasonId=="string"?e.reasonId:void 0);if(t)return`${Da(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=Fa(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(Ma,"layerImportNextAction");function Ha(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Ha,"arkRunCallSiteName");function Ka(e){let t=Ha(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(Ka,"arkRunNextAction");function Ae(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Ma(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 Ka(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(Ae,"deterministicNextAction");var Ua=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],tu=new Set(Ua);var Rs={"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"},ja="ARKRUN_INTERACTION_NAME_INCOMPLETE";function ks(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(ks,"isDomainRoleLayer");function Va(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Va,"compareFindings");function fe(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Rs[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:Ae({ruleId:Rs[t],fromLayer:s?.fromLayer,target:s?.target})}}a(fe,"finding");function Ga(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(Ga,"bagForFile");function As(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(As,"emitKinds");function bs(e){return e==="subscribe"||e==="register-handler"}a(bs,"handleKinds");function Ba(e){return e==="resolve"||e==="resolve-singleton"}a(Ba,"dependKinds");function za(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(fe(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((u,p)=>u.file.localeCompare(p.file));if(l.length===0){r.push(fe(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(u=>u.hasKernelFactory))continue;let c=l[0];r.push(fe(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(za,"evaluateMissingRoot");function Wa(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||!gs(c))continue;let u=r(l.from);u&&ks(u,s.get(u)??[])&&i.push(fe(e,"arkrun-kernel-in-domain",l.from,l.line,`${u} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:u,target:c},o))}return i}a(Wa,"evaluateKernelInDomain");function qa(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.size===0)return[];let l=new Map(t.map(p=>[p.name,p.intentPrefixes??[]])),c=new Set(r.filter(p=>p.hasKernelFactory).map(p=>p.file)),u=[];for(let p of n){if(c.has(p.file))continue;let m=p.typeName;if(e.ignoreDirectNewForErrors!==!1&&(m.endsWith("Error")||m==="Error")||m.endsWith("DTO")||m.endsWith("VO"))continue;let f=o(p.file);!f||!i.has(f)||ks(f,l.get(f)??[])||u.push(fe(e,"arkrun-direct-new",p.file,p.line,`${f} must not construct ${p.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:f,target:p.typeName},s))}return u}a(qa,"evaluateDirectNew");function Ya(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(!As(c.kind)&&!bs(c.kind)&&!Ba(c.kind))continue;let u=r(c.file);if(!u||!l.has(u))continue;if(!c.nameLiteral){e.mode==="enforced"&&c.kind!=="publisher"&&i.push({code:ja,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 p=Ga(n,c.file);if(As(c.kind)){if(p.raises.has(c.nameLiteral)||p.sends.has(c.nameLiteral))continue;s.push(fe(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:u,target:c.nameLiteral},o));continue}if(bs(c.kind)){if(p.reactsTo.has(c.nameLiteral))continue;s.push(fe(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:u,target:c.nameLiteral},o));continue}p.uses.has(c.nameLiteral)||s.push(fe(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:u,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(Ya,"evaluateUndeclared");function Xa(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||!hs(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(fe(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(Xa,"evaluateTransportBypass");function vs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Ft(e.classification),r=Ya(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...za(t,e.compositionRootHits,n),...Wa(t,e.layers,e.dependencies,e.layerForFile,n),...qa(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Xa(t,e.dependencies,e.layerForFile,n)].sort(Va),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,u=`${l.code}\0${l.file??""}\0${l.message}`;return c<u?-1:c>u?1:0});return{findings:o,completenessReasons:s}}a(vs,"evaluateArkRunSensors");function Ss(e){return q(e)}a(Ss,"arkOrderGlobToRegExp");function Is(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(Is,"isArkOrderModuleSpecifier");var Es={"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 Za(e,t){return!t||t.length===0?!0:t.some(n=>Ss(n).test(e))}a(Za,"matchesArkOrderAppliesTo");function Ja(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(Ja,"isDomainRoleLayer");function le(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Es[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:Ae({ruleId:Es[t],fromLayer:s?.fromLayer,target:s?.target})}}a(le,"finding");function ws(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Ft(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(le(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 u of e.planeRootHits){let p=c.get(u.matchedRoot)??[];p.push(u),c.set(u.matchedRoot,p)}for(let u of o){let p=c.get(u)??[];if(p.length===0){r.push(le(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(u)} matched no governed files and has no createOrderPlane factory.`,{target:u},n));continue}p.some(m=>m.hasPlaneFactory)||r.push(le(t,"arkorder-missing-plane",p[0].file,1,`ArkOrder plane root ${JSON.stringify(u)} has no createOrderPlane factory.`,{target:u},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let u=c.specifier;if(!u||!Is(u))continue;let p=e.layerForFile(c.from);p&&Ja(p,s.get(p)??[])&&r.push(le(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:p,target:u},n))}for(let c of e.genericUpdates)r.push(le(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(le(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(le(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(le(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(le(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 u=e.layerForFile(c.file);!u||!l.has(u)||Za(c.file,t.appliesTo)&&r.push(le(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:u,target:c.key},n))}return r.sort((c,u)=>c.file.localeCompare(u.file)||c.ruleId.localeCompare(u.ruleId)||c.line-u.line),{findings:r,completenessReasons:[]}}a(ws,"evaluateArkOrderSensors");var we={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Cs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...we,default:[]},kernelRoots:{...we},managedLayers:{...we,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},xs={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...we,default:[]},managedLayers:{...we,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...we,default:[]},appliesTo:{...we,default:[]}}};function ot(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ot,"isObject");function Qa(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)ot(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Qa,"declaredLayerNames");function _s(e){if(!ot(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(_s,"defaultedArkRun");function Os(e){if(!ot(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(Os,"defaultedArkOrder");function Ts(e,t,n,r){if(!Array.isArray(t))return;let o=Qa(e);t.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!o.has(s)&&r.push({path:`$.${n}.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})})}a(Ts,"validateManagedLayersDeclared");function Ns(e,t){let n=e.arkRun;if(n===void 0||!ot(n))return;let r=n.managedLayers;if(Ts(e,r,"arkRun",t),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(r)||r.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Ns,"validateArkRunExtra");function Ps(e,t){let n=e.arkOrder;if(n===void 0||!ot(n))return;let r=n.managedLayers;if(Ts(e,r,"arkOrder",t),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(r)||r.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Ps,"validateArkOrderExtra");var Mt={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ks={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:{...Mt,minItems:1}}}]},Us={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:{...Mt,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...Mt,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:{...Mt},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)."},arkRulesFile:{type:"string",minLength:1,description:"Filename read at each child slice root this wall already resolved. The only token is <Layer>, replaced with a declared layer name (arkrules.<Layer>.json). No slash and no wildcard. A discovered file that omits appliesTo is scoped to that slice directory. Explicit appliesTo outside the slice fails config load (ARKRULE_SCOPE_ESCAPES_SLICE). The effective id is <childId>#<localId>. A build that rejects unknown childSlices fields fails at config load (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 unpinned alias as an owed move. pinned true lists the alias separately and does not count it as debt. reason is a doctor label and does not pin by itself. 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},pinned:{type:"boolean",description:"True when a framework forces the path to stay. The alias is not an owed move and does not clear other honesty debt."},reason:{type:"string",minLength:1,description:"Doctor label, such as framework-route. A label alone does not pin."}}}},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 Z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Z,"isObject");function Ht(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(Ht,"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 js(e,t){sl(e,t),il(e,t),dl(e,t),El(e,t),Il(e,t)}a(js,"validateSliceContract");var $s='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',Ls="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function el(e){return e==="*"||e==="**"}a(el,"isWildcardSegment");function Vs(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&&el(t[n-1]??"");)n-=1;let r=t.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(Vs,"coveredFolder");function tl(e,t){return e.length<=t.length&&e.every((n,r)=>t[r]===n)}a(tl,"isPrefixOf");function nl(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(!Z(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("/"),u=c.findIndex(f=>f.includes("*")),p=u===-1?c:c.slice(0,u),m=Vs(p.join("/"));m&&o.push(m)}}return o}a(nl,"ruleLayerFolders");function rl(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 Ls;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=Vs(n);return o===null?null:o.length===0?Ls:t.some(s=>tl(o,s))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(rl,"stopAtEntryIssue");function sl(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!Z(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:$s});return}if(!Z(s)){t.push({path:i,message:$s});return}for(let p of Object.keys(s))p!=="mode"&&p!=="stopAt"&&t.push({path:Ht(i,p),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,u=nl(e,r);l.forEach((p,m)=>{let f=`${i}.stopAt[${m}]`;if(typeof p!="string"){t.push({path:f,message:"must be a non-empty path or glob"});return}let y=rl(p,u);if(y){t.push({path:f,message:y});return}let d=be(p.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(d)){t.push({path:f,message:"duplicate stopAt entry"});return}c.add(d)})})}a(sl,"validateSharedImportsSlice");var ol=["deny","advisory"],Fs='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function il(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!Z(r))return;let s=r.childSlices;if(!Z(s)||s.siblings===void 0)return;let i=s.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof i=="string"){ol.includes(i)||t.push({path:l,message:Fs});return}if(!Z(i)){t.push({path:l,message:Fs});return}for(let u of Object.keys(i))u!=="default"&&u!=="enforce"&&u!=="ratchet"&&t.push({path:Ht(l,u),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((u,p)=>{let m=`${l}.enforce[${p}]`;if(typeof u!="string"||u.trim().length===0){t.push({path:m,message:"must be a non-empty child slice id or subtree path"});return}let f=be(u.trim().replace(/\\/g,"/"));if(f.split("/").some(y=>y.length===0||y==="."||y==="..")){t.push({path:m,message:"must be a child slice id or subtree path without . or .."});return}if(f.includes("*")){t.push({path:m,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(f)){t.push({path:m,message:"duplicate enforce entry"});return}c.add(f)})})}a(il,"validateChildSliceSiblings");var al="must be a slice id with a slash. A bare name is ambiguous across universes.",ll="* matches one whole path segment. ** and a partial segment are not wildcards.";function cl(e){let t=be(e.trim().replace(/\\/g,"/"));if(t.length===0)return"must be a non-empty slice id";if(!t.includes("/"))return al;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 ll}return null}a(cl,"childCrossSlicePatternIssue");function Ds(e){return be(e.trim().replace(/\\/g,"/")).toLowerCase()}a(Ds,"childCrossSlicePatternKey");function dl(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!Z(r))return;let s=r.childSlices;if(!Z(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((u,p)=>{let m=`${l}[${p}]`;if(!Z(u)){t.push({path:m,message:"must be an object with from and to"});return}for(let y of Object.keys(u))y!=="from"&&y!=="to"&&t.push({path:Ht(m,y),message:"unknown field"});for(let y of["from","to"]){let d=u[y],g=`${m}.${y}`;if(typeof d!="string"||d.trim().length===0){t.push({path:g,message:"must be a non-empty slice id"});continue}let b=cl(d);b&&t.push({path:g,message:b})}if(typeof u.from!="string"||typeof u.to!="string")return;let f=`${Ds(u.from)}\0${Ds(u.to)}`;if(!f.startsWith("\0")&&!f.endsWith("\0")){if(c.has(f)){t.push({path:m,message:"duplicate child slice allowance"});return}c.add(f)}})})}a(dl,"validateChildSliceAllowedCrossSlice");var Ve="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.",ul="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/*).",fl="overlaps a slice folder. An alias covers only files outside the slice trees.",pl="two slice aliases match the same file";function gl(e){return be(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(gl,"aliasPathSegments");function hl(e){let t=e[e.length-1];return t===void 0||t.includes("*")?[...e]:[...e,"**"]}a(hl,"aliasSegmentsWithSubtree");function Gs(e){let t=[];for(let n of e){if(n.includes("*"))break;t.push(n)}return t}a(Gs,"concreteGlobPrefix");function it(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(it,"segmentsArePrefix");function ml(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(ml,"anchoredSlicePrefix");function yl(e,t){let n=Gs(e),r=n.length<e.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return it(t,n)||it(t,o)?!0:r?it(n,t)&&n.length<t.length||it(n,["src",...t])&&n.length<t.length+1||it(n,["app",...t])&&n.length<t.length+1:!1}a(yl,"globOverlapsAnchored");function Rl(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=Gs(e);return n.length<e.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(Rl,"globOverlapsBare");function Al(e,t){let n=t.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return Rl(e,n[0]);let r=ml(t);return r?yl(e,r):!1}a(Al,"globOverlapsSliceEntry");function bl(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(bl,"aliasGlobIssue");function kl(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 u=0;u<s.length;u+=1)s[u]!=="*"&&(i=u);if(i<0)continue;let l=s.filter((u,p)=>p>=i||u==="*").map(u=>u==="*"?null:u),c=s.slice(i).map(u=>u==="*"?null:u);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(kl,"universeShapes");function Dt(e,t){return e.literals.length!==t.length?!1:e.literals.every((n,r)=>n===null||n===t[r])}a(Dt,"shapeMatches");function vl(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 Ve;let r=n.split("/").map(s=>s.toLowerCase());if(t.length===0||t.some(s=>Dt(s,r)))return Ve;if(t.some(s=>Dt(s,r.slice(0,-1))))return null;let o=new Set(t.filter(s=>s.legacy!==void 0&&!Dt({literals:s.legacy},r)&&Dt({literals:s.legacy},r.slice(0,-1))).map(s=>s.literals.map(i=>i??"*").join("/")));return o.size===1?null:o.size>1?ul:Ve}a(vl,"aliasTargetIssue");function Ms(e){let t=e[0];return(t==="src"||t==="app")&&e.length>1?[e,e.slice(1)]:[e]}a(Ms,"aliasGlobVariants");function Sl(e,t){let n=Ms(e),r=Ms(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(Sl,"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],u=t[r];(c===u||c==="*"||u==="*")&&(l=Ce(e,t,n+1,r+1,o))}return o.set(s,l),l}a(Ce,"globsCanMatchSame");var Hs="must be a filename with exactly one <Layer> token and no slash or wildcard (arkrules.<Layer>.json)";function Il(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!Z(r))return;let s=r.childSlices;if(!Z(s)||s.arkRulesFile===void 0)return;let i=`$.rules[${o}].childSlices.arkRulesFile`,l=s.arkRulesFile;if(typeof l!="string"||l.length===0){t.push({path:i,message:Hs});return}(l.split("<Layer>").length!==2||/[*\\/]/.test(l)||l.includes(".."))&&t.push({path:i,message:Hs})})}a(Il,"validateChildSliceArkRulesFile");function El(e,t){let n=e.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!Z(r))return;let s=r.childSlices;if(!Z(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=kl(r.sliceFolders,r.sliceIdentity),u=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(s.sliceFolders)?s.sliceFolders:[]].filter(m=>typeof m=="string"&&m.length>0),p=[];i.forEach((m,f)=>{let y=`${l}[${f}]`;if(!Z(m)){t.push({path:y,message:"must be an object with from and to"});return}for(let b of Object.keys(m))b!=="from"&&b!=="to"&&b!=="pinned"&&b!=="reason"&&t.push({path:Ht(y,b),message:"unknown field"});let d=m.from,g=m.to;if(typeof d!="string"||d.trim().length===0)t.push({path:`${y}.from`,message:"must be a non-empty path glob"});else{let b=bl(d);if(b)t.push({path:`${y}.from`,message:b});else{let v=hl(gl(d));u.some(I=>Al(v,I))&&t.push({path:`${y}.from`,message:fl});for(let I of p)if(Sl(I,v)){t.push({path:y,message:pl});break}p.push(v)}}if(typeof g!="string"||g.trim().length===0)t.push({path:`${y}.to`,message:Ve});else{let b=vl(g,c);b&&t.push({path:`${y}.to`,message:b})}})})}a(El,"validateChildSliceAliases");function Kt(e){if(typeof e!="string")return null;let t=e.trim().replace(/^@/,"").toLowerCase();return t.length>0?t:null}a(Kt,"normalizeStewardId");function Bs(e){let t=Kt(e);return!t||On(t)||t.includes(" ")||t.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(t)}a(Bs,"isGitHubHandle");function wl(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(!t.includes("@")||t.includes(" ")||On(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(wl,"isGitHubEmail");function Cl(e){if(typeof e!="string")return null;let t=e.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return t&&Bs(t[1])?Kt(t[1]):null}a(Cl,"githubHandleFromEmail");function zs(e){let t=Cl(e);if(t)return t;let n=Kt(e);return!n||On(n)?null:Bs(n)||wl(n)?n:null}a(zs,"canonicalStewardId");var xl=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function On(e){let t=Kt(e);return!t||xl.test(t)}a(On,"isAutomationAuthor");var ie="1.3",_l=["public","auth","admin","internal"];function Ol(e){return e?.optional===!0||e?.reserved===!0||e?.allowEmpty===!0}a(Ol,"isFutureHouseLayer");function Tl(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(Tl,"layerOwnersList");function Ys(e){return e?.requireLayerOwners!==!0||!Array.isArray(e.layers)?[]:e.layers.filter(t=>!Ol(t)&&!Tl(t)).map(t=>t.name)}a(Ys,"layersMissingRequiredOwners");function Xs(e){return`Add a GitHub handle or email to ${e}'s owners in ark.config.json (/ark-adopt).`}a(Xs,"missingLayerOwnersNextAction");var Tn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Ws=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Nl=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Pl(){let e=[];for(let t of Ws)for(let n of Ws)t===n||Nl.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(Pl,"createDefaultRules");var Zs=Pl(),Nn=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],J={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qs={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Tn,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:Tn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:ie,default:ie},name:{type:"string",minLength:1},include:{...J,minItems:1,default:["src"]},exclude:{...J,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Zs,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...J,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{description:"A project-relative ArkRules path, or a list of paths merged into one catalog for this layer. A string keeps today's behaviour. An older build that types this value as a string rejects an array at config load.",oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1}}]},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...J,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...J,minItems:1},exclude:J,entrypoints:{...J,minItems:1,description:"Optional public surface globs for this layer. When non-empty, cross-layer imports into this layer must target a file matching one of these globs; deep imports into internal layer files are denied."},intentPrefixes:J,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[..._l]},owners:{...J,minItems:1},forbiddenGlobals:J,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},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:{...J,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:{...J,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:Ks,childSlices:Us}},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:{...J,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:{...J,minItems:1}}},arkRun:Cs,arkOrder:xs}},pe=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
13
13
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
14
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function $l(e,t){let n=e.arkRules;if(!(n===void 0||!rt(n)))for(let[r,o]of Object.entries(n)){let s=Ke("$.arkRules",r);if(typeof o=="string"){o.length===0&&t.push({path:s,message:"must be a non-empty relative path string"});continue}if(!Array.isArray(o)||o.length===0){t.push({path:s,message:"must be a non-empty path string or an array of paths"});continue}let i=new Set;o.forEach((l,c)=>{let u=`${s}[${c}]`;if(typeof l!="string"||l.length===0){t.push({path:u,message:"must be a non-empty relative path string"});return}i.has(l)&&t.push({path:u,message:"duplicate path"}),i.add(l)})}}a($l,"validateArkRulesRefs");function Ll(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"&&(zs(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Ll,"validateLayerOwners");function Fl(e){let t={...e,$schema:e.$schema===void 0?On:e.$schema,schemaVersion:e.schemaVersion===void 0?oe:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Zs.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=_s(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Os(e.arkOrder)),t}a(Fl,"defaultedConfig");function Dl(e){return e===oe?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Dl,"migratedFromOf");function Ml(){let e=new Set([oe]);for(let t of Tn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Ml,"knownInputVersions");function Hl(e,t="ark.config.json"){if(!rt(e))throw new pe(t,[{path:"$",message:`must be an object; received ${me(e)}`}]);let n=Ml(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${oe}`}]);if(r!=="unversioned"&&!n.has(r))throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${oe}`}]);let o=r,s={...e},i=0;for(;o!==oe&&i<Tn.length+1;){i+=1;let l=Tn.find(c=>c.from===o);if(!l)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${oe}`}]);o=l.to,s.schemaVersion=o}if(o!==oe)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${oe}`}]);return{candidate:Fl(s),migratedFrom:Dl(r)}}a(Hl,"migrateArkConfig");function Nn(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Hl(e,t),o=[];if(Ie(n,qs,"$",qs,o),Ns(n,o),Ps(n,o),Ll(n,o),js(n,o),$l(n,o),o.length>0)throw new pe(t,o);return{config:n,migratedFrom:r}}a(Nn,"loadArkConfigContract");function Js(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new pe(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Nn(n,t)}a(Js,"parseArkConfigJson");var at="4.8.24";function lt(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}a(lt,"childSlicesOf");var Qs=Object.freeze([{key:"childSlices.arkRulesFile",minVersion:at,uses:a(e=>typeof lt(e)?.arkRulesFile=="string","uses")},{key:"childSlices.sliceAliases.pinned",minVersion:at,uses:a(e=>{let t=lt(e)?.sliceAliases;return Array.isArray(t)?t.some(n=>{if(n===null||typeof n!="object")return!1;let r=n;return r.pinned!==void 0||r.reason!==void 0}):!1},"uses")},{key:"sharedImportsSlice.stopAt",minVersion:at,uses:a(e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:at,uses:a(e=>lt(e)?.message!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:at,uses:a(e=>{let t=lt(e)?.siblings;return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:a(e=>lt(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 xe(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}a(xe,"versionCore");function ct(e,t){let n=xe(e),r=xe(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(ct,"compareArkgateVersion");function eo(e,t){return t&&xe(t)&&ct(t,e)<0?t.replace(/^v/,""):e}a(eo,"effectiveFloor");function to(e,t){let n=[],r=null;for(let o of Qs){if(!(e??[]).some(i=>i&&o.uses(i)))continue;n.push(o.key);let s=eo(o.minVersion,t);(!r||ct(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}a(to,"configVersionFloors");var Kl=/^(?:=\s*)?v?(\d+\.\d+\.\d+)$/,Ul=/(?<![\w@/.-])arkgate@v?(\d+\.\d+\.\d+)(?![\w.])/g,jl=/pedroknigge\/arkgate@v?(\d+\.\d+\.\d+)(?![\w.])/g,Vl=/pedroknigge\/arkgate@/,Gl=/^\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 Pn(e,t,n=0){let r=e.indexOf(`"${t}"`,n);return r<0?1:$n(e,r)}a(Pn,"lineOfJsonKey");function Bl(e,t){let n=[],r=t.split(`
16
- `);for(let o=0;o<r.length;o+=1){let s=r[o]??"";if(!Vl.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 u=r[c]??"";if(u.trim().length===0)continue;if(u.length-u.trimStart().length<=l)break;let p=Gl.exec(u);p&&n.push({file:e,line:c+1,version:p[1]??"",source:"ci"})}}return n}a(Bl,"actionVersionInputs");function no(e,t,n){let r=[];for(let o of[Ul,jl]){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(...Bl(e,t)),r}a(no,"textPins");function zl(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"&&xe(o.version)&&s.push({file:e,line:Pn(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"&&xe(c.version)){let u=t.indexOf('"node_modules/arkgate"');s.push({file:e,line:Pn(t,"version",u<0?0:u),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],u=c&&typeof c=="object"?c.arkgate:void 0;if(typeof u!="string")continue;let p=Kl.exec(u.trim());if(!p)continue;let m=t.indexOf(`"${l}"`);s.push({file:e,line:Pn(t,"arkgate",m<0?0:m),version:p[1]??"",source:n})}let i=o.scripts;if(i&&typeof i=="object"){let l=t.indexOf('"scripts"');for(let c of no(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(zl,"jsonPins");function Wl(e,t,n){return typeof t!="string"||t.length===0?[]:(n==="hook"||n==="ci"?no(e,t,n):zl(e,t,n)).filter(o=>xe(o.version)!==null)}a(Wl,"parseArkgatePins");function ro(e){let t=to(e.rules,e.runningVersion);if(!t||!e.pins?.length)return[];let n=e.runningVersion,r=n&&xe(n)&&ct(n,t.required)>0?n.replace(/^v/,""):t.required,o=a(l=>Qs.filter(c=>t.keys.includes(c.key)&&ct(l.version,eo(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,i=[];for(let l of e.pins){if(ct(l.version,t.required)>=0)continue;let c=`${l.file}\0${l.line}`;if(s.has(c))continue;s.add(c);let u=o(l);i.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,path:l.file,line:l.line,message:`ark.config.json uses ${u.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(ro,"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 u=new Set,p=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}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(b=>typeof b!="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 b of g){let I;try{I=Z(b)}catch(C){s.push(U("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${b}": ${C instanceof Error?C.message:String(C)}`,{layer:d.name,pattern:b}));continue}let E=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(C=>I.test(C))&&!E&&s.push(U("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${b}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:b,failsStrict:!1,reserved:!1}))}}for(let d of p)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 m=new Set;if(i.length>1)for(let d of r){let g=-1,b=[];for(let I of i)for(let E of I.patterns??[]){if(!Z(E).test(d))continue;let C=cn(E,d);C>g?(g=C,b=[I.name]):C===g&&!b.includes(I.name)&&b.push(I.name)}b.length>1&&m.add([...b].sort().join(" + "))}m.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: ${[...m].join(", ")}.`,{pairs:[...m]}));let f=r.filter(d=>!ne(d,i));f.length>0&&s.push(U("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));for(let d of Rr(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 xr(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 ro({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 y=Ys(t);if(y.length>0){let d=y[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:y,nextAction:Xs(d)}))}return s}a(Ln,"collectAnalysisConfigWarnings");function io(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 m of[...e.get(c)??[]].sort())e.has(m)&&(n.has(m)?o.has(m)&&r.set(c,Math.min(r.get(c)??0,n.get(m)??0)):(l(m),r.set(c,Math.min(r.get(c)??0,r.get(m)??0))));if(r.get(c)!==n.get(c))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==c);u.length>1&&i.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[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(io,"detectArchitectureCycles");function dt(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=He(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let f=Or(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});f&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:f.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:f.toPath,toSlice:f.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${f.fromPath} \u2192 slice ${f.toSlice} (${f.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=i.sliceVerdict,m=p?_t({surface:"import",verdict:p,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}:{},...Ot(p),message:u?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...u?{failsStrict:!1,severity:"warning"}:{}})}t.push(...Xl(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=io(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(dt,"evaluateArchitectureGraph");var ql="CROSS_PARENT_VIA_SHARED",Yl="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function so(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&he(r.sharedImportsSlice)==="deny-cross-parent")return r}a(so,"denyingCrossParentRule");function Fn(e,t,n,r){let o=Qe(n,e,pn(e,t,r)).universeId;return o?{kind:"slice",id:o}:Me(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Fn,"placeFile");function oo(e,t){return vr(t,Ct(e.sharedImportsSlice))}a(oo,"isWalkStop");function Xl(e){let t=e.rules??[];if(!t.some(s=>he(s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=Zl(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=so(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Fn(i,s.fromLayer,s.from,e.config.layers),c=Fn(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||oo(i,s.to))continue;let u=[{file:s.to,path:[s.from,s.to]}],p=new Set([s.to]);for(;u.length>0;){let m=u.shift();if(!m)break;for(let f of n.get(m.file)??[]){let y=so(t,f.fromLayer,f.toLayer);if(!y)continue;let d=Fn(y,f.fromLayer,f.to,e.config.layers);if(d.kind==="shared"){if(p.has(f.to)||oo(y,f.to))continue;p.add(f.to),u.push({file:f.to,path:[...m.path,f.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase()||It(i.allowedCrossSlice,l.id,d.id))continue;if(i.sliceIdentity==="stars"){let C=fn(i,pn(i,s.fromLayer,e.config.layers),s.from,f.to);if(C.crossSliceAllowed||C.from.universeId&&C.from.universeId===C.to.universeId)continue}let g=[...m.path,f.to],b=`${s.from}\0${f.to}`,I={file:s.from,target:f.to,line:s.line,fromLayer:s.fromLayer,toLayer:f.toLayer,fromSlice:l.id,toSlice:d.id,path:g},E=r.get(b);(!E||g.length<E.path.length||g.length===E.path.length&&g.join("\0")<E.path.join("\0"))&&r.set(b,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=et(s.fromSlice),l=et(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:ql,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}. ${Yl}`}})}a(Xl,"crossParentViaSharedViolations");function Zl(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(Zl,"valueHop");function ao(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:Pr({sensor:e.sensor,code:e.code})}:{},...r||o?{freezable:!1}:{},nextAction:t}}a(ao,"toArkRuleEngineViolation");function Jl(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Jl,"arkRulesMapIsOn");function lo(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(lo,"arkRuleFindingNextAction");function Ql(e,t){return t.some(n=>{try{return Z(n).test(e)}catch{return!1}})}a(Ql,"matchesAny");function ec(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:b})=>({file:g,line:b})),l=t.safetyUses.filter(g=>g.kind==="any-cast").map(({file:g,line:b})=>({file:g,line:b})),c=t.safetyUses.filter(g=>(g.kind==="dynamic-import"||g.kind==="dynamic-require")&&!Ql(g.file,s)).map(g=>({file:g.file,line:g.line,kind:g.kind==="dynamic-require"?"require":"import"})),u=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"})),p=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})),m={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],y=c.filter(g=>g.kind==="import");if(y.length>0){let g=y[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${y.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];f.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];f.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];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let g=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:g.file,line:g.line,message:`${u.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 p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:f}}a(ec,"evaluateSafety");function tc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(tc,"ambientForbiddenGlobal");function co(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return hn(e,n.length>0?n:Tt.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(co,"intentLayer");function nc(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||!tc(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??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&sn(s.symbol,c))){if(s.source==="import-based"){let p=Ze(s.symbol,c);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...u?{edgeKind:u}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}Fe(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},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 yn({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=co(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=co(s.intent,e.contract);if(!l)continue;let c=He(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.sliceVerdict,p=`${i} must not reference ${l} intent ${s.intent}.`,m=u?_t({surface:"intent",verdict:u,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,childMessage:c.rule.childSlices?.message,defaultMessage:p}):c.rule.message??p;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}:{},...Ot(u),message:m})}return r}a(nc,"contentViolations");function uo(e,t){return t==="enforced"?{violations:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:n.failsStrict,...n.severity?{severity:n.severity}:{}})),warnings:[]}:{violations:[],warnings:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:!1}))}}a(uo,"splitExtraPlaneFindings");function Ge(e){let{facts:t}=e,n=At(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((A,h)=>{let R=`${A.code}\0${A.file??""}\0${A.message}`,O=`${h.code}\0${h.file??""}\0${h.message}`;return R<O?-1:R>O?1:0}),i=t.files.map(A=>({...A,layer:ne(A.path,e.contract.config.layers)??null})),l=new Map(i.map(A=>[A.path,A.layer])),c=t.dependencies.map(A=>{let h=A.target?l.get(A.target)??ne(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:l.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...h?{toLayer:h}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),u=Ln({config:e.contract.config,rules:e.contract.config.rules,files:i.map(A=>A.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),p=ec(e,t),m=e.contract.arkRules??st(),f=i.map(A=>A.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?es(e.coverageInputs.fileContents):{},...e.fileHints??{}},g=a(A=>l.get(A)??ne(A,e.contract.config.layers),"resolveLayer"),b=[...Zr({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:g,fileHints:d}),...Jr(m,f),...Qr({arkRulesActive:Jl(e.contract.config),arkRules:m,layers:e.contract.config.layers??[],files:f.map(A=>({path:A,layer:g(A)}))})],I=(m.invariants?.length??0)>0,E=fs({hasEnforcedInvariant:Cn(m.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),C=E.length>0?[]:us({adopted:e.adopted===!0,hasDomainInvariants:wn(m.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),_=[...E.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.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})),...C.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.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=b.filter(A=>A.failsStrict).map(A=>ao(A,lo(A,!1))),te=b.filter(A=>!A.failsStrict).map(A=>({...ao(A,lo(A,!0)),failsStrict:!1})),Y=I?cs({arkRules:m,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},v=Y.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),j=Y.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${A.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),qe=ps(i),ge=vs({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(A=>l.get(A)??ne(A,e.contract.config.layers),"layerForFile"),classification:qe}),{violations:Ye,warnings:se}=uo(ge.findings,e.contract.config.arkRun?.mode),Te=ws({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(A=>l.get(A)??ne(A,e.contract.config.layers),"layerForFile"),classification:qe}),{violations:ke,warnings:Qn}=uo(Te.findings,e.contract.config.arkOrder?.mode),Yt=[...Y.partial&&Y.coverage.some(A=>A.mode==="enforced"&&A.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."}]:[],...ge.completenessReasons,...Te.completenessReasons],ve=dt({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(A=>A.layer).map(A=>A.path),contentViolations:[...nc(e,t,l),...q,..._,...v,...Ye,...ke],edges:c,warnings:[...u,...p.warnings,...te,...j,...se,...Qn],safety:p.report}),Ne=o==="complete"&&Yt.length>0?"partial":o,mt=Ne==="complete"?s:[...s,...Yt].sort((A,h)=>{let R=`${A.code}\0${A.file??""}\0${A.message}`,O=`${h.code}\0${h.file??""}\0${h.message}`;return R<O?-1:R>O?1:0}),er=ve.violations.filter(A=>A.failsStrict!==!1),yt=Ne==="complete"&&er.length===0,S=yt&&ve.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Ne,completenessReasons:mt,valid:yt,strictValid:S,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(A=>A.name),edges:c,capabilityUses:t.capabilityUses,violations:ve.violations,warnings:ve.warnings}}}a(Ge,"analyzeCanonicalResolvedProject");function rc(e){return Ge({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(rc,"analyzeResolvedProject");function Be(e){return e.flatMap(t=>t.to?[{from:t.from,to:t.to}]:[])}a(Be,"resolvedEdgeDependencies");function Q(e){return`${e.from}->${e.to}`}a(Q,"dependencyKey");function ut(e,t,n,r="dependency"){return{id:`${e}:${r}:${Q(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Q(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Q(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Q(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Q(t)} from the candidate, then preflight again.`}:{}}}a(ut,"dependencyFinding");function ft(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[Q(f),f])),s=new Map(e.baseDependencies.map(f=>[Q(f),f])),i=new Map(e.candidateDependencies.map(f=>[Q(f),f]));for(let f of[...n.values()].sort((y,d)=>y.path.localeCompare(d.path))){let y=r.get(f.path);y?y.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:y.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${y.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:y.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((y,d)=>y.path.localeCompare(d.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let l=new Set;for(let f of[...o.values()].sort((y,d)=>Q(y).localeCompare(Q(d)))){if(i.has(Q(f))){t.push(ut("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let y={from:f.to,to:f.from};i.has(Q(y))?(l.add(Q(y)),t.push(ut("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(ut("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,y]of[...i].sort(([d],[g])=>d.localeCompare(g)))s.has(f)||o.has(f)||l.has(f)||!c.has(y.from)&&!c.has(y.to)||t.push({...ut("unplanned",y,`${y.from} -> ${y.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,y]of[...s].sort(([d],[g])=>d.localeCompare(g)))i.has(f)||u.has(y.from)||u.has(y.to)||!c.has(y.from)&&!c.has(y.to)||t.push({...ut("unplanned",y,`${y.from} -> ${y.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,y)=>p[f.classification]-p[y.classification]||(f.subject===y.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(y.id));let m={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}a(ft,"analyzeArchitectureConvergence");var Dn="1.0";var Ut=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 $l(e,t){let n=e.arkRules;if(!(n===void 0||!rt(n)))for(let[r,o]of Object.entries(n)){let s=Ke("$.arkRules",r);if(typeof o=="string"){o.length===0&&t.push({path:s,message:"must be a non-empty relative path string"});continue}if(!Array.isArray(o)||o.length===0){t.push({path:s,message:"must be a non-empty path string or an array of paths"});continue}let i=new Set;o.forEach((l,c)=>{let u=`${s}[${c}]`;if(typeof l!="string"||l.length===0){t.push({path:u,message:"must be a non-empty relative path string"});return}i.has(l)&&t.push({path:u,message:"duplicate path"}),i.add(l)})}}a($l,"validateArkRulesRefs");function Ll(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"&&(zs(i)||t.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Ll,"validateLayerOwners");function Fl(e){let t={...e,$schema:e.$schema===void 0?Tn: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?Zs.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=_s(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=Os(e.arkOrder)),t}a(Fl,"defaultedConfig");function Dl(e){return e===ie?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(Dl,"migratedFromOf");function Ml(){let e=new Set([ie]);for(let t of Nn)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(Ml,"knownInputVersions");function Hl(e,t="ark.config.json"){if(!rt(e))throw new pe(t,[{path:"$",message:`must be an object; received ${me(e)}`}]);let n=Ml(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${ie}`}]);if(r!=="unversioned"&&!n.has(r))throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);let o=r,s={...e},i=0;for(;o!==ie&&i<Nn.length+1;){i+=1;let l=Nn.find(c=>c.from===o);if(!l)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${ie}`}]);o=l.to,s.schemaVersion=o}if(o!==ie)throw new pe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${ie}`}]);return{candidate:Fl(s),migratedFrom:Dl(r)}}a(Hl,"migrateArkConfig");function Pn(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Hl(e,t),o=[];if(Ie(n,qs,"$",qs,o),Ns(n,o),Ps(n,o),Ll(n,o),js(n,o),$l(n,o),o.length>0)throw new pe(t,o);return{config:n,migratedFrom:r}}a(Pn,"loadArkConfigContract");function Js(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new pe(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Pn(n,t)}a(Js,"parseArkConfigJson");var at="4.8.24";function lt(e){let t=e.childSlices;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}a(lt,"childSlicesOf");var Qs=Object.freeze([{key:"childSlices.arkRulesFile",minVersion:at,uses:a(e=>typeof lt(e)?.arkRulesFile=="string","uses")},{key:"childSlices.sliceAliases.pinned",minVersion:at,uses:a(e=>{let t=lt(e)?.sliceAliases;return Array.isArray(t)?t.some(n=>{if(n===null||typeof n!="object")return!1;let r=n;return r.pinned!==void 0||r.reason!==void 0}):!1},"uses")},{key:"sharedImportsSlice.stopAt",minVersion:at,uses:a(e=>e.sharedImportsSlice!==null&&typeof e.sharedImportsSlice=="object","uses")},{key:"childSlices.message",minVersion:at,uses:a(e=>lt(e)?.message!==void 0,"uses")},{key:"childSlices.siblings.ratchet",minVersion:at,uses:a(e=>{let t=lt(e)?.siblings;return t!==null&&typeof t=="object"&&"ratchet"in t},"uses")},{key:"childSlices",minVersion:"4.8.23",uses:a(e=>lt(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 xe(e){let t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}a(xe,"versionCore");function ct(e,t){let n=xe(e),r=xe(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(ct,"compareArkgateVersion");function eo(e,t){return t&&xe(t)&&ct(t,e)<0?t.replace(/^v/,""):e}a(eo,"effectiveFloor");function to(e,t){let n=[],r=null;for(let o of Qs){if(!(e??[]).some(i=>i&&o.uses(i)))continue;n.push(o.key);let s=eo(o.minVersion,t);(!r||ct(s,r)>0)&&(r=s)}return r?{keys:n,required:r}:null}a(to,"configVersionFloors");var Kl=/^(?:=\s*)?v?(\d+\.\d+\.\d+)$/,Ul=/(?<![\w@/.-])arkgate@v?(\d+\.\d+\.\d+)(?![\w.])/g,jl=/pedroknigge\/arkgate@v?(\d+\.\d+\.\d+)(?![\w.])/g,Vl=/pedroknigge\/arkgate@/,Gl=/^\s*version:\s*['"]?v?(\d+\.\d+\.\d+)['"]?\s*$/;function Ln(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
15
+ `&&(n+=1);return n}a(Ln,"lineOfIndex");function $n(e,t,n=0){let r=e.indexOf(`"${t}"`,n);return r<0?1:Ln(e,r)}a($n,"lineOfJsonKey");function Bl(e,t){let n=[],r=t.split(`
16
+ `);for(let o=0;o<r.length;o+=1){let s=r[o]??"";if(!Vl.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 u=r[c]??"";if(u.trim().length===0)continue;if(u.length-u.trimStart().length<=l)break;let p=Gl.exec(u);p&&n.push({file:e,line:c+1,version:p[1]??"",source:"ci"})}}return n}a(Bl,"actionVersionInputs");function no(e,t,n){let r=[];for(let o of[Ul,jl]){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;)r.push({file:e,line:Ln(t,s.index),version:s[1]??"",source:n})}return n==="ci"&&r.push(...Bl(e,t)),r}a(no,"textPins");function zl(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"&&xe(o.version)&&s.push({file:e,line:$n(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"&&xe(c.version)){let u=t.indexOf('"node_modules/arkgate"');s.push({file:e,line:$n(t,"version",u<0?0:u),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],u=c&&typeof c=="object"?c.arkgate:void 0;if(typeof u!="string")continue;let p=Kl.exec(u.trim());if(!p)continue;let m=t.indexOf(`"${l}"`);s.push({file:e,line:$n(t,"arkgate",m<0?0:m),version:p[1]??"",source:n})}let i=o.scripts;if(i&&typeof i=="object"){let l=t.indexOf('"scripts"');for(let c of no(e,t.slice(Math.max(l,0)),"package-json"))s.push({...c,line:c.line+(l<0?0:Ln(t,l)-1)})}return s}a(zl,"jsonPins");function Wl(e,t,n){return typeof t!="string"||t.length===0?[]:(n==="hook"||n==="ci"?no(e,t,n):zl(e,t,n)).filter(o=>xe(o.version)!==null)}a(Wl,"parseArkgatePins");function ro(e){let t=to(e.rules,e.runningVersion);if(!t||!e.pins?.length)return[];let n=e.runningVersion,r=n&&xe(n)&&ct(n,t.required)>0?n.replace(/^v/,""):t.required,o=a(l=>Qs.filter(c=>t.keys.includes(c.key)&&ct(l.version,eo(c.minVersion,n))<0).map(c=>c.key),"needing"),s=new Set,i=[];for(let l of e.pins){if(ct(l.version,t.required)>=0)continue;let c=`${l.file}\0${l.line}`;if(s.has(c))continue;s.add(c);let u=o(l);i.push({ruleId:"CONFIG_CHILD_SLICES_VERSION",failsStrict:!1,path:l.file,line:l.line,message:`ark.config.json uses ${u.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(ro,"configVersionPinFindings");function K(e,t,n={}){return{ruleId:e,message:t,...n}}a(K,"configWarning");function Fn(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(K("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(K("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(K("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(K("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,p=new Set;for(let d of i){if(!d.name){s.push(K("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(d.name)&&p.add(d.name),u.add(d.name),d.forbiddenGlobals!==void 0&&(!Array.isArray(d.forbiddenGlobals)||d.forbiddenGlobals.some(v=>typeof v!="string"))&&s.push(K("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(K("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${d.name}" has no file patterns and will never classify files.`,{layer:d.name}));continue}for(let v of g){let I;try{I=q(v)}catch(x){s.push(K("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid pattern "${v}": ${x instanceof Error?x.message:String(x)}`,{layer:d.name,pattern:v}));continue}let C=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;!r.some(x=>I.test(x))&&!C&&s.push(K("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" pattern "${v}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:d.name,pattern:v,failsStrict:!1,reserved:!1}))}let b=d.optional===!0||d.reserved===!0||d.allowEmpty===!0;for(let v of Array.isArray(d.entrypoints)?d.entrypoints:[]){if(typeof v!="string"||v.length===0)continue;let I;try{I=q(v)}catch(C){s.push(K("CONFIG_INVALID_LAYER_PATTERN",`Layer "${d.name}" has an invalid entrypoint "${v}": ${C instanceof Error?C.message:String(C)}`,{layer:d.name,pattern:v,entrypoint:!0}));continue}!r.some(C=>I.test(C))&&!b&&s.push(K("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${d.name}" entrypoint "${v}" matched no included files (possible typo).`,{layer:d.name,pattern:v,failsStrict:!1,reserved:!1,entrypoint:!0}))}}for(let d of p)s.push(K("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(K("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(K("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${d.to}".`,{fromLayer:d.from,toLayer:d.to}));let m=new Set;if(i.length>1)for(let d of r){let g=-1,b=[];for(let v of i)for(let I of v.patterns??[]){if(!q(I).test(d))continue;let C=cn(I,d);C>g?(g=C,b=[v.name]):C===g&&!b.includes(v.name)&&b.push(v.name)}b.length>1&&m.add([...b].sort().join(" + "))}m.size>0&&s.push(K("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let f=r.filter(d=>!ne(d,i));f.length>0&&s.push(K("CONFIG_UNCLASSIFIED_FILES",`${f.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:f.length,samples:f.slice(0,5)}));for(let d of Ar(n))s.push(K("CONFIG_SLICE_IDENTITY_COLLISION",d.message,{paths:[...d.paths],fromLayer:d.from,toLayer:d.to,failsStrict:!1}));for(let d of _r(n,r))s.push(K(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 ro({rules:n,pins:e.arkgatePins,runningVersion:e.runningArkgateVersion}))s.push(K(d.ruleId,d.message,{failsStrict:!1,file:d.path,line:d.line,nextAction:d.nextAction}));let y=Ys(t);if(y.length>0){let d=y[0]??"this layer";s.push(K("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:y,nextAction:Xs(d)}))}return s}a(Fn,"collectAnalysisConfigWarnings");function io(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 m of[...e.get(c)??[]].sort())e.has(m)&&(n.has(m)?o.has(m)&&r.set(c,Math.min(r.get(c)??0,n.get(m)??0)):(l(m),r.set(c,Math.min(r.get(c)??0,r.get(m)??0))));if(r.get(c)!==n.get(c))return;let u=[],p;do{if(p=s.pop(),p===void 0)break;o.delete(p),u.push(p)}while(p!==c);u.length>1&&i.push(u.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,u)=>c[0]<u[0]?-1:c[0]>u[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(io,"detectArchitectureCycles");function dt(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=He(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i){let f=Tr(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});f&&n.push({ruleId:"SHARED_IMPORTS_SLICE",file:f.fromPath,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:f.toPath,toSlice:f.toSlice,failsStrict:!1,severity:"warning",message:`shared root ${f.fromPath} \u2192 slice ${f.toSlice} (${f.toPath}). The wall is direct-only.`});continue}let l=i.rule,c=!!l.peerIsolation,u=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),p=i.sliceVerdict,m=p?_t({surface:"import",verdict:p,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}:{},...Ot(p),message:u?`${m} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:m,...u?{failsStrict:!1,severity:"warning"}:{}})}t.push(...Xl(e));let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=io(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(dt,"evaluateArchitectureGraph");var ql="CROSS_PARENT_VIA_SHARED",Yl="ark-check and CI report this path. The write hook and ESLint see one edge at a time and do not block it.";function so(e,t,n){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&!(r.allowed!==!1||!r.peerIsolation)&&he(r.sharedImportsSlice)==="deny-cross-parent")return r}a(so,"denyingCrossParentRule");function Dn(e,t,n,r){let o=Qe(n,e,pn(e,t,r)).universeId;return o?{kind:"slice",id:o}:Me(n,e.sharedRoots)?{kind:"shared"}:{kind:"other"}}a(Dn,"placeFile");function oo(e,t){return Sr(t,Ct(e.sharedImportsSlice))}a(oo,"isWalkStop");function Xl(e){let t=e.rules??[];if(!t.some(s=>he(s.sharedImportsSlice)==="deny-cross-parent"))return[];let n=new Map;for(let s of e.edges){let i=Zl(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=so(t,s.fromLayer,s.toLayer);if(!i)continue;let l=Dn(i,s.fromLayer,s.from,e.config.layers),c=Dn(i,s.fromLayer,s.to,e.config.layers);if(l.kind!=="slice"||c.kind!=="shared"||oo(i,s.to))continue;let u=[{file:s.to,path:[s.from,s.to]}],p=new Set([s.to]);for(;u.length>0;){let m=u.shift();if(!m)break;for(let f of n.get(m.file)??[]){let y=so(t,f.fromLayer,f.toLayer);if(!y)continue;let d=Dn(y,f.fromLayer,f.to,e.config.layers);if(d.kind==="shared"){if(p.has(f.to)||oo(y,f.to))continue;p.add(f.to),u.push({file:f.to,path:[...m.path,f.to]});continue}if(d.kind!=="slice"||d.id.toLowerCase()===l.id.toLowerCase()||It(i.allowedCrossSlice,l.id,d.id))continue;if(i.sliceIdentity==="stars"){let C=fn(i,pn(i,s.fromLayer,e.config.layers),s.from,f.to);if(C.crossSliceAllowed||C.from.universeId&&C.from.universeId===C.to.universeId)continue}let g=[...m.path,f.to],b=`${s.from}\0${f.to}`,v={file:s.from,target:f.to,line:s.line,fromLayer:s.fromLayer,toLayer:f.toLayer,fromSlice:l.id,toSlice:d.id,path:g},I=r.get(b);(!I||g.length<I.path.length||g.length===I.path.length&&g.join("\0")<I.path.join("\0"))&&r.set(b,v)}}}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=et(s.fromSlice),l=et(s.toSlice);return{ruleId:"LAYER_IMPORT_VIOLATION",reasonId:ql,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}. ${Yl}`}})}a(Xl,"crossParentViaSharedViolations");function Zl(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(Zl,"valueHop");function ao(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(ao,"toArkRuleEngineViolation");function Jl(e){let t=e.arkRules;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}a(Jl,"arkRulesMapIsOn");function lo(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(lo,"arkRuleFindingNextAction");function Ql(e,t){return t.some(n=>{try{return q(n).test(e)}catch{return!1}})}a(Ql,"matchesAny");function ec(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:b})=>({file:g,line:b})),l=t.safetyUses.filter(g=>g.kind==="any-cast").map(({file:g,line:b})=>({file:g,line:b})),c=t.safetyUses.filter(g=>(g.kind==="dynamic-import"||g.kind==="dynamic-require")&&!Ql(g.file,s)).map(g=>({file:g.file,line:g.line,kind:g.kind==="dynamic-require"?"require":"import"})),u=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"})),p=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})),m={tsSuppressions:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:u,disabledPeerIsolationRules:p,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},f=[],y=c.filter(g=>g.kind==="import");if(y.length>0){let g=y[0];f.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:g.file,line:g.line,message:`${y.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];f.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];f.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];f.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:g.file,line:g.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(u.length>0){let g=u[0];f.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:g.file,line:g.line,message:`${u.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 p.length>0&&f.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${p.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:f}}a(ec,"evaluateSafety");function tc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(tc,"ambientForbiddenGlobal");function co(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return hn(e,n.length>0?n:Tt.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(co,"intentLayer");function nc(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||!tc(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??[],u=s.source==="import-based"?t.dependencies.find(p=>p.from===s.file&&p.line===s.line&&p.specifier===s.symbol&&!p.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&sn(s.symbol,c))){if(s.source==="import-based"){let p=Ze(s.symbol,c);if(p){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...u?{edgeKind:u}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${p}".`});continue}}Fe(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...u?{edgeKind:u}:{},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 yn({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=co(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=co(s.intent,e.contract);if(!l)continue;let c=He(e.contract.config.rules,i,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let u=c.sliceVerdict,p=`${i} must not reference ${l} intent ${s.intent}.`,m=u?_t({surface:"intent",verdict:u,fromLayer:i,toLayer:l,fromPath:s.file,ruleMessage:c.rule.message,childMessage:c.rule.childSlices?.message,defaultMessage:p}):c.rule.message??p;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}:{},...Ot(u),message:m})}return r}a(nc,"contentViolations");function uo(e,t){return t==="enforced"?{violations:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:n.failsStrict,...n.severity?{severity:n.severity}:{}})),warnings:[]}:{violations:[],warnings:e.map(n=>({ruleId:n.ruleId,file:n.file,line:n.line,message:n.message,fromLayer:n.fromLayer,target:n.target,nextAction:n.nextAction,sensor:n.sensor,failsStrict:!1}))}}a(uo,"splitExtraPlaneFindings");function Ge(e){let{facts:t}=e,n=At(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((A,h)=>{let R=`${A.code}\0${A.file??""}\0${A.message}`,O=`${h.code}\0${h.file??""}\0${h.message}`;return R<O?-1:R>O?1:0}),i=t.files.map(A=>({...A,layer:ne(A.path,e.contract.config.layers)??null})),l=new Map(i.map(A=>[A.path,A.layer])),c=t.dependencies.map(A=>{let h=A.target?l.get(A.target)??ne(A.target,e.contract.config.layers):void 0;return{from:A.from,fromLayer:l.get(A.from)??null,...A.resolution==="resolved-project"&&A.target?{to:A.target,...h?{toLayer:h}:{}}:{},line:A.line,kind:A.kind,typeOnly:A.typeOnly,...A.targetTypeOnlyExports?{targetTypeOnlyExports:A.targetTypeOnlyExports}:{},...A.sourcePureTypeModule?{sourcePureTypeModule:A.sourcePureTypeModule}:{},...A.namedBindingsTypeOnly?{namedBindingsTypeOnly:A.namedBindingsTypeOnly}:{},...A.portProofEligible?{portProofEligible:A.portProofEligible}:{}}}),u=Fn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(A=>A.path),arkgatePins:e.arkgatePins,runningArkgateVersion:e.runningArkgateVersion}),p=ec(e,t),m=e.contract.arkRules??st(),f=i.map(A=>A.path),d={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?es(e.coverageInputs.fileContents):{},...e.fileHints??{}},g=a(A=>l.get(A)??ne(A,e.contract.config.layers),"resolveLayer"),b=[...Zr({arkRules:m,classShapes:e.contract.classShapes??t.classShapes??[],files:f,layerForFile:g,fileHints:d}),...Jr(m,f),...Qr({arkRulesActive:Jl(e.contract.config),arkRules:m,layers:e.contract.config.layers??[],files:f.map(A=>({path:A,layer:g(A)}))})],v=(m.invariants?.length??0)>0,I=fs({hasEnforcedInvariant:xn(m.invariants),coverage:e.contract.config.coverage,...e.coverageRootsPresent===!1?{declaredPathPresent:!1}:{}}),C=I.length>0?[]:us({adopted:e.adopted===!0,hasDomainInvariants:Cn(m.invariants),coverage:e.contract.config.coverage,...e.invariantTestsPathPresent===!1?{declaredPathPresent:!1}:{}}),x=[...I.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.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})),...C.map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.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}))],Y=b.filter(A=>A.failsStrict).map(A=>ao(A,lo(A,!1))),te=b.filter(A=>!A.failsStrict).map(A=>({...ao(A,lo(A,!0)),failsStrict:!1})),X=v?cs({arkRules:m,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},S=X.violations.filter(A=>A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,nextAction:`Add a test title or declared symbol covering ${A.arkruleId} (declared in ${A.arkruleSource}), then preflight again.`})),j=X.violations.filter(A=>!A.failsStrict).map(A=>({ruleId:A.ruleId,file:A.file,line:A.line,message:A.message,fromLayer:A.fromLayer,arkruleId:A.arkruleId,arkruleSource:A.arkruleSource,failsStrict:!1,nextAction:A.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${A.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${A.arkruleId} in ${A.arkruleSource} (advisory / partial).`})),qe=ps(i),ge=vs({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(A=>l.get(A)??ne(A,e.contract.config.layers),"layerForFile"),classification:qe}),{violations:Ye,warnings:oe}=uo(ge.findings,e.contract.config.arkRun?.mode),Te=ws({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(A=>l.get(A)??ne(A,e.contract.config.layers),"layerForFile"),classification:qe}),{violations:ke,warnings:er}=uo(Te.findings,e.contract.config.arkOrder?.mode),Yt=[...X.partial&&X.coverage.some(A=>A.mode==="enforced"&&A.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."}]:[],...ge.completenessReasons,...Te.completenessReasons],ve=dt({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(A=>A.layer).map(A=>A.path),contentViolations:[...nc(e,t,l),...Y,...x,...S,...Ye,...ke],edges:c,warnings:[...u,...p.warnings,...te,...j,...oe,...er],safety:p.report}),Ne=o==="complete"&&Yt.length>0?"partial":o,mt=Ne==="complete"?s:[...s,...Yt].sort((A,h)=>{let R=`${A.code}\0${A.file??""}\0${A.message}`,O=`${h.code}\0${h.file??""}\0${h.message}`;return R<O?-1:R>O?1:0}),tr=ve.violations.filter(A=>A.failsStrict!==!1),yt=Ne==="complete"&&tr.length===0,E=yt&&ve.warnings.every(A=>A.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:Ne,completenessReasons:mt,valid:yt,strictValid:E,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:p.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:i,layers:e.contract.config.layers.map(A=>A.name),edges:c,capabilityUses:t.capabilityUses,violations:ve.violations,warnings:ve.warnings}}}a(Ge,"analyzeCanonicalResolvedProject");function rc(e){return Ge({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(rc,"analyzeResolvedProject");function Be(e){return e.flatMap(t=>t.to?[{from:t.from,to:t.to}]:[])}a(Be,"resolvedEdgeDependencies");function Q(e){return`${e.from}->${e.to}`}a(Q,"dependencyKey");function ut(e,t,n,r="dependency"){return{id:`${e}:${r}:${Q(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Q(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Q(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Q(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Q(t)} from the candidate, then preflight again.`}:{}}}a(ut,"dependencyFinding");function ft(e){let t=[],n=new Map(e.changeMap.map.files.map(f=>[f.path,f])),r=new Map(e.changes.map(f=>[f.path,f])),o=new Map(e.changeMap.map.dependencies.map(f=>[Q(f),f])),s=new Map(e.baseDependencies.map(f=>[Q(f),f])),i=new Map(e.candidateDependencies.map(f=>[Q(f),f]));for(let f of[...n.values()].sort((y,d)=>y.path.localeCompare(d.path))){let y=r.get(f.path);y?y.operation!==f.operation?t.push({id:`contradictory:file:${f.path}`,classification:"contradictory",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:y.operation,message:`${f.path} was planned as ${f.operation} but the actual operation is ${y.operation}.`,nextAction:`Change ${f.path} to the planned ${f.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${f.path}`,classification:"satisfied",subject:"file",path:f.path,expectedOperation:f.operation,actualOperation:y.operation,message:`${f.path} matches the planned ${f.operation} operation.`}):t.push({id:`missing:file:${f.path}`,classification:"missing",subject:"file",path:f.path,expectedOperation:f.operation,message:`${f.path} was planned as ${f.operation} but is absent from the actual change.`,nextAction:`${f.operation[0].toUpperCase()}${f.operation.slice(1)} ${f.path} in the complete change set, then preflight again.`})}for(let f of[...r.values()].sort((y,d)=>y.path.localeCompare(d.path)))n.has(f.path)||t.push({id:`unplanned:file:${f.path}`,classification:"unplanned",subject:"file",path:f.path,actualOperation:f.operation,message:`${f.path} has an unplanned ${f.operation} operation.`,nextAction:`Remove ${f.path} from the change set, then preflight again.`});let l=new Set;for(let f of[...o.values()].sort((y,d)=>Q(y).localeCompare(Q(d)))){if(i.has(Q(f))){t.push(ut("satisfied",f,`${f.from} -> ${f.to} exists in the candidate architecture.`));continue}let y={from:f.to,to:f.from};i.has(Q(y))?(l.add(Q(y)),t.push(ut("contradictory",f,`${f.from} -> ${f.to} was planned, but the candidate contains the reverse edge.`))):t.push(ut("missing",f,`${f.from} -> ${f.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[f,y]of[...i].sort(([d],[g])=>d.localeCompare(g)))s.has(f)||o.has(f)||l.has(f)||!c.has(y.from)&&!c.has(y.to)||t.push({...ut("unplanned",y,`${y.from} -> ${y.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(f=>f.operation==="delete").map(f=>f.path));for(let[f,y]of[...s].sort(([d],[g])=>d.localeCompare(g)))i.has(f)||u.has(y.from)||u.has(y.to)||!c.has(y.from)&&!c.has(y.to)||t.push({...ut("unplanned",y,`${y.from} -> ${y.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let p={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((f,y)=>p[f.classification]-p[y.classification]||(f.subject===y.subject?0:f.subject==="file"?-1:1)||f.id.localeCompare(y.id));let m={satisfied:t.filter(f=>f.classification==="satisfied").length,missing:t.filter(f=>f.classification==="missing").length,contradictory:t.filter(f=>f.classification==="contradictory").length,unplanned:t.filter(f=>f.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}a(ft,"analyzeArchitectureConvergence");var Mn="1.0";var Ut=class extends Error{static{a(this,"ArchitectureChangeMapValidationError")}issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
17
17
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
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 _e(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(_e,"requiredString");function Kn(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(Kn,"canonicalProjectPath");function sc(e,t,n="architecture change map"){let r=[];if(!Mn(e))throw new Ut(n,[{path:"$",message:"must be an object"}]);Hn(e,["$schema","schemaVersion","files","dependencies"],"$",r);let o=_e(e,"$schema","$",r),s=_e(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 b=`$.files[${g}]`;if(!Mn(d)){r.push({path:b,message:"must be an object"});return}Hn(d,["path","operation","layer"],b,r);let I=_e(d,"path",b,r),E=_e(d,"operation",b,r),C=_e(d,"layer",b,r),_=I?Kn(I):void 0;I&&!_&&r.push({path:`${b}.path`,message:"must be a canonical project-relative path"}),E&&!["create","update","delete"].includes(E)&&r.push({path:`${b}.operation`,message:"must be create, update, or delete"}),C&&!i.has(C)&&r.push({path:`${b}.layer`,message:`references unknown layer ${JSON.stringify(C)}`}),_&&c.has(_)&&r.push({path:`${b}.path`,message:`duplicates planned path ${_}`}),_&&c.add(_);let q=_?ne(_,t.layers):void 0;_&&C&&i.has(C)&&q!==C&&r.push({path:`${b}.layer`,message:q?`${_} resolves to ${q}, not ${C}`:`${_} is not assigned to an architecture layer`}),_&&E&&["create","update","delete"].includes(E)&&C&&l.push({path:_,operation:E,layer:C})});let u=[],p=new Map(l.map(d=>[d.path,d.operation])),m=new Set,f=e.dependencies??[];if(Array.isArray(f)?f.forEach((d,g)=>{let b=`$.dependencies[${g}]`;if(!Mn(d)){r.push({path:b,message:"must be an object"});return}Hn(d,["from","to"],b,r);let I=_e(d,"from",b,r),E=_e(d,"to",b,r);I&&!c.has(I)&&r.push({path:`${b}.from`,message:`must reference a planned file path: ${I}`}),E&&!c.has(E)&&r.push({path:`${b}.to`,message:`must reference a planned file path: ${E}`}),I&&p.get(I)==="delete"&&r.push({path:`${b}.from`,message:`cannot depend from deleted file ${I}`}),E&&p.get(E)==="delete"&&r.push({path:`${b}.to`,message:`cannot depend on deleted file ${E}`}),I&&E&&I===E&&r.push({path:b,message:"must not declare a self dependency"});let C=I&&E?`${I}\0${E}`:void 0;C&&m.has(C)&&r.push({path:b,message:`duplicates dependency ${I} -> ${E}`}),C&&m.add(C),I&&E&&u.push({from:I,to:E})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new Ut(n,r);let y={$schema:o,schemaVersion:Dn,files:l.sort((d,g)=>d.path.localeCompare(g.path)),dependencies:u.sort((d,g)=>d.from.localeCompare(g.from)||d.to.localeCompare(g.to))};return{map:y,hash:G(K(y))}}a(sc,"loadArchitectureChangeMap");function oc(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(oc,"identityViolations");function ic(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(ic,"preparedChange");function jt(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}a(jt,"isArkRulesPlaneRule");function fo(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,e.file??"",t,e.target??e.message].join("|")}a(fo,"ratchetKey");function po(e,t){let n=new Map;for(let r of e){if(!jt(r.ruleId)||r.failsStrict===!1)continue;let o=fo(r);n.set(o,(n.get(o)??0)+1)}return t.map(r=>{if(!jt(r.ruleId))return r;let o=fo(r),s=n.get(o)??0;return s===0?r:(n.set(o,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}a(po,"ratchetPreExistingArkRules");function ac(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>jt(n.ruleId)),warnings:e.ir.warnings.filter(n=>jt(n.ruleId))}}}a(ac,"baseAnalysisSummary");function Un(e){return jn(e,Se(e.baseFacts),Se(e.candidateFacts))}a(Un,"preflightResolvedChange");function jn(e,t,n){let r=ac(Ge({...e.baseAnalysisInputs??{},contract:e.contract,facts:t}),e.changeMap!==void 0),o=Ge({...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=oc(t,n),c=new Map,u=[];for(let g of e.changes){let b=Kn(g.path);if(!b){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(b)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}c.set(b,g);let I=s.get(b),E=i.get(b);if("delete"in g&&g.delete)I||l.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:b,line:1,message:`Candidate facts still contain deleted file ${b}.`});else{let C="content"in g?g.content:"",_=G(C);E?E.contentHash!==_&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:b,line:1,expectedContentHash:_,candidateContentHash:E.contentHash,message:`Candidate facts for ${b} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:b,line:1,message:`Candidate facts do not contain changed file ${b}.`})}u.push(ic(g,b,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 b=s.get(g),I=i.get(g);b&&I&&K(b)===K(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 p=e.changeMap?ft({changeMap:e.changeMap,changes:u,baseDependencies:Be(r.ir.edges),candidateDependencies:Be(o.ir.edges)}):void 0,m=po(r.ir.violations,o.ir.violations),f=po(r.ir.warnings,o.ir.warnings),y=[...l,...m].map(g=>({...g,nextAction:Ae(g)})),d=y.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.completeness==="complete"&&f.every(g=>g.failsStrict===!1)&&d.length===0&&(p?.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}:{},...p?{convergence:p}:{},changes:u.sort((g,b)=>g.path<b.path?-1:g.path>b.path?1:0),violations:y,warnings:f}}a(jn,"preflightCanonicalChange");function ze(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(ze,"literalText");function mo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(mo,"lineOf");function go(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(go,"isTypeOnlyReference");function yo(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(yo,"singleFileChecker");function Vn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Vn,"symbolAt");function Gn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Vn(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Gn,"localDeclaration");function Bn(e,t){let n,r=[],o=a((i,l,c,u=!1)=>r.push({specifier:c,kind:l,line:mo(t,i),typeOnly:u,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",ze(e,i.moduleSpecifier),go(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",ze(e,i.moduleSpecifier),go(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",ze(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Gn(e,n??(n=yo(e,t)),t,i.expression);(l||u)&&o(i,u?"require":"dynamic-import",ze(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(Bn,"extractSemanticDependencies");function lc(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=ze(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(lc,"staticAccessPath");function cc(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(cc,"runtimeIdentifierReference");function ho(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(ho,"bestForbiddenMatch");function zn(e,t,n){if(n.length===0)return[];let r=new Set(n),o=yo(e,t),s=new Map,i=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let y of f.declarationList.declarations)e.isIdentifier(y.name)&&i.add(y.name.text);let l=a(f=>{let y=lc(e,f);if(!y)return;let d=Vn(o,y.root),g=d?s.get(d):void 0;return g?[...g,...y.segments.slice(1)]:Gn(e,o,t,y.root)||i.has(y.root.text)?void 0:y.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let y of f.declarationList.declarations){if(!y.initializer||!e.isIdentifier(y.name))continue;let d=l(y.initializer),g=Vn(o,y.name);!d||!g||s.set(g,d)}let c=[],u=new Set,p=a((f,y)=>{let d=mo(t,y),g=`${f}:${y.getStart(t)}`;u.has(g)||(u.add(g),c.push({name:f,line:d,node:y}))},"flag"),m=a(f=>{let y=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!y){let d=l(f),g=d?ho(r,d):void 0;g&&p(g,f)}else e.isIdentifier(f)&&r.has(f.text)&&cc(e,f)&&!Gn(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=l(f.initializer);if(d)for(let g of f.name.elements){if(!e.isIdentifier(g.name))continue;let b=g.propertyName?ze(e,g.propertyName)??g.propertyName.text:g.name.text,I=ho(r,[...d,b]);I&&p(I,f.initializer)}}e.forEachChild(f,m)},"visit");return m(t),c}a(zn,"collectForbiddenCapabilityUses");function dc(e,t,n){let r=[];for(let o of n?.dependencies??Bn(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Xe(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??zn(e,t,rn)){let s=Je(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(dc,"collectCapabilityUses");function Wn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(Wn,"omitLayerDescriptions");function Ro(e){let{stewards:t,...n}=Wn(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(Ro,"effectiveContractPolicyPayload");var Oo="1.0",uc="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function w(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${uc}`: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(w,"addFinding");function D(e){return[...new Set(e??[])].sort()}a(D,"sortedUnique");function ie(e,t,n,r,o){let s=D(n),i=D(r),l=new Set(s),c=new Set(i),u=i.filter(m=>!l.has(m)),p=s.filter(m=>!c.has(m));u.length===0&&p.length===0||(u.length>0&&w(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),p.length>0&&w(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(ie,"compareStringSets");function pt(e,t,n,r,o,s,i){if(n===r)return;w(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(pt,"compareBoolean");function Gt(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(Gt,"keyed");function fc(e,t,n){let r=Gt(t,s=>s.name),o=Gt(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&w(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){w(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){w(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;ie(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."}),ie(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 u=vt(i),p=vt(l);ie(e,`${c}.forbiddenGlobals`,u.rawGlobals,p.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),ie(e,`${c}.capabilities`,u.atoms,p.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")&&w(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)}),pt(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."),pt(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(fc,"compareLayers");function pc(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=Gt(t,r),s=Gt(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&w(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),u=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?w(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):w(e,{kind:"allow-added",path:u,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&&w(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&w(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.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 p=l.peerIsolation===!0,m=c.peerIsolation===!0;if(p!==m){let b=l.from===l.to&&c.from===c.to;w(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:b?m?"strengthening":"weakening":"judgment-required",message:b?m?"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:p,after:m})}D(l.sliceFolders).join("\0")!==D(c.sliceFolders).join("\0")&&w(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:D(l.sliceFolders),after:D(c.sliceFolders)});let f=l.sliceIdentity??"path",y=c.sliceIdentity??"path";if(f!==y&&w(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:y}),!p&&!m)continue;Vt(e,`${u}.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."),Vt(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",D((l.allowedCrossSlice??[]).map(Xn)),D((c.allowedCrossSlice??[]).map(Xn)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let d=he(l.sharedImportsSlice)??null,g=he(c.sharedImportsSlice)??null;if(d!==g){let b=_o(g)>_o(d);w(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:b?"strengthening":"weakening",message:xc(d,g),before:d,after:g})}else g==="deny-cross-parent"&&Vt(e,`${u}.sharedImportsSlice.stopAt`,"shared-walk-stop",bo(l.sharedImportsSlice),bo(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.");hc(e,u,l,c)}}a(pc,"compareRules");function Ao(e){let t=e.childSlices;return t?JSON.stringify([D(t.sliceFolders??[]),t.sliceIdentity??"path",D(t.commonFolders??[])]):""}a(Ao,"childSliceFoldersKey");function bo(e){return D(Ct(e).map(t=>gt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(bo,"stopAtKeys");function ko(e){return e==="always"?2:e==="auto"?1:0}a(ko,"siblingRatchetRank");function gc(e){return D((e??[]).map(t=>gt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(gc,"enforceKeys");function vo(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:gc(t.enforce),ratchet:_r(t)}}a(vo,"childSliceSiblingPolicy");function hc(e,t,n,r){let o=vo(n),s=vo(r);if(o===null&&s===null)return;if(o===null&&s!==null){w(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){w(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(Ao(n)!==Ao(r)){w(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";w(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"&&(mc(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce),o.ratchet!==s.ratchet)){let c=ko(s.ratchet)>ko(o.ratchet);w(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&&w(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}),bc(e,t,n,r),Ac(e,t,n,r)}a(hc,"compareChildSlices");function To(e,t){if(JSON.stringify(e)===JSON.stringify(t))return null;let n=t.filter(o=>!e.includes(o)),r=e.filter(o=>!t.includes(o));return{added:n,removed:r,bothWays:n.length>0&&r.length>0}}a(To,"stringListDelta");function mc(e,t,n,r){let o=To(n,r);if(!o)return;let{added:s,bothWays:i}=o;w(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(mc,"compareSiblingEnforceList");function Xn(e){return JSON.stringify([e.from,e.to])}a(Xn,"crossSliceKey");function So(e){return D((e.childSlices?.allowedCrossSlice??[]).map(Xn))}a(So,"childCrossSliceKeys");function We(e){return gt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(We,"allowanceSegments");function Io(e,t){let n=We(e),r=We(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(Io,"patternWidens");function yc(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=We(n[0]).join("/")===We(r[0]).join("/"),s=We(n[1]).join("/")===We(r[1]).join("/"),i=Io(n[0],r[0]),l=Io(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(yc,"allowanceWidens");function Rc(e){return JSON.stringify([gt(e.from.trim().replace(/\\/g,"/")).toLowerCase(),gt(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Rc,"aliasEntryKey");function Eo(e){return D((e.childSlices?.sliceAliases??[]).map(Rc))}a(Eo,"sliceAliasKeys");function Ac(e,t,n,r){let o=Eo(n),s=Eo(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(u=>!o.includes(u)),l=o.filter(u=>!s.includes(u)),c=i.length>0&&l.length>0;w(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 bc(e,t,n,r){let o=So(n),s=So(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(u=>!i.some(p=>yc(p,u))).length===0){w(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}Vt(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(bc,"compareChildCrossSliceAllowances");function Vt(e,t,n,r,o,s,i){let l=To(r,o);if(!l)return;let{added:c,bothWays:u}=l;w(e,{kind:u?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":c.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:c.length>0?s:i,before:r,after:o})}a(Vt,"compareDeclaredExceptions");function kc(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&&w(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"])pt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(kc,"compareSafety");function qn(e){return e.mode==="enforced"?"enforced":"advisory"}a(qn,"arkRunMode");function Yn(e){return e.mode==="enforced"?"enforced":"advisory"}a(Yn,"arkOrderMode");function vc(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Yn(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Yn(r),l=Yn(o);if(i!==l){let c=i==="advisory"&&l==="enforced";w(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})}ie(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."}),ie(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(vc,"compareArkOrder");function Sc(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${qn(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=qn(r),l=qn(o);if(i!==l){let c=i==="advisory"&&l==="enforced";w(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})}ie(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."}),ie(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."}),pt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Sc,"compareArkRun");function Ic(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(Ic,"overallClassification");function wo(e,t){return`${e}::${t}`}a(wo,"ruleKey");function Co(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(wo(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(wo(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Co,"indexEffectiveRules");function Ec(e){return typeof e=="string"?e.length>0?[e]:[]:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(Ec,"arkRulesRefPaths");function wc(e,t){if(!e)return[];let n=new Set;for(let r of[...e.structure,...e.invariants])r.provenance?.layer===t&&r.provenance.sourceFile&&n.add(r.provenance.sourceFile);return[...n]}a(wc,"arkRulesLayerSources");function xo(e,t,n){return[...new Set([...Ec(e),...wc(t,n)])].sort()}a(xo,"arkRulesCatalogPaths");function Cc(e,t,n,r,o,s){let i=new Map((s??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},u=new Set([...Object.keys(l),...Object.keys(c)]);for(let f of[...r?.structure??[],...r?.invariants??[],...o?.structure??[],...o?.invariants??[]])f.provenance?.layer&&u.add(f.provenance.layer);for(let f of[...u].sort()){let y=l[f],d=c[f],g=`$.arkRules[${f}]`,b=xo(y,r,f),I=xo(d,o,f);if(b.join("\0")===I.join("\0"))continue;if(typeof y=="string"&&typeof d=="string"&&y!==d&&b.length===1&&I.length===1&&b[0]===y&&I[0]===d){w(e,{kind:"arkrules-ref-path-changed",path:g,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:y,after:d});continue}let E=new Set(b),C=new Set(I);for(let _ of I)E.has(_)||w(e,{kind:"arkrules-ref-added",path:_,classification:"strengthening",message:`ArkRules reference for layer ${f} was added (${_}).`,after:_});for(let _ of b)C.has(_)||w(e,{kind:"arkrules-ref-removed",path:_,classification:"weakening",message:`ArkRules reference for layer ${f} was removed (${_}).`,before:_})}let p=Co(r),m=Co(o);for(let f of[...new Set([...p.structure.keys(),...m.structure.keys()])].sort()){let y=p.structure.get(f),d=m.structure.get(f),g=`$.arkRules.structure[${f}]`;if(!y&&d){w(e,{kind:"arkrule-structure-added",path:g,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(y&&!d){w(e,{kind:"arkrule-structure-removed",path:g,classification:"weakening",message:`Structure ArkRule ${y.id} was removed.`,before:y});continue}if(!(!y||!d)){if(y.mode!==d.mode){let b=y.mode==="advisory"&&d.mode==="enforced";w(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${g}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:y.mode,after:d.mode})}y.sensor!==d.sensor&&w(e,{kind:"arkrule-sensor-changed",path:`${g}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:y.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...m.invariants.keys()])].sort()){let y=p.invariants.get(f),d=m.invariants.get(f),g=`$.arkRules.invariants[${f}]`;if(!y&&d){w(e,{kind:"arkrule-invariant-added",path:g,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(y&&!d){w(e,{kind:"arkrule-invariant-removed",path:g,classification:"weakening",message:`Invariant ${y.id} was removed.`,before:y});continue}if(!(!y||!d)&&y.mode!==d.mode)if(y.mode==="advisory"&&d.mode==="enforced"){let I=i?.get(d.id),E=ds(I);E.ok?w(e,{kind:"arkrule-invariant-promoted",path:`${g}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:y.mode,after:d.mode}):w(e,{kind:"arkrule-invariant-promote-refused",path:`${g}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${E.reason}`,before:y.mode,after:d.mode})}else w(e,{kind:"arkrule-invariant-demoted",path:`${g}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:y.mode,after:d.mode})}}a(Cc,"compareArkRules");function No(e,t,n){let r=[];ie(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ie(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."}),ie(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."}),pt(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";w(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)&&w(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}),fc(r,e.layers,t.layers),pc(r,e.rules,t.rules),kc(r,e,t),Cc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Sc(r,e,t),vc(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Oo,classification:Ic(r),findings:r}}a(No,"classifyArkPolicyDelta");function Po(e,t){if(!e||e.schemaVersion!==Oo||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(Po,"policyDeltaAcknowledgementMatches");function gt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(gt,"trimTrailingSlashes");function _o(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(_o,"sharedImportsSliceRank");function xc(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(xc,"sharedImportsSliceMessage");function Oe(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(Oe,"normalizePath");function $o(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a($o,"isIdentifierStart");function Bt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(Bt,"isIdentifierCharacter");function ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ee,"skipWhitespace");function ht(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(ht,"readString");function re(e,t,n){return e.startsWith(t,n)&&!Bt(e[n-1])&&!Bt(e[n+t.length])}a(re,"isWordAt");function Lo(e,t){let n=ee(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ee(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!re(e,"type",n))return!1;let o=ee(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||re(e,"as",o)||!$o(e[o]))return!1;for(n=o;n<e.length&&Bt(e[n]);)n+=1;if(n=ee(e,n),re(e,"as",n)){if(n=ee(e,n+2),!$o(e[n]))return!1;for(;n<e.length&&Bt(e[n]);)n+=1}r=!0}return!1}a(Lo,"bracedNamedBindingsAreTypeOnly");function _c(e,t){if(t=ee(e,t+6),e[t]==="(")return ht(e,ee(e,t+1));let n=!1;if(re(e,"type",t)){let o=ee(e,t+4);e[o]!==","&&!re(e,"from",o)&&(n=!0)}else Lo(e,t)&&(n=!0);let r=Fo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(_c,"specifierAfterImport");function Oc(e,t){t=t+6;let n=ee(e,t),r=!1;if(re(e,"type",n)){let s=ee(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Lo(e,n)&&(r=!0);let o=Fo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(Oc,"specifierAfterExport");function Fo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(re(e,"from",t))return ht(e,ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ht(e,t);if(t>0&&(re(e,"import",t)||re(e,"export",t)))return}}a(Fo,"specifierInStaticStatement");function Tc(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(Tc,"skipTemplateLiteral");function Nc(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ee(e,t+7);if(e[r]!=="(")return;r=ee(e,r+1);let o=ht(e,r);return o?{...o,requireCall:!0}:void 0}a(Nc,"specifierAfterRequire");function Pc(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=Tc(e,n);continue}if(r==="'"||r==='"'){let s=ht(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&re(e,"import",n)?_c(e,n):r==="e"&&re(e,"export",n)?Oc(e,n):r==="r"&&re(e,"require",n)?Nc(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(Pc,"moduleSpecifiers");function Do(e,t){let n=[],r=[];for(let o of Pc(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=Xe(s);if(!u)continue;let p=e.content.slice(0,o.offset).split(`
18
+ `)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Hn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Hn,"isObject");function Kn(e,t,n,r){for(let o of Object.keys(e))t.includes(o)||r.push({path:`${n}.${o}`,message:"unknown field"})}a(Kn,"unknownFields");function _e(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(_e,"requiredString");function Un(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(Un,"canonicalProjectPath");function sc(e,t,n="architecture change map"){let r=[];if(!Hn(e))throw new Ut(n,[{path:"$",message:"must be an object"}]);Kn(e,["$schema","schemaVersion","files","dependencies"],"$",r);let o=_e(e,"$schema","$",r),s=_e(e,"schemaVersion","$",r);s&&s!==Mn&&r.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected ${Mn}`});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 b=`$.files[${g}]`;if(!Hn(d)){r.push({path:b,message:"must be an object"});return}Kn(d,["path","operation","layer"],b,r);let v=_e(d,"path",b,r),I=_e(d,"operation",b,r),C=_e(d,"layer",b,r),x=v?Un(v):void 0;v&&!x&&r.push({path:`${b}.path`,message:"must be a canonical project-relative path"}),I&&!["create","update","delete"].includes(I)&&r.push({path:`${b}.operation`,message:"must be create, update, or delete"}),C&&!i.has(C)&&r.push({path:`${b}.layer`,message:`references unknown layer ${JSON.stringify(C)}`}),x&&c.has(x)&&r.push({path:`${b}.path`,message:`duplicates planned path ${x}`}),x&&c.add(x);let Y=x?ne(x,t.layers):void 0;x&&C&&i.has(C)&&Y!==C&&r.push({path:`${b}.layer`,message:Y?`${x} resolves to ${Y}, not ${C}`:`${x} is not assigned to an architecture layer`}),x&&I&&["create","update","delete"].includes(I)&&C&&l.push({path:x,operation:I,layer:C})});let u=[],p=new Map(l.map(d=>[d.path,d.operation])),m=new Set,f=e.dependencies??[];if(Array.isArray(f)?f.forEach((d,g)=>{let b=`$.dependencies[${g}]`;if(!Hn(d)){r.push({path:b,message:"must be an object"});return}Kn(d,["from","to"],b,r);let v=_e(d,"from",b,r),I=_e(d,"to",b,r);v&&!c.has(v)&&r.push({path:`${b}.from`,message:`must reference a planned file path: ${v}`}),I&&!c.has(I)&&r.push({path:`${b}.to`,message:`must reference a planned file path: ${I}`}),v&&p.get(v)==="delete"&&r.push({path:`${b}.from`,message:`cannot depend from deleted file ${v}`}),I&&p.get(I)==="delete"&&r.push({path:`${b}.to`,message:`cannot depend on deleted file ${I}`}),v&&I&&v===I&&r.push({path:b,message:"must not declare a self dependency"});let C=v&&I?`${v}\0${I}`:void 0;C&&m.has(C)&&r.push({path:b,message:`duplicates dependency ${v} -> ${I}`}),C&&m.add(C),v&&I&&u.push({from:v,to:I})}):r.push({path:"$.dependencies",message:"must be an array"}),r.length>0)throw new Ut(n,r);let y={$schema:o,schemaVersion:Mn,files:l.sort((d,g)=>d.path.localeCompare(g.path)),dependencies:u.sort((d,g)=>d.from.localeCompare(g.from)||d.to.localeCompare(g.to))};return{map:y,hash:G(U(y))}}a(sc,"loadArchitectureChangeMap");function oc(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(oc,"identityViolations");function ic(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(ic,"preparedChange");function jt(e){return e.startsWith("ARKRULE_")||e.startsWith("INVARIANT_")}a(jt,"isArkRulesPlaneRule");function fo(e){let t=typeof e.arkruleId=="string"?e.arkruleId:"";return[e.ruleId,e.file??"",t,e.target??e.message].join("|")}a(fo,"ratchetKey");function po(e,t){let n=new Map;for(let r of e){if(!jt(r.ruleId)||r.failsStrict===!1)continue;let o=fo(r);n.set(o,(n.get(o)??0)+1)}return t.map(r=>{if(!jt(r.ruleId))return r;let o=fo(r),s=n.get(o)??0;return s===0?r:(n.set(o,s-1),{...r,preExisting:!0,failsStrict:!1,severity:"warning"})})}a(po,"ratchetPreExistingArkRules");function ac(e,t){return{completeness:e.completeness,completenessReasons:e.completenessReasons,ir:{edges:t?e.ir.edges:[],violations:e.ir.violations.filter(n=>jt(n.ruleId)),warnings:e.ir.warnings.filter(n=>jt(n.ruleId))}}}a(ac,"baseAnalysisSummary");function jn(e){return Vn(e,Se(e.baseFacts),Se(e.candidateFacts))}a(jn,"preflightResolvedChange");function Vn(e,t,n){let r=ac(Ge({...e.baseAnalysisInputs??{},contract:e.contract,facts:t}),e.changeMap!==void 0),o=Ge({...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=oc(t,n),c=new Map,u=[];for(let g of e.changes){let b=Un(g.path);if(!b){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(b)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}c.set(b,g);let v=s.get(b),I=i.get(b);if("delete"in g&&g.delete)v||l.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base facts.`}),I&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:b,line:1,message:`Candidate facts still contain deleted file ${b}.`});else{let C="content"in g?g.content:"",x=G(C);I?I.contentHash!==x&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:b,line:1,expectedContentHash:x,candidateContentHash:I.contentHash,message:`Candidate facts for ${b} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:b,line:1,message:`Candidate facts do not contain changed file ${b}.`})}u.push(ic(g,b,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 b=s.get(g),v=i.get(g);b&&v&&U(b)===U(v)||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 p=e.changeMap?ft({changeMap:e.changeMap,changes:u,baseDependencies:Be(r.ir.edges),candidateDependencies:Be(o.ir.edges)}):void 0,m=po(r.ir.violations,o.ir.violations),f=po(r.ir.warnings,o.ir.warnings),y=[...l,...m].map(g=>({...g,nextAction:Ae(g)})),d=y.filter(g=>g.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.completeness==="complete"&&f.every(g=>g.failsStrict===!1)&&d.length===0&&(p?.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}:{},...p?{convergence:p}:{},changes:u.sort((g,b)=>g.path<b.path?-1:g.path>b.path?1:0),violations:y,warnings:f}}a(Vn,"preflightCanonicalChange");function ze(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(ze,"literalText");function mo(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(mo,"lineOf");function go(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(go,"isTypeOnlyReference");function yo(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(yo,"singleFileChecker");function Gn(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(Gn,"symbolAt");function Bn(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):Gn(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(Bn,"localDeclaration");function zn(e,t){let n,r=[],o=a((i,l,c,u=!1)=>r.push({specifier:c,kind:l,line:mo(t,i),typeOnly:u,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",ze(e,i.moduleSpecifier),go(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",ze(e,i.moduleSpecifier),go(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",ze(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!Bn(e,n??(n=yo(e,t)),t,i.expression);(l||u)&&o(i,u?"require":"dynamic-import",ze(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(zn,"extractSemanticDependencies");function lc(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=ze(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(lc,"staticAccessPath");function cc(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(cc,"runtimeIdentifierReference");function ho(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(ho,"bestForbiddenMatch");function Wn(e,t,n){if(n.length===0)return[];let r=new Set(n),o=yo(e,t),s=new Map,i=new Set;for(let f of t.statements)if(e.isVariableStatement(f))for(let y of f.declarationList.declarations)e.isIdentifier(y.name)&&i.add(y.name.text);let l=a(f=>{let y=lc(e,f);if(!y)return;let d=Gn(o,y.root),g=d?s.get(d):void 0;return g?[...g,...y.segments.slice(1)]:Bn(e,o,t,y.root)||i.has(y.root.text)?void 0:y.segments},"resolvePath");for(let f of t.statements)if(e.isVariableStatement(f))for(let y of f.declarationList.declarations){if(!y.initializer||!e.isIdentifier(y.name))continue;let d=l(y.initializer),g=Gn(o,y.name);!d||!g||s.set(g,d)}let c=[],u=new Set,p=a((f,y)=>{let d=mo(t,y),g=`${f}:${y.getStart(t)}`;u.has(g)||(u.add(g),c.push({name:f,line:d,node:y}))},"flag"),m=a(f=>{let y=f.parent&&(e.isPropertyAccessExpression(f.parent)||e.isElementAccessExpression(f.parent))&&f.parent.expression===f;if((e.isPropertyAccessExpression(f)||e.isElementAccessExpression(f))&&!y){let d=l(f),g=d?ho(r,d):void 0;g&&p(g,f)}else e.isIdentifier(f)&&r.has(f.text)&&cc(e,f)&&!Bn(e,o,t,f)&&p(f.text,f);if(e.isVariableDeclaration(f)&&e.isObjectBindingPattern(f.name)&&f.initializer){let d=l(f.initializer);if(d)for(let g of f.name.elements){if(!e.isIdentifier(g.name))continue;let b=g.propertyName?ze(e,g.propertyName)??g.propertyName.text:g.name.text,v=ho(r,[...d,b]);v&&p(v,f.initializer)}}e.forEachChild(f,m)},"visit");return m(t),c}a(Wn,"collectForbiddenCapabilityUses");function dc(e,t,n){let r=[];for(let o of n?.dependencies??zn(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Xe(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Wn(e,t,rn)){let s=Je(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(dc,"collectCapabilityUses");function qn(e){return{...e,layers:e.layers.map(t=>{let{description:n,trustBoundary:r,owners:o,...s}=t;return s})}}a(qn,"omitLayerDescriptions");function Ro(e){let{stewards:t,...n}=qn(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(Ro,"effectiveContractPolicyPayload");var Oo="1.0",uc="add a short note under docs/adr/ (or docs/decisions/) and put that file path in --policy-ack as adrPath.";function w(e,t){let n=t.classification==="weakening"||t.classification==="judgment-required"?`Restore the previous protection at ${t.path}, or ${uc}`: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(w,"addFinding");function P(e){return[...new Set(e??[])].sort()}a(P,"sortedUnique");function re(e,t,n,r,o){let s=P(n),i=P(r),l=new Set(s),c=new Set(i),u=i.filter(m=>!l.has(m)),p=s.filter(m=>!c.has(m));u.length===0&&p.length===0||(u.length>0&&w(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),p.length>0&&w(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(re,"compareStringSets");function pt(e,t,n,r,o,s,i){if(n===r)return;w(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(pt,"compareBoolean");function Gt(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(Gt,"keyed");function fc(e,t,n){let r=Gt(t,s=>s.name),o=Gt(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&w(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){w(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){w(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 u=P(i.entrypoints),p=P(l.entrypoints);u.length===0&&p.length>0?w(e,{kind:"enabled",path:`${c}.entrypoints`,classification:"strengthening",message:"Cross-layer imports into this layer are now restricted to declared entrypoints.",before:u,after:p}):u.length>0&&p.length===0?w(e,{kind:"disabled",path:`${c}.entrypoints`,classification:"weakening",message:"Entrypoint restriction was removed from this layer; deep cross-layer imports are allowed again.",before:u,after:p}):u.length>0&&p.length>0&&re(e,`${c}.entrypoints`,u,p,{added:"weakening",removed:"strengthening",addedMessage:"Additional entrypoints widen the cross-layer import surface of this layer.",removedMessage:"Fewer entrypoints narrow the cross-layer import surface of this layer."});let m=vt(i),f=vt(l);re(e,`${c}.forbiddenGlobals`,m.rawGlobals,f.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`,m.atoms,f.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")&&w(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)}),pt(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."),pt(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(fc,"compareLayers");function pc(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=Gt(t,r),s=Gt(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&w(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),u=`$.rules[${i}]`;if(!l&&c){c.allowed===!1?w(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:c}):w(e,{kind:"allow-added",path:u,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&&w(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&w(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${u}.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 p=l.peerIsolation===!0,m=c.peerIsolation===!0;if(p!==m){let b=l.from===l.to&&c.from===c.to;w(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:b?m?"strengthening":"weakening":"judgment-required",message:b?m?"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:p,after:m})}P(l.sliceFolders).join("\0")!==P(c.sliceFolders).join("\0")&&w(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:P(l.sliceFolders),after:P(c.sliceFolders)});let f=l.sliceIdentity??"path",y=c.sliceIdentity??"path";if(f!==y&&w(e,{kind:"slice-identity-changed",path:`${u}.sliceIdentity`,classification:"judgment-required",message:"Slice identity changed and can reclassify existing slice ids. Baselines and allowedCrossSlice use those ids.",before:f,after:y}),!p&&!m)continue;Vt(e,`${u}.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."),Vt(e,`${u}.allowedCrossSlice`,"cross-slice-allowance",P((l.allowedCrossSlice??[]).map(Zn)),P((c.allowedCrossSlice??[]).map(Zn)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again.");let d=he(l.sharedImportsSlice)??null,g=he(c.sharedImportsSlice)??null;if(d!==g){let b=_o(g)>_o(d);w(e,{kind:"shared-imports-slice",path:`${u}.sharedImportsSlice`,classification:b?"strengthening":"weakening",message:xc(d,g),before:d,after:g})}else g==="deny-cross-parent"&&Vt(e,`${u}.sharedImportsSlice.stopAt`,"shared-walk-stop",bo(l.sharedImportsSlice),bo(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.");hc(e,u,l,c)}}a(pc,"compareRules");function Ao(e){let t=e.childSlices;return t?JSON.stringify([P(t.sliceFolders??[]),t.sliceIdentity??"path",P(t.commonFolders??[])]):""}a(Ao,"childSliceFoldersKey");function bo(e){return P(Ct(e).map(t=>gt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(bo,"stopAtKeys");function ko(e){return e==="always"?2:e==="auto"?1:0}a(ko,"siblingRatchetRank");function gc(e){return P((e??[]).map(t=>gt(t.trim().replace(/\\/g,"/")).toLowerCase()))}a(gc,"enforceKeys");function vo(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:gc(t.enforce),ratchet:Or(t)}}a(vo,"childSliceSiblingPolicy");function hc(e,t,n,r){let o=vo(n),s=vo(r);if(o===null&&s===null)return;if(o===null&&s!==null){w(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){w(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(Ao(n)!==Ao(r)){w(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";w(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"&&(mc(e,`${t}.childSlices.siblings.enforce`,o.enforce,s.enforce),o.ratchet!==s.ratchet)){let c=ko(s.ratchet)>ko(o.ratchet);w(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&&w(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}),bc(e,t,n,r),Ac(e,t,n,r)}a(hc,"compareChildSlices");function To(e,t){if(JSON.stringify(e)===JSON.stringify(t))return null;let n=t.filter(o=>!e.includes(o)),r=e.filter(o=>!t.includes(o));return{added:n,removed:r,bothWays:n.length>0&&r.length>0}}a(To,"stringListDelta");function mc(e,t,n,r){let o=To(n,r);if(!o)return;let{added:s,bothWays:i}=o;w(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(mc,"compareSiblingEnforceList");function Zn(e){return JSON.stringify([e.from,e.to])}a(Zn,"crossSliceKey");function So(e){return P((e.childSlices?.allowedCrossSlice??[]).map(Zn))}a(So,"childCrossSliceKeys");function We(e){return gt(e.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(t=>t.length>0)}a(We,"allowanceSegments");function Io(e,t){let n=We(e),r=We(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(Io,"patternWidens");function yc(e,t){let n=JSON.parse(e),r=JSON.parse(t),o=We(n[0]).join("/")===We(r[0]).join("/"),s=We(n[1]).join("/")===We(r[1]).join("/"),i=Io(n[0],r[0]),l=Io(n[1],r[1]);return!(o||i)||!(s||l)?!1:i||l}a(yc,"allowanceWidens");function Rc(e){return JSON.stringify([gt(e.from.trim().replace(/\\/g,"/")).toLowerCase(),gt(e.to.trim().replace(/\\/g,"/")).toLowerCase()])}a(Rc,"aliasEntryKey");function Eo(e){return P((e.childSlices?.sliceAliases??[]).map(Rc))}a(Eo,"sliceAliasKeys");function Ac(e,t,n,r){let o=Eo(n),s=Eo(r);if(JSON.stringify(o)===JSON.stringify(s))return;let i=s.filter(u=>!o.includes(u)),l=o.filter(u=>!s.includes(u)),c=i.length>0&&l.length>0;w(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 bc(e,t,n,r){let o=So(n),s=So(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(u=>!i.some(p=>yc(p,u))).length===0){w(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}Vt(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(bc,"compareChildCrossSliceAllowances");function Vt(e,t,n,r,o,s,i){let l=To(r,o);if(!l)return;let{added:c,bothWays:u}=l;w(e,{kind:u?`${n}-changed`:c.length>0?`${n}-added`:`${n}-removed`,path:t,classification:u?"judgment-required":c.length>0?"weakening":"strengthening",message:u?`${s} Entries were added and removed in the same change.`:c.length>0?s:i,before:r,after:o})}a(Vt,"compareDeclaredExceptions");function kc(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&&w(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"])pt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(kc,"compareSafety");function Yn(e){return e.mode==="enforced"?"enforced":"advisory"}a(Yn,"arkRunMode");function Xn(e){return e.mode==="enforced"?"enforced":"advisory"}a(Xn,"arkOrderMode");function vc(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Xn(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Xn(r),l=Xn(o);if(i!==l){let c=i==="advisory"&&l==="enforced";w(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})}re(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."}),re(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(vc,"compareArkOrder");function Sc(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){w(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Yn(o)}).`,after:o});return}if(r&&!o){w(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Yn(r),l=Yn(o);if(i!==l){let c=i==="advisory"&&l==="enforced";w(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})}re(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."}),re(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."}),pt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Sc,"compareArkRun");function Ic(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(Ic,"overallClassification");function wo(e,t){return`${e}::${t}`}a(wo,"ruleKey");function Co(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(wo(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(wo(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Co,"indexEffectiveRules");function Ec(e){return typeof e=="string"?e.length>0?[e]:[]:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}a(Ec,"arkRulesRefPaths");function wc(e,t){if(!e)return[];let n=new Set;for(let r of[...e.structure,...e.invariants])r.provenance?.layer===t&&r.provenance.sourceFile&&n.add(r.provenance.sourceFile);return[...n]}a(wc,"arkRulesLayerSources");function xo(e,t,n){return[...new Set([...Ec(e),...wc(t,n)])].sort()}a(xo,"arkRulesCatalogPaths");function Cc(e,t,n,r,o,s){let i=new Map((s??[]).map(f=>[f.invariantId,f])),l=t.arkRules??{},c=n.arkRules??{},u=new Set([...Object.keys(l),...Object.keys(c)]);for(let f of[...r?.structure??[],...r?.invariants??[],...o?.structure??[],...o?.invariants??[]])f.provenance?.layer&&u.add(f.provenance.layer);for(let f of[...u].sort()){let y=l[f],d=c[f],g=`$.arkRules[${f}]`,b=xo(y,r,f),v=xo(d,o,f);if(b.join("\0")===v.join("\0"))continue;if(typeof y=="string"&&typeof d=="string"&&y!==d&&b.length===1&&v.length===1&&b[0]===y&&v[0]===d){w(e,{kind:"arkrules-ref-path-changed",path:g,classification:"judgment-required",message:`ArkRules file path for layer ${f} changed; verify the effective rules still match intent.`,before:y,after:d});continue}let I=new Set(b),C=new Set(v);for(let x of v)I.has(x)||w(e,{kind:"arkrules-ref-added",path:x,classification:"strengthening",message:`ArkRules reference for layer ${f} was added (${x}).`,after:x});for(let x of b)C.has(x)||w(e,{kind:"arkrules-ref-removed",path:x,classification:"weakening",message:`ArkRules reference for layer ${f} was removed (${x}).`,before:x})}let p=Co(r),m=Co(o);for(let f of[...new Set([...p.structure.keys(),...m.structure.keys()])].sort()){let y=p.structure.get(f),d=m.structure.get(f),g=`$.arkRules.structure[${f}]`;if(!y&&d){w(e,{kind:"arkrule-structure-added",path:g,classification:"strengthening",message:`Structure ArkRule ${d.id} was added (${d.mode}).`,after:d});continue}if(y&&!d){w(e,{kind:"arkrule-structure-removed",path:g,classification:"weakening",message:`Structure ArkRule ${y.id} was removed.`,before:y});continue}if(!(!y||!d)){if(y.mode!==d.mode){let b=y.mode==="advisory"&&d.mode==="enforced";w(e,{kind:b?"arkrule-promoted":"arkrule-demoted",path:`${g}.mode`,classification:b?"strengthening":"weakening",message:b?`Structure ArkRule ${d.id} was promoted to enforced.`:`Structure ArkRule ${d.id} was demoted to advisory.`,before:y.mode,after:d.mode})}y.sensor!==d.sensor&&w(e,{kind:"arkrule-sensor-changed",path:`${g}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${d.id} changed sensor identity.`,before:y.sensor,after:d.sensor})}}for(let f of[...new Set([...p.invariants.keys(),...m.invariants.keys()])].sort()){let y=p.invariants.get(f),d=m.invariants.get(f),g=`$.arkRules.invariants[${f}]`;if(!y&&d){w(e,{kind:"arkrule-invariant-added",path:g,classification:"strengthening",message:`Invariant ${d.id} was added (${d.mode}).`,after:d});continue}if(y&&!d){w(e,{kind:"arkrule-invariant-removed",path:g,classification:"weakening",message:`Invariant ${y.id} was removed.`,before:y});continue}if(!(!y||!d)&&y.mode!==d.mode)if(y.mode==="advisory"&&d.mode==="enforced"){let v=i?.get(d.id),I=ds(v);I.ok?w(e,{kind:"arkrule-invariant-promoted",path:`${g}.mode`,classification:"strengthening",message:`Invariant ${d.id} was promoted to enforced (coverage evidence present).`,before:y.mode,after:d.mode}):w(e,{kind:"arkrule-invariant-promote-refused",path:`${g}.mode`,classification:"judgment-required",message:`Invariant ${d.id} cannot be promoted to enforced: ${I.reason}`,before:y.mode,after:d.mode})}else w(e,{kind:"arkrule-invariant-demoted",path:`${g}.mode`,classification:"weakening",message:`Invariant ${d.id} was demoted to advisory.`,before:y.mode,after:d.mode})}}a(Cc,"compareArkRules");function No(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."}),pt(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";w(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)&&w(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}),fc(r,e.layers,t.layers),pc(r,e.rules,t.rules),kc(r,e,t),Cc(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Sc(r,e,t),vc(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Oo,classification:Ic(r),findings:r}}a(No,"classifyArkPolicyDelta");function Po(e,t){if(!e||e.schemaVersion!==Oo||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=P(e.findingIds),r=P(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}a(Po,"policyDeltaAcknowledgementMatches");function gt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(gt,"trimTrailingSlashes");function _o(e){return e==="deny"?2:e==="deny-cross-parent"?1:0}a(_o,"sharedImportsSliceRank");function xc(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(xc,"sharedImportsSliceMessage");function Oe(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(Oe,"normalizePath");function $o(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a($o,"isIdentifierStart");function Bt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(Bt,"isIdentifierCharacter");function ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ee,"skipWhitespace");function ht(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(ht,"readString");function se(e,t,n){return e.startsWith(t,n)&&!Bt(e[n-1])&&!Bt(e[n+t.length])}a(se,"isWordAt");function Lo(e,t){let n=ee(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ee(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!se(e,"type",n))return!1;let o=ee(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||se(e,"as",o)||!$o(e[o]))return!1;for(n=o;n<e.length&&Bt(e[n]);)n+=1;if(n=ee(e,n),se(e,"as",n)){if(n=ee(e,n+2),!$o(e[n]))return!1;for(;n<e.length&&Bt(e[n]);)n+=1}r=!0}return!1}a(Lo,"bracedNamedBindingsAreTypeOnly");function _c(e,t){if(t=ee(e,t+6),e[t]==="(")return ht(e,ee(e,t+1));let n=!1;if(se(e,"type",t)){let o=ee(e,t+4);e[o]!==","&&!se(e,"from",o)&&(n=!0)}else Lo(e,t)&&(n=!0);let r=Fo(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(_c,"specifierAfterImport");function Oc(e,t){t=t+6;let n=ee(e,t),r=!1;if(se(e,"type",n)){let s=ee(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Lo(e,n)&&(r=!0);let o=Fo(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(Oc,"specifierAfterExport");function Fo(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(se(e,"from",t))return ht(e,ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ht(e,t);if(t>0&&(se(e,"import",t)||se(e,"export",t)))return}}a(Fo,"specifierInStaticStatement");function Tc(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(Tc,"skipTemplateLiteral");function Nc(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ee(e,t+7);if(e[r]!=="(")return;r=ee(e,r+1);let o=ht(e,r);return o?{...o,requireCall:!0}:void 0}a(Nc,"specifierAfterRequire");function Pc(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=Tc(e,n);continue}if(r==="'"||r==='"'){let s=ht(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&se(e,"import",n)?_c(e,n):r==="e"&&se(e,"export",n)?Oc(e,n):r==="r"&&se(e,"require",n)?Nc(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(Pc,"moduleSpecifiers");function Do(e,t){let n=[],r=[];for(let o of Pc(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let u=Xe(s);if(!u)continue;let p=e.content.slice(0,o.offset).split(`
20
20
  `).length;r.push({file:e.path,symbol:s,capability:u,evidence:{kind:"import",file:e.path,line:p,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=$c(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(Do,"moduleFactsFor");function $c(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($c,"resolveSpecifier");function Mo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=He(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:Cr(s,o.sliceVerdict)??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(Mo,"violationsFor");var Lc={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 Fc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(Fc,"hasActiveArkRules");function Dc(e,t){return Fc(e,t)?G(K(Ro({config:e,arkRules:t,warnings:[]}))):G(K(Wn(e)))}a(Dc,"policyHashFor");function Zn(e,t,n){let r=typeof e=="string"?Js(e,t):Nn(e,t),o=n?.arkRules??st();return{...r,arkRules:o,policyHash:Dc(r.config,o)}}a(Zn,"loadContract");function Mc(e){let t=Zn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Zn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=No(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&&Po(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(Mc,"analyzePolicyDelta");function zt(e){let t=e.files.map(m=>{let f=Oe(m.path);return{path:f,content:m.content,contentHash:G(m.content),layer:ne(f,e.contract.config.layers)??null}}).sort((m,f)=>m.path.localeCompare(f.path)),n=new Map(t.map(m=>[m.path,m])),r=[],o=[];for(let m of t){let f=Do(m,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=Mo(r,e.contract.config),i=new Map(e.contract.config.layers.map(m=>[m.name,m])),l=new Map(e.contract.config.layers.map(m=>[m.name,new Set(Fe(m))]));for(let m of o){let f=n.get(m.file)?.layer;if(!f)continue;let y=i.get(f),d=Ze(m.symbol,y?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${m.symbol}" because it is the import form of forbidden global "${d}".`,symbol:m.symbol,evidence:m.evidence});continue}l.get(f)?.has(m.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...Lc}],p={schemaVersion:or,policyHash:e.contract.policyHash,compilerOptionsHash:G(K(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&s.length===0,ir:p}}a(zt,"analyzeProject");function Jn(e){let t=new Map(e.files.map(n=>[Oe(n.path),n]));for(let n of e.changes){let r=Oe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return zt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(Jn,"analyzeChange");function Hc(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(Hc,"explainViolation");function Ho(e){return G(K(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Ho,"analysisTreeHash");function Kc(e){let t=zt(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,"/"),b=Oe(d.path);if(!b||b===".."||b.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(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,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=Jn({...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}}),u=dt({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}:{}}))}),p=r.map(d=>{let g=Oe(d.path),b=n.get(g),I=l.get(g);return{path:g,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...I?{candidateContentHash:I.contentHash}:{}}}).sort((d,g)=>d.path.localeCompare(g.path)),m=[...s,...u.violations].map(d=>({...d,nextAction:Ae(d)})),f=m.filter(d=>d.failsStrict!==!1),y=e.changeMap?ft({changeMap:e.changeMap,changes:p,baseDependencies:Be(t.ir.edges),candidateDependencies:Be(i.ir.edges)}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&f.length===0&&(y?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Ho(t.ir.files),candidateTreeHash:Ho(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...y?{convergence:y}:{},changes:p,violations:m,warnings:u.warnings}}a(Kc,"preflightChange");var Wt=new WeakSet;function Ko(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))Ko(t);return Object.freeze(e)}a(Ko,"deepFreeze");function Cp(e){let t=Ko(bt(e));return Wt.add(t),t}a(Cp,"createTrustedResolvedCandidateFacts");function xp(e){if(!Wt.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Ge(e)}a(xp,"analyzeTrustedResolvedProject");function _p(e){let t=e.baseFacts,n=e.candidateFacts;return!Wt.has(t)||!Wt.has(n)?Un(e):jn(e,t,n)}a(_p,"preflightTrustedResolvedChange");export{rn as AMBIENT_CAPABILITY_ENTRIES,tn as CAPABILITY_IDS,Tt as DEFAULT_INTENT_PREFIXES,sr as RESOLVED_CANDIDATE_FACTS_SCHEMA,$e as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,gn as SOURCE_POLICY_MESSAGES,sn as ambientCoveredByForbiddenGlobals,ft as analyzeArchitectureConvergence,Jn as analyzeChange,Mc as analyzePolicyDelta,zt as analyzeProject,rc as analyzeResolvedProject,xp as analyzeTrustedResolvedProject,Je as capabilityForAmbientName,Xe as capabilityForModuleSpecifier,yn as classifyPublishFacts,Ln as collectAnalysisConfigWarnings,dc as collectCapabilityUses,zn as collectForbiddenCapabilityUses,to as configVersionFloors,bt as createResolvedCandidateFacts,Cp as createTrustedResolvedCandidateFacts,io as detectArchitectureCycles,G as deterministicHash,Fe as effectiveCapabilityDeny,dt as evaluateArchitectureGraph,Hc as explainViolation,Bn as extractSemanticDependencies,Ze as forbiddenGlobalForModuleSpecifier,sc as loadArchitectureChangeMap,Zn as loadContract,Se as loadResolvedCandidateFacts,mn as looksLikeArkIntent,Bo as lowerForbiddenGlobal,vt as loweredLayerCoverage,Wl as parseArkgatePins,Kc as preflightChange,Un as preflightResolvedChange,_p as preflightTrustedResolvedChange,hn as resolveIntentLayer,At as resolvedFactsEvidenceRequirementsHash,K as stableSerialize};
21
+ `).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=$c(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(Do,"moduleFactsFor");function $c(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($c,"resolveSpecifier");function Mo(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=He(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:xr(s,o.sliceVerdict)??`${s.from} must not depend on ${s.to}.`,edge:r,evidence:r.evidence})}return n}a(Mo,"violationsFor");var Lc={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 Fc(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(Fc,"hasActiveArkRules");function Dc(e,t){return Fc(e,t)?G(U(Ro({config:e,arkRules:t,warnings:[]}))):G(U(qn(e)))}a(Dc,"policyHashFor");function Jn(e,t,n){let r=typeof e=="string"?Js(e,t):Pn(e,t),o=n?.arkRules??st();return{...r,arkRules:o,policyHash:Dc(r.config,o)}}a(Jn,"loadContract");function Mc(e){let t=Jn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Jn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=No(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&&Po(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(Mc,"analyzePolicyDelta");function zt(e){let t=e.files.map(m=>{let f=Oe(m.path);return{path:f,content:m.content,contentHash:G(m.content),layer:ne(f,e.contract.config.layers)??null}}).sort((m,f)=>m.path.localeCompare(f.path)),n=new Map(t.map(m=>[m.path,m])),r=[],o=[];for(let m of t){let f=Do(m,n);r.push(...f.edges),o.push(...f.capabilityUses)}let s=Mo(r,e.contract.config),i=new Map(e.contract.config.layers.map(m=>[m.name,m])),l=new Map(e.contract.config.layers.map(m=>[m.name,new Set(Fe(m))]));for(let m of o){let f=n.get(m.file)?.layer;if(!f)continue;let y=i.get(f),d=Ze(m.symbol,y?.forbiddenGlobals??[]);if(d){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${f} must not use module "${m.symbol}" because it is the import form of forbidden global "${d}".`,symbol:m.symbol,evidence:m.evidence});continue}l.get(f)?.has(m.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${f} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let c=t.length===0?"complete":"partial",u=c==="complete"?[]:[{...Lc}],p={schemaVersion:ir,policyHash:e.contract.policyHash,compilerOptionsHash:G(U(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:u,valid:c==="complete"&&s.length===0,ir:p}}a(zt,"analyzeProject");function Qn(e){let t=new Map(e.files.map(n=>[Oe(n.path),n]));for(let n of e.changes){let r=Oe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return zt({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(Qn,"analyzeChange");function Hc(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(Hc,"explainViolation");function Ho(e){return G(U(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Ho,"analysisTreeHash");function Kc(e){let t=zt(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,"/"),b=Oe(d.path);if(!b||b===".."||b.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(b)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:b,line:1,message:`The atomic change set contains more than one operation for ${b}.`});continue}o.add(b),"delete"in d&&d.delete&&!n.has(b)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:b,line:1,message:`Cannot delete ${b} because it is not present in the supplied base tree.`}),r.push("delete"in d&&d.delete?{path:b,delete:!0}:{path:b,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=Qn({...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}}),u=dt({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}:{}}))}),p=r.map(d=>{let g=Oe(d.path),b=n.get(g),v=l.get(g);return{path:g,operation:"delete"in d&&d.delete?"delete":b?"update":"create",...b?{beforeContentHash:b.contentHash}:{},...v?{candidateContentHash:v.contentHash}:{}}}).sort((d,g)=>d.path.localeCompare(g.path)),m=[...s,...u.violations].map(d=>({...d,nextAction:Ae(d)})),f=m.filter(d=>d.failsStrict!==!1),y=e.changeMap?ft({changeMap:e.changeMap,changes:p,baseDependencies:Be(t.ir.edges),candidateDependencies:Be(i.ir.edges)}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&f.length===0&&(y?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Ho(t.ir.files),candidateTreeHash:Ho(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...y?{convergence:y}:{},changes:p,violations:m,warnings:u.warnings}}a(Kc,"preflightChange");var Wt=new WeakSet;function Ko(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))Ko(t);return Object.freeze(e)}a(Ko,"deepFreeze");function Cp(e){let t=Ko(bt(e));return Wt.add(t),t}a(Cp,"createTrustedResolvedCandidateFacts");function xp(e){if(!Wt.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Ge(e)}a(xp,"analyzeTrustedResolvedProject");function _p(e){let t=e.baseFacts,n=e.candidateFacts;return!Wt.has(t)||!Wt.has(n)?jn(e):Vn(e,t,n)}a(_p,"preflightTrustedResolvedChange");export{rn as AMBIENT_CAPABILITY_ENTRIES,tn as CAPABILITY_IDS,Tt as DEFAULT_INTENT_PREFIXES,or as RESOLVED_CANDIDATE_FACTS_SCHEMA,$e as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,gn as SOURCE_POLICY_MESSAGES,sn as ambientCoveredByForbiddenGlobals,ft as analyzeArchitectureConvergence,Qn as analyzeChange,Mc as analyzePolicyDelta,zt as analyzeProject,rc as analyzeResolvedProject,xp as analyzeTrustedResolvedProject,Je as capabilityForAmbientName,Xe as capabilityForModuleSpecifier,yn as classifyPublishFacts,Fn as collectAnalysisConfigWarnings,dc as collectCapabilityUses,Wn as collectForbiddenCapabilityUses,to as configVersionFloors,bt as createResolvedCandidateFacts,Cp as createTrustedResolvedCandidateFacts,io as detectArchitectureCycles,G as deterministicHash,Fe as effectiveCapabilityDeny,dt as evaluateArchitectureGraph,Hc as explainViolation,zn as extractSemanticDependencies,Ze as forbiddenGlobalForModuleSpecifier,sc as loadArchitectureChangeMap,Jn as loadContract,Se as loadResolvedCandidateFacts,mn as looksLikeArkIntent,Bo as lowerForbiddenGlobal,vt as loweredLayerCoverage,Wl as parseArkgatePins,Kc as preflightChange,jn as preflightResolvedChange,_p as preflightTrustedResolvedChange,hn as resolveIntentLayer,At as resolvedFactsEvidenceRequirementsHash,U as stableSerialize};