arkgate 4.6.0 → 4.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.md +11 -5
  3. package/bin/ark-check-runtime.mjs +115 -128
  4. package/bin/ark-mcp-runtime.mjs +86 -48
  5. package/bin/ark.mjs +21 -78
  6. package/bin/lib/agent-projection.mjs +1 -1
  7. package/bin/lib/analysis-engine.mjs +3 -3
  8. package/bin/lib/ci-and-commands.mjs +11 -11
  9. package/bin/lib/config-contract.mjs +2 -0
  10. package/bin/lib/contract-smells.mjs +5 -5
  11. package/bin/lib/design-smells.mjs +1 -1
  12. package/bin/lib/doctor-advisories.mjs +9 -0
  13. package/bin/lib/doctor-next-actions.mjs +92 -0
  14. package/bin/lib/doctor-plan.mjs +61 -71
  15. package/bin/lib/field-install.mjs +1 -1
  16. package/bin/lib/first-run-help.mjs +221 -0
  17. package/bin/lib/html-report-advisories.mjs +20 -0
  18. package/bin/lib/improvement-compass-map.mjs +20 -20
  19. package/bin/lib/pilot-loop.mjs +1 -1
  20. package/bin/lib/post-green-path.mjs +2 -2
  21. package/bin/lib/prepare-change.mjs +9 -0
  22. package/bin/lib/product-copy.mjs +1 -1
  23. package/bin/lib/start-preview.mjs +17 -10
  24. package/bin/lib/status-command.mjs +19 -0
  25. package/bin/lib/status-manifest.mjs +23 -0
  26. package/bin/lib/team-parliament-io.mjs +338 -0
  27. package/bin/lib/team-parliament.mjs +383 -0
  28. package/bin/lib/upgrade-whats-new.mjs +16 -0
  29. package/bin/lib/violations.mjs +8 -4
  30. package/dist/{configTypes-CC0FEXoF.d.ts → configTypes-B8uIcLaG.d.ts} +5 -0
  31. package/dist/eslint/index.cjs +2 -2
  32. package/dist/eslint/index.d.ts +1 -1
  33. package/dist/eslint/index.js +2 -2
  34. package/dist/index.cjs +8 -8
  35. package/dist/index.d.ts +66 -2
  36. package/dist/index.js +8 -8
  37. package/docs/README.md +5 -5
  38. package/docs/agent-guide.md +21 -17
  39. package/docs/configuration.md +36 -2
  40. package/docs/develop.md +13 -1
  41. package/docs/enthusiast/README.md +1 -1
  42. package/docs/enthusiast/how-to-agent-gates.md +3 -3
  43. package/docs/enthusiast/how-to-pick-shape.md +2 -2
  44. package/docs/enthusiast/tutorial-first-project.md +4 -3
  45. package/docs/package-surface.md +5 -3
  46. package/docs/product-voice.md +48 -10
  47. package/docs/use.md +10 -5
  48. package/package.json +2 -2
  49. package/schemas/ark.config.schema.json +9 -0
  50. package/schemas/ark.status-manifest.schema.json +51 -0
  51. package/server.json +3 -3
  52. package/templates/agent-skills/README.md +1 -1
  53. package/templates/agent-skills/ark-adopt/SKILL.md +59 -23
  54. package/templates/agent-skills/ark-architect/SKILL.md +24 -145
  55. package/templates/agent-skills/ark-autopilot/SKILL.md +49 -32
  56. package/templates/agent-skills/ark-contract/SKILL.md +21 -105
  57. package/templates/agent-skills/ark-coverage/SKILL.md +7 -3
  58. package/templates/agent-skills/ark-explain/SKILL.md +8 -4
  59. package/templates/agent-skills/ark-explore/SKILL.md +38 -21
  60. package/templates/agent-skills/ark-fix/SKILL.md +34 -157
  61. package/templates/agent-skills/ark-loop/SKILL.md +31 -153
  62. package/templates/agent-skills/ark-place/SKILL.md +35 -14
  63. package/templates/agent-skills/ark-runtime/SKILL.md +3 -3
  64. package/templates/agent-skills/ark-think/SKILL.md +6 -2
  65. package/templates/agent-skills/ark-upgrade/SKILL.md +21 -10
  66. package/templates/skills/ark-adopt.md +59 -23
  67. package/templates/skills/ark-architect.md +24 -145
  68. package/templates/skills/ark-autopilot.md +49 -32
  69. package/templates/skills/ark-contract.md +21 -105
  70. package/templates/skills/ark-coverage.md +7 -3
  71. package/templates/skills/ark-explain.md +8 -4
  72. package/templates/skills/ark-explore.md +38 -21
  73. package/templates/skills/ark-fix.md +34 -157
  74. package/templates/skills/ark-loop.md +31 -153
  75. package/templates/skills/ark-place.md +35 -14
  76. package/templates/skills/ark-runtime.md +3 -3
  77. package/templates/skills/ark-think.md +6 -2
  78. package/templates/skills/ark-upgrade.md +21 -10
