arkgate 3.8.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,43 @@ in the immutable pre-2.0 archive linked below.
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 3.8.1 — 2026-07-22
9
+
10
+ Corrective **patch** over 3.8.0. Closes silent fail-open on peerIsolation incomplete evidence,
11
+ improves pure-IR type-only and relative-`require` graph accuracy, and splits the Domain analysis
12
+ vocabulary pilot without changing public gate import paths. **No required config migration.**
13
+ Z09 / residual `RB-11` remain open for retained adoption and independent close.
14
+
15
+ ### Fixed
16
+
17
+ - **peerIsolation fail-closed (S1):** when `peerIsolation: true` is configured, missing paths, no
18
+ slice folders, or unclassifiable slices **deny** (cannot prove same-slice). No silent fail-open.
19
+ Incomplete path evidence can surface new denials; that is intentional safety, not a config
20
+ migration.
21
+ - **Pure IR type-only named bindings (S5):** all-type lists (`import { type A }`,
22
+ `export { type A } from '…'`) are type-only for capability evidence; mixed lists and
23
+ default+named imports stay value.
24
+ - **Relative `require` edges (S4):** pure module graph emits dependency edges for relative
25
+ `require(...)` like relative import; package require remains capability evidence only.
26
+
27
+ ### Changed
28
+
29
+ - **Plan-B god-module pilot:** split `src/domain/analysis.ts` by concern into a DomainModel pilot
30
+ cluster — Analysis IR + facade in `analysis.ts`; `stableHash.ts`; `resolvedCandidateFactsTypes.ts`;
31
+ create/load in `resolvedCandidateFacts.ts`; import-free `resolvedCandidateFactsSchema.ts` for
32
+ `generate:cli-pure`. Public root/gate import paths unchanged. Judgment-only hygiene; no contract
33
+ or gate weakening.
34
+
35
+ ### Documentation
36
+
37
+ - **Queue hygiene:** Phase Z engineering slices remain closed in 3.8.0+; `Z09` is a parked claim
38
+ gate (residual `RB-11` = retained adoption + independent close only). No engineering `doing`.
39
+ Y06/Y09 stay parked; Y07 low priority; Y10 archived until field demand + ADR; K01 runtime-only.
40
+ After the analysis pilot, self-hosted design-weak residual is package barrel `src/index.ts`
41
+ only (plan-B judgment; never mechanical-safe).
42
+ - **Pin honesty:** migration guide, claims matrix, and TS support pin current stable as
43
+ **arkgate@3.8.1** (not 3.7.0 / unpublished corrective).
44
+
8
45
  ## 3.8.0 — 2026-07-21
9
46
 
10
47
  This corrective minor makes complete analysis fail closed, restores one resolved architecture
package/README.md CHANGED
@@ -16,9 +16,9 @@ and makes sure a “green” check means something real.
16
16
 
17
17
  </div>
18
18
 
19
- > **ArkGate 3.8.0** is current stable: complete analysis fails closed, complete candidates share
20
- > one resolved architecture verdict, managed upgrades are digest-bound, and an opt-in design-delta
21
- > ratchet blocks new or worsened UI domain logic. [Release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.0.md).
19
+ > **ArkGate 3.8.1** is current stable: 3.8.0 complete analysis / resolved verdict / managed upgrades
20
+ > / design-delta, plus peerIsolation fail-closed and pure-IR require/type-only accuracy.
21
+ > [Release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.1.md).
22
22
 
23
23
  > **TypeScript 7 distribution note:** ArkGate prefers a usable project compiler API, then its
24
24
  > exact, physically distinct TypeScript 6 analysis host. Analysis reports required
