arkgate 3.8.2 → 3.8.3

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,34 @@ in the immutable pre-2.0 archive linked below.
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 3.8.3 — 2026-07-22
9
+
10
+ Corrective **patch** over 3.8.2 from multi-repo field evidence (PROPIA pnpm workspace upgrade;
11
+ Amarilla greenfield `start`). **No required config migration.** Z09 / residual `RB-11` remain open.
12
+
13
+ ### Fixed
14
+
15
+ - **pnpm workspace upgrade install:** `packageInstallArgv` emits `pnpm add -D arkgate@… -w` on
16
+ workspace roots (`pnpm-workspace.yaml`). Yarn workspaces get `-W`. npm single-package path
17
+ unchanged.
18
+ - **Upgrade re-install when already current:** skip package-manager install when
19
+ `node_modules/arkgate` already matches this CLI version; go straight to managed preview.
20
+ - **Install failure recovery copy:** prints the exact failed install command and a
21
+ `--no-install` re-run path.
22
+ - **`start` package pin by default:** `start --apply` pins `arkgate` in `devDependencies`
23
+ unless `--no-install` (was: only with explicit `--install`).
24
+ - **Compact start always writes `.mcp.json`:** every host gets project MCP registration;
25
+ setup budget raised to 8 files / 32 KB so MCP fits with host hooks.
26
+ - **Unbound upgrade apply when content matches:** `--apply` without `--plan-digest` is a
27
+ successful no-op when `wouldWrite` is 0 (optional stamp refresh still needs the digest).
28
+ - **Upgrade applied copy:** distinguishes content writes vs stamp/metadata refresh instead of
29
+ a single “Applied N changes” when only stamps moved.
30
+
31
+ ### Tests
32
+
33
+ - `tests/unit/static-check/fieldJourney383.test.ts` — workspace argv, skip-when-current, start pin.
34
+ - Z06 / O03 / installFieldFixes expectations updated for default pin and MCP-in-compact.
35
+
8
36
  ## 3.8.2 — 2026-07-22
9
37
 
10
38
  Corrective **patch** over 3.8.1 from PREDIAL WEB field evidence. Aligns doctor skill freshness with
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.2** is current stable: field DX on top of 3.8.1skill stale matches upgrade content
20
- > identity, honest upgrade preview, doctor session notes, Y06 pure opt-in nudge, Codex legacy advisory.
21
- > [Release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.2.md).
19
+ > **ArkGate 3.8.3** is current stable: field journey on top of 3.8.2pnpm/yarn workspace install,
20
+ > default `start` package pin, compact `.mcp.json`, upgrade recovery/UX.
21
+ > [Release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.3.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.2) | [release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.2.md) · [3.0.0 baseline](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.0.0.md) |
425
+ | Latest release (3.8.3) | [release notes](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.3.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
  ---
@@ -618,11 +618,98 @@ export function execCommandParts(root, bin, binArgs = []) {
618
618
  return { command: 'npx', args: [bin, ...binArgs] };
619
619
  }
620
620
 
621
+ /**
622
+ * True when this directory is a pnpm workspace root (needs `pnpm add -w` for root deps).
623
+ * Nested packages under the workspace are not roots.
624
+ */
625
+ export function isPnpmWorkspaceRoot(root) {
626
+ return fs.existsSync(path.join(root, 'pnpm-workspace.yaml'));
627
+ }
628
+
629
+ /**
630
+ * True when package.json declares npm/yarn workspaces (yarn classic needs `-W` at root).
631
+ */
632
+ export function isNpmYarnWorkspaceRoot(root) {
633
+ const pkg = readPackageJson(root);
634
+ if (!pkg) return false;
635
+ const ws = pkg.workspaces;
636
+ return Array.isArray(ws) || (ws && typeof ws === 'object' && Array.isArray(ws.packages));
637
+ }
638
+
639
+ /**
640
+ * Normalize a version/range/spec into an installable package argument for arkgate.
641
+ * Accepts `latest`, `^3.8.2`, `arkgate@latest`, or a full package name.
642
+ */
643
+ export function normalizeArkgateInstallSpec(versionSpec) {
644
+ const raw = typeof versionSpec === 'string' && versionSpec.trim() ? versionSpec.trim() : 'latest';
645
+ if (raw.startsWith('arkgate@') || raw === 'arkgate') return raw === 'arkgate' ? 'arkgate@latest' : raw;
646
+ if (raw.includes('/') || raw.startsWith('file:') || raw.startsWith('link:')) return raw;
647
+ return `arkgate@${raw}`;
648
+ }
649
+
650
+ /**
651
+ * Package-manager argv to add a dev dependency (e.g. arkgate@latest).
652
+ * pnpm workspace roots get `-w`; yarn classic workspaces get `-W`.
653
+ *
654
+ * @param {string} root
655
+ * @param {string} [versionSpec] package name or name@version (default arkgate@latest)
656
+ * @returns {[string, string[]]}
657
+ */
658
+ export function packageInstallArgv(root, versionSpec = 'latest') {
659
+ const pkgSpec = normalizeArkgateInstallSpec(versionSpec);
660
+ const pm = detectPackageManager(root);
661
+ if (pm === 'pnpm') {
662
+ const args = ['add', '-D', pkgSpec];
663
+ if (isPnpmWorkspaceRoot(root)) args.push('-w');
664
+ return ['pnpm', args];
665
+ }
666
+ if (pm === 'yarn') {
667
+ const args = ['add', '-D', pkgSpec];
668
+ if (isNpmYarnWorkspaceRoot(root)) args.push('-W');
669
+ return ['yarn', args];
670
+ }
671
+ return ['npm', ['install', '-D', pkgSpec]];
672
+ }
673
+
674
+ /**
675
+ * Whether an install of arkgate@latest can be skipped because node_modules already
676
+ * resolves the same version as this CLI package.
677
+ *
678
+ * @param {string} root
679
+ * @param {string} [cliVersion] this binary's package version
680
+ * @returns {{ skip: boolean, installedVersion: string|null, reason: string }}
681
+ */
682
+ export function shouldSkipArkgateInstall(root, cliVersion) {
683
+ const pkgPath = path.join(root, 'node_modules', 'arkgate', 'package.json');
684
+ if (!fs.existsSync(pkgPath)) {
685
+ return { skip: false, installedVersion: null, reason: 'not-installed' };
686
+ }
687
+ let installedVersion = null;
688
+ try {
689
+ installedVersion = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version ?? null;
690
+ } catch {
691
+ return { skip: false, installedVersion: null, reason: 'unreadable' };
692
+ }
693
+ if (
694
+ typeof cliVersion === 'string' &&
695
+ cliVersion &&
696
+ installedVersion &&
697
+ installedVersion === cliVersion
698
+ ) {
699
+ return { skip: true, installedVersion, reason: 'already-current' };
700
+ }
701
+ return { skip: false, installedVersion, reason: 'version-differs' };
702
+ }
703
+
621
704
  /** Package-manager aware "install a dev dependency" hint (e.g. for a missing typescript). */
622
705
  export function installDevHint(root, pkg) {
623
706
  const pm = detectPackageManager(root);
624
- if (pm === 'pnpm') return `pnpm add -D ${pkg}`;
625
- if (pm === 'yarn') return `yarn add -D ${pkg}`;
707
+ if (pm === 'pnpm') {
708
+ return isPnpmWorkspaceRoot(root) ? `pnpm add -D ${pkg} -w` : `pnpm add -D ${pkg}`;
709
+ }
710
+ if (pm === 'yarn') {
711
+ return isNpmYarnWorkspaceRoot(root) ? `yarn add -D ${pkg} -W` : `yarn add -D ${pkg}`;
712
+ }
626
713
  return `npm install -D ${pkg}`;
627
714
  }
628
715
 
package/bin/ark.mjs CHANGED
@@ -14,8 +14,10 @@ import {
14
14
  INIT_WIZARD_CHOICES,
15
15
  isValidArchetypeId,
16
16
  mapWizardChoiceToArchetype,
17
+ packageInstallArgv,
17
18
  resolveArchetypePreset,
18
19
  resolveOperatingMode,
20
+ shouldSkipArkgateInstall,
19
21
  } from './ark-shared.mjs';
20
22
  import { pinArkgateDevDependency, FALSE_GREEN_GAP_ID } from './lib/field-install.mjs';
21
23
  import { validateHardWriteRequest } from './lib/enforcement-profiles.mjs';
@@ -155,9 +157,9 @@ Options:
155
157
  (Also the implicit default when stdin/stdout are not a TTY — agents never hang on prompts.)
156
158
  --force Allow generated files to overwrite existing files.
157
159
  --no-strict Skip the final strict ark-check run.
158
- --install Add arkgate to package.json explicitly before applying a start plan.
160
+ --install Pin and install arkgate as a project devDependency (default for start).
159
161
  --no-install Skip adding/installing arkgate as a project devDependency (start/upgrade).
160
- --apply Apply a start plan; for upgrade, update/repreview or apply with --no-install.
162
+ --apply Apply a start plan; for upgrade, update/repreview or apply managed bytes.
161
163
  --accept-conflicts
162
164
  Allow upgrade to recreate deleted managed assets or replace recorded conflicts.
163
165
  --plan-digest Digest emitted by an upgrade preview; required to apply managed bytes.
@@ -189,20 +191,7 @@ function cliVersion() {
189
191
  }
190
192
  }
191
193
 
192
- // The package-manager command that adds arkgate as a dev dependency.
193
- // Prefer an explicit version/range when pin already chose one (avoid pin=^2.9.0 then
194
- // `npm i arkgate@latest` rewriting package.json to a different range).
195
- function packageInstallArgv(root, versionSpec) {
196
- const range =
197
- typeof versionSpec === 'string' && versionSpec.trim()
198
- ? versionSpec.trim()
199
- : 'latest';
200
- const spec = range.startsWith('arkgate@') ? range : `arkgate@${range}`;
201
- const pm = detectPackageManager(root);
202
- if (pm === 'pnpm') return ['pnpm', ['add', '-D', spec]];
203
- if (pm === 'yarn') return ['yarn', ['add', '-D', spec]];
204
- return ['npm', ['install', '-D', spec]];
205
- }
194
+ // packageInstallArgv is imported from ark-shared (workspace-aware -w / -W).
206
195
 