@@ -0,0 +1,383 @@
1
+ /**
2
+ * GENERATED FILE — do not edit by hand.
3
+ *
4
+ * Canonical algorithm: src/domain/teamParliament.ts
5
+ * Regenerate: node scripts/generate-cli-pure.mjs
6
+ * Drift check: node scripts/generate-cli-pure.mjs --check
7
+ *
8
+ * Pure CLI helper (bin/lib/team-parliament.mjs). Zero Node I/O.
9
+ */
10
+
11
+ export const TEAM_PERSONAS = ['touch', 'contributor', 'agent', 'steward'];
12
+ export const CONTRACT_DIFF_KINDS = [
13
+ 'unchanged',
14
+ 'tighten',
15
+ 'loosen',
16
+ 'reclassify',
17
+ 'baseline-grow',
18
+ 'baseline-shrink',
19
+ ];
20
+ function posixRel(value) {
21
+ return String(value ?? '')
22
+ .replace(/\\/g, '/')
23
+ .replace(/^\.\//, '');
24
+ }
25
+ /** True for constitution files: ark.config.json, .ark-baseline.json, arkrules/*.json */
26
+ export function isLawRelativePath(relPath) {
27
+ const n = posixRel(relPath);
28
+ if (n === 'ark.config.json' || n.endsWith('/ark.config.json'))
29
+ return true;
30
+ if (n === '.ark-baseline.json' || n.endsWith('/.ark-baseline.json'))
31
+ return true;
32
+ const base = n.split('/').pop() ?? n;
33
+ if (base === 'ark.config.json' || base === '.ark-baseline.json')
34
+ return true;
35
+ if ((n.startsWith('arkrules/') || n.includes('/arkrules/')) && n.endsWith('.json')) {
36
+ return true;
37
+ }
38
+ return false;
39
+ }
40
+ const PRODUCT_SOURCE = /\.(tsx?|jsx?|mjs|cjs)$/i;
41
+ /** Governable product source (not law, not tests-only heuristic — basename extension). */
42
+ export function isProductSourceRelativePath(relPath) {
43
+ const n = posixRel(relPath);
44
+ if (!n || isLawRelativePath(n))
45
+ return false;
46
+ const base = n.split('/').pop() ?? n;
47
+ if (base.endsWith('.d.ts'))
48
+ return false;
49
+ return PRODUCT_SOURCE.test(base);
50
+ }
51
+ export function classifyChangeSet(paths) {
52
+ const lawPaths = [];
53
+ const productPaths = [];
54
+ const otherPaths = [];
55
+ const seen = new Set();
56
+ for (const raw of paths) {
57
+ const n = posixRel(raw);
58
+ if (!n || seen.has(n))
59
+ continue;
60
+ seen.add(n);
61
+ if (isLawRelativePath(n))
62
+ lawPaths.push(n);
63
+ else if (isProductSourceRelativePath(n))
64
+ productPaths.push(n);
65
+ else
66
+ otherPaths.push(n);
67
+ }
68
+ lawPaths.sort();
69
+ productPaths.sort();
70
+ otherPaths.sort();
71
+ return {
72
+ lawPaths,
73
+ productPaths,
74
+ otherPaths,
75
+ mixed: lawPaths.length > 0 && productPaths.length > 0,
76
+ hasLaw: lawPaths.length > 0,
77
+ hasProduct: productPaths.length > 0,
78
+ };
79
+ }
80
+ export function mapPolicyClassToKind(classification) {
81
+ if (classification == null)
82
+ return null;
83
+ if (classification === 'strengthening')
84
+ return 'tighten';
85
+ if (classification === 'weakening')
86
+ return 'loosen';
87
+ if (classification === 'judgment-required')
88
+ return 'reclassify';
89
+ return 'unchanged';
90
+ }
91
+ export function classifyBaselineKeyDelta(baseKeys, candidateKeys) {
92
+ const base = new Set(baseKeys.filter(Boolean));
93
+ const candidate = new Set(candidateKeys.filter(Boolean));
94
+ const grow = [...candidate].filter((key) => !base.has(key)).sort();
95
+ const shrink = [...base].filter((key) => !candidate.has(key)).sort();
96
+ const kinds = [];
97
+ if (grow.length > 0)
98
+ kinds.push('baseline-grow');
99
+ if (shrink.length > 0)
100
+ kinds.push('baseline-shrink');
101
+ return { grow, shrink, kinds };
102
+ }
103
+ export function normalizeStewardId(value) {
104
+ if (typeof value !== 'string')
105
+ return null;
106
+ const trimmed = value.trim().replace(/^@/, '').toLowerCase();
107
+ return trimmed.length > 0 ? trimmed : null;
108
+ }
109
+ /** GitHub handle (login), not a display name. Spaces and emails are not handles. */
110
+ export function isGitHubHandle(value) {
111
+ const id = normalizeStewardId(value);
112
+ if (!id || isAutomationAuthor(id) || id.includes(' ') || id.includes('@'))
113
+ return false;
114
+ return /^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(id);
115
+ }
116
+ export function isGitHubEmail(value) {
117
+ if (typeof value !== 'string')
118
+ return false;
119
+ const email = value.trim().toLowerCase();
120
+ if (!email.includes('@') || email.includes(' ') || isAutomationAuthor(email))
121
+ return false;
122
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
123
+ }
124
+ /** `123+login@users.noreply.github.com` or `login@users.noreply.github.com` → login. */
125
+ export function githubHandleFromEmail(email) {
126
+ if (typeof email !== 'string')
127
+ return null;
128
+ const match = email.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);
129
+ if (!match)
130
+ return null;
131
+ return isGitHubHandle(match[1]) ? normalizeStewardId(match[1]) : null;
132
+ }
133
+ /**
134
+ * Handle, GitHub noreply mail, or any email — same person when handle ↔ noreply.
135
+ * Display names (`Pedro Knigge`) are not identity.
136
+ */
137
+ export function canonicalStewardId(value) {
138
+ const fromNoreply = githubHandleFromEmail(value);
139
+ if (fromNoreply)
140
+ return fromNoreply;
141
+ const id = normalizeStewardId(value);
142
+ if (!id || isAutomationAuthor(id))
143
+ return null;
144
+ if (isGitHubHandle(id) || isGitHubEmail(id))
145
+ return id;
146
+ return null;
147
+ }
148
+ export function formatStewardMention(id) {
149
+ return id.includes('@') ? id : `@${id}`;
150
+ }
151
+ /**
152
+ * Who is acting: GitHub handle or email.
153
+ * Prefer explicit / GITHUB_ACTOR / ARK_STEWARD / email; git display names never win.
154
+ */
155
+ export function resolveStewardHandle(input) {
156
+ for (const candidate of [
157
+ input.explicit,
158
+ input.githubActor,
159
+ input.arkSteward,
160
+ input.authorEmail,
161
+ input.gitName,
162
+ ]) {
163
+ const id = canonicalStewardId(candidate);
164
+ if (id)
165
+ return id;
166
+ }
167
+ return null;
168
+ }
169
+ export function isSteward(author, stewards) {
170
+ const who = canonicalStewardId(author);
171
+ if (!who || !Array.isArray(stewards) || stewards.length === 0)
172
+ return false;
173
+ return stewards.some((entry) => canonicalStewardId(entry) === who);
174
+ }
175
+ const BOT_STEWARD = /bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;
176
+ export function isAutomationAuthor(value) {
177
+ const id = normalizeStewardId(value);
178
+ return !id || BOT_STEWARD.test(id);
179
+ }
180
+ /** @handles from a CODEOWNERS file body (comments and bare paths ignored). */
181
+ export function parseCodeownersHandles(text) {
182
+ if (typeof text !== 'string' || !text.trim())
183
+ return [];
184
+ const found = [];
185
+ for (const rawLine of text.split(/\r?\n/)) {
186
+ const line = rawLine.trim();
187
+ if (!line || line.startsWith('#'))
188
+ continue;
189
+ for (const token of line.split(/\s+/)) {
190
+ if (!token.startsWith('@'))
191
+ continue;
192
+ const id = normalizeStewardId(token);
193
+ if (id && !isAutomationAuthor(id))
194
+ found.push(id);
195
+ }
196
+ }
197
+ return [...new Set(found)];
198
+ }
199
+ /**
200
+ * Empty list + several hands → propose owners.
201
+ * Existing list + CODEOWNERS ahead or author count grew → show the gap.
202
+ * Never a gate input. Propose GitHub handles or emails — never git display names. Never auto-remove.
203
+ */
204
+ export function suggestStewards(input) {
205
+ const existing = [
206
+ ...new Set((input.existingStewards ?? [])
207
+ .map((id) => canonicalStewardId(id) ?? normalizeStewardId(id))
208
+ .filter((id) => Boolean(id))),
209
+ ];
210
+ const fromOwners = [
211
+ ...new Set((input.codeowners ?? [])
212
+ .map((id) => canonicalStewardId(id))
213
+ .filter((id) => Boolean(id))),
214
+ ];
215
+ const uniqueGit = [
216
+ ...new Set((input.gitAuthors ?? [])
217
+ .map((id) => normalizeStewardId(id))
218
+ .filter((id) => Boolean(id) && !isAutomationAuthor(id))),
219
+ ];
220
+ const gitIds = [
221
+ ...new Set((input.gitAuthors ?? [])
222
+ .map((id) => canonicalStewardId(id))
223
+ .filter((id) => Boolean(id))),
224
+ ];
225
+ const authorCount = Math.max(uniqueGit.length, fromOwners.length);
226
+ const multiHand = uniqueGit.length >= 2 || fromOwners.length >= 1;
227
+ const needsStewards = multiHand && existing.length === 0;
228
+ const missingFromList = fromOwners.filter((id) => !existing.includes(id));
229
+ const teamGrew = existing.length > 0 &&
230
+ fromOwners.length === 0 &&
231
+ uniqueGit.length >= 2 &&
232
+ uniqueGit.length > existing.length;
233
+ const drift = existing.length > 0 && (missingFromList.length > 0 || teamGrew);
234
+ const source = fromOwners.length > 0 ? 'codeowners' : gitIds.length > 0 ? 'git-authors' : 'none';
235
+ const proposed = needsStewards
236
+ ? (fromOwners.length > 0 ? fromOwners : gitIds).slice(0, 6)
237
+ : missingFromList.slice(0, 6);
238
+ const named = proposed.map((id) => formatStewardMention(id)).join(', ');
239
+ const listed = existing.map((id) => formatStewardMention(id)).join(', ');
240
+ let ask = '';
241
+ if (needsStewards) {
242
+ ask =
243
+ proposed.length > 0
244
+ ? `This repo has several people and no stewards. Add ${named} as stewards so only they can loosen the law or grow the baseline? Say yes, or name the GitHub handles or emails.`
245
+ : 'This repo has several people and no stewards. Who owns ark.config.json? Name GitHub handles or emails for the stewards[] list.';
246
+ }
247
+ else if (missingFromList.length > 0) {
248
+ ask = `CODEOWNERS is ahead of stewards[]: add ${missingFromList.map((id) => formatStewardMention(id)).join(', ')}? The current list stays unless you say yes or name the GitHub handles or emails.`;
249
+ }
250
+ else if (teamGrew) {
251
+ ask = `This repo started with ${existing.length} steward(s) (${listed}) and now has ${uniqueGit.length} recent git authors. Who else owns the law? Name GitHub handles or emails, or say the list is still right.`;
252
+ }
253
+ const shouldAct = needsStewards || drift;
254
+ return {
255
+ advisory: true,
256
+ notAScore: true,
257
+ multiHand,
258
+ needsStewards,
259
+ drift,
260
+ authorCount,
261
+ stewardCount: existing.length,
262
+ proposed,
263
+ missingFromList,
264
+ source,
265
+ ask,
266
+ nextAction: shouldAct
267
+ ? '/ark-adopt (ask, then update stewards[] — do not invent names)'
268
+ : '',
269
+ };
270
+ }
271
+ export function personaCheckBudget(persona) {
272
+ if (persona === 'touch') {
273
+ return {
274
+ persona,
275
+ scan: 'none',
276
+ contractDiff: false,
277
+ denyContractEdit: true,
278
+ denyLoosenUnlessSteward: true,
279
+ };
280
+ }
281
+ if (persona === 'contributor') {
282
+ return {
283
+ persona,
284
+ scan: 'changed',
285
+ contractDiff: false,
286
+ denyContractEdit: true,
287
+ denyLoosenUnlessSteward: true,
288
+ };
289
+ }
290
+ if (persona === 'agent') {
291
+ return {
292
+ persona,
293
+ scan: 'changed+ungoverned',
294
+ contractDiff: false,
295
+ denyContractEdit: true,
296
+ denyLoosenUnlessSteward: true,
297
+ };
298
+ }
299
+ return {
300
+ persona: 'steward',
301
+ scan: 'full',
302
+ contractDiff: true,
303
+ denyContractEdit: false,
304
+ denyLoosenUnlessSteward: true,
305
+ };
306
+ }
307
+ export function isTeamPersona(value) {
308
+ return TEAM_PERSONAS.includes(value);
309
+ }
310
+ /**
311
+ * Gate for a diff vs the merge base.
312
+ * Contract session still forbids mixing law with product source.
313
+ * Loosen / baseline-grow require a steward when the list is non-empty.
314
+ */
315
+ export function evaluateTeamGate(input) {
316
+ const kinds = [];
317
+ if (input.policyKind && input.policyKind !== 'unchanged')
318
+ kinds.push(input.policyKind);
319
+ if ((input.baselineGrowCount ?? 0) > 0)
320
+ kinds.push('baseline-grow');
321
+ const { changeSet } = input;
322
+ if (changeSet.mixed) {
323
+ return {
324
+ deny: true,
325
+ reasonId: 'mixed-law-and-product',
326
+ message: 'This change mixes the constitution with product files. Split the PR, or run a steward --contract-session that touches only ark.config / arkrules / .ark-baseline.json.',
327
+ kinds,
328
+ };
329
+ }
330
+ if (changeSet.hasLaw && !input.contractSession) {
331
+ return {
332
+ deny: true,
333
+ reasonId: 'law-in-feature',
334
+ message: 'This feature change edits the constitution. Move ark.config / arkrules / .ark-baseline.json to a steward --contract-session PR.',
335
+ kinds,
336
+ };
337
+ }
338
+ const stewards = input.stewards ?? [];
339
+ const grow = (input.baselineGrowCount ?? 0) > 0;
340
+ const loosen = input.policyKind === 'loosen';
341
+ if (stewards.length > 0 && (loosen || grow) && !isSteward(input.author, stewards)) {
342
+ return {
343
+ deny: true,
344
+ reasonId: loosen ? 'steward-only-loosen' : 'steward-only-baseline-grow',
345
+ message: loosen
346
+ ? 'Loosening the contract is steward-only. Listed stewards may pass --contract-session with --author matching stewards[].'
347
+ : 'Growing the baseline is steward-only. Freeze new debt in a contract-session PR owned by a steward.',
348
+ kinds,
349
+ };
350
+ }
351
+ return { deny: false, reasonId: 'ok', message: '', kinds };
352
+ }
353
+ export function formatVsBaseLine(facts) {
354
+ const pinEqual = facts.pinLocal != null && facts.pinBase != null && facts.pinLocal === facts.pinBase;
355
+ const pinBit = facts.pinLocal == null && facts.pinBase == null
356
+ ? 'pin unknown'
357
+ : pinEqual
358
+ ? 'pin equal'
359
+ : `pin local ${facts.pinLocal ?? '?'} ≠ pin of base ${facts.pinBase ?? '?'}`;
360
+ const contractBit = facts.contractEqual ? 'contract equal' : 'contract local ≠ contract of base';
361
+ const baselineBit = facts.baselineGrew ? 'baseline local grew' : 'baseline did not grow';
362
+ return `vs ${facts.baseRef}: ${pinBit} · ${contractBit} · ${baselineBit}`;
363
+ }
364
+ /** Parse v1 `violations[]` or v2 `records` object into a sorted unique key list. */
365
+ export function baselineKeysFromDocument(raw) {
366
+ if (raw == null || typeof raw !== 'object')
367
+ return [];
368
+ const doc = raw;
369
+ const fromArray = Array.isArray(doc.violations)
370
+ ? doc.violations.filter((key) => typeof key === 'string' && key.length > 0)
371
+ : [];
372
+ const fromRecords = doc.records && typeof doc.records === 'object' && !Array.isArray(doc.records)
373
+ ? Object.keys(doc.records).filter((key) => key.length > 0)
374
+ : [];
375
+ return [...new Set([...fromArray, ...fromRecords])].sort();
376
+ }
377
+ export function baselineRecordsDocument(keys, note) {
378
+ const violations = [...new Set(keys.filter(Boolean))].sort();
379
+ const records = {};
380
+ for (const key of violations)
381
+ records[key] = { id: key };
382
+ return { version: 2, note, violations, records };
383
+ }
@@ -33,6 +33,22 @@ export function buildUpgradeWhatsNewSuggestions() {
33
33
  neverGateInput: true,
34
34
  title: 'Suggested improvements — try or inspect after this package',
35
35
  items: [
36
+ {
37
+ id: 'five-door-autonomy',
38
+ title: 'Five doors (invoke = write or map)',
39
+ try: '/ark-adopt · /ark-place · /ark-autopilot · /ark-explore · /ark-upgrade',
40
+ inspect: 'Skill bodies + doctor next action (other /ark-* names are shortcuts)',
41
+ why:
42
+ 'Invoking a door is the approval. The CLI is sensor + gate — it does not apply the change. Explore maps only. Same 13 skill names.',
43
+ },
44
+ {
45
+ id: 'team-parliament',
46
+ title: 'Team parliament (law vs feature)',
47
+ try: 'npx arkgate-check --changed --base origin/dev',
48
+ inspect: 'doctor.stewardNudge · ark status --vs · optional stewards[] (GitHub handle or email)',
49
+ why:
50
+ 'Product PRs must not amend ark.config.json. Law-only PRs use --contract-session. Doctor asks for stewards or shows list drift. Display names are not identity.',
51
+ },
36
52
  {
37
53
  id: 'plain-language-doctor',
38
54
  title: 'Doctor in plain language',
@@ -12,14 +12,18 @@ const color = {
12
12
 
13
13
  /** Canonical: src/domain/baselineKey.ts → bin/lib/baseline-key.mjs (R4). */
14
14
  import { baselineKey, baselineOccurrenceKeys } from './baseline-key.mjs';
15
+ import { baselineKeysFromDocument, baselineRecordsDocument } from './team-parliament.mjs';
15
16
  import { toAdapterDiagnostic } from './adapter-contract.mjs';
16
17
  export { baselineKey, baselineOccurrenceKeys };
17
18
 
19
+ const BASELINE_NOTE =
20
+ 'Frozen ark-check violations (one record per edge). Only NEW keys vs the merge-base fail --against / --baseline. Regenerate with: ark-check --update-baseline';
21
+
18
22
  export function readBaseline(root, baselinePath) {
19
23
  const fullPath = path.isAbsolute(baselinePath) ? baselinePath : path.join(root, baselinePath);
20
24
  if (!fs.existsSync(fullPath)) return { keys: new Set(), fullPath, exists: false };
21
25
  const raw = JSON.parse(fs.readFileSync(fullPath, 'utf8'));
22
- return { keys: new Set(raw.violations ?? []), fullPath, exists: true };
26
+ return { keys: new Set(baselineKeysFromDocument(raw)), fullPath, exists: true };
23
27
  }
24
28
 
25
29
  export function writeBaseline(root, baselinePath, violations) {
@@ -27,7 +31,7 @@ export function writeBaseline(root, baselinePath, violations) {
27
31
  const keys = baselineOccurrenceKeys(violations).sort();
28
32
  fs.writeFileSync(
29
33
  fullPath,
30
- `${JSON.stringify({ version: 1, note: 'Frozen ark-check violations. Only NEW violations fail --baseline runs. Regenerate with: ark-check --update-baseline', violations: keys }, null, 2)}\n`
34
+ `${JSON.stringify(baselineRecordsDocument(keys, BASELINE_NOTE), null, 2)}\n`
31
35
  );
32
36
  return { fullPath, count: keys.length };
33
37
  }
@@ -154,8 +158,8 @@ export function printViolationBreakdown(summary, { toStderr = false } = {}) {
154
158
  out(' framework/kernel through a sanctioned entrypoint. Before treating it as debt:');
155
159
  out(' • If the edge is intended, allow it — or split the target layer into a public');
156
160
  out(' surface app-land may import + internals it may not (see the target dirs above');
157
- out(' to find the surface). Do it via /ark-contract.');
158
- out(' • Only the minority hitting real internals is genuine debt for /ark-fix.');
161
+ out(' to find the surface). Do it via /ark-adopt.');
162
+ out(' • Only the minority hitting real internals is genuine debt for /ark-autopilot.');
159
163
  out(` Fixing the contract clears ~${summary.edges[0].count} of ${summary.total} at once.`);
160
164
  }
161
165
  }
@@ -59,6 +59,11 @@ type ArkConfig = {
59
59
  safety?: ArkConfigSafety;
60
60
  /** ADR 0012 — modular ArkRules references (schema 1.1+). */
61
61
  arkRules?: ArkConfigArkRulesRefs;
62
+ /**
63
+ * Optional GitHub handles or emails who may loosen the contract or grow the baseline.
64
+ * Metadata — excluded from policy hash. Absence means no steward lock (policy-ack still applies).
65
+ */
66
+ stewards?: string[];
62
67
  };
63
68
  type ArkConfigIssue = {
64
69
  path: string;
@@ -1,3 +1,3 @@
1
- "use strict";var Oe=Object.create;var N=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var Te=(e,t)=>{for(var n in t)N(e,n,{get:t[n],enumerable:!0})},Q=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pe(t))!ve.call(e,s)&&s!==n&&N(e,s,{get:()=>t[s],enumerable:!(r=_e(t,s))||r.enumerable});return e};var ee=(e,t,n)=>(n=e!=null?Oe($e(e)):{},Q(t||!e||!e.__esModule?N(n,"default",{value:e,enumerable:!0}):n,e)),je=e=>Q(N({},"__esModule",{value:!0}),e);var ut={};Te(ut,{default:()=>pt,findConfigPath:()=>T,globToRegExp:()=>E,isEdgeDenied:()=>F,layerForRelativePath:()=>R,loadArkConfig:()=>j,noDeniedCapabilities:()=>Ne,noDomainInfraImports:()=>we,noForbiddenGlobals:()=>Le,noRawEventPublish:()=>Ee,patternSpecificity:()=>M,plugin:()=>v,readTsconfigPathAliases:()=>be,requirePublishSource:()=>Ce,resolveImportSpecifier:()=>Se,resolveRelativeImport:()=>Ae});module.exports=je(ut);var k=ee(require("fs"),1),p=ee(require("path"),1);var te=new Map;function ne(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function O(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function De(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function E(e){let t=te.get(e);if(t)return t;let n=O(e),r=De(n),s="",i=0;for(let c=0;c<n.length;c+=1){let g=n[c];g==="\\"&&c+1<n.length?(s+=ne(n[c+1]),c+=1):g==="*"?n[c+1]==="*"?n[c+2]==="/"?(s+="(?:.*/)?",c+=2):(s+=".*",c+=1):s+="[^/]*":g==="?"?s+="[^/]":g==="{"&&r?(s+="(?:",i+=1):g==="}"&&r&&i>0?(s+=")",i-=1):g===","&&r&&i>0?s+="|":s+=ne(g)}let a=new RegExp(`^${s}$`);return te.set(e,a),a}function Me(e){return O(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function M(e,t){let n=O(String(e)),r=Me(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let c=0,g=-1;for(let f of r){let d=-1;for(let o=c;o<a.length;o+=1)if(a[o]===f){d=o;break}if(d<0)return i;g=d,c=d+1}return(g+1)*1e6+r.length*1e4+s}function R(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>E(a).test(n))){for(let a of i.patterns??[])if(E(a).test(n)){let c=M(a,n);c>s&&(s=c,r=i.name)}}return r}function re(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function Ve(e){let t=new Set;for(let n of e??[]){let s=O(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let c=s[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Fe(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return Ve(r?.patterns)}function Ke(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function V(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath,c=Fe(s,t,r?.layers),g=i&&a?re(i,c):void 0,f=i&&a?re(a,c):void 0;if(Ke({fromPath:i,toPath:a,folderCount:c.length,fromSlice:g,toSlice:f}))return s;continue}if(t!==n)return s}}function F(e,t,n,r){return V(e,t,n,r)!==void 0}var He=["**/*.gen.ts","**/*.gen.tsx","**/*.generated.ts","**/*.generated.tsx"];function Ge(e){let t=Array.isArray(e?.exclude)?e.exclude.filter(r=>typeof r=="string"):[];return[...e?.excludeGenerated===!1?[]:He,...t]}function se(e,t){let n=String(e).split(/[/\\]/).join("/");return Ge(t).some(r=>E(r).test(n))}var oe=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Be=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),mt=Object.freeze(Object.keys(Be).sort()),K=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"}),Ue=Object.freeze({process:Object.freeze(["process","node:process"])});function ie(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=K[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=K[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:K[e.slice(0,i)]??null}function H(e,t){for(let n of t)if(Ue[n]?.includes(e))return n;return null}function ae(e){if(e?.pure===!0)return[...oe].sort();let n=(e?.capabilities?.deny??[]).filter(r=>oe.includes(r));return[...new Set(n)].sort()}var G="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",le=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],qe=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function We(){let e=[];for(let t of le)for(let n of le)t===n||qe.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var de=We(),B=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],I={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ce={$schema:"https://json-schema.org/draft/2020-12/schema",$id:G,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:G,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...I,minItems:1,default:["src"]},exclude:{...I,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:{...I,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...I,minItems:1},exclude:I,intentPrefixes:I,description:{type:"string",minLength:1},forbiddenGlobals:I,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:{...I,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}}}}},S=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
1
+ "use strict";var Oe=Object.create;var N=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var Te=(e,t)=>{for(var n in t)N(e,n,{get:t[n],enumerable:!0})},Q=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pe(t))!ve.call(e,s)&&s!==n&&N(e,s,{get:()=>t[s],enumerable:!(r=_e(t,s))||r.enumerable});return e};var ee=(e,t,n)=>(n=e!=null?Oe($e(e)):{},Q(t||!e||!e.__esModule?N(n,"default",{value:e,enumerable:!0}):n,e)),je=e=>Q(N({},"__esModule",{value:!0}),e);var ut={};Te(ut,{default:()=>pt,findConfigPath:()=>T,globToRegExp:()=>E,isEdgeDenied:()=>F,layerForRelativePath:()=>R,loadArkConfig:()=>j,noDeniedCapabilities:()=>Ne,noDomainInfraImports:()=>we,noForbiddenGlobals:()=>Le,noRawEventPublish:()=>Ee,patternSpecificity:()=>M,plugin:()=>v,readTsconfigPathAliases:()=>be,requirePublishSource:()=>Ce,resolveImportSpecifier:()=>Se,resolveRelativeImport:()=>Ae});module.exports=je(ut);var I=ee(require("fs"),1),p=ee(require("path"),1);var te=new Map;function ne(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function O(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,n+=1;continue}t+="/";continue}t+=r}return t}function De(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function E(e){let t=te.get(e);if(t)return t;let n=O(e),r=De(n),s="",i=0;for(let c=0;c<n.length;c+=1){let g=n[c];g==="\\"&&c+1<n.length?(s+=ne(n[c+1]),c+=1):g==="*"?n[c+1]==="*"?n[c+2]==="/"?(s+="(?:.*/)?",c+=2):(s+=".*",c+=1):s+="[^/]*":g==="?"?s+="[^/]":g==="{"&&r?(s+="(?:",i+=1):g==="}"&&r&&i>0?(s+=")",i-=1):g===","&&r&&i>0?s+="|":s+=ne(g)}let a=new RegExp(`^${s}$`);return te.set(e,a),a}function Me(e){return O(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}function M(e,t){let n=O(String(e)),r=Me(n),s=n.replace(/\*/g,"").length,i=r.length*1e4+s;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return s;let c=0,g=-1;for(let f of r){let d=-1;for(let o=c;o<a.length;o+=1)if(a[o]===f){d=o;break}if(d<0)return i;g=d,c=d+1}return(g+1)*1e6+r.length*1e4+s}function R(e,t){let n=String(e).split(/[/\\]/).join("/"),r,s=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>E(a).test(n))){for(let a of i.patterns??[])if(E(a).test(n)){let c=M(a,n);c>s&&(s=c,r=i.name)}}return r}function re(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(s=>String(s).toLowerCase()));for(let s=0;s<n.length-1;s+=1)if(r.has(n[s].toLowerCase()))return`${n[s].toLowerCase()}/${n[s+1].toLowerCase()}`}function Ve(e){let t=new Set;for(let n of e??[]){let s=O(String(n)).split("/").filter(Boolean);for(let i=0;i<s.length;i+=1){let a=s[i];if((a==="**"||a==="*")&&i>0){let c=s[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function Fe(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(s=>typeof s=="string"&&s.length>0);let r=(n??[]).find(s=>s.name===t);return Ve(r?.patterns)}function Ke(e){return!e.fromPath||!e.toPath||e.folderCount<=0||!e.fromSlice||!e.toSlice?!0:e.fromSlice!==e.toSlice}function V(e,t,n,r){for(let s of e??[])if(!(s.from!==t||s.to!==n)&&s.allowed===!1){if(s.peerIsolation){let i=r?.fromPath,a=r?.toPath,c=Fe(s,t,r?.layers),g=i&&a?re(i,c):void 0,f=i&&a?re(a,c):void 0;if(Ke({fromPath:i,toPath:a,folderCount:c.length,fromSlice:g,toSlice:f}))return s;continue}if(t!==n)return s}}function F(e,t,n,r){return V(e,t,n,r)!==void 0}var He=["**/*.gen.ts","**/*.gen.tsx","**/*.generated.ts","**/*.generated.tsx"];function Ge(e){let t=Array.isArray(e?.exclude)?e.exclude.filter(r=>typeof r=="string"):[];return[...e?.excludeGenerated===!1?[]:He,...t]}function se(e,t){let n=String(e).split(/[/\\]/).join("/");return Ge(t).some(r=>E(r).test(n))}var oe=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Be=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),mt=Object.freeze(Object.keys(Be).sort()),K=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"}),Ue=Object.freeze({process:Object.freeze(["process","node:process"])});function ie(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=K[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),s=K[r];if(s)return s;let i=e.indexOf("/",n+1);return i<0?null:K[e.slice(0,i)]??null}function H(e,t){for(let n of t)if(Ue[n]?.includes(e))return n;return null}function ae(e){if(e?.pure===!0)return[...oe].sort();let n=(e?.capabilities?.deny??[]).filter(r=>oe.includes(r));return[...new Set(n)].sort()}var G="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",le=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],qe=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function We(){let e=[];for(let t of le)for(let n of le)t===n||qe.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var de=We(),B=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"}],S={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ce={$schema:"https://json-schema.org/draft/2020-12/schema",$id:G,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:G,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.1",default:"1.1"},name:{type:"string",minLength:1},include:{...S,minItems:1,default:["src"]},exclude:{...S,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:{...S,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},stewards:{...S,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...S,minItems:1},exclude:S,intentPrefixes:S,description:{type:"string",minLength:1},forbiddenGlobals:S,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:{...S,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}}}}},k=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
2
2
  ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
3
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function x(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ye(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function C(e,t,n,r,s){if(t.$ref){let i=Ye(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}C(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!pe(e)){s.push({path:n,message:`must be an object; received ${x(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:_(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:_(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in i||C(e[c],a,_(n,c),r,s)}for(let[a,c]of Object.entries(i))e[a]!==void 0&&C(e[a],c,_(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${x(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>C(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${x(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${x(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${x(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Je(e){return{...e,$schema:e.$schema===void 0?G:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":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 ze(){let e=new Set(["1.1"]);for(let t of B)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function Ze(e,t="ark.config.json"){if(!pe(e))throw new S(t,[{path:"$",message:`must be an object; received ${x(e)}`}]);let n=ze(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<B.length+1;){a+=1;let g=B.find(f=>f.from===s);if(!g)throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=g.to,i.schemaVersion=s}if(s!=="1.1")throw new S(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let c=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Je(i),migratedFrom:c}}function Xe(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ze(e,t),s=[];if(C(n,ce,"$",ce,s),s.length>0)throw new S(t,s);return{config:n,migratedFrom:r}}function ue(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new S(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Xe(n,t)}var Qe="docs/diagnostics.md";function h(e){return typeof e=="string"&&e.length>0?e:void 0}function fe(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function et(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function tt(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 nt(e){return`${Qe}#${e}`}function rt(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return 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, test at the public interface, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, test at the public interface, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${h(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ge(e,t="error",n){let r=h(e.ruleId)??h(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...h(e.target)?{target:h(e.target)}:{},...h(e.fromLayer)?{fromLayer:h(e.fromLayer)}:{},...h(e.toLayer)?{toLayer:h(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}:{},...h(e.capability)?{capability:h(e.capability)}:{},...h(e.edgeKind)?{edgeKind:h(e.edgeKind)}:{},...h(e.arkruleId)?{arkruleId:h(e.arkruleId)}:{},...h(e.arkruleSource)?{arkruleSource:h(e.arkruleSource)}:{}},a=n??et(e),c=tt(a);return{ruleId:r,severity:s,message:h(e.message)??r,location:{file:h(e.file)??"<unknown>",line:fe(e.line,1),column:fe(e.column,1)},evidence:i,nextAction:h(e.nextAction)??rt(r,i,e),findingRef:c,targetKey:a,docsCodePath:nt(r)}}var me={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."},At=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 st(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function U(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&st(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:me.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:me.PUBLISH_MISSING_SOURCE}),t}function L(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}function w(e,t,n,r,s){let i=ge({...r,line:r.line??t.loc?.start?.line,column:r.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:n,...s?{data:s}:{},diagnostic:i}),i}function T(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=p.default.dirname(p.default.resolve(e));for(;;){let n=p.default.join(t,"ark.config.json");if(k.default.existsSync(n))return n;let r=p.default.dirname(t);if(r===t)return null;t=r}}var ye=new Map;function j(e){if(!k.default.existsSync(e))return null;let t=k.default.readFileSync(e,"utf8"),n=ye.get(e);if(n?.source===t)return n.config;let r=ue(t,e).config;return ye.set(e,{source:t,config:r}),r}function W(e,t){return(e.include??[]).some(r=>{let s=String(r).replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");return s==="."||t===s||t.startsWith(`${s}/`)})&&!se(t,e)}function he(e){let t=[e,`${e}.ts`,`${e}.tsx`,`${e}.mts`,`${e}.cts`,`${e}.js`,`${e}.jsx`,p.default.join(e,"index.ts"),p.default.join(e,"index.tsx"),p.default.join(e,"index.js")];for(let n of t)try{if(k.default.existsSync(n)&&k.default.statSync(n).isFile())return n}catch{}return null}function be(e){let t=p.default.resolve(e),n=null;for(;;){let f=p.default.join(t,"tsconfig.json");if(k.default.existsSync(f)){n=f;break}let d=p.default.dirname(t);if(d===t)break;t=d}if(!n)return{baseUrl:e,aliases:[]};let r=f=>{try{let d=k.default.readFileSync(f,"utf8");return d=d.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1"),JSON.parse(d)}catch{return null}},s=(f,d)=>{if(d>4)return{};let o=r(f);if(!o)return{};let l=o.compilerOptions??{},u=l.baseUrl,m=l.paths,y=o.extends;if(typeof y=="string"&&!y.startsWith("@")){let b=p.default.resolve(p.default.dirname(f),y.endsWith(".json")?y:`${y}.json`);if(k.default.existsSync(b)){let A=s(b,d+1);u=u??A.baseUrl,m={...A.paths??{},...m??{}}}}return{baseUrl:u,paths:m}},i=s(n,0),a=p.default.dirname(n),c=p.default.resolve(a,i.baseUrl||"."),g=[];for(let[f,d]of Object.entries(i.paths||{})){if(!Array.isArray(d)||d.length===0)continue;let o=f.replace(/\*$/,"");o&&g.push({from:o,to:String(d[0]).replace(/\*$/,"")})}return g.sort((f,d)=>d.from.length-f.from.length),{baseUrl:c,aliases:g}}function Ae(e,t){if(!t.startsWith("."))return null;let n=p.default.resolve(p.default.dirname(e),t);return he(n)}function Se(e,t,n){if(!t)return null;if(t.startsWith("."))return Ae(e,t);let r=n||p.default.dirname(e),{baseUrl:s,aliases:i}=be(r),a=i.find(g=>t.startsWith(g.from));if(!a)return null;let c=p.default.resolve(s,`${a.to}${t.slice(a.from.length)}`);return he(c)}function D(e){return typeof e?.value=="string"?e.value:void 0}function Y(e){return e?.name??D(e)}function J(e){return e.sourceCode??e.getSourceCode?.()}function ke(e,t){let n=J(e)?.getScope?.(t);for(;n;){let r=n.references?.find(s=>s.identifier===t);if(r)return r;n=n.upper??void 0}}function P(e,t,n){let r=ke(e,t);if(r?.resolved)return(r.resolved.defs?.length??0)>0;let s=J(e)?.getScope?.(t);for(;s;){let i=s.set?.get(n);if(i)return(i.defs?.length??0)>0;s=s.upper??void 0}return!1}function ot(e,t){let n=ke(e,t);return n?n.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}function Ie(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let n=Ie(e.object),r=Y(e.property);if(!(!n||!r))return{root:n.root,segments:[...n.segments,r]}}function it(e){return Y(e.callee?.property)}function Re(e,t){return e?.properties?.find(n=>Y(n.key)===t)}function $(e,t){return Re(e,t)!==void 0}function at(e){let t=Re(e,"metadata")?.value;return $(t,"source")}function xe(e){return it(e)==="publish"}function q(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(n=>n.type==="ImportSpecifier")?t.every(n=>n.importKind==="type"):t.every(n=>n.exportKind==="type")}function lt(e){let t=e;for(;t?.parent;)t=t.parent;return t?.type==="Program"?t:void 0}function ct(e){let t=lt(e)?.body;if(!t)return!1;let n=!1;for(let r of t){if(r.type==="ImportDeclaration"){if(!q(r))return!1;continue}if(!(r.type==="TSInterfaceDeclaration"||r.type==="TSTypeAliasDeclaration")){if(r.type==="ExportNamedDeclaration"){if(r.declaration){if(r.declaration.type!=="TSInterfaceDeclaration"&&r.declaration.type!=="TSTypeAliasDeclaration")return!1}else if(!q(r))return!1;n=!0;continue}return!1}}return n}var we={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=L(e),n=T(t),r=n?j(n):null,s=n?p.default.dirname(n):null,i=a=>{let c=D(a.source);if(c&&r&&s&&t){let g=p.default.isAbsolute(t)?t:p.default.resolve(t),f=p.default.relative(s,g).split(p.default.sep).join("/");if(!W(r,f))return;let d=R(f,r.layers);if(!d)return;let o=Se(g,c,s);if(!o)return;let l=p.default.relative(s,o).split(p.default.sep).join("/");if(l.startsWith(".."))return;let u=R(l,r.layers);if(!u)return;let m={fromPath:f,toPath:l,layers:r.layers},y=V(r.rules,d,u,m);if(y||F(r.rules,d,u,m)){let b=a.type?.startsWith("Export")?"export":"import",A=q(a),z=!!y?.peerIsolation,Z=A&&!z,X=y?.message??`${d} must not ${b} ${u}.`;w(e,a,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:f,fromLayer:d,toLayer:u,target:l,edgeKind:b,...z?{peerIsolation:!0}:{},...A?{typeOnly:!0}:{},...Z?{severity:"warning"}:{},...ct(a)?{sourcePureTypeModule:!0}:{},message:Z?`${X} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:X},{fromLayer:d,toLayer:u,specifier:c})}return}};return{ImportDeclaration:i,ExportNamedDeclaration:i,ExportAllDeclaration:i}}},Ee={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],r=D(n),s=U({publishCall:xe(t),rawIntentName:r,objectHasIntent:$(n,"intent"),arkPublishCandidate:!1,hasSource:!0});if(s.some(i=>i.ruleId==="RAW_EVENT_PUBLISH")){let i=s.find(a=>a.ruleId==="RAW_EVENT_PUBLISH");w(e,t,"rawPublish",{...i,file:L(e)})}}}}},Ce={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],r=t.arguments?.[2],i=U({publishCall:xe(t),rawIntentName:D(n),objectHasIntent:$(n,"intent"),arkPublishCandidate:!0,hasSource:at(n)||$(r,"source")}).find(a=>a.ruleId==="PUBLISH_MISSING_SOURCE");i&&w(e,t,"missingSource",{...i,file:L(e)})}}}},Le={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` is a standalone fallback when no project config applies."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.',forbiddenModule:'{{layer}} must not use module "{{specifier}}" because it is the import form of forbidden global "{{name}}".'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=L(e),n=e.options?.[0],r=T(t),s=r?j(r):null,i=r?p.default.dirname(r):null,a=null,c="this layer";if(s&&i&&t){let o=p.default.isAbsolute(t)?t:p.default.resolve(t),l=p.default.relative(i,o).split(p.default.sep).join("/");if(!W(s,l))return{};let u=s.layers?.find(m=>m.name===R(l,s.layers));u?.forbiddenGlobals?.length?(a=new Set(u.forbiddenGlobals),c=u.name):a=null}else n?.globals&&(a=new Set(n.globals));if(!a)return{};let g=typeof J(e)?.getScope=="function",f=(o,l)=>{let u=p.default.isAbsolute(t)?t:p.default.resolve(t),m=i?p.default.relative(i,u).split(p.default.sep).join("/"):t;w(e,o,s?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:m,fromLayer:c,target:l,message:`${c} must not use the ambient global "${l}".`},{name:l,layer:c})},d=(o,l,u,m)=>{if(u||typeof l!="string")return;let y=H(l,a);if(!y)return;let b=p.default.isAbsolute(t)?t:p.default.resolve(t),A=i?p.default.relative(i,b).split(p.default.sep).join("/"):t;w(e,o,"forbiddenModule",{ruleId:"FORBIDDEN_GLOBAL",file:A,fromLayer:c,target:l,edgeKind:m,message:`${c} must not use module "${l}" because it is the import form of forbidden global "${y}".`},{layer:c,name:y,specifier:l,importKind:m})};return{MemberExpression(o){if(o.parent?.type==="MemberExpression"&&o.parent.object===o)return;let l=Ie(o);if(!l||P(e,l.root,l.segments[0]))return;let u=l.segments[0]==="globalThis",m=u?l.segments.slice(1):l.segments,y;for(let b=m.length;b>=(u?1:2);b-=1){let A=m.slice(0,b).join(".");if(a.has(A)){y=A;break}}y?f(o,y):!g&&a.has(l.segments[0])&&f(o,l.segments[0])},CallExpression(o){let l=o;if(l.callee?.type==="Identifier"&&l.callee.name==="require"&&l.arguments?.[0]?.type==="Literal"&&!P(e,o,"require")&&d(o,l.arguments[0].value,!1,"require"),g)return;let u=l.callee?.type==="Identifier"?l.callee.name:void 0;u&&a.has(u)&&f(o,u)},ImportDeclaration(o){let l=o,u=(l.specifiers??[]).filter(y=>y.type==="ImportSpecifier"),m=u.length>0&&u.length===(l.specifiers??[]).length&&u.every(y=>y.importKind==="type");d(o,l.source?.value,l.importKind==="type"||m,"import")},ImportExpression(o){let l=o;l.source?.type==="Literal"&&d(o,l.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(o){let l=o;d(o,l.moduleReference?.expression?.value,l.importKind==="type"||l.isTypeOnly===!0,"require")},ExportNamedDeclaration(o){let l=o;if(!l.source)return;let u=l.specifiers??[],m=u.length>0&&u.every(y=>y.exportKind==="type");d(o,l.source.value,l.exportKind==="type"||m,"export")},ExportAllDeclaration(o){let l=o;d(o,l.source?.value,l.exportKind==="type","export")},NewExpression(o){if(g)return;let l=o.callee?.type==="Identifier"?o.callee.name:void 0;l&&a.has(l)&&f(o,l)},Identifier(o){!g||!o.name||!a.has(o.name)||!ot(e,o)||P(e,o,o.name)||f(o,o.name)}}}},Ne={meta:{type:"problem",docs:{description:"Disallow importing modules whose effect capability the layer denies (ark.config.json capabilities.deny / pure \u2014 same wall surface as ark-check). Import dimension only: ambient globals stay with no-forbidden-globals and the CLI/hook symbol path."},messages:{deniedCapability:'{{layer}} denies the {{capability}} capability (ark.config.json); "{{specifier}}" imports it. Define a port and bind the implementation in an adapter layer.'},schema:[]},create(e){let t=L(e),n=T(t),r=n?j(n):null,s=n?p.default.dirname(n):null;if(!r||!s||!t)return{};let i=p.default.isAbsolute(t)?t:p.default.resolve(t),a=p.default.relative(s,i).split(p.default.sep).join("/");if(!W(r,a))return{};let c=r.layers?.find(d=>d.name===R(a,r.layers));if(!c)return{};let g=new Set(ae(c));if(g.size===0)return{};let f=(d,o,l,u)=>{if(l||typeof o!="string"||H(o,c.forbiddenGlobals??[]))return;let m=ie(o);!m||!g.has(m)||w(e,d,"deniedCapability",{ruleId:"CAPABILITY_VIOLATION",file:a,fromLayer:c.name,target:o,capability:m,edgeKind:u,message:`${c.name} denies the ${m} capability; found import of "${o}".`},{layer:c.name,capability:m,specifier:o})};return{ImportDeclaration(d){let o=d,l=(o.specifiers??[]).filter(m=>m.type==="ImportSpecifier"),u=l.length>0&&l.length===(o.specifiers??[]).length&&l.every(m=>m.importKind==="type");f(d,o.source?.value,o.importKind==="type"||u,"import")},ImportExpression(d){let o=d;o.source?.type==="Literal"&&f(d,o.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(d){let o=d;f(d,o.moduleReference?.expression?.value,o.importKind==="type"||o.isTypeOnly===!0,"require")},ExportNamedDeclaration(d){let o=d;if(!o.source)return;let l=o.specifiers??[],u=l.length>0&&l.every(m=>m.exportKind==="type");f(d,o.source.value,o.exportKind==="type"||u,"export")},ExportAllDeclaration(d){let o=d;f(d,o.source?.value,o.exportKind==="type","export")},CallExpression(d){let o=d;o.callee?.type==="Identifier"&&o.callee.name==="require"&&o.arguments?.[0]?.type==="Literal"&&!P(e,d,"require")&&f(d,o.arguments[0].value,!1,"require")}}}},dt={"no-domain-infra-imports":we,"no-raw-event-publish":Ee,"require-publish-source":Ce,"no-forbidden-globals":Le,"no-denied-capabilities":Ne},v={rules:dt};v.configs={recommended:{plugins:{ark:v},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error","ark/no-denied-capabilities":"error"}}};var pt=v;0&&(module.exports={findConfigPath,globToRegExp,isEdgeDenied,layerForRelativePath,loadArkConfig,noDeniedCapabilities,noDomainInfraImports,noForbiddenGlobals,noRawEventPublish,patternSpecificity,plugin,readTsconfigPathAliases,requirePublishSource,resolveImportSpecifier,resolveRelativeImport});
3
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function x(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ye(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function C(e,t,n,r,s){if(t.$ref){let i=Ye(t.$ref,r);if(!i){s.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}C(e,i,n,r,s);return}if(t.const!==void 0&&!Object.is(e,t.const)){s.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){s.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!pe(e)){s.push({path:n,message:`must be an object; received ${x(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&s.push({path:_(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||s.push({path:_(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let c of Object.keys(e))c in i||C(e[c],a,_(n,c),r,s)}for(let[a,c]of Object.entries(i))e[a]!==void 0&&C(e[a],c,_(n,a),r,s);return}if(t.type==="array"){if(!Array.isArray(e)){s.push({path:n,message:`must be an array; received ${x(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&s.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&s.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>C(i,t.items,`${n}[${a}]`,r,s));return}if(t.type==="string"){if(typeof e!="string"){s.push({path:n,message:`must be a string; received ${x(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&s.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&s.push({path:n,message:`must be a boolean; received ${x(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){s.push({path:n,message:`must be an integer; received ${x(e)}`});return}t.minimum!==void 0&&e<t.minimum&&s.push({path:n,message:`must be at least ${t.minimum}`})}}function Je(e){return{...e,$schema:e.$schema===void 0?G:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.1":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 ze(){let e=new Set(["1.1"]);for(let t of B)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}function Ze(e,t="ark.config.json"){if(!pe(e))throw new k(t,[{path:"$",message:`must be an object; received ${x(e)}`}]);let n=ze(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.1`}]);if(r!=="unversioned"&&!n.has(r))throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let s=r,i={...e},a=0;for(;s!=="1.1"&&a<B.length+1;){a+=1;let g=B.find(f=>f.from===s);if(!g)throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(s)}; expected 1.1`}]);s=g.to,i.schemaVersion=s}if(s!=="1.1")throw new k(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected 1.1`}]);let c=r==="unversioned"?"unversioned":r==="1.0"?"1.0":null;return{candidate:Je(i),migratedFrom:c}}function Xe(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ze(e,t),s=[];if(C(n,ce,"$",ce,s),s.length>0)throw new k(t,s);return{config:n,migratedFrom:r}}function ue(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new k(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Xe(n,t)}var Qe="docs/diagnostics.md";function h(e){return typeof e=="string"&&e.length>0?e:void 0}function fe(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function et(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,s=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",s??"",i??""].join("|")}function tt(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 nt(e){return`${Qe}#${e}`}function rt(e,t,n){if(e==="LAYER_IMPORT_VIOLATION")return 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, test at the public interface, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`;if(e==="FORBIDDEN_GLOBAL")return`Inject ${t.target??"the capability"} through a port, test at the public interface, then preflight again.`;if(e==="CAPABILITY_VIOLATION")return`Define a ${h(n.capability)??"capability"} port in ${t.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;if(e==="CIRCULAR_DEPENDENCY")return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";if(e==="RAW_EVENT_PUBLISH")return"Publish through a registered intent creator, then run Ark again.";if(e==="PUBLISH_MISSING_SOURCE")return"Add metadata.source to the publish call, then run Ark again.";if(e==="ARKRULE_STRUCTURE"||e==="ARKRULE_INVARIANT"||e==="INVARIANT_UNCOVERED"||e.startsWith("ARKRULE_")){let r=t.arkruleSource??"arkrules/<Layer>.json";return`Fix the structure or invariant for ${t.arkruleId??"the ArkRule"} (declared in ${r}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`}return`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ge(e,t="error",n){let r=h(e.ruleId)??h(e.code)??"ARK_UNKNOWN",s=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...h(e.target)?{target:h(e.target)}:{},...h(e.fromLayer)?{fromLayer:h(e.fromLayer)}:{},...h(e.toLayer)?{toLayer:h(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}:{},...h(e.capability)?{capability:h(e.capability)}:{},...h(e.edgeKind)?{edgeKind:h(e.edgeKind)}:{},...h(e.arkruleId)?{arkruleId:h(e.arkruleId)}:{},...h(e.arkruleSource)?{arkruleSource:h(e.arkruleSource)}:{}},a=n??et(e),c=tt(a);return{ruleId:r,severity:s,message:h(e.message)??r,location:{file:h(e.file)??"<unknown>",line:fe(e.line,1),column:fe(e.column,1)},evidence:i,nextAction:h(e.nextAction)??rt(r,i,e),findingRef:c,targetKey:a,docsCodePath:nt(r)}}var me={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."},At=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 st(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function U(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&st(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:me.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:me.PUBLISH_MISSING_SOURCE}),t}function L(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}function w(e,t,n,r,s){let i=ge({...r,line:r.line??t.loc?.start?.line,column:r.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:n,...s?{data:s}:{},diagnostic:i}),i}function T(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=p.default.dirname(p.default.resolve(e));for(;;){let n=p.default.join(t,"ark.config.json");if(I.default.existsSync(n))return n;let r=p.default.dirname(t);if(r===t)return null;t=r}}var ye=new Map;function j(e){if(!I.default.existsSync(e))return null;let t=I.default.readFileSync(e,"utf8"),n=ye.get(e);if(n?.source===t)return n.config;let r=ue(t,e).config;return ye.set(e,{source:t,config:r}),r}function W(e,t){return(e.include??[]).some(r=>{let s=String(r).replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");return s==="."||t===s||t.startsWith(`${s}/`)})&&!se(t,e)}function he(e){let t=[e,`${e}.ts`,`${e}.tsx`,`${e}.mts`,`${e}.cts`,`${e}.js`,`${e}.jsx`,p.default.join(e,"index.ts"),p.default.join(e,"index.tsx"),p.default.join(e,"index.js")];for(let n of t)try{if(I.default.existsSync(n)&&I.default.statSync(n).isFile())return n}catch{}return null}function be(e){let t=p.default.resolve(e),n=null;for(;;){let f=p.default.join(t,"tsconfig.json");if(I.default.existsSync(f)){n=f;break}let d=p.default.dirname(t);if(d===t)break;t=d}if(!n)return{baseUrl:e,aliases:[]};let r=f=>{try{let d=I.default.readFileSync(f,"utf8");return d=d.replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1"),JSON.parse(d)}catch{return null}},s=(f,d)=>{if(d>4)return{};let o=r(f);if(!o)return{};let l=o.compilerOptions??{},u=l.baseUrl,m=l.paths,y=o.extends;if(typeof y=="string"&&!y.startsWith("@")){let b=p.default.resolve(p.default.dirname(f),y.endsWith(".json")?y:`${y}.json`);if(I.default.existsSync(b)){let A=s(b,d+1);u=u??A.baseUrl,m={...A.paths??{},...m??{}}}}return{baseUrl:u,paths:m}},i=s(n,0),a=p.default.dirname(n),c=p.default.resolve(a,i.baseUrl||"."),g=[];for(let[f,d]of Object.entries(i.paths||{})){if(!Array.isArray(d)||d.length===0)continue;let o=f.replace(/\*$/,"");o&&g.push({from:o,to:String(d[0]).replace(/\*$/,"")})}return g.sort((f,d)=>d.from.length-f.from.length),{baseUrl:c,aliases:g}}function Ae(e,t){if(!t.startsWith("."))return null;let n=p.default.resolve(p.default.dirname(e),t);return he(n)}function Se(e,t,n){if(!t)return null;if(t.startsWith("."))return Ae(e,t);let r=n||p.default.dirname(e),{baseUrl:s,aliases:i}=be(r),a=i.find(g=>t.startsWith(g.from));if(!a)return null;let c=p.default.resolve(s,`${a.to}${t.slice(a.from.length)}`);return he(c)}function D(e){return typeof e?.value=="string"?e.value:void 0}function Y(e){return e?.name??D(e)}function J(e){return e.sourceCode??e.getSourceCode?.()}function ke(e,t){let n=J(e)?.getScope?.(t);for(;n;){let r=n.references?.find(s=>s.identifier===t);if(r)return r;n=n.upper??void 0}}function P(e,t,n){let r=ke(e,t);if(r?.resolved)return(r.resolved.defs?.length??0)>0;let s=J(e)?.getScope?.(t);for(;s;){let i=s.set?.get(n);if(i)return(i.defs?.length??0)>0;s=s.upper??void 0}return!1}function ot(e,t){let n=ke(e,t);return n?n.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}function Ie(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let n=Ie(e.object),r=Y(e.property);if(!(!n||!r))return{root:n.root,segments:[...n.segments,r]}}function it(e){return Y(e.callee?.property)}function Re(e,t){return e?.properties?.find(n=>Y(n.key)===t)}function $(e,t){return Re(e,t)!==void 0}function at(e){let t=Re(e,"metadata")?.value;return $(t,"source")}function xe(e){return it(e)==="publish"}function q(e){if(e.importKind==="type"||e.exportKind==="type")return!0;let t=e.specifiers??[];return t.length===0?!1:t.every(n=>n.type==="ImportSpecifier")?t.every(n=>n.importKind==="type"):t.every(n=>n.exportKind==="type")}function lt(e){let t=e;for(;t?.parent;)t=t.parent;return t?.type==="Program"?t:void 0}function ct(e){let t=lt(e)?.body;if(!t)return!1;let n=!1;for(let r of t){if(r.type==="ImportDeclaration"){if(!q(r))return!1;continue}if(!(r.type==="TSInterfaceDeclaration"||r.type==="TSTypeAliasDeclaration")){if(r.type==="ExportNamedDeclaration"){if(r.declaration){if(r.declaration.type!=="TSInterfaceDeclaration"&&r.declaration.type!=="TSTypeAliasDeclaration")return!1}else if(!q(r))return!1;n=!0;continue}return!1}}return n}var we={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=L(e),n=T(t),r=n?j(n):null,s=n?p.default.dirname(n):null,i=a=>{let c=D(a.source);if(c&&r&&s&&t){let g=p.default.isAbsolute(t)?t:p.default.resolve(t),f=p.default.relative(s,g).split(p.default.sep).join("/");if(!W(r,f))return;let d=R(f,r.layers);if(!d)return;let o=Se(g,c,s);if(!o)return;let l=p.default.relative(s,o).split(p.default.sep).join("/");if(l.startsWith(".."))return;let u=R(l,r.layers);if(!u)return;let m={fromPath:f,toPath:l,layers:r.layers},y=V(r.rules,d,u,m);if(y||F(r.rules,d,u,m)){let b=a.type?.startsWith("Export")?"export":"import",A=q(a),z=!!y?.peerIsolation,Z=A&&!z,X=y?.message??`${d} must not ${b} ${u}.`;w(e,a,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:f,fromLayer:d,toLayer:u,target:l,edgeKind:b,...z?{peerIsolation:!0}:{},...A?{typeOnly:!0}:{},...Z?{severity:"warning"}:{},...ct(a)?{sourcePureTypeModule:!0}:{},message:Z?`${X} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:X},{fromLayer:d,toLayer:u,specifier:c})}return}};return{ImportDeclaration:i,ExportNamedDeclaration:i,ExportAllDeclaration:i}}},Ee={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],r=D(n),s=U({publishCall:xe(t),rawIntentName:r,objectHasIntent:$(n,"intent"),arkPublishCandidate:!1,hasSource:!0});if(s.some(i=>i.ruleId==="RAW_EVENT_PUBLISH")){let i=s.find(a=>a.ruleId==="RAW_EVENT_PUBLISH");w(e,t,"rawPublish",{...i,file:L(e)})}}}}},Ce={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],r=t.arguments?.[2],i=U({publishCall:xe(t),rawIntentName:D(n),objectHasIntent:$(n,"intent"),arkPublishCandidate:!0,hasSource:at(n)||$(r,"source")}).find(a=>a.ruleId==="PUBLISH_MISSING_SOURCE");i&&w(e,t,"missingSource",{...i,file:L(e)})}}}},Le={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` is a standalone fallback when no project config applies."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.',forbiddenModule:'{{layer}} must not use module "{{specifier}}" because it is the import form of forbidden global "{{name}}".'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=L(e),n=e.options?.[0],r=T(t),s=r?j(r):null,i=r?p.default.dirname(r):null,a=null,c="this layer";if(s&&i&&t){let o=p.default.isAbsolute(t)?t:p.default.resolve(t),l=p.default.relative(i,o).split(p.default.sep).join("/");if(!W(s,l))return{};let u=s.layers?.find(m=>m.name===R(l,s.layers));u?.forbiddenGlobals?.length?(a=new Set(u.forbiddenGlobals),c=u.name):a=null}else n?.globals&&(a=new Set(n.globals));if(!a)return{};let g=typeof J(e)?.getScope=="function",f=(o,l)=>{let u=p.default.isAbsolute(t)?t:p.default.resolve(t),m=i?p.default.relative(i,u).split(p.default.sep).join("/"):t;w(e,o,s?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:m,fromLayer:c,target:l,message:`${c} must not use the ambient global "${l}".`},{name:l,layer:c})},d=(o,l,u,m)=>{if(u||typeof l!="string")return;let y=H(l,a);if(!y)return;let b=p.default.isAbsolute(t)?t:p.default.resolve(t),A=i?p.default.relative(i,b).split(p.default.sep).join("/"):t;w(e,o,"forbiddenModule",{ruleId:"FORBIDDEN_GLOBAL",file:A,fromLayer:c,target:l,edgeKind:m,message:`${c} must not use module "${l}" because it is the import form of forbidden global "${y}".`},{layer:c,name:y,specifier:l,importKind:m})};return{MemberExpression(o){if(o.parent?.type==="MemberExpression"&&o.parent.object===o)return;let l=Ie(o);if(!l||P(e,l.root,l.segments[0]))return;let u=l.segments[0]==="globalThis",m=u?l.segments.slice(1):l.segments,y;for(let b=m.length;b>=(u?1:2);b-=1){let A=m.slice(0,b).join(".");if(a.has(A)){y=A;break}}y?f(o,y):!g&&a.has(l.segments[0])&&f(o,l.segments[0])},CallExpression(o){let l=o;if(l.callee?.type==="Identifier"&&l.callee.name==="require"&&l.arguments?.[0]?.type==="Literal"&&!P(e,o,"require")&&d(o,l.arguments[0].value,!1,"require"),g)return;let u=l.callee?.type==="Identifier"?l.callee.name:void 0;u&&a.has(u)&&f(o,u)},ImportDeclaration(o){let l=o,u=(l.specifiers??[]).filter(y=>y.type==="ImportSpecifier"),m=u.length>0&&u.length===(l.specifiers??[]).length&&u.every(y=>y.importKind==="type");d(o,l.source?.value,l.importKind==="type"||m,"import")},ImportExpression(o){let l=o;l.source?.type==="Literal"&&d(o,l.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(o){let l=o;d(o,l.moduleReference?.expression?.value,l.importKind==="type"||l.isTypeOnly===!0,"require")},ExportNamedDeclaration(o){let l=o;if(!l.source)return;let u=l.specifiers??[],m=u.length>0&&u.every(y=>y.exportKind==="type");d(o,l.source.value,l.exportKind==="type"||m,"export")},ExportAllDeclaration(o){let l=o;d(o,l.source?.value,l.exportKind==="type","export")},NewExpression(o){if(g)return;let l=o.callee?.type==="Identifier"?o.callee.name:void 0;l&&a.has(l)&&f(o,l)},Identifier(o){!g||!o.name||!a.has(o.name)||!ot(e,o)||P(e,o,o.name)||f(o,o.name)}}}},Ne={meta:{type:"problem",docs:{description:"Disallow importing modules whose effect capability the layer denies (ark.config.json capabilities.deny / pure \u2014 same wall surface as ark-check). Import dimension only: ambient globals stay with no-forbidden-globals and the CLI/hook symbol path."},messages:{deniedCapability:'{{layer}} denies the {{capability}} capability (ark.config.json); "{{specifier}}" imports it. Define a port and bind the implementation in an adapter layer.'},schema:[]},create(e){let t=L(e),n=T(t),r=n?j(n):null,s=n?p.default.dirname(n):null;if(!r||!s||!t)return{};let i=p.default.isAbsolute(t)?t:p.default.resolve(t),a=p.default.relative(s,i).split(p.default.sep).join("/");if(!W(r,a))return{};let c=r.layers?.find(d=>d.name===R(a,r.layers));if(!c)return{};let g=new Set(ae(c));if(g.size===0)return{};let f=(d,o,l,u)=>{if(l||typeof o!="string"||H(o,c.forbiddenGlobals??[]))return;let m=ie(o);!m||!g.has(m)||w(e,d,"deniedCapability",{ruleId:"CAPABILITY_VIOLATION",file:a,fromLayer:c.name,target:o,capability:m,edgeKind:u,message:`${c.name} denies the ${m} capability; found import of "${o}".`},{layer:c.name,capability:m,specifier:o})};return{ImportDeclaration(d){let o=d,l=(o.specifiers??[]).filter(m=>m.type==="ImportSpecifier"),u=l.length>0&&l.length===(o.specifiers??[]).length&&l.every(m=>m.importKind==="type");f(d,o.source?.value,o.importKind==="type"||u,"import")},ImportExpression(d){let o=d;o.source?.type==="Literal"&&f(d,o.source.value,!1,"dynamic-import")},TSImportEqualsDeclaration(d){let o=d;f(d,o.moduleReference?.expression?.value,o.importKind==="type"||o.isTypeOnly===!0,"require")},ExportNamedDeclaration(d){let o=d;if(!o.source)return;let l=o.specifiers??[],u=l.length>0&&l.every(m=>m.exportKind==="type");f(d,o.source.value,o.exportKind==="type"||u,"export")},ExportAllDeclaration(d){let o=d;f(d,o.source?.value,o.exportKind==="type","export")},CallExpression(d){let o=d;o.callee?.type==="Identifier"&&o.callee.name==="require"&&o.arguments?.[0]?.type==="Literal"&&!P(e,d,"require")&&f(d,o.arguments[0].value,!1,"require")}}}},dt={"no-domain-infra-imports":we,"no-raw-event-publish":Ee,"require-publish-source":Ce,"no-forbidden-globals":Le,"no-denied-capabilities":Ne},v={rules:dt};v.configs={recommended:{plugins:{ark:v},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error","ark/no-denied-capabilities":"error"}}};var pt=v;0&&(module.exports={findConfigPath,globToRegExp,isEdgeDenied,layerForRelativePath,loadArkConfig,noDeniedCapabilities,noDomainInfraImports,noForbiddenGlobals,noRawEventPublish,patternSpecificity,plugin,readTsconfigPathAliases,requirePublishSource,resolveImportSpecifier,resolveRelativeImport});
@@ -1,4 +1,4 @@
1
- import { A as ArkConfig } from '../configTypes-CC0FEXoF.js';
1
+ import { A as ArkConfig } from '../configTypes-B8uIcLaG.js';
2
2
 
3
3
  /**
4
4
  * Pure layer-glob matching for ark.config.json.