@@ -422,7 +422,7 @@ for real systems. Details: [production-hardening.md](https://github.com/pedrokni
422
422
  | Security reporting | [SECURITY.md](SECURITY.md) |
423
423
  | Demos | [docs/demos/](https://github.com/pedroknigge/arkgate/tree/main/docs/demos) |
424
424
  | Examples | [examples/](https://github.com/pedroknigge/arkgate/blob/main/examples/README.md) |
425
- | Latest release (3.8.0) | [release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.0.md) · [3.0.0 baseline](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.0.0.md) |
425
+ | Latest release (3.8.1) | [release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.1.md) · [3.0.0 baseline](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.0.0.md) |
426
426
  | Roadmap and decisions | [ROADMAP.md](https://github.com/pedroknigge/arkgate/blob/main/ROADMAP.md) · [ADRs](https://github.com/pedroknigge/arkgate/tree/main/docs/adr) · [Changelog](CHANGELOG.md) |
427
427
 
428
428
  ---
@@ -191,7 +191,9 @@ function resolveSliceFolders(rule, layerName, layers) {
191
191
  * Same-layer is always allowed (historical short-circuit).
192
192
  * - `peerIsolation: true` + `allowed: false`: deny only when importer and importee
193
193
  * resolve to **different** slice ids (same or cross layer). Same-slice → allow.
194
- * Missing paths or unclassifiable slices → fail-open (do not deny).
194
+ * Missing paths, no slice folders, or unclassifiable slices → **fail-closed**
195
+ * (deny): isolation is configured, so insufficient evidence must not silently
196
+ * allow a possible cross-slice edge.
195
197
  */
196
198
  export function findDeniedEdgeRule(rules, from, to, options) {
197
199
  for (const rule of rules ?? []) {
@@ -202,15 +204,18 @@ export function findDeniedEdgeRule(rules, from, to, options) {
202
204
  if (rule.peerIsolation) {
203
205
  const fromPath = options?.fromPath;
204
206
  const toPath = options?.toPath;
207
+ // Isolation is active: without both paths we cannot prove same-slice.
205
208
  if (!fromPath || !toPath)
206
- continue;
209
+ return rule;
207
210
  const folders = resolveSliceFolders(rule, from, options?.layers);
211
+ // Configured isolation without classifiable folders cannot allow.
208
212
  if (folders.length === 0)
209
- continue;
213
+ return rule;
210
214
  const fromSlice = sliceIdForPath(fromPath, folders);
211
215
  const toSlice = sliceIdForPath(toPath, folders);
216
+ // Unclassifiable either side: cannot prove same-slice → deny.
212
217
  if (!fromSlice || !toSlice)
213
- continue;
218
+ return rule;
214
219
  if (fromSlice !== toSlice)
215
220
  return rule;
216
221
  continue; // same slice: this peerIsolation rule does not deny
@@ -1,10 +1,10 @@
1
1
  // GENERATED from src/kernel/analysis.ts by scripts/generate-analysis-engine.mjs.
2
2
  // Do not edit this file directly.
3
- var It="1.0",ze=["network","filesystem","clock","randomness","environment","process","persistence"];function S(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function R(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(R).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${R(t[n])}`).join(",")}}`}function H(e,t){let n=R(e),s=R(t);return n<s?-1:n>s?1:0}function O(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function be(e){let t={schemaVersion:"1.0",include:O(e.include??[]),exclude:O(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:O(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:O(n.patterns??[]),exclude:O(n.exclude??[]),forbiddenGlobals:O(n.forbiddenGlobals??[]),intentPrefixes:O(n.intentPrefixes??[]),capabilityDeny:O(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(H),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(R(t))}function Rt(e){let t=e.completenessReasons.map(m=>({code:m.code,message:m.message,...m.file?{file:m.file}:{}})).sort(H),n=e.files.map(m=>({...m,typeOnlyExportNames:O(m.typeOnlyExportNames)})).sort((m,a)=>m.path<a.path?-1:m.path>a.path?1:0),s=e.dependencies.map(m=>({...m,...m.namedBindings?{namedBindings:O(m.namedBindings)}:{}})).sort(H),r=e.capabilityUses.map(m=>({...m})).sort(H),i=e.ambientUses.map(m=>({...m})).sort(H),o=e.publishCalls.map(m=>({...m})).sort(H),p=e.intentReferences.map(m=>({...m})).sort(H),f=e.safetyUses.map(m=>({...m})).sort(H),g=e.files.map(({path:m,contentHash:a})=>({path:m,contentHash:a})).sort((m,a)=>m.path<a.path?-1:m.path>a.path?1:0),h=S(R(g));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:h,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:r,ambientUses:i,publishCalls:o,intentReferences:p,safetyUses:f}}function Ke(e){let t=Rt(e);return{...t,factsHash:S(R(t))}}function Ae(e){return Ke(We(P(e,"$"),!1))}function P(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function T(e,t,n){let s=new Set(t),r=Object.keys(e).find(i=>!s.has(i));if(r)throw new Error(`${n}.${r} is not part of schema 1.0.`)}function v(e,t,n){let s=e[t];if(typeof s!="string"||s.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return s}function z(e,t,n){if(e[t]!==void 0)return v(e,t,n)}function L(e,t,n){let s=v(e,t,n),r=s.replace(/\\/g,"/");if(!r||r.startsWith("/")||/^[A-Za-z]:\//.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let p of r.split("/"))if(!(!p||p==="."))if(p===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(p);let o=i.join("/");if(!o||o!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}function k(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Ye(e,t,n){let s=e[t];if(!Number.isInteger(s)||Number(s)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(s)}function K(e,t,n){let s=Ye(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function D(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function M(e,t,n,s){let r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return r}function Be(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function Et(e,t,n){let s=new Set;for(let r of e){let i=t(r);if(s.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);s.add(i)}}function We(e,t){T(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=M(e,"schemaVersion",["1.0"],"$"),s=M(e,"completeness",["complete","partial","unavailable"],"$"),r=D(e,"completenessReasons","$").map((c,d)=>{let u=`$.completenessReasons[${d}]`,y=P(c,u);T(y,["code","message","file"],u);let b=y.file===void 0?void 0:L(y,"file",u);return{code:v(y,"code",u),message:v(y,"message",u),...b?{file:b}:{}}});if(s==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=D(e,"files","$").map((c,d)=>{let u=`$.files[${d}]`,y=P(c,u);return T(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:L(y,"path",u),contentHash:v(y,"contentHash",u),parseStatus:M(y,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:Ye(y,"parseDiagnosticCount",u),exportsOnlyTypes:k(y,"exportsOnlyTypes",u),typeOnlyExportNames:Be(y.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:k(y,"hasTopLevelSideEffects",u)}}),o=D(e,"dependencies","$").map((c,d)=>{let u=`$.dependencies[${d}]`,y=P(c,u);T(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let b=z(y,"specifier",u),A=z(y,"target",u),I=M(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(I==="resolved-project"&&!A)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(I!=="resolved-project"&&A)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(I!=="dynamic"&&!b)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:L(y,"from",u),...b?{specifier:b}:{},kind:M(y,"kind",["import","export","dynamic-import","require"],u),typeOnly:k(y,"typeOnly",u),line:K(y,"line",u),resolution:I,...A?{target:L(y,"target",u)}:{},...y.namedBindings!==void 0?{namedBindings:Be(y.namedBindings,`${u}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:k(y,"targetTypeOnlyExports",u)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:k(y,"sourcePureTypeModule",u)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:k(y,"namedBindingsTypeOnly",u)}:{},...y.portProofEligible!==void 0?{portProofEligible:k(y,"portProofEligible",u)}:{}}}),p=D(e,"capabilityUses","$").map((c,d)=>{let u=`$.capabilityUses[${d}]`,y=P(c,u);return T(y,["file","line","symbol","capability","source"],u),{file:L(y,"file",u),line:K(y,"line",u),symbol:v(y,"symbol",u),capability:M(y,"capability",ze,u),source:M(y,"source",["ambient-global","import-based"],u)}}),f=D(e,"ambientUses","$").map((c,d)=>{let u=`$.ambientUses[${d}]`,y=P(c,u);return T(y,["file","line","symbol"],u),{file:L(y,"file",u),line:K(y,"line",u),symbol:v(y,"symbol",u)}}),g=D(e,"publishCalls","$").map((c,d)=>{let u=`$.publishCalls[${d}]`,y=P(c,u);T(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let b=z(y,"rawIntentName",u),A=z(y,"sourceIntent",u);return{file:L(y,"file",u),line:K(y,"line",u),...b?{rawIntentName:b}:{},objectHasIntent:k(y,"objectHasIntent",u),arkPublishCandidate:k(y,"arkPublishCandidate",u),hasSource:k(y,"hasSource",u),...A?{sourceIntent:A}:{}}}),h=D(e,"intentReferences","$").map((c,d)=>{let u=`$.intentReferences[${d}]`,y=P(c,u);return T(y,["file","line","intent"],u),{file:L(y,"file",u),line:K(y,"line",u),intent:v(y,"intent",u)}}),m=D(e,"safetyUses","$").map((c,d)=>{let u=`$.safetyUses[${d}]`,y=P(c,u);T(y,["file","line","kind","symbol"],u);let b=z(y,"symbol",u),A=M(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(A==="in-memory-store"&&!b)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(A!=="in-memory-store"&&b)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:L(y,"file",u),line:K(y,"line",u),kind:A,...b?{symbol:b}:{}}});Et(i,c=>c.path,"$.files");let a=new Set(i.map(c=>c.path));for(let c of i){if(c.parseStatus==="parsed"&&c.parseDiagnosticCount!==0)throw new Error(`$.files[${c.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(c.parseStatus==="invalid"&&c.parseDiagnosticCount===0)throw new Error(`$.files[${c.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&i.some(c=>c.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let c of o)if(!a.has(c.from))throw new Error(`$.dependencies references missing source file ${c.from}.`);for(let[c,d]of[["$.capabilityUses",p],["$.ambientUses",f],["$.publishCalls",g],["$.intentReferences",h],["$.safetyUses",m]])for(let u of d)if(!a.has(u.file))throw new Error(`${c} references missing file ${u.file}.`);let l=z(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:v(e,"resolverIdentity","$"),compilerIdentity:v(e,"compilerIdentity","$"),compilerOptionsHash:v(e,"compilerOptionsHash","$"),tsconfigHash:v(e,"tsconfigHash","$"),evidenceRequirementsHash:v(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:o,capabilityUses:p,ambientUses:f,publishCalls:g,intentReferences:h,safetyUses:m}}function W(e){let t=P(e,"$"),n=v(t,"factsHash","$"),s=v(t,"candidateTreeHash","$"),r=Ke(We(t,!0));if(r.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${r.factsHash}).`);if(s!==r.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${r.candidateTreeHash}).`);return r}var C={type:"string",minLength:1},Y={type:"integer",minimum:1},_={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},vt={$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:{const:"1.0"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:C,message:C,file:_}}},resolverIdentity:C,compilerIdentity:C,compilerOptionsHash:C,tsconfigHash:C,candidateTreeHash:C,evidenceRequirementsHash:C,projectPackageName:C,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:_,contentHash:C,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:C},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:_,specifier:C,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Y,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:_,namedBindings:{type:"array",items:C},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:_,line:Y,symbol:C,capability:{enum:ze},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:_,line:Y,symbol:C}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:_,line:Y,rawIntentName:C,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:C}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:_,line:Y,intent:C}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:_,line:Y,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:C},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:C},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 Ie=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),le=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Ee=Object.freeze(Object.keys(le).sort()),Ce=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"}),Re=Object.freeze({process:Object.freeze(["process","node:process"])});function te(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ce[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ce[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ce[e.slice(0,i)]??null}function ne(e,t){for(let n of t)if(Re[n]?.includes(e))return n;return null}function se(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=le[s];if(r)return r}return null}function J(e){if(e?.pure===!0)return[...Ie].sort();let n=(e?.capabilities?.deny??[]).filter(s=>Ie.includes(s));return[...new Set(n)].sort()}function ve(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let r=s.length;r>=1;r-=1)if(n.has(s.slice(0,r).join(".")))return!0;return!1}function ce(e){let t=new Set,n=new Set,s=Object.keys(le);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(o=>o===r||o.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let o of i)t.add(`ambient:${o}`);for(let o of Re[r]??[])t.add(`import-exact:${o}`)}for(let r of J(e)){if(t.add(`import:${r}`),r==="process")for(let i of Re.process)t.add(`import-exact:${i}`);for(let i of s)se(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function St(e){let t=new Set,n=se(e);n&&t.add(n);for(let[s,r]of Object.entries(le))(s===e||s.startsWith(`${e}.`))&&t.add(r);return[...t].sort()}var Je=new Map;function Xe(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function Se(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=s}return t}function wt(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function U(e){let t=Je.get(e);if(t)return t;let n=Se(e),s=wt(n),r="",i=0;for(let p=0;p<n.length;p+=1){let f=n[p];f==="\\"&&p+1<n.length?(r+=Xe(n[p+1]),p+=1):f==="*"?n[p+1]==="*"?n[p+2]==="/"?(r+="(?:.*/)?",p+=2):(r+=".*",p+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=Xe(f)}let o=new RegExp(`^${r}$`);return Je.set(e,o),o}function we(e){let t=Se(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function F(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(o=>U(o).test(n))){for(let o of i.patterns??[])if(U(o).test(n)){let p=we(o);p>r&&(r=p,s=i.name)}}return s}function Ze(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(s.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function xt(e){let t=new Set;for(let n of e??[]){let r=Se(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let o=r[i];if((o==="**"||o==="*")&&i>0){let p=r[i-1];p&&!p.includes("*")&&!p.includes("{")&&!p.includes("}")&&t.add(p)}}}return[...t]}function $t(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let s=(n??[]).find(r=>r.name===t);return xt(s?.patterns)}function X(e,t,n,s){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let i=s?.fromPath,o=s?.toPath;if(!i||!o)continue;let p=$t(r,t,s?.layers);if(p.length===0)continue;let f=Ze(i,p),g=Ze(o,p);if(!f||!g)continue;if(f!==g)return r;continue}if(t!==n)return r}}var xe={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."},$e=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 ke(e,t){return t.flatMap((s,r)=>(s.prefixes??s.intentPrefixes??[]).map(i=>({layer:s.name,layerIndex:r,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,r)=>r.prefix.length-s.prefix.length||s.layerIndex-r.layerIndex)[0]?.layer}function Qe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Oe(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Qe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:xe.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:xe.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function Pe(e){let{config:t,rules:n,files:s,manifest:r}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&i.push(w("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)))i.push(w("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let c=t.safety[l];c!==void 0&&(!Number.isInteger(c)||c<0)&&i.push(w("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],p=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],f=new Set([...o.map(l=>l.name).filter(Boolean),...p.map(l=>l.name).filter(l=>!!l)]);o.length===0&&i.push(w("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let g=new Set,h=new Set;for(let l of o){if(!l.name){i.push(w("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}g.has(l.name)&&h.add(l.name),g.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(d=>typeof d!="string"))&&i.push(w("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let c=Array.isArray(l.patterns)?l.patterns:[];if(c.length===0){i.push(w("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let d of c){let u;try{u=U(d)}catch(y){i.push(w("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${d}": ${y instanceof Error?y.message:String(y)}`,{layer:l.name,pattern:d}));continue}!s.some(y=>u.test(y))&&!l.optional&&i.push(w("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${d}" matched no included files.`,{layer:l.name,pattern:d,failsStrict:!1}))}}for(let l of h)i.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&i.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&i.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(o.length>1)for(let l of s){let c=-1,d=[];for(let u of o)for(let y of u.patterns??[]){if(!U(y).test(l))continue;let b=we(y);b>c?(c=b,d=[u.name]):b===c&&!d.includes(u.name)&&d.push(u.name)}d.length>1&&m.add([...d].sort().join(" + "))}m.size>0&&i.push(w("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 a=s.filter(l=>!F(l,o));return a.length>0&&i.push(w("CONFIG_UNCLASSIFIED_FILES",`${a.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:a.length,samples:a.slice(0,5)})),i}function et(e){let t=0,n=new Map,s=new Map,r=new Set,i=[],o=[],p=f=>{n.set(f,t),s.set(f,t),t+=1,i.push(f),r.add(f);for(let m of[...e.get(f)??[]].sort())e.has(m)&&(n.has(m)?r.has(m)&&s.set(f,Math.min(s.get(f)??0,n.get(m)??0)):(p(m),s.set(f,Math.min(s.get(f)??0,s.get(m)??0))));if(s.get(f)!==n.get(f))return;let g=[],h;do{if(h=i.pop(),h===void 0)break;r.delete(h),g.push(h)}while(h!==f);g.length>1&&o.push(g.sort())};for(let f of[...e.keys()].sort())n.has(f)||p(f);return o.sort((f,g)=>f[0]<g[0]?-1:f[0]>g[0]?1:0).map(f=>({ruleId:"CIRCULAR_DEPENDENCY",file:f[0],line:1,target:f.join(" \u2192 "),message:`Circular dependency among ${f.length} files: ${f.join(" \u2192 ")} \u2192 ${f[0]}.`,cycleKind:"value"}))}function ie(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),s=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&s.has(i.from)&&s.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let o=X(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!o)continue;let p=!!o.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!p&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...p?{peerIsolation:!0}:{},message:o.message??(p?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}). Extract shared code or use events/ports across slices.`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let i=et(s);r==="soft"||r==="framework-soft"?n.push(...i.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}function kt(e,t){return t.some(n=>{try{return U(n).test(e)}catch{return!1}})}function Ot(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,r=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],o=t.safetyUses.filter(d=>d.kind==="ts-suppression").map(({file:d,line:u})=>({file:d,line:u})),p=t.safetyUses.filter(d=>d.kind==="any-cast").map(({file:d,line:u})=>({file:d,line:u})),f=t.safetyUses.filter(d=>(d.kind==="dynamic-import"||d.kind==="dynamic-require")&&!kt(d.file,i)).map(d=>({file:d.file,line:d.line,kind:d.kind==="dynamic-require"?"require":"import"})),g=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(d=>d.kind==="in-memory-store").map(d=>({file:d.file,line:d.line,store:d.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(d=>d.peerIsolation===!1||d.allowed===!1&&!!d.from&&d.from===d.to&&d.peerIsolation!==!0).map(d=>({from:d.from,to:d.to})),m={tsSuppressions:o,anyCasts:p,nonLiteralDynamicImports:f,inMemoryProductionStores:g,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:s,maxAnyCasts:r}},a=[],l=f.filter(d=>d.kind==="import");if(l.length>0){let d=l[0];a.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let c=f.filter(d=>d.kind==="require");if(c.length>0){let d=c[0];a.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${c.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>s){let d=o[0];a.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(p.length>r){let d=p[0];a.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${p.length} explicit any cast(s) exceed safety.maxAnyCasts (${r}).`})}if(g.length>0){let d=g[0];a.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:d.file,line:d.line,message:`${g.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return h.length>0&&a.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${h.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:a}}function Pt(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function tt(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return ke(e,n.length>0?n:$e.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Tt(e,t,n){let s=[],r=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let o=n.get(i.file);!o||!Pt(i.symbol,r.get(o)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,message:`${o} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let o=n.get(i.file);if(!o)continue;let p=r.get(o),f=p?.forbiddenGlobals??[],g=i.source==="import-based"?t.dependencies.find(h=>h.from===i.file&&h.line===i.line&&h.specifier===i.symbol&&!h.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&ve(i.symbol,f))){if(i.source==="import-based"){let h=ne(i.symbol,f);if(h){s.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:o,target:i.symbol,...g?{edgeKind:g}:{},message:`${o} must not use module "${i.symbol}" because it is the import form of forbidden global "${h}".`});continue}}J(p).includes(i.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:o,target:i.symbol,capability:i.capability,...g?{edgeKind:g}:{},message:i.source==="import-based"?`${o} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${o} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let o=n.get(i.file);if(!o)continue;for(let f of Oe({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))s.push({ruleId:f.ruleId,file:i.file,line:i.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:f.message});if(!i.sourceIntent)continue;let p=tt(i.sourceIntent,e.contract);!p||p===o||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:o,toLayer:p,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${p}, but the publishing file is classified as ${o}.`})}for(let i of t.intentReferences){let o=n.get(i.file);if(!o)continue;let p=tt(i.intent,e.contract);if(!p)continue;let f=X(e.contract.config.rules,o,p);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:o,toLayer:p,target:i.intent,message:f.message??`${o} must not reference ${p} intent ${i.intent}.`})}return s}function Te(e){let{facts:t}=e,n=be(e.contract.config),s=t.evidenceRequirementsHash===n,r=s?t.completeness:"unavailable",i=s?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((c,d)=>{let u=`${c.code}\0${c.file??""}\0${c.message}`,y=`${d.code}\0${d.file??""}\0${d.message}`;return u<y?-1:u>y?1:0}),o=t.files.map(c=>({...c,layer:F(c.path,e.contract.config.layers)??null})),p=new Map(o.map(c=>[c.path,c.layer])),f=t.dependencies.map(c=>{let d=c.target?p.get(c.target)??F(c.target,e.contract.config.layers):void 0;return{from:c.from,fromLayer:p.get(c.from)??null,...c.resolution==="resolved-project"&&c.target?{to:c.target,...d?{toLayer:d}:{}}:{},line:c.line,kind:c.kind,typeOnly:c.typeOnly,...c.targetTypeOnlyExports?{targetTypeOnlyExports:c.targetTypeOnlyExports}:{},...c.sourcePureTypeModule?{sourcePureTypeModule:c.sourcePureTypeModule}:{},...c.namedBindingsTypeOnly?{namedBindingsTypeOnly:c.namedBindingsTypeOnly}:{},...c.portProofEligible?{portProofEligible:c.portProofEligible}:{}}}),g=Pe({config:e.contract.config,rules:e.contract.config.rules,files:o.map(c=>c.path)}),h=Ot(e,t),m=ie({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(c=>c.layer).map(c=>c.path),contentViolations:Tt(e,t,p),edges:f,warnings:[...g,...h.warnings],safety:h.report}),a=r==="complete"&&m.violations.length===0,l=a&&m.warnings.every(c=>c.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:r,completenessReasons:i,valid:a,strictValid:l,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:o,layers:e.contract.config.layers.map(c=>c.name),edges:f,capabilityUses:t.capabilityUses,violations:m.violations,warnings:m.warnings}}}function de(e){return Te({contract:e.contract,facts:W(e.facts)})}var Le="1.0";var pe=class extends Error{issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
3
+ function E(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function C(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(C).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${C(t[n])}`).join(",")}}`}var K="1.0",Ke=["network","filesystem","clock","randomness","environment","process","persistence"];function j(e,t){let n=C(e),s=C(t);return n<s?-1:n>s?1:0}function T(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}function ce(e){let t={schemaVersion:"1.0",include:T(e.include??[]),exclude:T(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:T(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:T(n.patterns??[]),exclude:T(n.exclude??[]),forbiddenGlobals:T(n.forbiddenGlobals??[]),intentPrefixes:T(n.intentPrefixes??[]),capabilityDeny:T(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(j),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return E(C(t))}function wt(e){let t=e.completenessReasons.map(m=>({code:m.code,message:m.message,...m.file?{file:m.file}:{}})).sort(j),n=e.files.map(m=>({...m,typeOnlyExportNames:T(m.typeOnlyExportNames)})).sort((m,a)=>m.path<a.path?-1:m.path>a.path?1:0),s=e.dependencies.map(m=>({...m,...m.namedBindings?{namedBindings:T(m.namedBindings)}:{}})).sort(j),i=e.capabilityUses.map(m=>({...m})).sort(j),r=e.ambientUses.map(m=>({...m})).sort(j),o=e.publishCalls.map(m=>({...m})).sort(j),p=e.intentReferences.map(m=>({...m})).sort(j),f=e.safetyUses.map(m=>({...m})).sort(j),g=e.files.map(({path:m,contentHash:a})=>({path:m,contentHash:a})).sort((m,a)=>m.path<a.path?-1:m.path>a.path?1:0),h=E(C(g));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:h,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:i,ambientUses:r,publishCalls:o,intentReferences:p,safetyUses:f}}function We(e){let t=wt(e);return{...t,factsHash:E(C(t))}}function de(e){return We(Ze(L(e,"$"),!1))}function L(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function _(e,t,n){let s=new Set(t),i=Object.keys(e).find(r=>!s.has(r));if(i)throw new Error(`${n}.${i} is not part of schema 1.0.`)}function S(e,t,n){let s=e[t];if(typeof s!="string"||s.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return s}function Y(e,t,n){if(e[t]!==void 0)return S(e,t,n)}function F(e,t,n){let s=S(e,t,n),i=s.replace(/\\/g,"/");if(!i||i.startsWith("/")||/^[A-Za-z]:\//.test(i)||/[\u0000-\u001f\u007f]/.test(i))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let r=[];for(let p of i.split("/"))if(!(!p||p==="."))if(p===".."){if(r.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);r.pop()}else r.push(p);let o=r.join("/");if(!o||o!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return o}function P(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Je(e,t,n){let s=e[t];if(!Number.isInteger(s)||Number(s)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(s)}function W(e,t,n){let s=Je(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function H(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function M(e,t,n,s){let i=e[t];if(typeof i!="string"||!n.includes(i))throw new Error(`${s}.${t} must be one of ${n.join(", ")}.`);return i}function Ye(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}function xt(e,t,n){let s=new Set;for(let i of e){let r=t(i);if(s.has(r))throw new Error(`${n} must not contain duplicate facts (${r}).`);s.add(r)}}function Ze(e,t){_(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=M(e,"schemaVersion",["1.0"],"$"),s=M(e,"completeness",["complete","partial","unavailable"],"$"),i=H(e,"completenessReasons","$").map((c,d)=>{let u=`$.completenessReasons[${d}]`,y=L(c,u);_(y,["code","message","file"],u);let b=y.file===void 0?void 0:F(y,"file",u);return{code:S(y,"code",u),message:S(y,"message",u),...b?{file:b}:{}}});if(s==="complete"&&i.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(s!=="complete"&&i.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let r=H(e,"files","$").map((c,d)=>{let u=`$.files[${d}]`,y=L(c,u);return _(y,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],u),{path:F(y,"path",u),contentHash:S(y,"contentHash",u),parseStatus:M(y,"parseStatus",["parsed","invalid"],u),parseDiagnosticCount:Je(y,"parseDiagnosticCount",u),exportsOnlyTypes:P(y,"exportsOnlyTypes",u),typeOnlyExportNames:Ye(y.typeOnlyExportNames,`${u}.typeOnlyExportNames`),hasTopLevelSideEffects:P(y,"hasTopLevelSideEffects",u)}}),o=H(e,"dependencies","$").map((c,d)=>{let u=`$.dependencies[${d}]`,y=L(c,u);_(y,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],u);let b=Y(y,"specifier",u),A=Y(y,"target",u),R=M(y,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],u);if(R==="resolved-project"&&!A)throw new Error(`${u}.target is required for resolved-project dependencies.`);if(R!=="resolved-project"&&A)throw new Error(`${u}.target is only allowed for resolved-project dependencies.`);if(R!=="dynamic"&&!b)throw new Error(`${u}.specifier is required unless resolution is dynamic.`);return{from:F(y,"from",u),...b?{specifier:b}:{},kind:M(y,"kind",["import","export","dynamic-import","require"],u),typeOnly:P(y,"typeOnly",u),line:W(y,"line",u),resolution:R,...A?{target:F(y,"target",u)}:{},...y.namedBindings!==void 0?{namedBindings:Ye(y.namedBindings,`${u}.namedBindings`)}:{},...y.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:P(y,"targetTypeOnlyExports",u)}:{},...y.sourcePureTypeModule!==void 0?{sourcePureTypeModule:P(y,"sourcePureTypeModule",u)}:{},...y.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:P(y,"namedBindingsTypeOnly",u)}:{},...y.portProofEligible!==void 0?{portProofEligible:P(y,"portProofEligible",u)}:{}}}),p=H(e,"capabilityUses","$").map((c,d)=>{let u=`$.capabilityUses[${d}]`,y=L(c,u);return _(y,["file","line","symbol","capability","source"],u),{file:F(y,"file",u),line:W(y,"line",u),symbol:S(y,"symbol",u),capability:M(y,"capability",Ke,u),source:M(y,"source",["ambient-global","import-based"],u)}}),f=H(e,"ambientUses","$").map((c,d)=>{let u=`$.ambientUses[${d}]`,y=L(c,u);return _(y,["file","line","symbol"],u),{file:F(y,"file",u),line:W(y,"line",u),symbol:S(y,"symbol",u)}}),g=H(e,"publishCalls","$").map((c,d)=>{let u=`$.publishCalls[${d}]`,y=L(c,u);_(y,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],u);let b=Y(y,"rawIntentName",u),A=Y(y,"sourceIntent",u);return{file:F(y,"file",u),line:W(y,"line",u),...b?{rawIntentName:b}:{},objectHasIntent:P(y,"objectHasIntent",u),arkPublishCandidate:P(y,"arkPublishCandidate",u),hasSource:P(y,"hasSource",u),...A?{sourceIntent:A}:{}}}),h=H(e,"intentReferences","$").map((c,d)=>{let u=`$.intentReferences[${d}]`,y=L(c,u);return _(y,["file","line","intent"],u),{file:F(y,"file",u),line:W(y,"line",u),intent:S(y,"intent",u)}}),m=H(e,"safetyUses","$").map((c,d)=>{let u=`$.safetyUses[${d}]`,y=L(c,u);_(y,["file","line","kind","symbol"],u);let b=Y(y,"symbol",u),A=M(y,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],u);if(A==="in-memory-store"&&!b)throw new Error(`${u}.symbol is required for in-memory-store facts.`);if(A!=="in-memory-store"&&b)throw new Error(`${u}.symbol is only allowed for in-memory-store facts.`);return{file:F(y,"file",u),line:W(y,"line",u),kind:A,...b?{symbol:b}:{}}});xt(r,c=>c.path,"$.files");let a=new Set(r.map(c=>c.path));for(let c of r){if(c.parseStatus==="parsed"&&c.parseDiagnosticCount!==0)throw new Error(`$.files[${c.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(c.parseStatus==="invalid"&&c.parseDiagnosticCount===0)throw new Error(`$.files[${c.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&r.some(c=>c.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let c of o)if(!a.has(c.from))throw new Error(`$.dependencies references missing source file ${c.from}.`);for(let[c,d]of[["$.capabilityUses",p],["$.ambientUses",f],["$.publishCalls",g],["$.intentReferences",h],["$.safetyUses",m]])for(let u of d)if(!a.has(u.file))throw new Error(`${c} references missing file ${u.file}.`);let l=Y(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:i,resolverIdentity:S(e,"resolverIdentity","$"),compilerIdentity:S(e,"compilerIdentity","$"),compilerOptionsHash:S(e,"compilerOptionsHash","$"),tsconfigHash:S(e,"tsconfigHash","$"),evidenceRequirementsHash:S(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:r,dependencies:o,capabilityUses:p,ambientUses:f,publishCalls:g,intentReferences:h,safetyUses:m}}function U(e){let t=L(e,"$"),n=S(t,"factsHash","$"),s=S(t,"candidateTreeHash","$"),i=We(Ze(t,!0));if(i.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${i.factsHash}).`);if(s!==i.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${i.candidateTreeHash}).`);return i}var $t=["network","filesystem","clock","randomness","environment","process","persistence"],I={type:"string",minLength:1},J={type:"integer",minimum:1},N={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Xe={$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:{const:"1.0"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:I,message:I,file:N}}},resolverIdentity:I,compilerIdentity:I,compilerOptionsHash:I,tsconfigHash:I,candidateTreeHash:I,evidenceRequirementsHash:I,projectPackageName:I,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:N,contentHash:I,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:I},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:N,specifier:I,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:J,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:N,namedBindings:{type:"array",items:I},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:N,line:J,symbol:I,capability:{enum:$t},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:N,line:J,symbol:I}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:N,line:J,rawIntentName:I,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:I}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:N,line:J,intent:I}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:N,line:J,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:I},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:I},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 Qe="1.0";var Ee=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),pe=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Se=Object.freeze(Object.keys(pe).sort()),Re=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"}),ve=Object.freeze({process:Object.freeze(["process","node:process"])});function ne(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Re[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),i=Re[s];if(i)return i;let r=e.indexOf("/",n+1);return r<0?null:Re[e.slice(0,r)]??null}function se(e,t){for(let n of t)if(ve[n]?.includes(e))return n;return null}function ie(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),i=pe[s];if(i)return i}return null}function Z(e){if(e?.pure===!0)return[...Ee].sort();let n=(e?.capabilities?.deny??[]).filter(s=>Ee.includes(s));return[...new Set(n)].sort()}function we(e,t){if(t.length===0)return!1;let n=new Set(t),s=e.split(".");for(let i=s.length;i>=1;i-=1)if(n.has(s.slice(0,i).join(".")))return!0;return!1}function fe(e){let t=new Set,n=new Set,s=Object.keys(pe);for(let i of e?.forbiddenGlobals??[]){let r=s.filter(o=>o===i||o.startsWith(`${i}.`));if(r.length===0)n.add(i);else for(let o of r)t.add(`ambient:${o}`);for(let o of ve[i]??[])t.add(`import-exact:${o}`)}for(let i of Z(e)){if(t.add(`import:${i}`),i==="process")for(let r of ve.process)t.add(`import-exact:${r}`);for(let r of s)ie(r)===i&&t.add(`ambient:${r}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}function kt(e){let t=new Set,n=ie(e);n&&t.add(n);for(let[s,i]of Object.entries(pe))(s===e||s.startsWith(`${e}.`))&&t.add(i);return[...t].sort()}var et=new Map;function tt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function xe(e){let t="";for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=s}return t}function Ot(e){let t=0;for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="\\"){n+=1;continue}if(s==="{")t+=1;else if(s==="}"&&(t-=1,t<0))return!1}return t===0}function G(e){let t=et.get(e);if(t)return t;let n=xe(e),s=Ot(n),i="",r=0;for(let p=0;p<n.length;p+=1){let f=n[p];f==="\\"&&p+1<n.length?(i+=tt(n[p+1]),p+=1):f==="*"?n[p+1]==="*"?n[p+2]==="/"?(i+="(?:.*/)?",p+=2):(i+=".*",p+=1):i+="[^/]*":f==="?"?i+="[^/]":f==="{"&&s?(i+="(?:",r+=1):f==="}"&&s&&r>0?(i+=")",r-=1):f===","&&s&&r>0?i+="|":i+=tt(f)}let o=new RegExp(`^${i}$`);return et.set(e,o),o}function $e(e){let t=xe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return s*1e4+i}function D(e,t){let n=String(e).split(/[/\\]/).join("/"),s,i=-1;for(let r of t??[])if(!(r.exclude??[]).some(o=>G(o).test(n))){for(let o of r.patterns??[])if(G(o).test(n)){let p=$e(o);p>i&&(i=p,s=r.name)}}return s}function nt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),s=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(s.has(n[i].toLowerCase()))return`${n[i].toLowerCase()}/${n[i+1].toLowerCase()}`}function Pt(e){let t=new Set;for(let n of e??[]){let i=xe(String(n)).split("/").filter(Boolean);for(let r=0;r<i.length;r+=1){let o=i[r];if((o==="**"||o==="*")&&r>0){let p=i[r-1];p&&!p.includes("*")&&!p.includes("{")&&!p.includes("}")&&t.add(p)}}}return[...t]}function Tt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let s=(n??[]).find(i=>i.name===t);return Pt(s?.patterns)}function X(e,t,n,s){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let r=s?.fromPath,o=s?.toPath;if(!r||!o)return i;let p=Tt(i,t,s?.layers);if(p.length===0)return i;let f=nt(r,p),g=nt(o,p);if(!f||!g||f!==g)return i;continue}if(t!==n)return i}}var ke={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."},Oe=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 Pe(e,t){return t.flatMap((s,i)=>(s.prefixes??s.intentPrefixes??[]).map(r=>({layer:s.name,layerIndex:i,prefix:r.endsWith(".")?r:`${r}.`}))).filter(({prefix:s})=>e.startsWith(s)).sort((s,i)=>i.prefix.length-s.prefix.length||s.layerIndex-i.layerIndex)[0]?.layer}function st(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Te(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&st(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:ke.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ke.PUBLISH_MISSING_SOURCE}),t}function w(e,t,n={}){return{ruleId:e,message:t,...n}}function Le(e){let{config:t,rules:n,files:s,manifest:i}=e,r=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&r.push(w("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)))r.push(w("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let c=t.safety[l];c!==void 0&&(!Number.isInteger(c)||c<0)&&r.push(w("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let o=Array.isArray(t.layers)?t.layers:[],p=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],f=new Set([...o.map(l=>l.name).filter(Boolean),...p.map(l=>l.name).filter(l=>!!l)]);o.length===0&&r.push(w("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let g=new Set,h=new Set;for(let l of o){if(!l.name){r.push(w("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}g.has(l.name)&&h.add(l.name),g.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(d=>typeof d!="string"))&&r.push(w("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let c=Array.isArray(l.patterns)?l.patterns:[];if(c.length===0){r.push(w("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let d of c){let u;try{u=G(d)}catch(y){r.push(w("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${d}": ${y instanceof Error?y.message:String(y)}`,{layer:l.name,pattern:d}));continue}!s.some(y=>u.test(y))&&!l.optional&&r.push(w("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${d}" matched no included files.`,{layer:l.name,pattern:d,failsStrict:!1}))}}for(let l of h)r.push(w("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(f.size>0)for(let l of n??[])l.from&&!f.has(l.from)&&r.push(w("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!f.has(l.to)&&r.push(w("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(o.length>1)for(let l of s){let c=-1,d=[];for(let u of o)for(let y of u.patterns??[]){if(!G(y).test(l))continue;let b=$e(y);b>c?(c=b,d=[u.name]):b===c&&!d.includes(u.name)&&d.push(u.name)}d.length>1&&m.add([...d].sort().join(" + "))}m.size>0&&r.push(w("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 a=s.filter(l=>!D(l,o));return a.length>0&&r.push(w("CONFIG_UNCLASSIFIED_FILES",`${a.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:a.length,samples:a.slice(0,5)})),r}function it(e){let t=0,n=new Map,s=new Map,i=new Set,r=[],o=[],p=f=>{n.set(f,t),s.set(f,t),t+=1,r.push(f),i.add(f);for(let m of[...e.get(f)??[]].sort())e.has(m)&&(n.has(m)?i.has(m)&&s.set(f,Math.min(s.get(f)??0,n.get(m)??0)):(p(m),s.set(f,Math.min(s.get(f)??0,s.get(m)??0))));if(s.get(f)!==n.get(f))return;let g=[],h;do{if(h=r.pop(),h===void 0)break;i.delete(h),g.push(h)}while(h!==f);g.length>1&&o.push(g.sort())};for(let f of[...e.keys()].sort())n.has(f)||p(f);return o.sort((f,g)=>f[0]<g[0]?-1:f[0]>g[0]?1:0).map(f=>({ruleId:"CIRCULAR_DEPENDENCY",file:f[0],line:1,target:f.join(" \u2192 "),message:`Circular dependency among ${f.length} files: ${f.join(" \u2192 ")} \u2192 ${f[0]}.`,cycleKind:"value"}))}function re(e){let t=e.contentViolations.map(r=>({...r})),n=(e.warnings??[]).map(r=>({...r})),s=new Map(e.files.map(r=>[r,new Set]));for(let r of e.edges){if(r.to&&r.to!==r.from&&!r.typeOnly&&s.has(r.from)&&s.get(r.from)?.add(r.to),!r.to||!r.fromLayer||!r.toLayer)continue;let o=X(e.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:e.config.layers});if(!o)continue;let p=!!o.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:r.from,line:r.line,fromLayer:r.fromLayer,toLayer:r.toLayer,target:r.to,...r.typeOnly?{typeOnly:!0}:{},...r.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...r.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...r.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!p&&r.portProofEligible?{portProofEligible:!0}:{},...r.kind?{edgeKind:r.kind}:{},...p?{peerIsolation:!0}:{},message:o.message??(p?`${r.fromLayer} must not ${r.kind} another slice of ${r.toLayer} (${r.from} \u2192 ${r.to}). Extract shared code or use events/ports across slices.`:`${r.fromLayer} must not ${r.kind} ${r.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let r=it(s);i==="soft"||i==="framework-soft"?n.push(...r.map(o=>({...o,message:`${o.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...r)}return{violations:t,warnings:n,safety:e.safety}}function Lt(e,t){return t.some(n=>{try{return G(n).test(e)}catch{return!1}})}function _t(e,t){let n=e.contract.config.safety??{},s=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,i=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,r=e.contract.config.dynamicImportAllowlist??[],o=t.safetyUses.filter(d=>d.kind==="ts-suppression").map(({file:d,line:u})=>({file:d,line:u})),p=t.safetyUses.filter(d=>d.kind==="any-cast").map(({file:d,line:u})=>({file:d,line:u})),f=t.safetyUses.filter(d=>(d.kind==="dynamic-import"||d.kind==="dynamic-require")&&!Lt(d.file,r)).map(d=>({file:d.file,line:d.line,kind:d.kind==="dynamic-require"?"require":"import"})),g=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(d=>d.kind==="in-memory-store").map(d=>({file:d.file,line:d.line,store:d.symbol??"in-memory store"})),h=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(d=>d.peerIsolation===!1||d.allowed===!1&&!!d.from&&d.from===d.to&&d.peerIsolation!==!0).map(d=>({from:d.from,to:d.to})),m={tsSuppressions:o,anyCasts:p,nonLiteralDynamicImports:f,inMemoryProductionStores:g,disabledPeerIsolationRules:h,thresholds:{maxTsSuppressions:s,maxAnyCasts:i}},a=[],l=f.filter(d=>d.kind==="import");if(l.length>0){let d=l[0];a.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${l.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let c=f.filter(d=>d.kind==="require");if(c.length>0){let d=c[0];a.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:d.file,line:d.line,message:`${c.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(o.length>s){let d=o[0];a.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${o.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${s}).`})}if(p.length>i){let d=p[0];a.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:d.file,line:d.line,message:`${p.length} explicit any cast(s) exceed safety.maxAnyCasts (${i}).`})}if(g.length>0){let d=g[0];a.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:d.file,line:d.line,message:`${g.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return h.length>0&&a.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${h.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:m,warnings:a}}function Ft(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,s)=>s.length-n.length)[0]}function rt(e,t){let n=t.config.layers.filter(s=>(s.intentPrefixes??[]).length>0);return Pe(e,n.length>0?n:Oe.map(s=>({name:s.layer,prefixes:s.prefixes})))}function Nt(e,t,n){let s=[],i=new Map(e.contract.config.layers.map(r=>[r.name,r]));for(let r of t.ambientUses){let o=n.get(r.file);!o||!Ft(r.symbol,i.get(o)?.forbiddenGlobals??[])||s.push({ruleId:"FORBIDDEN_GLOBAL",file:r.file,line:r.line,fromLayer:o,target:r.symbol,message:`${o} must not use the ambient global "${r.symbol}".`})}for(let r of t.capabilityUses){let o=n.get(r.file);if(!o)continue;let p=i.get(o),f=p?.forbiddenGlobals??[],g=r.source==="import-based"?t.dependencies.find(h=>h.from===r.file&&h.line===r.line&&h.specifier===r.symbol&&!h.typeOnly)?.kind:void 0;if(!(r.source==="ambient-global"&&we(r.symbol,f))){if(r.source==="import-based"){let h=se(r.symbol,f);if(h){s.push({ruleId:"FORBIDDEN_GLOBAL",file:r.file,line:r.line,fromLayer:o,target:r.symbol,...g?{edgeKind:g}:{},message:`${o} must not use module "${r.symbol}" because it is the import form of forbidden global "${h}".`});continue}}Z(p).includes(r.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",file:r.file,line:r.line,fromLayer:o,target:r.symbol,capability:r.capability,...g?{edgeKind:g}:{},message:r.source==="import-based"?`${o} denies the ${r.capability} capability; found import of "${r.symbol}".`:`${o} denies the ${r.capability} capability; found ambient "${r.symbol}".`})}}for(let r of t.publishCalls){let o=n.get(r.file);if(!o)continue;for(let f of Te({publishCall:!0,rawIntentName:r.rawIntentName,objectHasIntent:r.objectHasIntent,arkPublishCandidate:r.arkPublishCandidate,hasSource:r.hasSource}))s.push({ruleId:f.ruleId,file:r.file,line:r.line,...f.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:o}:{},message:f.message});if(!r.sourceIntent)continue;let p=rt(r.sourceIntent,e.contract);!p||p===o||s.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:r.file,line:r.line,fromLayer:o,toLayer:p,target:r.sourceIntent,message:`Publish source "${r.sourceIntent}" resolves to ${p}, but the publishing file is classified as ${o}.`})}for(let r of t.intentReferences){let o=n.get(r.file);if(!o)continue;let p=rt(r.intent,e.contract);if(!p)continue;let f=X(e.contract.config.rules,o,p);f&&s.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:r.file,line:r.line,fromLayer:o,toLayer:p,target:r.intent,message:f.message??`${o} must not reference ${p} intent ${r.intent}.`})}return s}function _e(e){let{facts:t}=e,n=ce(e.contract.config),s=t.evidenceRequirementsHash===n,i=s?t.completeness:"unavailable",r=s?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((c,d)=>{let u=`${c.code}\0${c.file??""}\0${c.message}`,y=`${d.code}\0${d.file??""}\0${d.message}`;return u<y?-1:u>y?1:0}),o=t.files.map(c=>({...c,layer:D(c.path,e.contract.config.layers)??null})),p=new Map(o.map(c=>[c.path,c.layer])),f=t.dependencies.map(c=>{let d=c.target?p.get(c.target)??D(c.target,e.contract.config.layers):void 0;return{from:c.from,fromLayer:p.get(c.from)??null,...c.resolution==="resolved-project"&&c.target?{to:c.target,...d?{toLayer:d}:{}}:{},line:c.line,kind:c.kind,typeOnly:c.typeOnly,...c.targetTypeOnlyExports?{targetTypeOnlyExports:c.targetTypeOnlyExports}:{},...c.sourcePureTypeModule?{sourcePureTypeModule:c.sourcePureTypeModule}:{},...c.namedBindingsTypeOnly?{namedBindingsTypeOnly:c.namedBindingsTypeOnly}:{},...c.portProofEligible?{portProofEligible:c.portProofEligible}:{}}}),g=Le({config:e.contract.config,rules:e.contract.config.rules,files:o.map(c=>c.path)}),h=_t(e,t),m=re({config:e.contract.config,rules:e.contract.config.rules,files:o.filter(c=>c.layer).map(c=>c.path),contentViolations:Nt(e,t,p),edges:f,warnings:[...g,...h.warnings],safety:h.report}),a=i==="complete"&&m.violations.length===0,l=a&&m.warnings.every(c=>c.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:i,completenessReasons:r,valid:a,strictValid:l,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:h.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:o,layers:e.contract.config.layers.map(c=>c.name),edges:f,capabilityUses:t.capabilityUses,violations:m.violations,warnings:m.warnings}}}function ue(e){return _e({contract:e.contract,facts:U(e.facts)})}var Fe="1.0";var me=class extends Error{issues;source;constructor(t,n){super(`Invalid architecture change map (${t}):
4
4
  ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
5
- `)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function _e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fe(e,t,n,s){for(let r of Object.keys(e))t.includes(r)||s.push({path:`${n}.${r}`,message:"unknown field"})}function G(e,t,n,s){let r=e[t];if(typeof r=="string"&&r.length>0)return r;s.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function Lt(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let r of t.split("/"))if(!(!r||r==="."))if(r===".."){if(n.length===0)return;n.pop()}else n.push(r);let s=n.join("/");return s&&s===t?s:void 0}function _t(e,t,n="architecture change map"){let s=[];if(!_e(e))throw new pe(n,[{path:"$",message:"must be an object"}]);Fe(e,["$schema","schemaVersion","files","dependencies"],"$",s);let r=G(e,"$schema","$",s),i=G(e,"schemaVersion","$",s);i&&i!==Le&&s.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(i)}; expected ${Le}`});let o=new Set(t.layers.map(c=>c.name)),p=[],f=new Set;!Array.isArray(e.files)||e.files.length===0?s.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((c,d)=>{let u=`$.files[${d}]`;if(!_e(c)){s.push({path:u,message:"must be an object"});return}Fe(c,["path","operation","layer"],u,s);let y=G(c,"path",u,s),b=G(c,"operation",u,s),A=G(c,"layer",u,s),I=y?Lt(y):void 0;y&&!I&&s.push({path:`${u}.path`,message:"must be a canonical project-relative path"}),b&&!["create","update","delete"].includes(b)&&s.push({path:`${u}.operation`,message:"must be create, update, or delete"}),A&&!o.has(A)&&s.push({path:`${u}.layer`,message:`references unknown layer ${JSON.stringify(A)}`}),I&&f.has(I)&&s.push({path:`${u}.path`,message:`duplicates planned path ${I}`}),I&&f.add(I);let he=I?F(I,t.layers):void 0;I&&A&&o.has(A)&&he!==A&&s.push({path:`${u}.layer`,message:he?`${I} resolves to ${he}, not ${A}`:`${I} is not assigned to an architecture layer`}),I&&b&&["create","update","delete"].includes(b)&&A&&p.push({path:I,operation:b,layer:A})});let g=[],h=new Map(p.map(c=>[c.path,c.operation])),m=new Set,a=e.dependencies??[];if(Array.isArray(a)?a.forEach((c,d)=>{let u=`$.dependencies[${d}]`;if(!_e(c)){s.push({path:u,message:"must be an object"});return}Fe(c,["from","to"],u,s);let y=G(c,"from",u,s),b=G(c,"to",u,s);y&&!f.has(y)&&s.push({path:`${u}.from`,message:`must reference a planned file path: ${y}`}),b&&!f.has(b)&&s.push({path:`${u}.to`,message:`must reference a planned file path: ${b}`}),y&&h.get(y)==="delete"&&s.push({path:`${u}.from`,message:`cannot depend from deleted file ${y}`}),b&&h.get(b)==="delete"&&s.push({path:`${u}.to`,message:`cannot depend on deleted file ${b}`}),y&&b&&y===b&&s.push({path:u,message:"must not declare a self dependency"});let A=y&&b?`${y}\0${b}`:void 0;A&&m.has(A)&&s.push({path:u,message:`duplicates dependency ${y} -> ${b}`}),A&&m.add(A),y&&b&&g.push({from:y,to:b})}):s.push({path:"$.dependencies",message:"must be an array"}),s.length>0)throw new pe(n,s);let l={$schema:r,schemaVersion:Le,files:p.sort((c,d)=>c.path.localeCompare(d.path)),dependencies:g.sort((c,d)=>c.from.localeCompare(d.from)||c.to.localeCompare(d.to))};return{map:l,hash:S(R(l))}}function x(e){return`${e.from}->${e.to}`}function re(e,t,n,s="dependency"){return{id:`${e}:${s}:${x(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${x(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${x(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${x(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${x(t)} from the candidate, then preflight again.`}:{}}}function ae(e){let t=[],n=new Map(e.changeMap.map.files.map(a=>[a.path,a])),s=new Map(e.changes.map(a=>[a.path,a])),r=new Map(e.changeMap.map.dependencies.map(a=>[x(a),a])),i=new Map(e.baseDependencies.map(a=>[x(a),a])),o=new Map(e.candidateDependencies.map(a=>[x(a),a]));for(let a of[...n.values()].sort((l,c)=>l.path.localeCompare(c.path))){let l=s.get(a.path);l?l.operation!==a.operation?t.push({id:`contradictory:file:${a.path}`,classification:"contradictory",subject:"file",path:a.path,expectedOperation:a.operation,actualOperation:l.operation,message:`${a.path} was planned as ${a.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${a.path} to the planned ${a.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${a.path}`,classification:"satisfied",subject:"file",path:a.path,expectedOperation:a.operation,actualOperation:l.operation,message:`${a.path} matches the planned ${a.operation} operation.`}):t.push({id:`missing:file:${a.path}`,classification:"missing",subject:"file",path:a.path,expectedOperation:a.operation,message:`${a.path} was planned as ${a.operation} but is absent from the actual change.`,nextAction:`${a.operation[0].toUpperCase()}${a.operation.slice(1)} ${a.path} in the complete change set, then preflight again.`})}for(let a of[...s.values()].sort((l,c)=>l.path.localeCompare(c.path)))n.has(a.path)||t.push({id:`unplanned:file:${a.path}`,classification:"unplanned",subject:"file",path:a.path,actualOperation:a.operation,message:`${a.path} has an unplanned ${a.operation} operation.`,nextAction:`Remove ${a.path} from the change set, then preflight again.`});let p=new Set;for(let a of[...r.values()].sort((l,c)=>x(l).localeCompare(x(c)))){if(o.has(x(a))){t.push(re("satisfied",a,`${a.from} -> ${a.to} exists in the candidate architecture.`));continue}let l={from:a.to,to:a.from};o.has(x(l))?(p.add(x(l)),t.push(re("contradictory",a,`${a.from} -> ${a.to} was planned, but the candidate contains the reverse edge.`))):t.push(re("missing",a,`${a.from} -> ${a.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[a,l]of[...o].sort(([c],[d])=>c.localeCompare(d)))i.has(a)||r.has(a)||p.has(a)||!f.has(l.from)&&!f.has(l.to)||t.push({...re("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let g=new Set(e.changeMap.map.files.filter(a=>a.operation==="delete").map(a=>a.path));for(let[a,l]of[...i].sort(([c],[d])=>c.localeCompare(d)))o.has(a)||g.has(l.from)||g.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...re("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((a,l)=>h[a.classification]-h[l.classification]||(a.subject===l.subject?0:a.subject==="file"?-1:1)||a.id.localeCompare(l.id));let m={satisfied:t.filter(a=>a.classification==="satisfied").length,missing:t.filter(a=>a.classification==="missing").length,contradictory:t.filter(a=>a.classification==="contradictory").length,unplanned:t.filter(a=>a.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}}function Z(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function it(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function nt(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let r=s.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function rt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=r=>r===t.fileName?t:void 0,s.fileExists=r=>r===t.fileName,s.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function Ne(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function De(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ne(t,s)}catch{i=void 0}return!!i?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function Me(e,t){let n,s=[],r=(o,p,f,g=!1)=>s.push({specifier:f,kind:p,line:it(t,o),typeOnly:g,unresolved:f===void 0,node:o}),i=o=>{if(e.isImportDeclaration(o))r(o,"import",Z(e,o.moduleSpecifier),nt(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)r(o,"export",Z(e,o.moduleSpecifier),nt(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))r(o,"require",Z(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let p=o.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!De(e,n??(n=rt(e,t)),t,o.expression);(p||g)&&r(o,g?"require":"dynamic-import",Z(e,o.arguments[0]))}e.forEachChild(o,i)};return i(t),s}function Ft(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let r=Z(e,s.argumentExpression);if(r===void 0)return;n.unshift(r)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function Nt(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function st(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let r=n.slice(0,s).join(".");if(e.has(r))return r}}function He(e,t,n){if(n.length===0)return[];let s=new Set(n),r=rt(e,t),i=new Map,o=new Set;for(let a of t.statements)if(e.isVariableStatement(a))for(let l of a.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let p=a=>{let l=Ft(e,a);if(!l)return;let c=Ne(r,l.root),d=c?i.get(c):void 0;return d?[...d,...l.segments.slice(1)]:De(e,r,t,l.root)||o.has(l.root.text)?void 0:l.segments};for(let a of t.statements)if(e.isVariableStatement(a))for(let l of a.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let c=p(l.initializer),d=Ne(r,l.name);!c||!d||i.set(d,c)}let f=[],g=new Set,h=(a,l)=>{let c=it(t,l),d=`${a}:${l.getStart(t)}`;g.has(d)||(g.add(d),f.push({name:a,line:c,node:l}))},m=a=>{let l=a.parent&&(e.isPropertyAccessExpression(a.parent)||e.isElementAccessExpression(a.parent))&&a.parent.expression===a;if((e.isPropertyAccessExpression(a)||e.isElementAccessExpression(a))&&!l){let c=p(a),d=c?st(s,c):void 0;d&&h(d,a)}else e.isIdentifier(a)&&s.has(a.text)&&Nt(e,a)&&!De(e,r,t,a)&&h(a.text,a);if(e.isVariableDeclaration(a)&&e.isObjectBindingPattern(a.name)&&a.initializer){let c=p(a.initializer);if(c)for(let d of a.name.elements){if(!e.isIdentifier(d.name))continue;let u=d.propertyName?Z(e,d.propertyName)??d.propertyName.text:d.name.text,y=st(s,[...c,u]);y&&h(y,a.initializer)}}e.forEachChild(a,m)};return m(t),f}function Dt(e,t,n){let s=[];for(let r of n?.dependencies??Me(e,t)){if(r.typeOnly||!r.specifier)continue;let i=te(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??He(e,t,Ee)){let i=se(r.name);i&&s.push({capability:i,symbol:r.name,line:r.line,source:"ambient-global"})}return s.sort((r,i)=>r.line-i.line||r.capability.localeCompare(i.capability)||r.symbol.localeCompare(i.symbol))}var Ve="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",at=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Mt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ht(){let e=[];for(let t of at)for(let n of at)t===n||Mt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var lt=Ht();var j={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ot={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ve,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:Ve,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},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:lt,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}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...j,minItems:1},exclude:j,intentPrefixes:j,description:{type:"string",minLength:1},forbiddenGlobals:j,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...j,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},ee=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
5
+ `)}`),this.name="ArchitectureChangeMapValidationError",this.source=t,this.issues=n}};function Ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function De(e,t,n,s){for(let i of Object.keys(e))t.includes(i)||s.push({path:`${n}.${i}`,message:"unknown field"})}function q(e,t,n,s){let i=e[t];if(typeof i=="string"&&i.length>0)return i;s.push({path:`${n}.${t}`,message:"must be a non-empty string"})}function Dt(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let i of t.split("/"))if(!(!i||i==="."))if(i===".."){if(n.length===0)return;n.pop()}else n.push(i);let s=n.join("/");return s&&s===t?s:void 0}function Ht(e,t,n="architecture change map"){let s=[];if(!Ne(e))throw new me(n,[{path:"$",message:"must be an object"}]);De(e,["$schema","schemaVersion","files","dependencies"],"$",s);let i=q(e,"$schema","$",s),r=q(e,"schemaVersion","$",s);r&&r!==Fe&&s.push({path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${Fe}`});let o=new Set(t.layers.map(c=>c.name)),p=[],f=new Set;!Array.isArray(e.files)||e.files.length===0?s.push({path:"$.files",message:"must be a non-empty array"}):e.files.forEach((c,d)=>{let u=`$.files[${d}]`;if(!Ne(c)){s.push({path:u,message:"must be an object"});return}De(c,["path","operation","layer"],u,s);let y=q(c,"path",u,s),b=q(c,"operation",u,s),A=q(c,"layer",u,s),R=y?Dt(y):void 0;y&&!R&&s.push({path:`${u}.path`,message:"must be a canonical project-relative path"}),b&&!["create","update","delete"].includes(b)&&s.push({path:`${u}.operation`,message:"must be create, update, or delete"}),A&&!o.has(A)&&s.push({path:`${u}.layer`,message:`references unknown layer ${JSON.stringify(A)}`}),R&&f.has(R)&&s.push({path:`${u}.path`,message:`duplicates planned path ${R}`}),R&&f.add(R);let Ie=R?D(R,t.layers):void 0;R&&A&&o.has(A)&&Ie!==A&&s.push({path:`${u}.layer`,message:Ie?`${R} resolves to ${Ie}, not ${A}`:`${R} is not assigned to an architecture layer`}),R&&b&&["create","update","delete"].includes(b)&&A&&p.push({path:R,operation:b,layer:A})});let g=[],h=new Map(p.map(c=>[c.path,c.operation])),m=new Set,a=e.dependencies??[];if(Array.isArray(a)?a.forEach((c,d)=>{let u=`$.dependencies[${d}]`;if(!Ne(c)){s.push({path:u,message:"must be an object"});return}De(c,["from","to"],u,s);let y=q(c,"from",u,s),b=q(c,"to",u,s);y&&!f.has(y)&&s.push({path:`${u}.from`,message:`must reference a planned file path: ${y}`}),b&&!f.has(b)&&s.push({path:`${u}.to`,message:`must reference a planned file path: ${b}`}),y&&h.get(y)==="delete"&&s.push({path:`${u}.from`,message:`cannot depend from deleted file ${y}`}),b&&h.get(b)==="delete"&&s.push({path:`${u}.to`,message:`cannot depend on deleted file ${b}`}),y&&b&&y===b&&s.push({path:u,message:"must not declare a self dependency"});let A=y&&b?`${y}\0${b}`:void 0;A&&m.has(A)&&s.push({path:u,message:`duplicates dependency ${y} -> ${b}`}),A&&m.add(A),y&&b&&g.push({from:y,to:b})}):s.push({path:"$.dependencies",message:"must be an array"}),s.length>0)throw new me(n,s);let l={$schema:i,schemaVersion:Fe,files:p.sort((c,d)=>c.path.localeCompare(d.path)),dependencies:g.sort((c,d)=>c.from.localeCompare(d.from)||c.to.localeCompare(d.to))};return{map:l,hash:E(C(l))}}function x(e){return`${e.from}->${e.to}`}function ae(e,t,n,s="dependency"){return{id:`${e}:${s}:${x(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${x(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${x(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${x(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${x(t)} from the candidate, then preflight again.`}:{}}}function oe(e){let t=[],n=new Map(e.changeMap.map.files.map(a=>[a.path,a])),s=new Map(e.changes.map(a=>[a.path,a])),i=new Map(e.changeMap.map.dependencies.map(a=>[x(a),a])),r=new Map(e.baseDependencies.map(a=>[x(a),a])),o=new Map(e.candidateDependencies.map(a=>[x(a),a]));for(let a of[...n.values()].sort((l,c)=>l.path.localeCompare(c.path))){let l=s.get(a.path);l?l.operation!==a.operation?t.push({id:`contradictory:file:${a.path}`,classification:"contradictory",subject:"file",path:a.path,expectedOperation:a.operation,actualOperation:l.operation,message:`${a.path} was planned as ${a.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${a.path} to the planned ${a.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${a.path}`,classification:"satisfied",subject:"file",path:a.path,expectedOperation:a.operation,actualOperation:l.operation,message:`${a.path} matches the planned ${a.operation} operation.`}):t.push({id:`missing:file:${a.path}`,classification:"missing",subject:"file",path:a.path,expectedOperation:a.operation,message:`${a.path} was planned as ${a.operation} but is absent from the actual change.`,nextAction:`${a.operation[0].toUpperCase()}${a.operation.slice(1)} ${a.path} in the complete change set, then preflight again.`})}for(let a of[...s.values()].sort((l,c)=>l.path.localeCompare(c.path)))n.has(a.path)||t.push({id:`unplanned:file:${a.path}`,classification:"unplanned",subject:"file",path:a.path,actualOperation:a.operation,message:`${a.path} has an unplanned ${a.operation} operation.`,nextAction:`Remove ${a.path} from the change set, then preflight again.`});let p=new Set;for(let a of[...i.values()].sort((l,c)=>x(l).localeCompare(x(c)))){if(o.has(x(a))){t.push(ae("satisfied",a,`${a.from} -> ${a.to} exists in the candidate architecture.`));continue}let l={from:a.to,to:a.from};o.has(x(l))?(p.add(x(l)),t.push(ae("contradictory",a,`${a.from} -> ${a.to} was planned, but the candidate contains the reverse edge.`))):t.push(ae("missing",a,`${a.from} -> ${a.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[a,l]of[...o].sort(([c],[d])=>c.localeCompare(d)))r.has(a)||i.has(a)||p.has(a)||!f.has(l.from)&&!f.has(l.to)||t.push({...ae("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let g=new Set(e.changeMap.map.files.filter(a=>a.operation==="delete").map(a=>a.path));for(let[a,l]of[...r].sort(([c],[d])=>c.localeCompare(d)))o.has(a)||g.has(l.from)||g.has(l.to)||!f.has(l.from)&&!f.has(l.to)||t.push({...ae("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let h={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((a,l)=>h[a.classification]-h[l.classification]||(a.subject===l.subject?0:a.subject==="file"?-1:1)||a.id.localeCompare(l.id));let m={satisfied:t.filter(a=>a.classification==="satisfied").length,missing:t.filter(a=>a.classification==="missing").length,contradictory:t.filter(a=>a.classification==="contradictory").length,unplanned:t.filter(a=>a.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}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function lt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function at(e,t){if(e.isImportDeclaration(t)){let s=t.importClause;if(!s)return!1;if(s.isTypeOnly)return!0;let i=s.namedBindings;return!!(i&&e.isNamedImports(i)&&i.elements.length>0&&i.elements.every(r=>r.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(s=>s.isTypeOnly))}function ct(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},s=e.createCompilerHost(n,!0);return s.getSourceFile=i=>i===t.fileName?t:void 0,s.fileExists=i=>i===t.fileName,s.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,s).getTypeChecker()}function He(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Me(e,t,n,s){let i=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,r;try{r=i?t.getShorthandAssignmentValueSymbol(s.parent):He(t,s)}catch{r=void 0}return!!r?.declarations?.some(o=>o.getSourceFile().fileName===n.fileName)}function je(e,t){let n,s=[],i=(o,p,f,g=!1)=>s.push({specifier:f,kind:p,line:lt(t,o),typeOnly:g,unresolved:f===void 0,node:o}),r=o=>{if(e.isImportDeclaration(o))i(o,"import",Q(e,o.moduleSpecifier),at(e,o));else if(e.isExportDeclaration(o)&&o.moduleSpecifier)i(o,"export",Q(e,o.moduleSpecifier),at(e,o));else if(e.isImportEqualsDeclaration(o)&&e.isExternalModuleReference(o.moduleReference))i(o,"require",Q(e,o.moduleReference.expression),o.isTypeOnly===!0);else if(e.isCallExpression(o)){let p=o.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(o.expression)&&o.expression.text==="require"&&!Me(e,n??(n=ct(e,t)),t,o.expression);(p||g)&&i(o,g?"require":"dynamic-import",Q(e,o.arguments[0]))}e.forEachChild(o,r)};return r(t),s}function Mt(e,t){let n=[],s=t;for(;e.isPropertyAccessExpression(s)||e.isElementAccessExpression(s);){if(e.isPropertyAccessExpression(s))n.unshift(s.name.text);else{let i=Q(e,s.argumentExpression);if(i===void 0)return;n.unshift(i)}s=s.expression}if(e.isIdentifier(s))return n.unshift(s.text),{root:s,segments:n}}function jt(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function ot(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let s=n.length;s>=1;s-=1){let i=n.slice(0,s).join(".");if(e.has(i))return i}}function Ve(e,t,n){if(n.length===0)return[];let s=new Set(n),i=ct(e,t),r=new Map,o=new Set;for(let a of t.statements)if(e.isVariableStatement(a))for(let l of a.declarationList.declarations)e.isIdentifier(l.name)&&o.add(l.name.text);let p=a=>{let l=Mt(e,a);if(!l)return;let c=He(i,l.root),d=c?r.get(c):void 0;return d?[...d,...l.segments.slice(1)]:Me(e,i,t,l.root)||o.has(l.root.text)?void 0:l.segments};for(let a of t.statements)if(e.isVariableStatement(a))for(let l of a.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let c=p(l.initializer),d=He(i,l.name);!c||!d||r.set(d,c)}let f=[],g=new Set,h=(a,l)=>{let c=lt(t,l),d=`${a}:${l.getStart(t)}`;g.has(d)||(g.add(d),f.push({name:a,line:c,node:l}))},m=a=>{let l=a.parent&&(e.isPropertyAccessExpression(a.parent)||e.isElementAccessExpression(a.parent))&&a.parent.expression===a;if((e.isPropertyAccessExpression(a)||e.isElementAccessExpression(a))&&!l){let c=p(a),d=c?ot(s,c):void 0;d&&h(d,a)}else e.isIdentifier(a)&&s.has(a.text)&&jt(e,a)&&!Me(e,i,t,a)&&h(a.text,a);if(e.isVariableDeclaration(a)&&e.isObjectBindingPattern(a.name)&&a.initializer){let c=p(a.initializer);if(c)for(let d of a.name.elements){if(!e.isIdentifier(d.name))continue;let u=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,y=ot(s,[...c,u]);y&&h(y,a.initializer)}}e.forEachChild(a,m)};return m(t),f}function Vt(e,t,n){let s=[];for(let i of n?.dependencies??je(e,t)){if(i.typeOnly||!i.specifier)continue;let r=ne(i.specifier);r&&s.push({capability:r,symbol:i.specifier,line:i.line,source:"import-based"})}for(let i of n?.ambientUses??Ve(e,t,Se)){let r=ie(i.name);r&&s.push({capability:r,symbol:i.name,line:i.line,source:"ambient-global"})}return s.sort((i,r)=>i.line-r.line||i.capability.localeCompare(r.capability)||i.symbol.localeCompare(r.symbol))}var Ge="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",dt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ut=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Gt(){let e=[];for(let t of dt)for(let n of dt)t===n||Ut.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ft=Gt();var V={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},pt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ge,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:Ge,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...V,minItems:1,default:["src"]},exclude:{...V,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ft,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...V,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...V,minItems:1},exclude:V,intentPrefixes:V,description:{type:"string",minLength:1},forbiddenGlobals:V,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...V,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},te=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
6
6
  ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
7
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ct(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function je(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Q(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function jt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function fe(e,t,n,s,r){if(t.$ref){let i=jt(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}fe(e,i,n,s,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ct(e)){r.push({path:n,message:`must be an object; received ${Q(e)}`});return}let i=t.properties??{};for(let o of t.required??[])e[o]===void 0&&r.push({path:je(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in i||r.push({path:je(n,o),message:"unknown field"});for(let[o,p]of Object.entries(i))e[o]!==void 0&&fe(e[o],p,je(n,o),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${Q(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(o=>JSON.stringify(o));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,o)=>fe(i,t.items,`${n}[${o}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${Q(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${Q(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${Q(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function Vt(e){return{...e,$schema:e.$schema===void 0?Ve:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?lt.map(t=>({...t})):e.rules}}function Ut(e,t="ark.config.json"){if(!ct(e))throw new ee(t,[{path:"$",message:`must be an object; received ${Q(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ee(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Vt(e),migratedFrom:n}}function Ue(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=Ut(e,t),r=[];if(fe(n,ot,"$",ot,r),r.length>0)throw new ee(t,r);return{config:n,migratedFrom:s}}function dt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new ee(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return Ue(n,t)}var pt="1.0";function E(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function $(e){return[...new Set(e??[])].sort()}function q(e,t,n,s,r){let i=$(n),o=$(s),p=new Set(i),f=new Set(o),g=o.filter(m=>!p.has(m)),h=i.filter(m=>!f.has(m));g.length===0&&h.length===0||(g.length>0&&E(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:o}),h.length>0&&E(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:o}))}function ue(e,t,n,s,r,i,o){if(n===s)return;E(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:o,before:n,after:s})}function me(e,t){let n=new Map,s=new Set;for(let r of e){let i=t(r);n.has(i)?s.add(i):n.set(i,r)}return{values:n,duplicates:[...s].sort()}}function Gt(e,t,n){let s=me(t,i=>i.name),r=me(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&E(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:r.duplicates});for(let i of[...new Set([...s.values.keys(),...r.values.keys()])].sort()){let o=s.values.get(i),p=r.values.get(i),f=`$.layers[${i}]`;if(!o&&p){E(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:p});continue}if(o&&!p){E(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!p)continue;q(e,`${f}.patterns`,o.patterns,p.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),q(e,`${f}.exclude`,o.exclude,p.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=ce(o),h=ce(p);q(e,`${f}.forbiddenGlobals`,g.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),q(e,`${f}.capabilities`,g.atoms,h.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),$(o.intentPrefixes).join("\0")!==$(p.intentPrefixes).join("\0")&&E(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:$(o.intentPrefixes),after:$(p.intentPrefixes)}),ue(e,`${f}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,p.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ue(e,`${f}.optional`,o.optional===!0,p.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.")}}function qt(e,t,n){let s=o=>`${o.from}->${o.to}`,r=me(t,s),i=me(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&E(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:i.duplicates});for(let o of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let p=r.values.get(o),f=i.values.get(o),g=`$.rules[${o}]`;if(!p&&f){f.allowed===!1&&E(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(p&&!f){p.allowed===!1&&E(e,{kind:"deny-removed",path:g,classification:"weakening",message:"A denied dependency edge was removed.",before:p});continue}if(!p||!f)continue;p.allowed!==f.allowed&&E(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${g}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:p.allowed,after:f.allowed});let h=p.peerIsolation===!0,m=f.peerIsolation===!0;if(h!==m){let a=p.from===p.to&&f.from===f.to;E(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${g}.peerIsolation`,classification:a?m?"strengthening":"weakening":"judgment-required",message:a?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:h,after:m})}$(p.sliceFolders).join("\0")!==$(f.sliceFolders).join("\0")&&E(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:$(p.sliceFolders),after:$(f.sliceFolders)})}}function Bt(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let o=s[i]??0,p=r[i]??0;o!==p&&E(e,{kind:p>o?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:p>o?"weakening":"strengthening",message:p>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:p})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])ue(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function zt(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"}function ft(e,t){let n=[];q(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),q(n,"$.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."}),q(n,"$.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."}),ue(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",i=t.cyclePolicy??"strict";if(r!==i){let o=s[i]===s[r]?"judgment-required":s[i]>s[r]?"strengthening":"weakening";E(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:r,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&E(n,{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}),Gt(n,e.layers,t.layers),qt(n,e.rules,t.rules),Bt(n,e,t),n.sort((o,p)=>o.path.localeCompare(p.path)||o.id.localeCompare(p.id)),{schemaVersion:pt,classification:zt(n),findings:n}}function ut(e,t){if(!e||e.schemaVersion!==pt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=$(e.findingIds),s=$(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}function B(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("/")}function mt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function V(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function oe(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,r="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:r,offset:s,excerpt:e.slice(s,t+1)};i==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=i}}function N(e,t,n){return e.startsWith(t,n)&&!mt(e[n-1])&&!mt(e[n+t.length])}function Kt(e,t){if(t=V(e,t+6),e[t]==="(")return oe(e,V(e,t+1));let n=!1;if(N(e,"type",t)){let r=V(e,t+4);e[r]!==","&&!N(e,"from",r)&&(n=!0)}let s=yt(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Yt(e,t){t=t+6;let n=V(e,t),s=!1;if(N(e,"type",n)){let i=V(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}let r=yt(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function yt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(N(e,"from",t))return oe(e,V(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return oe(e,t);if(t>0&&(N(e,"import",t)||N(e,"export",t)))return}}function Wt(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}function Jt(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=V(e,t+7);if(e[s]!=="(")return;s=V(e,s+1);let r=oe(e,s);return r?{...r,requireCall:!0}:void 0}function Xt(e){let t=[];for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
8
- `,n+2),n<0)break;continue}if(s==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(s==="`"){n=Wt(e,n);continue}if(s==="'"||s==='"'){let i=oe(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let r=s==="i"&&N(e,"import",n)?Kt(e,n):s==="e"&&N(e,"export",n)?Yt(e,n):s==="r"&&N(e,"require",n)?Jt(e,n):void 0;r&&(t.push(r),n=r.offset+r.excerpt.length-1)}return t}function gt(e,t){let n=[],s=[];for(let r of Xt(e.content)){let i=r.value;if(r.requireCall&&i.startsWith("."))continue;if(!i.startsWith(".")){if(r.typeOnly)continue;let g=te(i);if(!g)continue;let h=e.content.slice(0,r.offset).split(`
9
- `).length;s.push({file:e.path,symbol:i,capability:g,evidence:{kind:"import",file:e.path,line:h,excerpt:r.excerpt}});continue}let o=e.content.slice(0,r.offset).split(`
10
- `).length,p={kind:"import",file:e.path,line:o,excerpt:r.excerpt},f=Zt(e.path,i,t);n.push({from:e.path,specifier:i,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:p})}return{edges:n,capabilityUses:s}}function Zt(e,t,n){let s=e.split("/");s.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?s.pop():s.push(i));let r=s.join("/");for(let i of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let o=n.get(i);if(o)return o}}function ht(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let r=X(t.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:t.layers});r&&n.push({ruleId:`layer-dependency:${r.from}->${r.to}`,message:r.message??`${r.from} must not depend on ${r.to}.`,edge:s,evidence:s.evidence})}return n}var en={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 Ge(e,t){let n=typeof e=="string"?dt(e,t):Ue(e,t);return{...n,policyHash:S(R(n.config))}}function tn(e){let t=Ge(e.baseConfig,e.baseSource??"base ark.config.json"),n=Ge(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=ft(t.config,n.config),r=s.findings.filter(p=>p.classification==="weakening"||p.classification==="judgment-required").map(p=>p.id).sort(),i=r.length>0,o=i&&ut(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:r,requiresAcknowledgement:i,acknowledged:o,valid:!i||o}}function ye(e){let t=e.files.map(m=>{let a=B(m.path);return{path:a,content:m.content,contentHash:S(m.content),layer:F(a,e.contract.config.layers)??null}}).sort((m,a)=>m.path.localeCompare(a.path)),n=new Map(t.map(m=>[m.path,m])),s=[],r=[];for(let m of t){let a=gt(m,n);s.push(...a.edges),r.push(...a.capabilityUses)}let i=ht(s,e.contract.config),o=new Map(e.contract.config.layers.map(m=>[m.name,m])),p=new Map(e.contract.config.layers.map(m=>[m.name,new Set(J(m))]));for(let m of r){let a=n.get(m.file)?.layer;if(!a)continue;let l=o.get(a),c=ne(m.symbol,l?.forbiddenGlobals??[]);if(c){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${a} must not use module "${m.symbol}" because it is the import form of forbidden global "${c}".`,symbol:m.symbol,evidence:m.evidence});continue}p.get(a)?.has(m.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${a} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let f=t.length===0?"complete":"partial",g=f==="complete"?[]:[{...en}],h={schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:S(R(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:s,capabilityUses:r,violations:i};return{mode:"lexical-compatibility",completeness:f,completenessReasons:g,valid:f==="complete"&&i.length===0,ir:h}}function qe(e){let t=new Map(e.files.map(n=>[B(n.path),n]));for(let n of e.changes){let s=B(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return ye({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function nn(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}`}function ge(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, 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, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function bt(e){return S(R(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function sn(e){let t=ye(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],r=new Set,i=[];for(let l of e.changes){let c=l.path.replace(/\\/g,"/"),d=B(l.path);if(!d||d===".."||d.startsWith("../")||c.startsWith("/")||/^[A-Za-z]:\//.test(c)||c.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(r.has(d)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}r.add(d),"delete"in l&&l.delete&&!n.has(d)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base tree.`}),s.push("delete"in l&&l.delete?{path:d,delete:!0}:{path:d,content:"content"in l?l.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=qe({...e,changes:s}),p=new Map(o.ir.files.map(l=>[l.path,l])),f=o.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let c=p.get(l.evidence.file)?.layer;return{ruleId:l.ruleId,file:l.evidence.file,line:l.evidence.line,target:l.symbol,...l.capability?{capability:l.capability}:{},...c?{fromLayer:c}:{},edgeKind:"import",message:l.message}}),g=ie({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(l=>l.path),contentViolations:f,edges:o.ir.edges.filter(l=>!!l.fromLayer).map(l=>({from:l.from,fromLayer:l.fromLayer,...l.to?{to:l.to}:{},...l.toLayer?{toLayer:l.toLayer}:{},line:l.evidence.line,kind:"import"}))}),h=s.map(l=>{let c=B(l.path),d=n.get(c),u=p.get(c);return{path:c,operation:"delete"in l&&l.delete?"delete":d?"update":"create",...d?{beforeContentHash:d.contentHash}:{},...u?{candidateContentHash:u.contentHash}:{}}}).sort((l,c)=>l.path.localeCompare(c.path)),m=[...i,...g.violations].map(l=>({...l,nextAction:ge(l)})),a=e.changeMap?ae({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:o.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&o.valid&&m.length===0&&(a?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:bt(t.ir.files),candidateTreeHash:bt(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...a?{convergence:a}:{},changes:h,violations:m,warnings:g.warnings}}function rn(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let r of t.split("/"))if(!(!r||r==="."))if(r===".."){if(n.length===0)return;n.pop()}else n.push(r);let s=n.join("/");return s&&s===t?s:void 0}function an(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,s,r])=>s!==r).map(([s,r,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:s,before:r,candidate:i,message:`Base and candidate facts must use the same ${s}.`}))}function on(e,t,n,s){let r=n.get(t),i=s.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":r?"update":"create",...r?{beforeContentHash:r.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}function ln(e){let t=W(e.baseFacts),n=W(e.candidateFacts),s=de({contract:e.contract,facts:t}),r=de({contract:e.contract,facts:n}),i=new Map(t.files.map(a=>[a.path,a])),o=new Map(n.files.map(a=>[a.path,a])),p=an(t,n),f=new Map,g=[];for(let a of e.changes){let l=rn(a.path);if(!l){p.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(f.has(l)){p.push({ruleId:"DUPLICATE_CHANGE_PATH",file:l,line:1,message:`The atomic change set contains more than one operation for ${l}.`});continue}f.set(l,a);let c=i.get(l),d=o.get(l);if("delete"in a&&a.delete)c||p.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),d&&p.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let u="content"in a?a.content:"",y=S(u);d?d.contentHash!==y&&p.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:y,candidateContentHash:d.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):p.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}g.push(on(a,l,i,o))}e.changes.length===0&&p.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let a of new Set([...i.keys(),...o.keys()])){if(f.has(a))continue;let l=i.get(a),c=o.get(a);l&&c&&R(l)===R(c)||p.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:a,line:1,message:`Candidate facts change ${a}, but the atomic change set does not declare it.`})}let h=e.changeMap?ae({changeMap:e.changeMap,changes:g,baseDependencies:s.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[]),candidateDependencies:r.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[])}):void 0,m=[...p,...r.ir.violations].map(a=>({...a,nextAction:ge(a)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&r.strictValid&&m.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:s.completeness,candidateCompleteness:r.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:r.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:g.sort((a,l)=>a.path<l.path?-1:a.path>l.path?1:0),violations:m,warnings:r.ir.warnings}}var At=new WeakSet;function Ct(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))Ct(t);return Object.freeze(e)}function Cs(e){let t=Ct(Ae(e));return At.add(t),t}function Is(e){if(!At.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return Te(e)}export{Ee as AMBIENT_CAPABILITY_ENTRIES,Ie as CAPABILITY_IDS,$e as DEFAULT_INTENT_PREFIXES,vt as RESOLVED_CANDIDATE_FACTS_SCHEMA,It as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,xe as SOURCE_POLICY_MESSAGES,ve as ambientCoveredByForbiddenGlobals,ae as analyzeArchitectureConvergence,qe as analyzeChange,tn as analyzePolicyDelta,ye as analyzeProject,de as analyzeResolvedProject,Is as analyzeTrustedResolvedProject,se as capabilityForAmbientName,te as capabilityForModuleSpecifier,Oe as classifyPublishFacts,Pe as collectAnalysisConfigWarnings,Dt as collectCapabilityUses,He as collectForbiddenCapabilityUses,Ae as createResolvedCandidateFacts,Cs as createTrustedResolvedCandidateFacts,et as detectArchitectureCycles,S as deterministicHash,J as effectiveCapabilityDeny,ie as evaluateArchitectureGraph,nn as explainViolation,Me as extractSemanticDependencies,ne as forbiddenGlobalForModuleSpecifier,_t as loadArchitectureChangeMap,Ge as loadContract,W as loadResolvedCandidateFacts,Qe as looksLikeArkIntent,St as lowerForbiddenGlobal,ce as loweredLayerCoverage,sn as preflightChange,ln as preflightResolvedChange,ke as resolveIntentLayer,be as resolvedFactsEvidenceRequirementsHash,R as stableSerialize};
7
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ue(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ee(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function qt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ye(e,t,n,s,i){if(t.$ref){let r=qt(t.$ref,s);if(!r){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ye(e,r,n,s,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(r=>Object.is(r,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!ut(e)){i.push({path:n,message:`must be an object; received ${ee(e)}`});return}let r=t.properties??{};for(let o of t.required??[])e[o]===void 0&&i.push({path:Ue(n,o),message:"is required"});if(t.additionalProperties===!1)for(let o of Object.keys(e))o in r||i.push({path:Ue(n,o),message:"unknown field"});for(let[o,p]of Object.entries(r))e[o]!==void 0&&ye(e[o],p,Ue(n,o),s,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${ee(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let r=e.map(o=>JSON.stringify(o));new Set(r).size!==r.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((r,o)=>ye(r,t.items,`${n}[${o}]`,s,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${ee(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${ee(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${ee(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Bt(e){return{...e,$schema:e.$schema===void 0?Ge:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?ft.map(t=>({...t})):e.rules}}function zt(e,t="ark.config.json"){if(!ut(e))throw new te(t,[{path:"$",message:`must be an object; received ${ee(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new te(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Bt(e),migratedFrom:n}}function qe(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=zt(e,t),i=[];if(ye(n,pt,"$",pt,i),i.length>0)throw new te(t,i);return{config:n,migratedFrom:s}}function mt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new te(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return qe(n,t)}var yt="1.0";function v(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function k(e){return[...new Set(e??[])].sort()}function B(e,t,n,s,i){let r=k(n),o=k(s),p=new Set(r),f=new Set(o),g=o.filter(m=>!p.has(m)),h=r.filter(m=>!f.has(m));g.length===0&&h.length===0||(g.length>0&&v(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:r,after:o}),h.length>0&&v(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:r,after:o}))}function ge(e,t,n,s,i,r,o){if(n===s)return;v(e,{kind:s?"enabled":"disabled",path:t,classification:s?i:i==="strengthening"?"weakening":"strengthening",message:s?r:o,before:n,after:s})}function he(e,t){let n=new Map,s=new Set;for(let i of e){let r=t(i);n.has(r)?s.add(r):n.set(r,i)}return{values:n,duplicates:[...s].sort()}}function Kt(e,t,n){let s=he(t,r=>r.name),i=he(n,r=>r.name);(s.duplicates.length>0||i.duplicates.length>0)&&v(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:s.duplicates,after:i.duplicates});for(let r of[...new Set([...s.values.keys(),...i.values.keys()])].sort()){let o=s.values.get(r),p=i.values.get(r),f=`$.layers[${r}]`;if(!o&&p){v(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:p});continue}if(o&&!p){v(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:o});continue}if(!o||!p)continue;B(e,`${f}.patterns`,o.patterns,p.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),B(e,`${f}.exclude`,o.exclude,p.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=fe(o),h=fe(p);B(e,`${f}.forbiddenGlobals`,g.rawGlobals,h.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),B(e,`${f}.capabilities`,g.atoms,h.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),k(o.intentPrefixes).join("\0")!==k(p.intentPrefixes).join("\0")&&v(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:k(o.intentPrefixes),after:k(p.intentPrefixes)}),ge(e,`${f}.mayImportInfrastructure`,o.mayImportInfrastructure===!0,p.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),ge(e,`${f}.optional`,o.optional===!0,p.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.")}}function Yt(e,t,n){let s=o=>`${o.from}->${o.to}`,i=he(t,s),r=he(n,s);(i.duplicates.length>0||r.duplicates.length>0)&&v(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:r.duplicates});for(let o of[...new Set([...i.values.keys(),...r.values.keys()])].sort()){let p=i.values.get(o),f=r.values.get(o),g=`$.rules[${o}]`;if(!p&&f){f.allowed===!1&&v(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(p&&!f){p.allowed===!1&&v(e,{kind:"deny-removed",path:g,classification:"weakening",message:"A denied dependency edge was removed.",before:p});continue}if(!p||!f)continue;p.allowed!==f.allowed&&v(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${g}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:p.allowed,after:f.allowed});let h=p.peerIsolation===!0,m=f.peerIsolation===!0;if(h!==m){let a=p.from===p.to&&f.from===f.to;v(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${g}.peerIsolation`,classification:a?m?"strengthening":"weakening":"judgment-required",message:a?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:h,after:m})}k(p.sliceFolders).join("\0")!==k(f.sliceFolders).join("\0")&&v(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:k(p.sliceFolders),after:k(f.sliceFolders)})}}function Wt(e,t,n){let s=t.safety??{},i=n.safety??{};for(let r of["maxTsSuppressions","maxAnyCasts"]){let o=s[r]??0,p=i[r]??0;o!==p&&v(e,{kind:p>o?"threshold-raised":"threshold-lowered",path:`$.safety.${r}`,classification:p>o?"weakening":"strengthening",message:p>o?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:o,after:p})}for(let r of["allowInMemory","allowDisabledPeerIsolation"])ge(e,`$.safety.${r}`,s[r]===!0,i[r]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Jt(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"}function gt(e,t){let n=[];B(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),B(n,"$.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."}),B(n,"$.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."}),ge(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let s={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",r=t.cyclePolicy??"strict";if(i!==r){let o=s[r]===s[i]?"judgment-required":s[r]>s[i]?"strengthening":"weakening";v(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:o,message:"The cycle enforcement level changed.",before:i,after:r})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&v(n,{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}),Kt(n,e.layers,t.layers),Yt(n,e.rules,t.rules),Wt(n,e,t),n.sort((o,p)=>o.path.localeCompare(p.path)||o.id.localeCompare(p.id)),{schemaVersion:yt,classification:Jt(n),findings:n}}function ht(e,t){if(!e||e.schemaVersion!==yt||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=k(e.findingIds),s=k(t.findingIds);return n.length===s.length&&n.every((i,r)=>i===s[r])}function z(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("/")}function bt(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function be(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function $(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function le(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let s=t,i="";for(t+=1;t<e.length;t+=1){let r=e[t];if(r===n)return{value:i,offset:s,excerpt:e.slice(s,t+1)};r==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=r}}function O(e,t,n){return e.startsWith(t,n)&&!be(e[n-1])&&!be(e[n+t.length])}function At(e,t){let n=$(e,t);if(e[n]!=="{")return!1;n+=1;let s=!1;for(;n<e.length;){if(n=$(e,n),e[n]==="}")return s;if(e[n]===","){n+=1;continue}if(!O(e,"type",n))return!1;let i=$(e,n+4);if(i>=e.length||e[i]===","||e[i]==="}"||O(e,"as",i)||!bt(e[i]))return!1;for(n=i;n<e.length&&be(e[n]);)n+=1;if(n=$(e,n),O(e,"as",n)){if(n=$(e,n+2),!bt(e[n]))return!1;for(;n<e.length&&be(e[n]);)n+=1}s=!0}return!1}function Zt(e,t){if(t=$(e,t+6),e[t]==="(")return le(e,$(e,t+1));let n=!1;if(O(e,"type",t)){let i=$(e,t+4);e[i]!==","&&!O(e,"from",i)&&(n=!0)}else At(e,t)&&(n=!0);let s=Ct(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Xt(e,t){t=t+6;let n=$(e,t),s=!1;if(O(e,"type",n)){let r=$(e,n+4);(e[r]==="{"||e[r]==="*")&&(s=!0)}else At(e,n)&&(s=!0);let i=Ct(e,t,!1);return i&&s?{...i,typeOnly:!0}:i}function Ct(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(O(e,"from",t))return le(e,$(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return le(e,t);if(t>0&&(O(e,"import",t)||O(e,"export",t)))return}}function Qt(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}function en(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=$(e,t+7);if(e[s]!=="(")return;s=$(e,s+1);let i=le(e,s);return i?{...i,requireCall:!0}:void 0}function tn(e){let t=[];for(let n=0;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
8
+ `,n+2),n<0)break;continue}if(s==="/"&&e[n+1]==="*"){let r=e.indexOf("*/",n+2);if(r<0)break;n=r+1;continue}if(s==="`"){n=Qt(e,n);continue}if(s==="'"||s==='"'){let r=le(e,n);r&&(n=r.offset+r.excerpt.length-1);continue}let i=s==="i"&&O(e,"import",n)?Zt(e,n):s==="e"&&O(e,"export",n)?Xt(e,n):s==="r"&&O(e,"require",n)?en(e,n):void 0;i&&(t.push(i),n=i.offset+i.excerpt.length-1)}return t}function It(e,t){let n=[],s=[];for(let i of tn(e.content)){let r=i.value;if(!r.startsWith(".")){if(i.typeOnly)continue;let g=ne(r);if(!g)continue;let h=e.content.slice(0,i.offset).split(`
9
+ `).length;s.push({file:e.path,symbol:r,capability:g,evidence:{kind:"import",file:e.path,line:h,excerpt:i.excerpt}});continue}let o=e.content.slice(0,i.offset).split(`
10
+ `).length,p={kind:"import",file:e.path,line:o,excerpt:i.excerpt},f=nn(e.path,r,t);n.push({from:e.path,specifier:r,to:f?.path??null,resolution:f?"resolved":"unresolved",fromLayer:e.layer,toLayer:f?.layer??null,evidence:p})}return{edges:n,capabilityUses:s}}function nn(e,t,n){let s=e.split("/");s.pop();for(let r of t.split("/"))r==="."||r===""||(r===".."?s.pop():s.push(r));let i=s.join("/");for(let r of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let o=n.get(r);if(o)return o}}function Rt(e,t){let n=[];for(let s of e){if(!s.to||!s.fromLayer||!s.toLayer)continue;let i=X(t.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:s,evidence:s.evidence})}return n}var sn={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 Be(e,t){let n=typeof e=="string"?mt(e,t):qe(e,t);return{...n,policyHash:E(C(n.config))}}function rn(e){let t=Be(e.baseConfig,e.baseSource??"base ark.config.json"),n=Be(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),s=gt(t.config,n.config),i=s.findings.filter(p=>p.classification==="weakening"||p.classification==="judgment-required").map(p=>p.id).sort(),r=i.length>0,o=r&&ht(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:s.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:s.classification,findings:s.findings,blockingFindingIds:i,requiresAcknowledgement:r,acknowledged:o,valid:!r||o}}function Ae(e){let t=e.files.map(m=>{let a=z(m.path);return{path:a,content:m.content,contentHash:E(m.content),layer:D(a,e.contract.config.layers)??null}}).sort((m,a)=>m.path.localeCompare(a.path)),n=new Map(t.map(m=>[m.path,m])),s=[],i=[];for(let m of t){let a=It(m,n);s.push(...a.edges),i.push(...a.capabilityUses)}let r=Rt(s,e.contract.config),o=new Map(e.contract.config.layers.map(m=>[m.name,m])),p=new Map(e.contract.config.layers.map(m=>[m.name,new Set(Z(m))]));for(let m of i){let a=n.get(m.file)?.layer;if(!a)continue;let l=o.get(a),c=se(m.symbol,l?.forbiddenGlobals??[]);if(c){r.push({ruleId:"FORBIDDEN_GLOBAL",message:`${a} must not use module "${m.symbol}" because it is the import form of forbidden global "${c}".`,symbol:m.symbol,evidence:m.evidence});continue}p.get(a)?.has(m.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",message:`${a} denies the ${m.capability} capability; found import of "${m.symbol}".`,capability:m.capability,symbol:m.symbol,evidence:m.evidence})}let f=t.length===0?"complete":"partial",g=f==="complete"?[]:[{...sn}],h={schemaVersion:Qe,policyHash:e.contract.policyHash,compilerOptionsHash:E(C(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(m=>m.name),edges:s,capabilityUses:i,violations:r};return{mode:"lexical-compatibility",completeness:f,completenessReasons:g,valid:f==="complete"&&r.length===0,ir:h}}function ze(e){let t=new Map(e.files.map(n=>[z(n.path),n]));for(let n of e.changes){let s=z(n.path);"delete"in n&&n.delete?t.delete(s):"content"in n&&t.set(s,{path:s,content:n.content})}return Ae({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function an(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}`}function Ce(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, 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, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function Et(e){return E(C(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function on(e){let t=Ae(e),n=new Map(t.ir.files.map(l=>[l.path,l])),s=[],i=new Set,r=[];for(let l of e.changes){let c=l.path.replace(/\\/g,"/"),d=z(l.path);if(!d||d===".."||d.startsWith("../")||c.startsWith("/")||/^[A-Za-z]:\//.test(c)||c.includes("\0")){r.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(d)){r.push({ruleId:"DUPLICATE_CHANGE_PATH",file:d,line:1,message:`The atomic change set contains more than one operation for ${d}.`});continue}i.add(d),"delete"in l&&l.delete&&!n.has(d)&&r.push({ruleId:"DELETE_TARGET_MISSING",file:d,line:1,message:`Cannot delete ${d} because it is not present in the supplied base tree.`}),s.push("delete"in l&&l.delete?{path:d,delete:!0}:{path:d,content:"content"in l?l.content:""})}e.changes.length===0&&r.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let o=ze({...e,changes:s}),p=new Map(o.ir.files.map(l=>[l.path,l])),f=o.ir.violations.filter(l=>l.ruleId==="CAPABILITY_VIOLATION"||l.ruleId==="FORBIDDEN_GLOBAL").map(l=>{let c=p.get(l.evidence.file)?.layer;return{ruleId:l.ruleId,file:l.evidence.file,line:l.evidence.line,target:l.symbol,...l.capability?{capability:l.capability}:{},...c?{fromLayer:c}:{},edgeKind:"import",message:l.message}}),g=re({config:e.contract.config,rules:e.contract.config.rules,files:o.ir.files.map(l=>l.path),contentViolations:f,edges:o.ir.edges.filter(l=>!!l.fromLayer).map(l=>({from:l.from,fromLayer:l.fromLayer,...l.to?{to:l.to}:{},...l.toLayer?{toLayer:l.toLayer}:{},line:l.evidence.line,kind:"import"}))}),h=s.map(l=>{let c=z(l.path),d=n.get(c),u=p.get(c);return{path:c,operation:"delete"in l&&l.delete?"delete":d?"update":"create",...d?{beforeContentHash:d.contentHash}:{},...u?{candidateContentHash:u.contentHash}:{}}}).sort((l,c)=>l.path.localeCompare(c.path)),m=[...r,...g.violations].map(l=>({...l,nextAction:Ce(l)})),a=e.changeMap?oe({changeMap:e.changeMap,changes:h,baseDependencies:t.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[]),candidateDependencies:o.ir.edges.flatMap(l=>l.to?[{from:l.from,to:l.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&o.valid&&m.length===0&&(a?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:o.ir.compilerOptionsHash,baseTreeHash:Et(t.ir.files),candidateTreeHash:Et(o.ir.files),baseCompleteness:t.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...a?{convergence:a}:{},changes:h,violations:m,warnings:g.warnings}}function ln(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let i of t.split("/"))if(!(!i||i==="."))if(i===".."){if(n.length===0)return;n.pop()}else n.push(i);let s=n.join("/");return s&&s===t?s:void 0}function cn(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,s,i])=>s!==i).map(([s,i,r])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:s,before:i,candidate:r,message:`Base and candidate facts must use the same ${s}.`}))}function dn(e,t,n,s){let i=n.get(t),r=s.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":i?"update":"create",...i?{beforeContentHash:i.contentHash}:{},...r?{candidateContentHash:r.contentHash}:{}}}function pn(e){let t=U(e.baseFacts),n=U(e.candidateFacts),s=ue({contract:e.contract,facts:t}),i=ue({contract:e.contract,facts:n}),r=new Map(t.files.map(a=>[a.path,a])),o=new Map(n.files.map(a=>[a.path,a])),p=cn(t,n),f=new Map,g=[];for(let a of e.changes){let l=ln(a.path);if(!l){p.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(f.has(l)){p.push({ruleId:"DUPLICATE_CHANGE_PATH",file:l,line:1,message:`The atomic change set contains more than one operation for ${l}.`});continue}f.set(l,a);let c=r.get(l),d=o.get(l);if("delete"in a&&a.delete)c||p.push({ruleId:"DELETE_TARGET_MISSING",file:l,line:1,message:`Cannot delete ${l} because it is not present in the supplied base facts.`}),d&&p.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:l,line:1,message:`Candidate facts still contain deleted file ${l}.`});else{let u="content"in a?a.content:"",y=E(u);d?d.contentHash!==y&&p.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:l,line:1,expectedContentHash:y,candidateContentHash:d.contentHash,message:`Candidate facts for ${l} do not match the declared content.`}):p.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:l,line:1,message:`Candidate facts do not contain changed file ${l}.`})}g.push(dn(a,l,r,o))}e.changes.length===0&&p.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let a of new Set([...r.keys(),...o.keys()])){if(f.has(a))continue;let l=r.get(a),c=o.get(a);l&&c&&C(l)===C(c)||p.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:a,line:1,message:`Candidate facts change ${a}, but the atomic change set does not declare it.`})}let h=e.changeMap?oe({changeMap:e.changeMap,changes:g,baseDependencies:s.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[]),candidateDependencies:i.ir.edges.flatMap(a=>a.to?[{from:a.from,to:a.to}]:[])}):void 0,m=[...p,...i.ir.violations].map(a=>({...a,nextAction:Ce(a)}));return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:s.completeness==="complete"&&i.strictValid&&m.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:s.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:s.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:g.sort((a,l)=>a.path<l.path?-1:a.path>l.path?1:0),violations:m,warnings:i.ir.warnings}}var vt=new WeakSet;function St(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))St(t);return Object.freeze(e)}function Ls(e){let t=St(de(e));return vt.add(t),t}function _s(e){if(!vt.has(e.facts))throw new Error("Trusted resolved analysis requires immutable in-process canonical facts.");return _e(e)}export{Se as AMBIENT_CAPABILITY_ENTRIES,Ee as CAPABILITY_IDS,Oe as DEFAULT_INTENT_PREFIXES,Xe as RESOLVED_CANDIDATE_FACTS_SCHEMA,K as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ke as SOURCE_POLICY_MESSAGES,we as ambientCoveredByForbiddenGlobals,oe as analyzeArchitectureConvergence,ze as analyzeChange,rn as analyzePolicyDelta,Ae as analyzeProject,ue as analyzeResolvedProject,_s as analyzeTrustedResolvedProject,ie as capabilityForAmbientName,ne as capabilityForModuleSpecifier,Te as classifyPublishFacts,Le as collectAnalysisConfigWarnings,Vt as collectCapabilityUses,Ve as collectForbiddenCapabilityUses,de as createResolvedCandidateFacts,Ls as createTrustedResolvedCandidateFacts,it as detectArchitectureCycles,E as deterministicHash,Z as effectiveCapabilityDeny,re as evaluateArchitectureGraph,an as explainViolation,je as extractSemanticDependencies,se as forbiddenGlobalForModuleSpecifier,Ht as loadArchitectureChangeMap,Be as loadContract,U as loadResolvedCandidateFacts,st as looksLikeArkIntent,kt as lowerForbiddenGlobal,fe as loweredLayerCoverage,on as preflightChange,pn as preflightResolvedChange,Pe as resolveIntentLayer,ce as resolvedFactsEvidenceRequirementsHash,C as stableSerialize};