207
196
  function runCommand(command, commandArgs, cwd) {
208
197
  const result = spawnSync(command, commandArgs, { cwd, stdio: 'inherit', encoding: 'utf8' });
@@ -438,6 +427,32 @@ async function start(args) {
438
427
  if (!args.apply) return 0;
439
428
  applyStartPreview(args.root, preview);
440
429
  if (!args.json) console.log(`Applied ${preview.changes.length} previewed mutation(s).`);
430
+ // After applying exact preview bytes, install the pinned package when requested
431
+ // (preview itself never runs the package manager — field: start left pin without node_modules).
432
+ if (
433
+ args.install &&
434
+ !args.skipPackageManager &&
435
+ fs.existsSync(path.join(args.root, 'package.json'))
436
+ ) {
437
+ const skip = shouldSkipArkgateInstall(args.root, cliVersion());
438
+ if (!skip.skip) {
439
+ const [command, commandArgs] = packageInstallArgv(args.root, `^${cliVersion()}`);
440
+ if (!args.json) console.log(`Installing package: ${command} ${commandArgs.join(' ')}`);
441
+ // Keep stdout clean for --json consumers (package managers are chatty on stdout).
442
+ const status = args.json
443
+ ? (spawnSync(command, commandArgs, {
444
+ cwd: args.root,
445
+ stdio: ['ignore', 'pipe', 'pipe'],
446
+ encoding: 'utf8',
447
+ }).status ?? 1)
448
+ : runCommand(command, commandArgs, args.root);
449
+ if (status !== 0 && !args.json) {
450
+ console.log(
451
+ `Package manager exited ${status}. package.json is pinned; run the install command when online.`
452
+ );
453
+ }
454
+ }
455
+ }
441
456
  return 0;
442
457
  }
443
458
  const root = args.root;
@@ -492,7 +507,8 @@ async function start(args) {
492
507
  }
493
508
 
494
509
  // 2b) Pin arkgate as a project devDependency so CI/npx do not depend on a stale global.
495
- if (args.installExplicit && args.install && fs.existsSync(path.join(root, 'package.json'))) {
510
+ // Default install=true; only --no-install skips. (installExplicit tracks user override for copy.)
511
+ if (args.install && fs.existsSync(path.join(root, 'package.json'))) {
496
512
  const { pinned, installStatus } = ensureProjectArkgateDependency(root, {
497
513
  install: true,
498
514
  runPackageManager: !args.skipPackageManager,
@@ -507,7 +523,7 @@ async function start(args) {
507
523
  } else if (pinned.reason === 'already-present') {
508
524
  console.log(` arkgate already in package.json (${pinned.version}).`);
509
525
  }
510
- } else if (args.installExplicit && args.install === false) {
526
+ } else if (!args.install) {
511
527
  console.log(' Skipping arkgate package pin (--no-install).');
512
528
  }
513
529
 
@@ -789,7 +805,13 @@ async function main() {
789
805
 
790
806
  if (args.command === 'upgrade' || args.command === 'update') {
791
807
  try {
792
- return runUpgradeCommand(args, { arkCheck, packageInstallArgv, runArkCheck });
808
+ return runUpgradeCommand(args, {
809
+ arkCheck,
810
+ packageInstallArgv,
811
+ runArkCheck,
812
+ cliVersion: cliVersion(),
813
+ shouldSkipArkgateInstall,
814
+ });
793
815
  } catch (error) {
794
816
  console.error(error instanceof Error ? error.message : String(error));
795
817
  return 2;
@@ -149,7 +149,10 @@ export function buildManagedAssetCatalog({ root, tools, compact = false, skillsO
149
149
  'AGENTS.md',
150
150
  compact ? compactAgentInstructions(root, compactHost) : agentInstructions(root)
151
151
  );
152
- if (!compact || !compactHost || compactHost === 'claude') add('.mcp.json', mcpJson(root));
152
+ // Always write project MCP registration compact hosts other than Claude still need
153
+ // ark://manifest for agents (field: compact grok start left doctor reporting Missing .mcp.json
154
+ // when AGENTS lost compact markers or hosts were mixed).
155
+ add('.mcp.json', mcpJson(root));
153
156
  const deploy = detectDeployPathQuality(root);
154
157
  add(
155
158
  '.github/workflows/ark-check.yml',
@@ -513,7 +513,20 @@ export function applyManagedUpgrade(root, plan, expectedPlanDigest) {
513
513
  const resolvedRoot = path.resolve(root);
514
514
  if (resolvedRoot !== plan.root) throw new Error('managed upgrade plan root mismatch');
515
515
  if (plan.summary.blocked > 0) return publicPlan(plan, { blocked: true });
516
+ const wouldWrite = plan.summary.wouldWrite ?? 0;
517
+ const metadataRefresh = plan.summary.metadataRefresh ?? 0;
518
+ // Content already matches: unbound --apply is a no-op (exit success), not a digest error.
519
+ // Optional stamp-only refresh still requires the preview's exact --plan-digest.
516
520
  if (!expectedPlanDigest || expectedPlanDigest !== plan.planDigest) {
521
+ if (wouldWrite === 0 && (plan.summary.blocked ?? 0) === 0 && !expectedPlanDigest) {
522
+ return publicPlan(plan, {
523
+ readOnly: true,
524
+ applied: false,
525
+ blocked: false,
526
+ nothingToApply: true,
527
+ optionalStampRefresh: metadataRefresh,
528
+ });
529
+ }
517
530
  throw new Error('managed upgrade plan digest mismatch; run a new preview and use its exact nextCommand');
518
531
  }
519
532
 
@@ -637,7 +650,21 @@ export function renderManagedUpgrade(plan, options = {}) {
637
650
  '.'
638
651
  );
639
652
  if (plan.applied) {
640
- console.log(`Applied changes: ${summary.changed}.`);
653
+ // Distinguish content writes from optional stamp/metadata bookkeeping.
654
+ if (wouldWrite === 0 && metadataRefresh > 0) {
655
+ console.log(
656
+ `Refreshed ${metadataRefresh} version stamp(s)` +
657
+ (summary.manifestChanged ? ' and managed manifest' : '') +
658
+ ' (no content body changes).'
659
+ );
660
+ } else {
661
+ console.log(
662
+ `Applied ${wouldWrite} content write(s)` +
663
+ (metadataRefresh > 0 ? `, ${metadataRefresh} stamp refresh(es)` : '') +
664
+ (summary.manifestChanged ? ', managed manifest' : '') +
665
+ '.'
666
+ );
667
+ }
641
668
  return;
642
669
  }
643
670
  // Content already matches package templates — do not urge --apply as the primary next step.
@@ -70,12 +70,14 @@ function setupBudget(changes) {
70
70
  (total, item) => total + (item.afterBase64 ? Buffer.from(item.afterBase64, 'base64').length : 0),
71
71
  0
72
72
  );
73
+ // Compact start includes shared MCP + one host registration + CI + AGENTS + config.
74
+ // Budget raised from 5→8 so .mcp.json always fits (field: grok compact hit the old ceiling).
73
75
  return {
74
76
  files: generatedChanges.length,
75
77
  bytes,
76
- maxFiles: 5,
77
- maxBytes: 25 * 1024,
78
- ok: generatedChanges.length <= 5 && bytes < 25 * 1024,
78
+ maxFiles: 8,
79
+ maxBytes: 32 * 1024,
80
+ ok: generatedChanges.length <= 8 && bytes < 32 * 1024,
79
81
  };
80
82
  }
81
83
 
@@ -84,7 +86,8 @@ function commands(root, args, helpers) {
84
86
  return [`ark start --root ${root} --tools ${args.removeHost} --apply`];
85
87
  }
86
88
  const result = [];
87
- if (args.installExplicit && args.install && fs.existsSync(path.join(root, 'package.json'))) {
89
+ // Default install=true: surface the package pin/install command unless --no-install.
90
+ if (args.install !== false && fs.existsSync(path.join(root, 'package.json'))) {
88
91
  const [command, commandArgs] = helpers.packageInstallArgv(root, `^${helpers.cliVersion()}`);
89
92
  result.push(`${command} ${commandArgs.join(' ')}`);
90
93
  }
@@ -216,8 +219,9 @@ export async function planStart(args, helpers) {
216
219
  if (args.yes) childArgs.push('--yes');
217
220
  if (args.force) childArgs.push('--force');
218
221
  if (!args.strict) childArgs.push('--no-strict');
219
- if (args.installExplicit && args.install) childArgs.push('--install');
220
- if (args.installExplicit && !args.install) childArgs.push('--no-install');
222
+ // Propagate install intent into the shadow plan so package.json pin is in the diff by default.
223
+ if (args.install === false) childArgs.push('--no-install');
224
+ else childArgs.push('--install');
221
225
  if (args.tools) childArgs.push('--tools', args.tools);
222
226
  if (args.requireWriteHook) childArgs.push('--require-write-hook', args.requireWriteHook);
223
227
  const planned = spawnSync(process.execPath, [helpers.cliPath, ...childArgs], {
@@ -55,23 +55,50 @@ function verify(root, json, arkCheck, runArkCheck) {
55
55
  export function runUpgradeCommand(args, dependencies) {
56
56
  const root = args.root;
57
57
  if (args.apply && args.install) {
58
- const [command, commandArgs] = dependencies.packageInstallArgv(root);
59
- if (!args.json) console.log(`Updating ArkGate: ${command} ${commandArgs.join(' ')}`);
60
- const install = spawnSync(command, commandArgs, {
61
- cwd: root,
62
- stdio: args.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
63
- encoding: 'utf8',
64
- });
65
- const exitCode = install.status ?? 1;
66
- if (exitCode !== 0) {
67
- if (args.json && install.stderr) console.error(install.stderr.trim());
58
+ const skip =
59
+ typeof dependencies.shouldSkipArkgateInstall === 'function'
60
+ ? dependencies.shouldSkipArkgateInstall(root, dependencies.cliVersion)
61
+ : { skip: false };
62
+ if (skip.skip) {
63
+ if (!args.json) {
64
+ console.log(
65
+ `Package already at arkgate@${skip.installedVersion}; skipping install and recomputing managed preview.`
66
+ );
67
+ }
68
+ } else {
69
+ const [command, commandArgs] = dependencies.packageInstallArgv(root);
70
+ if (!args.json) console.log(`Updating ArkGate: ${command} ${commandArgs.join(' ')}`);
71
+ const install = spawnSync(command, commandArgs, {
72
+ cwd: root,
73
+ stdio: args.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
74
+ encoding: 'utf8',
75
+ });
76
+ const exitCode = install.status ?? 1;
77
+ if (exitCode !== 0) {
78
+ if (args.json && install.stderr) console.error(install.stderr.trim());
79
+ const recovery = `${command} ${commandArgs.join(' ')}`;
80
+ console.error(
81
+ `Package update failed (exit ${exitCode}). Fix the install and re-run:\n` +
82
+ ` ${recovery}\n` +
83
+ `Then: ark upgrade --no-install --root ${JSON.stringify(root)}` +
84
+ (args.tools ? ` --tools ${args.tools}` : '') +
85
+ (!args.strict ? ' --no-strict' : '') +
86
+ (args.json ? ' --json' : '')
87
+ );
88
+ return exitCode;
89
+ }
90
+ }
91
+ // Re-enter via installed CLI so the managed plan uses the newly installed package bytes.
92
+ let cli;
93
+ try {
94
+ cli = installedCli(root);
95
+ } catch {
68
96
  console.error(
69
- `Package update failed (exit ${exitCode}). Fix the install and re-run, or use ` +
70
- '`ark upgrade --no-install` against the installed version.'
97
+ 'arkgate is not installed in this project after the package step. Install it, then re-run with --no-install.'
71
98
  );
72
- return exitCode;
99
+ return 1;
73
100
  }
74
- return spawnSync(process.execPath, [installedCli(root), ...previewArgs(args)], {
101
+ return spawnSync(process.execPath, [cli, ...previewArgs(args)], {
75
102
  cwd: root,
76
103
  stdio: 'inherit',
77
104
  encoding: 'utf8',
@@ -111,7 +138,14 @@ export function runUpgradeCommand(args, dependencies) {
111
138
  return 0;
112
139
  }
113
140
 
114
- const applied = applyManagedUpgrade(root, plan, args.planDigest);
141
+ let applied;
142
+ try {
143
+ applied = applyManagedUpgrade(root, plan, args.planDigest);
144
+ } catch (error) {
145
+ const message = error instanceof Error ? error.message : String(error);
146
+ console.error(message);
147
+ return 2;
148
+ }
115
149
  if (applied.blocked) {
116
150
  if (args.json) console.log(JSON.stringify(applied, null, 2));
117
151
  else renderManagedUpgrade(applied, {
@@ -119,6 +153,14 @@ export function runUpgradeCommand(args, dependencies) {
119
153
  });
120
154
  return 1;
121
155
  }
156
+ if (applied.nothingToApply && !applied.applied) {
157
+ if (args.json) console.log(JSON.stringify(applied, null, 2));
158
+ else {
159
+ renderManagedUpgrade(applied);
160
+ console.log('No managed content writes pending (optional stamp refresh needs --plan-digest).');
161
+ }
162
+ return 0;
163
+ }
122
164
  const verification = args.strict
123
165
  ? { mode: 'strict-merge', ...verify(root, args.json, dependencies.arkCheck, dependencies.runArkCheck) }
124
166
  : { mode: 'skipped', exitCode: 0 };
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var We=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Zt=Object.prototype.hasOwnProperty;var Xt=(e,t)=>{for(var n in t)We(e,n,{get:t[n],enumerable:!0})},Qt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Jt(t))!Zt.call(e,r)&&r!==n&&We(e,r,{get:()=>t[r],enumerable:!(i=Wt(t,r))||i.enumerable});return e};var en=e=>Qt(We({},"__esModule",{value:!0}),e);var Xn={};Xt(Xn,{ANALYSIS_IR_SCHEMA_VERSION:()=>He,ARK_ANALYSIS_RESULT_SCHEMA:()=>It,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>bt,ARK_CONFIG_SCHEMA:()=>Te,ARK_CONFIG_SCHEMA_VERSION:()=>$t,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Yt,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Kt,POLICY_DELTA_SCHEMA_VERSION:()=>Ge,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Me,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>B,analyzeArchitectureConvergence:()=>X,analyzeChange:()=>xe,analyzePolicyDelta:()=>ut,analyzeProject:()=>pe,analyzeResolvedProject:()=>fe,classifyArkPolicyDelta:()=>Ue,collectAnalysisConfigWarnings:()=>ke,collectForbiddenCapabilityUses:()=>J,createAICodeGate:()=>ct,createAdapterResult:()=>Ct,createArchitectureProfile:()=>Ee,createArchitectureProfileFromArkConfig:()=>pt,createElevenLayerArkConfig:()=>ft,createResolvedCandidateFacts:()=>Fe,detectArchitectureCycles:()=>ze,deterministicHash:()=>S,elevenLayerProfile:()=>Ie,evaluateArchitectureGraph:()=>te,explainViolation:()=>yt,extractSemanticDependencies:()=>W,loadArkConfigContract:()=>Ce,loadContract:()=>Se,loadResolvedCandidateFacts:()=>H,parseArkConfigJson:()=>Ne,policyDeltaAcknowledgementMatches:()=>Be,preflightChange:()=>mt,preflightResolvedChange:()=>gt,resolvedFactsEvidenceRequirementsHash:()=>ce,stableSerialize:()=>E,toAdapterDiagnostic:()=>Pe,version:()=>ht});module.exports=en(Xn);var ht="3.8.2";var bt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function At(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function tn(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function Pe(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:i,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:At(e.line,1),column:At(e.column,1)},evidence:r,nextAction:I(e.nextAction)??tn(n,r,e)}}function Ct(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let i=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let s=[...(e.violations??[]).map(c=>Pe(c,"error")),...(e.warnings??[]).map(c=>Pe(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:i,diagnostics:s};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var It={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var Ze=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Qe=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),et=Object.freeze(Object.keys(Qe).sort()),Je=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"}),Xe=Object.freeze({process:Object.freeze(["process","node:process"])});function ye(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Je[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let i=e.slice(0,n),r=Je[i];if(r)return r;let s=e.indexOf("/",n+1);return s<0?null:Je[e.slice(0,s)]??null}function j(e,t){for(let n of t)if(Xe[n]?.includes(e))return n;return null}function Oe(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let i=t.slice(0,n).join("."),r=Qe[i];if(r)return r}return null}function ne(e){if(e?.pure===!0)return[...Ze].sort();let n=(e?.capabilities?.deny??[]).filter(i=>Ze.includes(i));return[...new Set(n)].sort()}function me(e,t){if(t.length===0)return!1;let n=new Set(t),i=e.split(".");for(let r=i.length;r>=1;r-=1)if(n.has(i.slice(0,r).join(".")))return!0;return!1}function Le(e){let t=new Set,n=new Set,i=Object.keys(Qe);for(let r of e?.forbiddenGlobals??[]){let s=i.filter(a=>a===r||a.startsWith(`${r}.`));if(s.length===0)n.add(r);else for(let a of s)t.add(`ambient:${a}`);for(let a of Xe[r]??[])t.add(`import-exact:${a}`)}for(let r of ne(e)){if(t.add(`import:${r}`),r==="process")for(let s of Xe.process)t.add(`import-exact:${s}`);for(let s of i)Oe(s)===r&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Et=new Map;function Rt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function tt(e){let t="";for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=i}return t}function nn(e){let t=0;for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"){n+=1;continue}if(i==="{")t+=1;else if(i==="}"&&(t-=1,t<0))return!1}return t===0}function Y(e){let t=Et.get(e);if(t)return t;let n=tt(e),i=nn(n),r="",s=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=Rt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&i?(r+="(?:",s+=1):f==="}"&&i&&s>0?(r+=")",s-=1):f===","&&i&&s>0?r+="|":r+=Rt(f)}let a=new RegExp(`^${r}$`);return Et.set(e,a),a}function nt(e){let t=tt(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function G(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Y(a).test(n))){for(let a of s.patterns??[])if(Y(a).test(n)){let c=nt(a);c>r&&(r=c,i=s.name)}}return i}function vt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function rn(e){let t=new Set;for(let n of e??[]){let r=tt(String(n)).split("/").filter(Boolean);for(let s=0;s<r.length;s+=1){let a=r[s];if((a==="**"||a==="*")&&s>0){let c=r[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function sn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(n??[]).find(r=>r.name===t);return rn(i?.patterns)}function N(e,t,n,i){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let s=i?.fromPath,a=i?.toPath;if(!s||!a)return r;let c=sn(r,t,i?.layers);if(c.length===0)return r;let f=vt(s,c),A=vt(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function re(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function kt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function St(e,t){if(e.isImportDeclaration(t)){let i=t.importClause;if(!i)return!1;if(i.isTypeOnly)return!0;let r=i.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(i=>i.isTypeOnly))}function wt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},i=e.createCompilerHost(n,!0);return i.getSourceFile=r=>r===t.fileName?t:void 0,i.fileExists=r=>r===t.fileName,i.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,i).getTypeChecker()}function rt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function it(e,t,n,i){let r=i.parent&&e.isShorthandPropertyAssignment(i.parent)&&i.parent.name===i,s;try{s=r?t.getShorthandAssignmentValueSymbol(i.parent):rt(t,i)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function W(e,t){let n,i=[],r=(a,c,f,A=!1)=>i.push({specifier:f,kind:c,line:kt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),s=a=>{if(e.isImportDeclaration(a))r(a,"import",re(e,a.moduleSpecifier),St(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",re(e,a.moduleSpecifier),St(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",re(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!it(e,n??(n=wt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",re(e,a.arguments[0]))}e.forEachChild(a,s)};return s(t),i}function an(e,t){let n=[],i=t;for(;e.isPropertyAccessExpression(i)||e.isElementAccessExpression(i);){if(e.isPropertyAccessExpression(i))n.unshift(i.name.text);else{let r=re(e,i.argumentExpression);if(r===void 0)return;n.unshift(r)}i=i.expression}if(e.isIdentifier(i))return n.unshift(i.text),{root:i,segments:n}}function on(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 xt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let i=n.length;i>=1;i-=1){let r=n.slice(0,i).join(".");if(e.has(r))return r}}function J(e,t,n){if(n.length===0)return[];let i=new Set(n),r=wt(e,t),s=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=an(e,o);if(!l)return;let p=rt(r,l.root),d=p?s.get(p):void 0;return d?[...d,...l.segments.slice(1)]:it(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=c(l.initializer),d=rt(r,l.name);!p||!d||s.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=kt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let p=c(o),d=p?xt(i,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&i.has(o.text)&&on(e,o)&&!it(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?re(e,d.propertyName)??d.propertyName.text:d.name.text,h=xt(i,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function st(e,t,n){let i=[];for(let r of n?.dependencies??W(e,t)){if(r.typeOnly||!r.specifier)continue;let s=ye(r.specifier);s&&i.push({capability:s,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??J(e,t,et)){let s=Oe(r.name);s&&i.push({capability:s,symbol:r.name,line:r.line,source:"ambient-global"})}return i.sort((r,s)=>r.line-s.line||r.capability.localeCompare(s.capability)||r.symbol.localeCompare(s.symbol))}var at={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."},ot=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 lt(e,t){return t.flatMap((i,r)=>(i.prefixes??i.intentPrefixes??[]).map(s=>({layer:i.name,layerIndex:r,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:i})=>e.startsWith(i)).sort((i,r)=>r.prefix.length-i.prefix.length||i.layerIndex-r.layerIndex)[0]?.layer}function Z(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ge(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Z(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:at.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:at.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ie(e,t){return e.slice(0,t).split(`
1
+ "use strict";var We=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Zt=Object.prototype.hasOwnProperty;var Xt=(e,t)=>{for(var n in t)We(e,n,{get:t[n],enumerable:!0})},Qt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Jt(t))!Zt.call(e,r)&&r!==n&&We(e,r,{get:()=>t[r],enumerable:!(i=Wt(t,r))||i.enumerable});return e};var en=e=>Qt(We({},"__esModule",{value:!0}),e);var Xn={};Xt(Xn,{ANALYSIS_IR_SCHEMA_VERSION:()=>He,ARK_ANALYSIS_RESULT_SCHEMA:()=>It,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>bt,ARK_CONFIG_SCHEMA:()=>Te,ARK_CONFIG_SCHEMA_VERSION:()=>$t,ARK_DESIGN_DELTA_SCHEMA_VERSION:()=>Yt,ARK_ENFORCEMENT_STATE_SCHEMA_VERSION:()=>Kt,POLICY_DELTA_SCHEMA_VERSION:()=>Ge,RESOLVED_CANDIDATE_FACTS_SCHEMA:()=>Me,RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION:()=>B,analyzeArchitectureConvergence:()=>X,analyzeChange:()=>xe,analyzePolicyDelta:()=>ut,analyzeProject:()=>pe,analyzeResolvedProject:()=>fe,classifyArkPolicyDelta:()=>Ue,collectAnalysisConfigWarnings:()=>ke,collectForbiddenCapabilityUses:()=>J,createAICodeGate:()=>ct,createAdapterResult:()=>Ct,createArchitectureProfile:()=>Ee,createArchitectureProfileFromArkConfig:()=>pt,createElevenLayerArkConfig:()=>ft,createResolvedCandidateFacts:()=>Fe,detectArchitectureCycles:()=>ze,deterministicHash:()=>S,elevenLayerProfile:()=>Ie,evaluateArchitectureGraph:()=>te,explainViolation:()=>yt,extractSemanticDependencies:()=>W,loadArkConfigContract:()=>Ce,loadContract:()=>Se,loadResolvedCandidateFacts:()=>H,parseArkConfigJson:()=>Ne,policyDeltaAcknowledgementMatches:()=>Be,preflightChange:()=>mt,preflightResolvedChange:()=>gt,resolvedFactsEvidenceRequirementsHash:()=>ce,stableSerialize:()=>E,toAdapterDiagnostic:()=>Pe,version:()=>ht});module.exports=en(Xn);var ht="3.8.3";var bt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function At(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function tn(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function Pe(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:i,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:At(e.line,1),column:At(e.column,1)},evidence:r,nextAction:I(e.nextAction)??tn(n,r,e)}}function Ct(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let i=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let s=[...(e.violations??[]).map(c=>Pe(c,"error")),...(e.warnings??[]).map(c=>Pe(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:i,diagnostics:s};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var It={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var Ze=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Qe=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),et=Object.freeze(Object.keys(Qe).sort()),Je=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"}),Xe=Object.freeze({process:Object.freeze(["process","node:process"])});function ye(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Je[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let i=e.slice(0,n),r=Je[i];if(r)return r;let s=e.indexOf("/",n+1);return s<0?null:Je[e.slice(0,s)]??null}function j(e,t){for(let n of t)if(Xe[n]?.includes(e))return n;return null}function Oe(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let i=t.slice(0,n).join("."),r=Qe[i];if(r)return r}return null}function ne(e){if(e?.pure===!0)return[...Ze].sort();let n=(e?.capabilities?.deny??[]).filter(i=>Ze.includes(i));return[...new Set(n)].sort()}function me(e,t){if(t.length===0)return!1;let n=new Set(t),i=e.split(".");for(let r=i.length;r>=1;r-=1)if(n.has(i.slice(0,r).join(".")))return!0;return!1}function Le(e){let t=new Set,n=new Set,i=Object.keys(Qe);for(let r of e?.forbiddenGlobals??[]){let s=i.filter(a=>a===r||a.startsWith(`${r}.`));if(s.length===0)n.add(r);else for(let a of s)t.add(`ambient:${a}`);for(let a of Xe[r]??[])t.add(`import-exact:${a}`)}for(let r of ne(e)){if(t.add(`import:${r}`),r==="process")for(let s of Xe.process)t.add(`import-exact:${s}`);for(let s of i)Oe(s)===r&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var Et=new Map;function Rt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function tt(e){let t="";for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=i}return t}function nn(e){let t=0;for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"){n+=1;continue}if(i==="{")t+=1;else if(i==="}"&&(t-=1,t<0))return!1}return t===0}function Y(e){let t=Et.get(e);if(t)return t;let n=tt(e),i=nn(n),r="",s=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=Rt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&i?(r+="(?:",s+=1):f==="}"&&i&&s>0?(r+=")",s-=1):f===","&&i&&s>0?r+="|":r+=Rt(f)}let a=new RegExp(`^${r}$`);return Et.set(e,a),a}function nt(e){let t=tt(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function G(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>Y(a).test(n))){for(let a of s.patterns??[])if(Y(a).test(n)){let c=nt(a);c>r&&(r=c,i=s.name)}}return i}function vt(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r].toLowerCase()}/${n[r+1].toLowerCase()}`}function rn(e){let t=new Set;for(let n of e??[]){let r=tt(String(n)).split("/").filter(Boolean);for(let s=0;s<r.length;s+=1){let a=r[s];if((a==="**"||a==="*")&&s>0){let c=r[s-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function sn(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(n??[]).find(r=>r.name===t);return rn(i?.patterns)}function N(e,t,n,i){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let s=i?.fromPath,a=i?.toPath;if(!s||!a)return r;let c=sn(r,t,i?.layers);if(c.length===0)return r;let f=vt(s,c),A=vt(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function re(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function kt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function St(e,t){if(e.isImportDeclaration(t)){let i=t.importClause;if(!i)return!1;if(i.isTypeOnly)return!0;let r=i.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(i=>i.isTypeOnly))}function wt(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},i=e.createCompilerHost(n,!0);return i.getSourceFile=r=>r===t.fileName?t:void 0,i.fileExists=r=>r===t.fileName,i.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,i).getTypeChecker()}function rt(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function it(e,t,n,i){let r=i.parent&&e.isShorthandPropertyAssignment(i.parent)&&i.parent.name===i,s;try{s=r?t.getShorthandAssignmentValueSymbol(i.parent):rt(t,i)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function W(e,t){let n,i=[],r=(a,c,f,A=!1)=>i.push({specifier:f,kind:c,line:kt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),s=a=>{if(e.isImportDeclaration(a))r(a,"import",re(e,a.moduleSpecifier),St(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",re(e,a.moduleSpecifier),St(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",re(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!it(e,n??(n=wt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",re(e,a.arguments[0]))}e.forEachChild(a,s)};return s(t),i}function an(e,t){let n=[],i=t;for(;e.isPropertyAccessExpression(i)||e.isElementAccessExpression(i);){if(e.isPropertyAccessExpression(i))n.unshift(i.name.text);else{let r=re(e,i.argumentExpression);if(r===void 0)return;n.unshift(r)}i=i.expression}if(e.isIdentifier(i))return n.unshift(i.text),{root:i,segments:n}}function on(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 xt(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let i=n.length;i>=1;i-=1){let r=n.slice(0,i).join(".");if(e.has(r))return r}}function J(e,t,n){if(n.length===0)return[];let i=new Set(n),r=wt(e,t),s=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=an(e,o);if(!l)return;let p=rt(r,l.root),d=p?s.get(p):void 0;return d?[...d,...l.segments.slice(1)]:it(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=c(l.initializer),d=rt(r,l.name);!p||!d||s.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=kt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let p=c(o),d=p?xt(i,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&i.has(o.text)&&on(e,o)&&!it(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?re(e,d.propertyName)??d.propertyName.text:d.name.text,h=xt(i,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function st(e,t,n){let i=[];for(let r of n?.dependencies??W(e,t)){if(r.typeOnly||!r.specifier)continue;let s=ye(r.specifier);s&&i.push({capability:s,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??J(e,t,et)){let s=Oe(r.name);s&&i.push({capability:s,symbol:r.name,line:r.line,source:"ambient-global"})}return i.sort((r,s)=>r.line-s.line||r.capability.localeCompare(s.capability)||r.symbol.localeCompare(s.symbol))}var at={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."},ot=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 lt(e,t){return t.flatMap((i,r)=>(i.prefixes??i.intentPrefixes??[]).map(s=>({layer:i.name,layerIndex:r,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:i})=>e.startsWith(i)).sort((i,r)=>r.prefix.length-i.prefix.length||i.layerIndex-r.layerIndex)[0]?.layer}function Z(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ge(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Z(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:at.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:at.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ie(e,t){return e.slice(0,t).split(`
2
2
  `).length}function ln(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,i;for(;(i=n.exec(e))!==null;)t.push({value:i[1],index:i.index});return t}function cn(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let i of n){let r;for(;(r=i.re.exec(e))!==null;){let s=r.index+r[0].indexOf(r[1]),a=r[0],c=i.kind==="import"&&/\bimport\s+type\b/.test(a)||i.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:s,kind:i.kind,typeOnly:c})}}return t.sort((i,r)=>i.index-r.index)}function dn(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=[],r=s=>{e.isStringLiteralLike(s)&&i.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,r)};return r(n),i}function pn(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function fn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function un(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Ae(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function yn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Pt(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(i=>!e.isPropertyAssignment(i)&&!e.isShorthandPropertyAssignment(i)?!1:yn(e,i.name)===n)}function be(e,t,n){return Pt(e,t,n)!==void 0}function he(e,t,n){let i=Pt(e,t,n);return i&&e.isPropertyAssignment(i)?i.initializer:void 0}function mn(e,t){let n=he(e,t,"metadata");return be(e,n,"source")}function Ot(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ot(e,t.name):!1:!1}function gn(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function hn(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],i=Ae(e,n);return i!==void 0&&Z(i)||be(e,n,"intent")||Ot(e,n)}function An(e,t){if(!e.isCallExpression(t))return!1;let[n,i,r]=t.arguments;return mn(e,n)||be(e,i,"source")||be(e,r,"source")}function bn(e,t){if(!e.isCallExpression(t))return;let[n,i,r]=t.arguments,s=he(e,n,"metadata");return Ae(e,he(e,s,"source"))??Ae(e,he(e,i,"source"))??Ae(e,he(e,r,"source"))}function Cn(e,t,n,i){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,c=s?.layer,f=[],A=u=>r.getLineAndCharacterOfPosition(u.getStart(r)).line+1,g=u=>{if(gn(e,u)){let o=u.arguments[0],l=Ae(e,o);for(let d of ge({publishCall:!0,rawIntentName:l,objectHasIntent:be(e,o,"intent"),arkPublishCandidate:hn(e,u),hasSource:An(e,u)}))f.push(v(d.ruleId,d.message,{line:A(u),filePath:a}));let p=bn(e,u);if(i&&c&&p&&Z(p)){let d=i.resolveLayer(p);d&&d!==c&&f.push(v("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${d}, but the target file is classified as ${c}.`,{line:A(u),filePath:a,target:p,fromLayer:c,toLayer:d}))}}e.forEachChild(u,g)};return g(r),f}function ct(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],i=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",s,u.ScriptTarget.Latest,!0):void 0,l=o?W(e.typescript,o):void 0,p=l?l.filter(m=>m.specifier!==void 0).map(m=>({value:m.specifier,index:m.node.getStart(o),kind:m.kind,typeOnly:m.typeOnly})):cn(s),d=e.typescript?dn(e.typescript,s):ln(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(A))for(let m of l?.filter(({unresolved:b})=>b)??[]){let b=m.kind==="require";c.push(v(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:m.line,filePath:A}))}let y=g!==void 0&&(i.has(g)||un(g)),h=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let m of n)if(m instanceof RegExp){m.lastIndex=0;let b=m.exec(s);m.lastIndex=0,b&&c.push(v("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:ie(s,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else s.includes(m)&&c.push(v("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:ie(s,s.indexOf(m)),filePath:A}));for(let m of p){let b=e.resolveImportTarget?.(m.value,A)??(e.resolveImportLayer?{layer:e.resolveImportLayer(m.value,A)}:void 0),C=typeof A=="string"?e.resolveImportTarget?.(A)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,ue=b?.layer;if(ue&&g){let we=N(e.architectureProfile?.rules,g,ue,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(we){if(m.typeOnly&&!we.peerIsolation)continue;let Ye=!!we.peerIsolation;c.push(v("LAYER_IMPORT_VIOLATION",we.message??(Ye?`Layer "${g}" must not import across slices into "${ue}".`:`Layer "${g}" must not import "${ue}".`),{line:ie(s,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:ue,suggestion:Ye?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:m.kind,peerIsolation:Ye,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!pn(m.value)&&!fn(m.value)||c.push(v("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:ie(s,m.index),source:m.value,target:m.value,filePath:A,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+h,details:{importKind:m.kind}}))}if(e.policies)for(let m of e.policies){let b=m.check({source:s,context:a});if(b!==!0)if(Array.isArray(b))for(let C of b)c.push(v("POLICY_VIOLATION",C.message,{filePath:A,suggestion:`Fix violation of policy "${m.name}".`}));else b===!1?c.push(v("POLICY_VIOLATION",`Policy ${m.name} failed on generated code`)):c.push(v("POLICY_VIOLATION",b.message))}if(r&&t.size>0)for(let m of d)Z(m.value)&&!t.has(m.value)&&c.push(v("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:ie(s,m.index),filePath:A,target:m.value,suggestion:`Register intent "${m.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let m of d){if(!Z(m.value))continue;let b=e.architectureProfile.resolveLayer(m.value);if(!b)continue;let C=N(e.architectureProfile.rules,g,b);C&&c.push(v("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${b}" through "${m.value}".`,{line:ie(s,m.index),filePath:A,target:m.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let m of e.extensions)try{let b=m.analyze(s,a);c.push(...b)}catch(b){c.push(v("EXTENSION_ERROR",`Extension "${m.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{let m=e.forbiddenGlobals[g];c.push(...J(e.typescript,o,m).map(b=>v("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:A,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of l??[]){if(b.typeOnly||!b.specifier)continue;let C=j(b.specifier,m);C&&c.push(v("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${C}".`,{line:b.line,filePath:A,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.capabilityWalls?.[g]?.length)try{let m=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let C of st(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&me(C.symbol,b)||C.source==="import-based"&&j(C.symbol,b)||c.push(v("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:A,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript)try{c.push(...Cn(e.typescript,s,a,e.architectureProfile))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var $t="1.0",_e="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Lt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],In=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function En(){let e=[];for(let t of Lt)for(let n of Lt)t===n||In.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var De=En();var U={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Te={$schema:"https://json-schema.org/draft/2020-12/schema",$id:_e,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:_e,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:{...U,minItems:1,default:["src"]},exclude:{...U,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:De,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...U,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:{...U,minItems:1},exclude:U,intentPrefixes:U,description:{type:"string",minLength:1},forbiddenGlobals:U,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:{...U,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}}}}},ae=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(i=>`- ${i.path}: ${i.message}`).join(`
4
4
  `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function _t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dt(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function se(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Rn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function $e(e,t,n,i,r){if(t.$ref){let s=Rn(t.$ref,i);if(!s){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}$e(e,s,n,i,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(s=>Object.is(s,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!_t(e)){r.push({path:n,message:`must be an object; received ${se(e)}`});return}let s=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:dt(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in s||r.push({path:dt(n,a),message:"unknown field"});for(let[a,c]of Object.entries(s))e[a]!==void 0&&$e(e[a],c,dt(n,a),i,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${se(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 s=e.map(a=>JSON.stringify(a));new Set(s).size!==s.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,a)=>$e(s,t.items,`${n}[${a}]`,i,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${se(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 ${se(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${se(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function vn(e){return{...e,$schema:e.$schema===void 0?_e: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?De.map(t=>({...t})):e.rules}}function Sn(e,t="ark.config.json"){if(!_t(e))throw new ae(t,[{path:"$",message:`must be an object; received ${se(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ae(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:vn(e),migratedFrom:n}}function Ce(e,t="ark.config.json"){let{candidate:n,migratedFrom:i}=Sn(e,t),r=[];if($e(n,Te,"$",Te,r),r.length>0)throw new ae(t,r);return{config:n,migratedFrom:i}}function Ne(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(i){throw new ae(t,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return Ce(n,t)}function Tt(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:_e,schemaVersion:"1.0"};for(let[n,i]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=i);return t}function xn(e){return e.endsWith(".")?e:`${e}.`}function kn(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Ee(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(xn)})),n=[...t].sort(kn),i=[...e.rules??[]];return{name:e.name,layers:t,rules:i,resolveLayer(r){return t.find(s=>s.match?.(r))?.name??n.find(s=>s.prefixes.some(a=>r.startsWith(a)))?.name}}}function pt(e,t={}){return Ee({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,i)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:i+1})),rules:e.rules??[]})}var wn=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Ie=Ee({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:wn,rules:De.map(e=>({...e}))}),Pn={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function ft(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,i=t==="."?"":`${t}/`;return Tt({include:e.include??[t],layers:Ie.layers.map(r=>({name:r.name,patterns:(Pn[r.name]??[r.name]).map(s=>`${i}${s}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...Ie.rules]})}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 E(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(E).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${E(t[n])}`).join(",")}}`}var B="1.0",Dt=["network","filesystem","clock","randomness","environment","process","persistence"];function K(e,t){let n=E(e),i=E(t);return n<i?-1:n>i?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(K),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(E(t))}function On(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(K),n=e.files.map(u=>({...u,typeOnlyExportNames:T(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),i=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:T(u.namedBindings)}:{}})).sort(K),r=e.capabilityUses.map(u=>({...u})).sort(K),s=e.ambientUses.map(u=>({...u})).sort(K),a=e.publishCalls.map(u=>({...u})).sort(K),c=e.intentReferences.map(u=>({...u})).sort(K),f=e.safetyUses.map(u=>({...u})).sort(K),A=e.files.map(({path:u,contentHash:o})=>({path:u,contentHash:o})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),g=S(E(A));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:i,capabilityUses:r,ambientUses:s,publishCalls:a,intentReferences:c,safetyUses:f}}function Ft(e){let t=On(e);return{...t,factsHash:S(E(t))}}function Fe(e){return Ft(Ht(D(e,"$"),!1))}function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function F(e,t,n){let i=new Set(t),r=Object.keys(e).find(s=>!i.has(s));if(r)throw new Error(`${n}.${r} is not part of schema 1.0.`)}function k(e,t,n){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return i}function oe(e,t,n){if(e[t]!==void 0)return k(e,t,n)}function M(e,t,n){let i=k(e,t,n),r=i.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 s=[];for(let c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(c);let a=s.join("/");if(!a||a!==i)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function _(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function Mt(e,t,n){let i=e[t];if(!Number.isInteger(i)||Number(i)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(i)}function le(e,t,n){let i=Mt(e,t,n);if(i===0)throw new Error(`${n}.${t} must be a positive integer.`);return i}function q(e,t,n){let i=e[t];if(!Array.isArray(i))throw new Error(`${n}.${t} must be an array.`);return i}function z(e,t,n,i){let r=e[t];if(typeof r!="string"||!n.includes(r))throw new Error(`${i}.${t} must be one of ${n.join(", ")}.`);return r}function Nt(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 Ln(e,t,n){let i=new Set;for(let r of e){let s=t(r);if(i.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);i.add(s)}}function Ht(e,t){F(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=z(e,"schemaVersion",["1.0"],"$"),i=z(e,"completeness",["complete","partial","unavailable"],"$"),r=q(e,"completenessReasons","$").map((p,d)=>{let y=`$.completenessReasons[${d}]`,h=D(p,y);F(h,["code","message","file"],y);let m=h.file===void 0?void 0:M(h,"file",y);return{code:k(h,"code",y),message:k(h,"message",y),...m?{file:m}:{}}});if(i==="complete"&&r.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(i!=="complete"&&r.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=q(e,"files","$").map((p,d)=>{let y=`$.files[${d}]`,h=D(p,y);return F(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:M(h,"path",y),contentHash:k(h,"contentHash",y),parseStatus:z(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:Mt(h,"parseDiagnosticCount",y),exportsOnlyTypes:_(h,"exportsOnlyTypes",y),typeOnlyExportNames:Nt(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:_(h,"hasTopLevelSideEffects",y)}}),a=q(e,"dependencies","$").map((p,d)=>{let y=`$.dependencies[${d}]`,h=D(p,y);F(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let m=oe(h,"specifier",y),b=oe(h,"target",y),C=z(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(C==="resolved-project"&&!b)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(C!=="resolved-project"&&b)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(C!=="dynamic"&&!m)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:M(h,"from",y),...m?{specifier:m}:{},kind:z(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:_(h,"typeOnly",y),line:le(h,"line",y),resolution:C,...b?{target:M(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:Nt(h.namedBindings,`${y}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:_(h,"targetTypeOnlyExports",y)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:_(h,"sourcePureTypeModule",y)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:_(h,"namedBindingsTypeOnly",y)}:{},...h.portProofEligible!==void 0?{portProofEligible:_(h,"portProofEligible",y)}:{}}}),c=q(e,"capabilityUses","$").map((p,d)=>{let y=`$.capabilityUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol","capability","source"],y),{file:M(h,"file",y),line:le(h,"line",y),symbol:k(h,"symbol",y),capability:z(h,"capability",Dt,y),source:z(h,"source",["ambient-global","import-based"],y)}}),f=q(e,"ambientUses","$").map((p,d)=>{let y=`$.ambientUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol"],y),{file:M(h,"file",y),line:le(h,"line",y),symbol:k(h,"symbol",y)}}),A=q(e,"publishCalls","$").map((p,d)=>{let y=`$.publishCalls[${d}]`,h=D(p,y);F(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let m=oe(h,"rawIntentName",y),b=oe(h,"sourceIntent",y);return{file:M(h,"file",y),line:le(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:_(h,"objectHasIntent",y),arkPublishCandidate:_(h,"arkPublishCandidate",y),hasSource:_(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=q(e,"intentReferences","$").map((p,d)=>{let y=`$.intentReferences[${d}]`,h=D(p,y);return F(h,["file","line","intent"],y),{file:M(h,"file",y),line:le(h,"line",y),intent:k(h,"intent",y)}}),u=q(e,"safetyUses","$").map((p,d)=>{let y=`$.safetyUses[${d}]`,h=D(p,y);F(h,["file","line","kind","symbol"],y);let m=oe(h,"symbol",y),b=z(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(b==="in-memory-store"&&!m)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(b!=="in-memory-store"&&m)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:M(h,"file",y),line:le(h,"line",y),kind:b,...m?{symbol:m}:{}}});Ln(s,p=>p.path,"$.files");let o=new Set(s.map(p=>p.path));for(let p of s){if(p.parseStatus==="parsed"&&p.parseDiagnosticCount!==0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(p.parseStatus==="invalid"&&p.parseDiagnosticCount===0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(i==="complete"&&s.some(p=>p.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let p of a)if(!o.has(p.from))throw new Error(`$.dependencies references missing source file ${p.from}.`);for(let[p,d]of[["$.capabilityUses",c],["$.ambientUses",f],["$.publishCalls",A],["$.intentReferences",g],["$.safetyUses",u]])for(let y of d)if(!o.has(y.file))throw new Error(`${p} references missing file ${y.file}.`);let l=oe(e,"projectPackageName","$");return{schemaVersion:n,completeness:i,completenessReasons:r,resolverIdentity:k(e,"resolverIdentity","$"),compilerIdentity:k(e,"compilerIdentity","$"),compilerOptionsHash:k(e,"compilerOptionsHash","$"),tsconfigHash:k(e,"tsconfigHash","$"),evidenceRequirementsHash:k(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:s,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function H(e){let t=D(e,"$"),n=k(t,"factsHash","$"),i=k(t,"candidateTreeHash","$"),r=Ft(Ht(t,!0));if(r.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${r.factsHash}).`);if(i!==r.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${r.candidateTreeHash}).`);return r}var $n=["network","filesystem","clock","randomness","environment","process","persistence"],R={type:"string",minLength:1},de={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Me={$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:R,message:R,file:V}}},resolverIdentity:R,compilerIdentity:R,compilerOptionsHash:R,tsconfigHash:R,candidateTreeHash:R,evidenceRequirementsHash:R,projectPackageName:R,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:R,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:R},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:V,specifier:R,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:de,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:R},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:V,line:de,symbol:R,capability:{enum:$n},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:de,symbol:R}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:de,rawIntentName:R,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:R}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:de,intent:R}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:de,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:R},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:R},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 He="1.0";function P(e){return`${e.from}->${e.to}`}function Re(e,t,n,i="dependency"){return{id:`${e}:${i}:${P(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${P(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${P(t)}, then preflight again.`}:e==="unplanned"?{nextAction:i==="dependency-removed"?`Restore the removed dependency ${P(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${P(t)} from the candidate, then preflight again.`}:{}}}function X(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),i=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),s=new Map(e.baseDependencies.map(o=>[P(o),o])),a=new Map(e.candidateDependencies.map(o=>[P(o),o]));for(let o of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=i.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...i.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...r.values()].sort((l,p)=>P(l).localeCompare(P(p)))){if(a.has(P(o))){t.push(Re("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(P(l))?(c.add(P(l)),t.push(Re("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Re("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...i.keys()]);for(let[o,l]of[...a].sort(([p],[d])=>p.localeCompare(d)))s.has(o)||r.has(o)||c.has(o)||!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 A=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...s].sort(([p],[d])=>p.localeCompare(d)))a.has(o)||A.has(l.from)||A.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 g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let u={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:u.missing===0&&u.contradictory===0&&u.unplanned===0,behavioralCompletion:"not-evaluated",summary:u,findings:t}}var Ge="1.0";function x(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 L(e){return[...new Set(e??[])].sort()}function Q(e,t,n,i,r){let s=L(n),a=L(i),c=new Set(s),f=new Set(a),A=a.filter(u=>!c.has(u)),g=s.filter(u=>!f.has(u));A.length===0&&g.length===0||(A.length>0&&x(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:s,after:a}),g.length>0&&x(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:s,after:a}))}function Ve(e,t,n,i,r,s,a){if(n===i)return;x(e,{kind:i?"enabled":"disabled",path:t,classification:i?r:r==="strengthening"?"weakening":"strengthening",message:i?s:a,before:n,after:i})}function je(e,t){let n=new Map,i=new Set;for(let r of e){let s=t(r);n.has(s)?i.add(s):n.set(s,r)}return{values:n,duplicates:[...i].sort()}}function _n(e,t,n){let i=je(t,s=>s.name),r=je(n,s=>s.name);(i.duplicates.length>0||r.duplicates.length>0)&&x(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:i.duplicates,after:r.duplicates});for(let s of[...new Set([...i.values.keys(),...r.values.keys()])].sort()){let a=i.values.get(s),c=r.values.get(s),f=`$.layers[${s}]`;if(!a&&c){x(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){x(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;Q(e,`${f}.patterns`,a.patterns,c.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`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let A=Le(a),g=Le(c);Q(e,`${f}.forbiddenGlobals`,A.rawGlobals,g.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`,A.atoms,g.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)."}),L(a.intentPrefixes).join("\0")!==L(c.intentPrefixes).join("\0")&&x(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:L(a.intentPrefixes),after:L(c.intentPrefixes)}),Ve(e,`${f}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Ve(e,`${f}.optional`,a.optional===!0,c.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 Tn(e,t,n){let i=a=>`${a.from}->${a.to}`,r=je(t,i),s=je(n,i);(r.duplicates.length>0||s.duplicates.length>0)&&x(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:s.duplicates});for(let a of[...new Set([...r.values.keys(),...s.values.keys()])].sort()){let c=r.values.get(a),f=s.values.get(a),A=`$.rules[${a}]`;if(!c&&f){f.allowed===!1&&x(e,{kind:"deny-added",path:A,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(c&&!f){c.allowed===!1&&x(e,{kind:"deny-removed",path:A,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!f)continue;c.allowed!==f.allowed&&x(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${A}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:f.allowed});let g=c.peerIsolation===!0,u=f.peerIsolation===!0;if(g!==u){let o=c.from===c.to&&f.from===f.to;x(e,{kind:u?"peer-isolation-enabled":"peer-isolation-disabled",path:`${A}.peerIsolation`,classification:o?u?"strengthening":"weakening":"judgment-required",message:o?u?"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:g,after:u})}L(c.sliceFolders).join("\0")!==L(f.sliceFolders).join("\0")&&x(e,{kind:"slice-folders-changed",path:`${A}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:L(c.sliceFolders),after:L(f.sliceFolders)})}}function Dn(e,t,n){let i=t.safety??{},r=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=i[s]??0,c=r[s]??0;a!==c&&x(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Ve(e,`$.safety.${s}`,i[s]===!0,r[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Nn(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 Ue(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."}),Ve(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let i={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",s=t.cyclePolicy??"strict";if(r!==s){let a=i[s]===i[r]?"judgment-required":i[s]>i[r]?"strengthening":"weakening";x(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:r,after:s})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&x(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}),_n(n,e.layers,t.layers),Tn(n,e.rules,t.rules),Dn(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:Ge,classification:Nn(n),findings:n}}function Be(e,t){if(!e||e.schemaVersion!==Ge||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=L(e.findingIds),i=L(t.findingIds);return n.length===i.length&&n.every((r,s)=>r===i[s])}function ee(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 Vt(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function qe(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function O(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function ve(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let i=t,r="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:r,offset:i,excerpt:e.slice(i,t+1)};s==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=s}}function $(e,t,n){return e.startsWith(t,n)&&!qe(e[n-1])&&!qe(e[n+t.length])}function jt(e,t){let n=O(e,t);if(e[n]!=="{")return!1;n+=1;let i=!1;for(;n<e.length;){if(n=O(e,n),e[n]==="}")return i;if(e[n]===","){n+=1;continue}if(!$(e,"type",n))return!1;let r=O(e,n+4);if(r>=e.length||e[r]===","||e[r]==="}"||$(e,"as",r)||!Vt(e[r]))return!1;for(n=r;n<e.length&&qe(e[n]);)n+=1;if(n=O(e,n),$(e,"as",n)){if(n=O(e,n+2),!Vt(e[n]))return!1;for(;n<e.length&&qe(e[n]);)n+=1}i=!0}return!1}function Fn(e,t){if(t=O(e,t+6),e[t]==="(")return ve(e,O(e,t+1));let n=!1;if($(e,"type",t)){let r=O(e,t+4);e[r]!==","&&!$(e,"from",r)&&(n=!0)}else jt(e,t)&&(n=!0);let i=Gt(e,t,!0);return i&&n?{...i,typeOnly:!0}:i}function Mn(e,t){t=t+6;let n=O(e,t),i=!1;if($(e,"type",n)){let s=O(e,n+4);(e[s]==="{"||e[s]==="*")&&(i=!0)}else jt(e,n)&&(i=!0);let r=Gt(e,t,!1);return r&&i?{...r,typeOnly:!0}:r}function Gt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if($(e,"from",t))return ve(e,O(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return ve(e,t);if(t>0&&($(e,"import",t)||$(e,"export",t)))return}}function Hn(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 Vn(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let i=O(e,t+7);if(e[i]!=="(")return;i=O(e,i+1);let r=ve(e,i);return r?{...r,requireCall:!0}:void 0}function jn(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
package/dist/index.d.ts CHANGED
@@ -234,7 +234,7 @@ declare function loadArkConfigContract(input: unknown, source?: string): ArkConf
234
234
  declare function parseArkConfigJson(json: string, source?: string): ArkConfigLoadResult;
235
235
 
236
236
  /** ArkGate library version — single source of truth. */
237
- declare const version = "3.8.2";
237
+ declare const version = "3.8.3";
238
238
 
239
239
  /** Versioned public result contract shared by every ArkGate enforcement adapter. */
240
240
  declare const ARK_ANALYSIS_RESULT_SCHEMA_VERSION: "1.3";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var jt="3.8.2";var Gt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ct(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ut(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function He(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:ct(e.line,1),column:ct(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Ut(n,r,e)}}function Bt(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>He(c,"error")),...(e.warnings??[]).map(c=>He(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var qt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var je=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ue=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Be=Object.freeze(Object.keys(Ue).sort()),Ve=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"}),Ge=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ve[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ve[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ve[e.slice(0,i)]??null}function V(e,t){for(let n of t)if(Ge[n]?.includes(e))return n;return null}function Re(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=Ue[s];if(r)return r}return null}function X(e){if(e?.pure===!0)return[...je].sort();let n=(e?.capabilities?.deny??[]).filter(s=>je.includes(s));return[...new Set(n)].sort()}function fe(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 ve(e){let t=new Set,n=new Set,s=Object.keys(Ue);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ge[r]??[])t.add(`import-exact:${a}`)}for(let r of X(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ge.process)t.add(`import-exact:${i}`);for(let i of s)Re(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dt=new Map;function pt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function qe(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 zt(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 K(e){let t=dt.get(e);if(t)return t;let n=qe(e),s=zt(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=pt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=pt(f)}let a=new RegExp(`^${r}$`);return dt.set(e,a),a}function ze(e){let t=qe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function j(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>K(a).test(n))){for(let a of i.patterns??[])if(K(a).test(n)){let c=ze(a);c>r&&(r=c,s=i.name)}}return s}function ft(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 Kt(e){let t=new Set;for(let n of e??[]){let r=qe(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Yt(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 Kt(s?.patterns)}function N(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,a=s?.toPath;if(!i||!a)return r;let c=Yt(r,t,s?.layers);if(c.length===0)return r;let f=ft(i,c),A=ft(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function mt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function ut(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 gt(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 Ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ye(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ke(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ee(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:mt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",Q(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ye(e,n??(n=gt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",Q(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function Wt(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=Q(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 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 yt(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 te(e,t,n){if(n.length===0)return[];let s=new Set(n),r=gt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Wt(e,o);if(!l)return;let p=Ke(r,l.root),d=p?i.get(p):void 0;return d?[...d,...l.segments.slice(1)]:Ye(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=c(l.initializer),d=Ke(r,l.name);!p||!d||i.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=mt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let p=c(o),d=p?yt(s,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&s.has(o.text)&&Jt(e,o)&&!Ye(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,h=yt(s,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function We(e,t,n){let s=[];for(let r of n?.dependencies??ee(e,t)){if(r.typeOnly||!r.specifier)continue;let i=pe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??te(e,t,Be)){let i=Re(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 Je={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."},Ze=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 Xe(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 Y(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Y(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Je.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Je.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ne(e,t){return e.slice(0,t).split(`
1
+ var jt="3.8.3";var Gt="1.3";function I(e){return typeof e=="string"&&e.length>0?e:void 0}function ct(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Ut(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CAPABILITY_VIOLATION"?`Define a ${I(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function He(e,t="error"){let n=I(e.ruleId)??I(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"?"warning":t,r={...I(e.target)?{target:I(e.target)}:{},...I(e.fromLayer)?{fromLayer:I(e.fromLayer)}:{},...I(e.toLayer)?{toLayer:I(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...I(e.capability)?{capability:I(e.capability)}:{},...I(e.edgeKind)?{edgeKind:I(e.edgeKind)}:{}};return{ruleId:n,severity:s,message:I(e.message)??n,location:{file:I(e.file)??"<unknown>",line:ct(e.line,1),column:ct(e.column,1)},evidence:r,nextAction:I(e.nextAction)??Ut(n,r,e)}}function Bt(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let s=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(c=>({code:I(c.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:I(c.message)??`Analysis ${t}: required evidence is incomplete.`,...I(c.file)?{file:I(c.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],r={...I(e.policyHash)?{policyHash:I(e.policyHash)}:{},...I(e.resolverIdentity)?{resolverIdentity:I(e.resolverIdentity)}:{},...I(e.factsHash)?{factsHash:I(e.factsHash)}:{},...I(e.candidateTreeHash)?{candidateTreeHash:I(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let c of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!r[c])throw new Error(`${c} is required for resolved ${t} adapter evidence.`)}let i=[...(e.violations??[]).map(c=>He(c,"error")),...(e.warnings??[]).map(c=>He(c,"warning"))],a={schemaVersion:"1.3",completenessReasons:s,diagnostics:i};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...a,mode:n,valid:!1,completeness:t,...r};let c={policyHash:r.policyHash,resolverIdentity:r.resolverIdentity,factsHash:r.factsHash,candidateTreeHash:r.candidateTreeHash};return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...c}:{...a,mode:n,valid:!1,completeness:t,...c}}return t==="complete"?{...a,mode:n,valid:e.valid,completeness:t,...r}:{...a,mode:n,valid:!1,completeness:t,...r}}var qt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.3"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1}}}}}};var je=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Ue=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Be=Object.freeze(Object.keys(Ue).sort()),Ve=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"}),Ge=Object.freeze({process:Object.freeze(["process","node:process"])});function pe(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Ve[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let s=e.slice(0,n),r=Ve[s];if(r)return r;let i=e.indexOf("/",n+1);return i<0?null:Ve[e.slice(0,i)]??null}function V(e,t){for(let n of t)if(Ge[n]?.includes(e))return n;return null}function Re(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let s=t.slice(0,n).join("."),r=Ue[s];if(r)return r}return null}function X(e){if(e?.pure===!0)return[...je].sort();let n=(e?.capabilities?.deny??[]).filter(s=>je.includes(s));return[...new Set(n)].sort()}function fe(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 ve(e){let t=new Set,n=new Set,s=Object.keys(Ue);for(let r of e?.forbiddenGlobals??[]){let i=s.filter(a=>a===r||a.startsWith(`${r}.`));if(i.length===0)n.add(r);else for(let a of i)t.add(`ambient:${a}`);for(let a of Ge[r]??[])t.add(`import-exact:${a}`)}for(let r of X(e)){if(t.add(`import:${r}`),r==="process")for(let i of Ge.process)t.add(`import-exact:${i}`);for(let i of s)Re(i)===r&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}var dt=new Map;function pt(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function qe(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 zt(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 K(e){let t=dt.get(e);if(t)return t;let n=qe(e),s=zt(n),r="",i=0;for(let c=0;c<n.length;c+=1){let f=n[c];f==="\\"&&c+1<n.length?(r+=pt(n[c+1]),c+=1):f==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&s?(r+="(?:",i+=1):f==="}"&&s&&i>0?(r+=")",i-=1):f===","&&s&&i>0?r+="|":r+=pt(f)}let a=new RegExp(`^${r}$`);return dt.set(e,a),a}function ze(e){let t=qe(String(e)),s=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return s*1e4+r}function j(e,t){let n=String(e).split(/[/\\]/).join("/"),s,r=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>K(a).test(n))){for(let a of i.patterns??[])if(K(a).test(n)){let c=ze(a);c>r&&(r=c,s=i.name)}}return s}function ft(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 Kt(e){let t=new Set;for(let n of e??[]){let r=qe(String(n)).split("/").filter(Boolean);for(let i=0;i<r.length;i+=1){let a=r[i];if((a==="**"||a==="*")&&i>0){let c=r[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Yt(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 Kt(s?.patterns)}function N(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,a=s?.toPath;if(!i||!a)return r;let c=Yt(r,t,s?.layers);if(c.length===0)return r;let f=ft(i,c),A=ft(a,c);if(!f||!A||f!==A)return r;continue}if(t!==n)return r}}function Q(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function mt(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function ut(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 gt(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 Ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ye(e,t,n,s){let r=s.parent&&e.isShorthandPropertyAssignment(s.parent)&&s.parent.name===s,i;try{i=r?t.getShorthandAssignmentValueSymbol(s.parent):Ke(t,s)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}function ee(e,t){let n,s=[],r=(a,c,f,A=!1)=>s.push({specifier:f,kind:c,line:mt(t,a),typeOnly:A,unresolved:f===void 0,node:a}),i=a=>{if(e.isImportDeclaration(a))r(a,"import",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)r(a,"export",Q(e,a.moduleSpecifier),ut(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))r(a,"require",Q(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let c=a.expression.kind===e.SyntaxKind.ImportKeyword,A=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Ye(e,n??(n=gt(e,t)),t,a.expression);(c||A)&&r(a,A?"require":"dynamic-import",Q(e,a.arguments[0]))}e.forEachChild(a,i)};return i(t),s}function Wt(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=Q(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 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 yt(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 te(e,t,n){if(n.length===0)return[];let s=new Set(n),r=gt(e,t),i=new Map,a=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&a.add(l.name.text);let c=o=>{let l=Wt(e,o);if(!l)return;let p=Ke(r,l.root),d=p?i.get(p):void 0;return d?[...d,...l.segments.slice(1)]:Ye(e,r,t,l.root)||a.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let p=c(l.initializer),d=Ke(r,l.name);!p||!d||i.set(d,p)}let f=[],A=new Set,g=(o,l)=>{let p=mt(t,l),d=`${o}:${l.getStart(t)}`;A.has(d)||(A.add(d),f.push({name:o,line:p,node:l}))},u=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let p=c(o),d=p?yt(s,p):void 0;d&&g(d,o)}else e.isIdentifier(o)&&s.has(o.text)&&Jt(e,o)&&!Ye(e,r,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let p=c(o.initializer);if(p)for(let d of o.name.elements){if(!e.isIdentifier(d.name))continue;let y=d.propertyName?Q(e,d.propertyName)??d.propertyName.text:d.name.text,h=yt(s,[...p,y]);h&&g(h,o.initializer)}}e.forEachChild(o,u)};return u(t),f}function We(e,t,n){let s=[];for(let r of n?.dependencies??ee(e,t)){if(r.typeOnly||!r.specifier)continue;let i=pe(r.specifier);i&&s.push({capability:i,symbol:r.specifier,line:r.line,source:"import-based"})}for(let r of n?.ambientUses??te(e,t,Be)){let i=Re(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 Je={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."},Ze=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 Xe(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 Y(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function ue(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Y(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Je.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Je.PUBLISH_MISSING_SOURCE}),t}function v(e,t,n){return{ruleId:e,code:e,message:t,...n}}function ne(e,t){return e.slice(0,t).split(`
2
2
  `).length}function Zt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,s;for(;(s=n.exec(e))!==null;)t.push({value:s[1],index:s.index});return t}function Xt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let s of n){let r;for(;(r=s.re.exec(e))!==null;){let i=r.index+r[0].indexOf(r[1]),a=r[0],c=s.kind==="import"&&/\bimport\s+type\b/.test(a)||s.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:r[1],index:i,kind:s.kind,typeOnly:c})}}return t.sort((s,r)=>s.index-r.index)}function Qt(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=[],r=i=>{e.isStringLiteralLike(i)&&s.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,r)};return r(n),s}function en(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function tn(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function nn(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function me(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function rn(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function ht(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(s=>!e.isPropertyAssignment(s)&&!e.isShorthandPropertyAssignment(s)?!1:rn(e,s.name)===n)}function ge(e,t,n){return ht(e,t,n)!==void 0}function ye(e,t,n){let s=ht(e,t,n);return s&&e.isPropertyAssignment(s)?s.initializer:void 0}function sn(e,t){let n=ye(e,t,"metadata");return ge(e,n,"source")}function At(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?At(e,t.name):!1:!1}function an(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function on(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],s=me(e,n);return s!==void 0&&Y(s)||ge(e,n,"intent")||At(e,n)}function ln(e,t){if(!e.isCallExpression(t))return!1;let[n,s,r]=t.arguments;return sn(e,n)||ge(e,s,"source")||ge(e,r,"source")}function cn(e,t){if(!e.isCallExpression(t))return;let[n,s,r]=t.arguments,i=ye(e,n,"metadata");return me(e,ye(e,i,"source"))??me(e,ye(e,s,"source"))??me(e,ye(e,r,"source"))}function dn(e,t,n,s){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,c=i?.layer,f=[],A=u=>r.getLineAndCharacterOfPosition(u.getStart(r)).line+1,g=u=>{if(an(e,u)){let o=u.arguments[0],l=me(e,o);for(let d of ue({publishCall:!0,rawIntentName:l,objectHasIntent:ge(e,o,"intent"),arkPublishCandidate:on(e,u),hasSource:ln(e,u)}))f.push(v(d.ruleId,d.message,{line:A(u),filePath:a}));let p=cn(e,u);if(s&&c&&p&&Y(p)){let d=s.resolveLayer(p);d&&d!==c&&f.push(v("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${p}" resolves to ${d}, but the target file is classified as ${c}.`,{line:A(u),filePath:a,target:p,fromLayer:c,toLayer:d}))}}e.forEachChild(u,g)};return g(r),f}function bt(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],s=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let c=[],f=a,A=f?.filePath,g=f?.layer,u=e.typescript,o=u?u.createSourceFile(A??"generated.ts",i,u.ScriptTarget.Latest,!0):void 0,l=o?ee(e.typescript,o):void 0,p=l?l.filter(m=>m.specifier!==void 0).map(m=>({value:m.specifier,index:m.node.getStart(o),kind:m.kind,typeOnly:m.typeOnly})):Xt(i),d=e.typescript?Qt(e.typescript,i):Zt(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(A))for(let m of l?.filter(({unresolved:b})=>b)??[]){let b=m.kind==="require";c.push(v(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:m.line,filePath:A}))}let y=g!==void 0&&(s.has(g)||nn(g)),h=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let m of n)if(m instanceof RegExp){m.lastIndex=0;let b=m.exec(i);m.lastIndex=0,b&&c.push(v("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${m}`,{line:b.index===void 0?void 0:ne(i,b.index),filePath:A,suggestion:"Remove infrastructure imports from domain/application layers."+h}))}else i.includes(m)&&c.push(v("FORBIDDEN_SUBSTRING",`Forbidden substring: ${m}`,{line:ne(i,i.indexOf(m)),filePath:A}));for(let m of p){let b=e.resolveImportTarget?.(m.value,A)??(e.resolveImportLayer?{layer:e.resolveImportLayer(m.value,A)}:void 0),C=typeof A=="string"?e.resolveImportTarget?.(A)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,de=b?.layer;if(de&&g){let Ee=N(e.architectureProfile?.rules,g,de,{fromPath:C?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(Ee){if(m.typeOnly&&!Ee.peerIsolation)continue;let Me=!!Ee.peerIsolation;c.push(v("LAYER_IMPORT_VIOLATION",Ee.message??(Me?`Layer "${g}" must not import across slices into "${de}".`:`Layer "${g}" must not import "${de}".`),{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,fromLayer:g,toLayer:de,suggestion:Me?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:m.kind,peerIsolation:Me,...m.typeOnly?{typeOnly:!0}:{}}}));continue}continue}y||m.typeOnly||!en(m.value)&&!tn(m.value)||c.push(v("FORBIDDEN_IMPORT",`Forbidden ${m.kind} target: "${m.value}".`,{line:ne(i,m.index),source:m.value,target:m.value,filePath:A,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+h,details:{importKind:m.kind}}))}if(e.policies)for(let m of e.policies){let b=m.check({source:i,context:a});if(b!==!0)if(Array.isArray(b))for(let C of b)c.push(v("POLICY_VIOLATION",C.message,{filePath:A,suggestion:`Fix violation of policy "${m.name}".`}));else b===!1?c.push(v("POLICY_VIOLATION",`Policy ${m.name} failed on generated code`)):c.push(v("POLICY_VIOLATION",b.message))}if(r&&t.size>0)for(let m of d)Y(m.value)&&!t.has(m.value)&&c.push(v("UNKNOWN_INTENT",`Unknown intent reference: "${m.value}"`,{line:ne(i,m.index),filePath:A,target:m.value,suggestion:`Register intent "${m.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let m of d){if(!Y(m.value))continue;let b=e.architectureProfile.resolveLayer(m.value);if(!b)continue;let C=N(e.architectureProfile.rules,g,b);C&&c.push(v("LAYER_REFERENCE_VIOLATION",C.message??`Layer "${g}" must not reference "${b}" through "${m.value}".`,{line:ne(i,m.index),filePath:A,target:m.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:C}}))}if(e.extensions)for(let m of e.extensions)try{let b=m.analyze(i,a);c.push(...b)}catch(b){c.push(v("EXTENSION_ERROR",`Extension "${m.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{let m=e.forbiddenGlobals[g];c.push(...te(e.typescript,o,m).map(b=>v("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:A,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of l??[]){if(b.typeOnly||!b.specifier)continue;let C=V(b.specifier,m);C&&c.push(v("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${C}".`,{line:b.line,filePath:A,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:C},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.capabilityWalls?.[g]?.length)try{let m=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let C of We(e.typescript,o))m.has(C.capability)&&(C.source==="ambient-global"&&fe(C.symbol,b)||C.source==="import-based"&&V(C.symbol,b)||c.push(v("CAPABILITY_VIOLATION",C.source==="import-based"?`${g} denies the ${C.capability} capability; found import of "${C.symbol}".`:`${g} denies the ${C.capability} capability; found ambient "${C.symbol}".`,{line:C.line,filePath:A,target:C.symbol,capability:C.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript)try{c.push(...dn(e.typescript,i,a,e.architectureProfile))}catch(m){c.push(v("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${m instanceof Error?m.message:String(m)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:c.length===0,violations:c}}}}var pn="1.0",xe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ct=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],fn=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function un(){let e=[];for(let t of Ct)for(let n of Ct)t===n||fn.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ke=un();var G={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},et={$schema:"https://json-schema.org/draft/2020-12/schema",$id:xe,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:xe,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:{...G,minItems:1,default:["src"]},exclude:{...G,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ke,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...G,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:{...G,minItems:1},exclude:G,intentPrefixes:G,description:{type:"string",minLength:1},forbiddenGlobals:G,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:{...G,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}}}}},ie=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
3
  ${n.map(s=>`- ${s.path}: ${s.message}`).join(`
4
4
  `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qe(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function re(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function yn(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function Se(e,t,n,s,r){if(t.$ref){let i=yn(t.$ref,s);if(!i){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Se(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(!It(e)){r.push({path:n,message:`must be an object; received ${re(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&r.push({path:Qe(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||r.push({path:Qe(n,a),message:"unknown field"});for(let[a,c]of Object.entries(i))e[a]!==void 0&&Se(e[a],c,Qe(n,a),s,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${re(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(a=>JSON.stringify(a));new Set(i).size!==i.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Se(i,t.items,`${n}[${a}]`,s,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${re(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 ${re(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${re(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function mn(e){return{...e,$schema:e.$schema===void 0?xe: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?ke.map(t=>({...t})):e.rules}}function gn(e,t="ark.config.json"){if(!It(e))throw new ie(t,[{path:"$",message:`must be an object; received ${re(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new ie(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:mn(e),migratedFrom:n}}function we(e,t="ark.config.json"){let{candidate:n,migratedFrom:s}=gn(e,t),r=[];if(Se(n,et,"$",et,r),r.length>0)throw new ie(t,r);return{config:n,migratedFrom:s}}function tt(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(s){throw new ie(t,[{path:"$",message:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}])}return we(n,t)}function Et(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:xe,schemaVersion:"1.0"};for(let[n,s]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=s);return t}function hn(e){return e.endsWith(".")?e:`${e}.`}function An(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Oe(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(hn)})),n=[...t].sort(An),s=[...e.rules??[]];return{name:e.name,layers:t,rules:s,resolveLayer(r){return t.find(i=>i.match?.(r))?.name??n.find(i=>i.prefixes.some(a=>r.startsWith(a)))?.name}}}function Rt(e,t={}){return Oe({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,s)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:s+1})),rules:e.rules??[]})}var bn=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Pe=Oe({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:bn,rules:ke.map(e=>({...e}))}),Cn={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function vt(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,s=t==="."?"":`${t}/`;return Et({include:e.include??[t],layers:Pe.layers.map(r=>({name:r.name,patterns:(Cn[r.name]??[r.name]).map(i=>`${s}${i}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...Pe.rules]})}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 E(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(E).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${E(t[n])}`).join(",")}}`}var W="1.0",St=["network","filesystem","clock","randomness","environment","process","persistence"];function q(e,t){let n=E(e),s=E(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 he(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(q),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0}};return S(E(t))}function In(e){let t=e.completenessReasons.map(u=>({code:u.code,message:u.message,...u.file?{file:u.file}:{}})).sort(q),n=e.files.map(u=>({...u,typeOnlyExportNames:T(u.typeOnlyExportNames)})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),s=e.dependencies.map(u=>({...u,...u.namedBindings?{namedBindings:T(u.namedBindings)}:{}})).sort(q),r=e.capabilityUses.map(u=>({...u})).sort(q),i=e.ambientUses.map(u=>({...u})).sort(q),a=e.publishCalls.map(u=>({...u})).sort(q),c=e.intentReferences.map(u=>({...u})).sort(q),f=e.safetyUses.map(u=>({...u})).sort(q),A=e.files.map(({path:u,contentHash:o})=>({path:u,contentHash:o})).sort((u,o)=>u.path<o.path?-1:u.path>o.path?1:0),g=S(E(A));return{schemaVersion:"1.0",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:g,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:s,capabilityUses:r,ambientUses:i,publishCalls:a,intentReferences:c,safetyUses:f}}function kt(e){let t=In(e);return{...t,factsHash:S(E(t))}}function nt(e){return kt(Pt(D(e,"$"),!1))}function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}function F(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 k(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 se(e,t,n){if(e[t]!==void 0)return k(e,t,n)}function M(e,t,n){let s=k(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 c of r.split("/"))if(!(!c||c==="."))if(c===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(c);let a=i.join("/");if(!a||a!==s)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}function _(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}function wt(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 ae(e,t,n){let s=wt(e,t,n);if(s===0)throw new Error(`${n}.${t} must be a positive integer.`);return s}function U(e,t,n){let s=e[t];if(!Array.isArray(s))throw new Error(`${n}.${t} must be an array.`);return s}function B(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 xt(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 En(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 Pt(e,t){F(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=B(e,"schemaVersion",["1.0"],"$"),s=B(e,"completeness",["complete","partial","unavailable"],"$"),r=U(e,"completenessReasons","$").map((p,d)=>{let y=`$.completenessReasons[${d}]`,h=D(p,y);F(h,["code","message","file"],y);let m=h.file===void 0?void 0:M(h,"file",y);return{code:k(h,"code",y),message:k(h,"message",y),...m?{file:m}:{}}});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=U(e,"files","$").map((p,d)=>{let y=`$.files[${d}]`,h=D(p,y);return F(h,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],y),{path:M(h,"path",y),contentHash:k(h,"contentHash",y),parseStatus:B(h,"parseStatus",["parsed","invalid"],y),parseDiagnosticCount:wt(h,"parseDiagnosticCount",y),exportsOnlyTypes:_(h,"exportsOnlyTypes",y),typeOnlyExportNames:xt(h.typeOnlyExportNames,`${y}.typeOnlyExportNames`),hasTopLevelSideEffects:_(h,"hasTopLevelSideEffects",y)}}),a=U(e,"dependencies","$").map((p,d)=>{let y=`$.dependencies[${d}]`,h=D(p,y);F(h,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],y);let m=se(h,"specifier",y),b=se(h,"target",y),C=B(h,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],y);if(C==="resolved-project"&&!b)throw new Error(`${y}.target is required for resolved-project dependencies.`);if(C!=="resolved-project"&&b)throw new Error(`${y}.target is only allowed for resolved-project dependencies.`);if(C!=="dynamic"&&!m)throw new Error(`${y}.specifier is required unless resolution is dynamic.`);return{from:M(h,"from",y),...m?{specifier:m}:{},kind:B(h,"kind",["import","export","dynamic-import","require"],y),typeOnly:_(h,"typeOnly",y),line:ae(h,"line",y),resolution:C,...b?{target:M(h,"target",y)}:{},...h.namedBindings!==void 0?{namedBindings:xt(h.namedBindings,`${y}.namedBindings`)}:{},...h.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:_(h,"targetTypeOnlyExports",y)}:{},...h.sourcePureTypeModule!==void 0?{sourcePureTypeModule:_(h,"sourcePureTypeModule",y)}:{},...h.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:_(h,"namedBindingsTypeOnly",y)}:{},...h.portProofEligible!==void 0?{portProofEligible:_(h,"portProofEligible",y)}:{}}}),c=U(e,"capabilityUses","$").map((p,d)=>{let y=`$.capabilityUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol","capability","source"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y),capability:B(h,"capability",St,y),source:B(h,"source",["ambient-global","import-based"],y)}}),f=U(e,"ambientUses","$").map((p,d)=>{let y=`$.ambientUses[${d}]`,h=D(p,y);return F(h,["file","line","symbol"],y),{file:M(h,"file",y),line:ae(h,"line",y),symbol:k(h,"symbol",y)}}),A=U(e,"publishCalls","$").map((p,d)=>{let y=`$.publishCalls[${d}]`,h=D(p,y);F(h,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],y);let m=se(h,"rawIntentName",y),b=se(h,"sourceIntent",y);return{file:M(h,"file",y),line:ae(h,"line",y),...m?{rawIntentName:m}:{},objectHasIntent:_(h,"objectHasIntent",y),arkPublishCandidate:_(h,"arkPublishCandidate",y),hasSource:_(h,"hasSource",y),...b?{sourceIntent:b}:{}}}),g=U(e,"intentReferences","$").map((p,d)=>{let y=`$.intentReferences[${d}]`,h=D(p,y);return F(h,["file","line","intent"],y),{file:M(h,"file",y),line:ae(h,"line",y),intent:k(h,"intent",y)}}),u=U(e,"safetyUses","$").map((p,d)=>{let y=`$.safetyUses[${d}]`,h=D(p,y);F(h,["file","line","kind","symbol"],y);let m=se(h,"symbol",y),b=B(h,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],y);if(b==="in-memory-store"&&!m)throw new Error(`${y}.symbol is required for in-memory-store facts.`);if(b!=="in-memory-store"&&m)throw new Error(`${y}.symbol is only allowed for in-memory-store facts.`);return{file:M(h,"file",y),line:ae(h,"line",y),kind:b,...m?{symbol:m}:{}}});En(i,p=>p.path,"$.files");let o=new Set(i.map(p=>p.path));for(let p of i){if(p.parseStatus==="parsed"&&p.parseDiagnosticCount!==0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(p.parseStatus==="invalid"&&p.parseDiagnosticCount===0)throw new Error(`$.files[${p.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(s==="complete"&&i.some(p=>p.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let p of a)if(!o.has(p.from))throw new Error(`$.dependencies references missing source file ${p.from}.`);for(let[p,d]of[["$.capabilityUses",c],["$.ambientUses",f],["$.publishCalls",A],["$.intentReferences",g],["$.safetyUses",u]])for(let y of d)if(!o.has(y.file))throw new Error(`${p} references missing file ${y.file}.`);let l=se(e,"projectPackageName","$");return{schemaVersion:n,completeness:s,completenessReasons:r,resolverIdentity:k(e,"resolverIdentity","$"),compilerIdentity:k(e,"compilerIdentity","$"),compilerOptionsHash:k(e,"compilerOptionsHash","$"),tsconfigHash:k(e,"tsconfigHash","$"),evidenceRequirementsHash:k(e,"evidenceRequirementsHash","$"),...l?{projectPackageName:l}:{},files:i,dependencies:a,capabilityUses:c,ambientUses:f,publishCalls:A,intentReferences:g,safetyUses:u}}function z(e){let t=D(e,"$"),n=k(t,"factsHash","$"),s=k(t,"candidateTreeHash","$"),r=kt(Pt(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 Rn=["network","filesystem","clock","randomness","environment","process","persistence"],R={type:"string",minLength:1},oe={type:"integer",minimum:1},H={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},rt={$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:R,message:R,file:H}}},resolverIdentity:R,compilerIdentity:R,compilerOptionsHash:R,tsconfigHash:R,candidateTreeHash:R,evidenceRequirementsHash:R,projectPackageName:R,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:H,contentHash:R,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:R},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:H,specifier:R,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:oe,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:H,namedBindings:{type:"array",items:R},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:H,line:oe,symbol:R,capability:{enum:Rn},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:H,line:oe,symbol:R}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:H,line:oe,rawIntentName:R,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:R}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:H,line:oe,intent:R}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:H,line:oe,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:R},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},factsHash:R},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 it="1.0";function P(e){return`${e.from}->${e.to}`}function Ae(e,t,n,s="dependency"){return{id:`${e}:${s}:${P(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${P(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${P(t)}, then preflight again.`}:e==="unplanned"?{nextAction:s==="dependency-removed"?`Restore the removed dependency ${P(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${P(t)} from the candidate, then preflight again.`}:{}}}function le(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),s=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[P(o),o])),i=new Map(e.baseDependencies.map(o=>[P(o),o])),a=new Map(e.candidateDependencies.map(o=>[P(o),o]));for(let o of[...n.values()].sort((l,p)=>l.path.localeCompare(p.path))){let l=s.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...s.values()].sort((l,p)=>l.path.localeCompare(p.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...r.values()].sort((l,p)=>P(l).localeCompare(P(p)))){if(a.has(P(o))){t.push(Ae("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};a.has(P(l))?(c.add(P(l)),t.push(Ae("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Ae("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let f=new Set([...n.keys(),...s.keys()]);for(let[o,l]of[...a].sort(([p],[d])=>p.localeCompare(d)))i.has(o)||r.has(o)||c.has(o)||!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 A=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...i].sort(([p],[d])=>p.localeCompare(d)))a.has(o)||A.has(l.from)||A.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 g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let u={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:u.missing===0&&u.contradictory===0&&u.unplanned===0,behavioralCompletion:"not-evaluated",summary:u,findings:t}}var st="1.0";function x(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 L(e){return[...new Set(e??[])].sort()}function J(e,t,n,s,r){let i=L(n),a=L(s),c=new Set(i),f=new Set(a),A=a.filter(u=>!c.has(u)),g=i.filter(u=>!f.has(u));A.length===0&&g.length===0||(A.length>0&&x(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:i,after:a}),g.length>0&&x(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:i,after:a}))}function Le(e,t,n,s,r,i,a){if(n===s)return;x(e,{kind:s?"enabled":"disabled",path:t,classification:s?r:r==="strengthening"?"weakening":"strengthening",message:s?i:a,before:n,after:s})}function $e(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 vn(e,t,n){let s=$e(t,i=>i.name),r=$e(n,i=>i.name);(s.duplicates.length>0||r.duplicates.length>0)&&x(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 a=s.values.get(i),c=r.values.get(i),f=`$.layers[${i}]`;if(!a&&c){x(e,{kind:"layer-added",path:f,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(a&&!c){x(e,{kind:"layer-removed",path:f,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!c)continue;J(e,`${f}.patterns`,a.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),J(e,`${f}.exclude`,a.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let A=ve(a),g=ve(c);J(e,`${f}.forbiddenGlobals`,A.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),J(e,`${f}.capabilities`,A.atoms,g.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)."}),L(a.intentPrefixes).join("\0")!==L(c.intentPrefixes).join("\0")&&x(e,{kind:"intent-prefixes-changed",path:`${f}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:L(a.intentPrefixes),after:L(c.intentPrefixes)}),Le(e,`${f}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Le(e,`${f}.optional`,a.optional===!0,c.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 Sn(e,t,n){let s=a=>`${a.from}->${a.to}`,r=$e(t,s),i=$e(n,s);(r.duplicates.length>0||i.duplicates.length>0)&&x(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 a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let c=r.values.get(a),f=i.values.get(a),A=`$.rules[${a}]`;if(!c&&f){f.allowed===!1&&x(e,{kind:"deny-added",path:A,classification:"strengthening",message:"A denied dependency edge was added.",after:f});continue}if(c&&!f){c.allowed===!1&&x(e,{kind:"deny-removed",path:A,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!f)continue;c.allowed!==f.allowed&&x(e,{kind:f.allowed?"deny-disabled":"deny-enabled",path:`${A}.allowed`,classification:f.allowed?"weakening":"strengthening",message:f.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:f.allowed});let g=c.peerIsolation===!0,u=f.peerIsolation===!0;if(g!==u){let o=c.from===c.to&&f.from===f.to;x(e,{kind:u?"peer-isolation-enabled":"peer-isolation-disabled",path:`${A}.peerIsolation`,classification:o?u?"strengthening":"weakening":"judgment-required",message:o?u?"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:g,after:u})}L(c.sliceFolders).join("\0")!==L(f.sliceFolders).join("\0")&&x(e,{kind:"slice-folders-changed",path:`${A}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:L(c.sliceFolders),after:L(f.sliceFolders)})}}function xn(e,t,n){let s=t.safety??{},r=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=s[i]??0,c=r[i]??0;a!==c&&x(e,{kind:c>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:c>a?"weakening":"strengthening",message:c>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:c})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Le(e,`$.safety.${i}`,s[i]===!0,r[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function kn(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 at(e,t){let n=[];J(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),J(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."}),J(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."}),Le(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 a=s[i]===s[r]?"judgment-required":s[i]>s[r]?"strengthening":"weakening";x(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:a,message:"The cycle enforcement level changed.",before:r,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&x(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}),vn(n,e.layers,t.layers),Sn(n,e.rules,t.rules),xn(n,e,t),n.sort((a,c)=>a.path.localeCompare(c.path)||a.id.localeCompare(c.id)),{schemaVersion:st,classification:kn(n),findings:n}}function ot(e,t){if(!e||e.schemaVersion!==st||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=L(e.findingIds),s=L(t.findingIds);return n.length===s.length&&n.every((r,i)=>r===s[i])}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 Ot(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}function _e(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function O(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function be(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 $(e,t,n){return e.startsWith(t,n)&&!_e(e[n-1])&&!_e(e[n+t.length])}function Lt(e,t){let n=O(e,t);if(e[n]!=="{")return!1;n+=1;let s=!1;for(;n<e.length;){if(n=O(e,n),e[n]==="}")return s;if(e[n]===","){n+=1;continue}if(!$(e,"type",n))return!1;let r=O(e,n+4);if(r>=e.length||e[r]===","||e[r]==="}"||$(e,"as",r)||!Ot(e[r]))return!1;for(n=r;n<e.length&&_e(e[n]);)n+=1;if(n=O(e,n),$(e,"as",n)){if(n=O(e,n+2),!Ot(e[n]))return!1;for(;n<e.length&&_e(e[n]);)n+=1}s=!0}return!1}function wn(e,t){if(t=O(e,t+6),e[t]==="(")return be(e,O(e,t+1));let n=!1;if($(e,"type",t)){let r=O(e,t+4);e[r]!==","&&!$(e,"from",r)&&(n=!0)}else Lt(e,t)&&(n=!0);let s=$t(e,t,!0);return s&&n?{...s,typeOnly:!0}:s}function Pn(e,t){t=t+6;let n=O(e,t),s=!1;if($(e,"type",n)){let i=O(e,n+4);(e[i]==="{"||e[i]==="*")&&(s=!0)}else Lt(e,n)&&(s=!0);let r=$t(e,t,!1);return r&&s?{...r,typeOnly:!0}:r}function $t(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if($(e,"from",t))return be(e,O(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return be(e,t);if(t>0&&($(e,"import",t)||$(e,"export",t)))return}}function On(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 Ln(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let s=O(e,t+7);if(e[s]!=="(")return;s=O(e,s+1);let r=be(e,s);return r?{...r,requireCall:!0}:void 0}function $n(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(`
@@ -187,5 +187,5 @@ production deployment would need to satisfy; it is not a readiness certification
187
187
  ## Release notes (maintainers)
188
188
 
189
189
  Ship notes for a version live under [releases/](https://github.com/pedroknigge/arkgate/tree/main/docs/releases) (latest:
190
- [3.8.2.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.2.md)).
190
+ [3.8.3.md](https://github.com/pedroknigge/arkgate/blob/main/docs/releases/3.8.3.md)).
191
191
  Publish path: signed annotated tag → GitHub Release → `publish-npm.yml` (see [CONTRIBUTING.md](https://github.com/pedroknigge/arkgate/blob/main/CONTRIBUTING.md)).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkgate",
3
- "version": "3.8.2",
3
+ "version": "3.8.3",
4
4
  "description": "ArkGate — architecture co-pilot for AI TypeScript (write gate, CI gate, plan/loop)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/pedroknigge/arkgate",
7
7
  "source": "github"
8
8
  },
9
- "version": "3.8.2",
9
+ "version": "3.8.3",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "arkgate",
14
- "version": "3.8.2",
14
+ "version": "3.8.3",
15
15
  "runtimeHint": "npx",
16
16
  "transport": {
17
17
  "type": "stdio"