arkgate 3.0.5 → 3.2.0

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 (42) hide show
  1. package/CHANGELOG.md +92 -1
  2. package/README.md +58 -21
  3. package/bin/ark-check.mjs +46 -4
  4. package/bin/ark-mcp.mjs +267 -26
  5. package/bin/ark.mjs +47 -0
  6. package/bin/lib/adapter-contract.mjs +27 -1
  7. package/bin/lib/analysis-engine.mjs +7 -1169
  8. package/bin/lib/ci-and-commands.mjs +4 -0
  9. package/bin/lib/contract-smells.mjs +514 -0
  10. package/bin/lib/doctor-plan.mjs +15 -4
  11. package/bin/lib/host-support-matrix.mjs +6 -2
  12. package/bin/lib/policy-delta-io.mjs +161 -0
  13. package/bin/lib/prepare-change.mjs +186 -0
  14. package/bin/lib/remediation.mjs +24 -0
  15. package/bin/lib/violations.mjs +2 -2
  16. package/bin/lib/write-path-capabilities.mjs +67 -1
  17. package/bin/lib/write-path-detect.mjs +4 -3
  18. package/dist/eslint/index.cjs +3 -977
  19. package/dist/eslint/index.js +3 -931
  20. package/dist/index.cjs +6 -1960
  21. package/dist/index.d.cts +152 -5
  22. package/dist/index.d.ts +152 -5
  23. package/dist/index.js +6 -1908
  24. package/docs/agent-guide.md +39 -5
  25. package/docs/ai-gates.md +17 -15
  26. package/docs/configuration.md +44 -0
  27. package/docs/demos/01-write-gate-self-correction.md +2 -2
  28. package/docs/enthusiast/README.md +5 -1
  29. package/docs/enthusiast/how-to-agent-gates.md +3 -5
  30. package/docs/enthusiast/how-to-policy-pack.md +4 -1
  31. package/docs/enthusiast/reference-archetypes.md +8 -1
  32. package/docs/enthusiast/reference-commands.md +8 -2
  33. package/docs/package-surface.md +12 -2
  34. package/docs/threat-model.md +10 -6
  35. package/package.json +7 -6
  36. package/schemas/ark.analysis-result.schema.json +5 -1
  37. package/schemas/ark.change-map.schema.json +77 -0
  38. package/server.json +3 -3
  39. package/docs/ark-check-example.json +0 -87
  40. package/docs/demos/03-copilot-autopilot.md +0 -93
  41. package/docs/migrate-from-ark-runtime-kernel.md +0 -174
  42. package/docs/production-hardening.md +0 -100
package/dist/index.cjs CHANGED
@@ -1,1960 +1,6 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/gate.ts
21
- var gate_exports = {};
22
- __export(gate_exports, {
23
- ANALYSIS_IR_SCHEMA_VERSION: () => ANALYSIS_IR_SCHEMA_VERSION,
24
- ARK_ANALYSIS_RESULT_SCHEMA: () => ARK_ANALYSIS_RESULT_SCHEMA,
25
- ARK_ANALYSIS_RESULT_SCHEMA_VERSION: () => ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
26
- ARK_CONFIG_SCHEMA: () => ARK_CONFIG_SCHEMA,
27
- ARK_CONFIG_SCHEMA_VERSION: () => ARK_CONFIG_SCHEMA_VERSION,
28
- analyzeChange: () => analyzeChange,
29
- analyzeProject: () => analyzeProject,
30
- collectAnalysisConfigWarnings: () => collectAnalysisConfigWarnings,
31
- collectForbiddenCapabilityUses: () => collectForbiddenCapabilityUses,
32
- createAICodeGate: () => createAICodeGate,
33
- createAdapterResult: () => createAdapterResult,
34
- createArchitectureProfile: () => createArchitectureProfile,
35
- createArchitectureProfileFromArkConfig: () => createArchitectureProfileFromArkConfig,
36
- createElevenLayerArkConfig: () => createElevenLayerArkConfig,
37
- detectArchitectureCycles: () => detectArchitectureCycles,
38
- deterministicHash: () => deterministicHash,
39
- elevenLayerProfile: () => elevenLayerProfile,
40
- evaluateArchitectureGraph: () => evaluateArchitectureGraph,
41
- explainViolation: () => explainViolation,
42
- extractSemanticDependencies: () => extractSemanticDependencies,
43
- loadArkConfigContract: () => loadArkConfigContract,
44
- loadContract: () => loadContract,
45
- parseArkConfigJson: () => parseArkConfigJson,
46
- stableSerialize: () => stableSerialize,
47
- toAdapterDiagnostic: () => toAdapterDiagnostic,
48
- version: () => version
49
- });
50
- module.exports = __toCommonJS(gate_exports);
51
-
52
- // src/version.ts
53
- var version = "3.0.5";
54
-
55
- // src/domain/adapterContract.ts
56
- var ARK_ANALYSIS_RESULT_SCHEMA_VERSION = "1.0";
57
- function text(value) {
58
- return typeof value === "string" && value.length > 0 ? value : void 0;
59
- }
60
- function positiveInteger(value, fallback) {
61
- return Number.isInteger(value) && Number(value) > 0 ? Number(value) : fallback;
62
- }
63
- function toAdapterDiagnostic(violation2, fallbackSeverity = "error") {
64
- const ruleId = text(violation2.ruleId) ?? text(violation2.code) ?? "ARK_UNKNOWN";
65
- const severity = violation2.severity === "warning" ? "warning" : fallbackSeverity;
66
- const evidence = {
67
- ...text(violation2.target) ? { target: text(violation2.target) } : {},
68
- ...text(violation2.fromLayer) ? { fromLayer: text(violation2.fromLayer) } : {},
69
- ...text(violation2.toLayer) ? { toLayer: text(violation2.toLayer) } : {},
70
- ...typeof violation2.typeOnly === "boolean" ? { typeOnly: violation2.typeOnly } : {}
71
- };
72
- return {
73
- ruleId,
74
- severity,
75
- message: text(violation2.message) ?? ruleId,
76
- location: {
77
- file: text(violation2.file) ?? "<unknown>",
78
- line: positiveInteger(violation2.line, 1),
79
- column: positiveInteger(violation2.column, 1)
80
- },
81
- evidence
82
- };
83
- }
84
- function createAdapterResult(input) {
85
- return {
86
- schemaVersion: ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
87
- valid: input.valid,
88
- diagnostics: [
89
- ...(input.violations ?? []).map((item) => toAdapterDiagnostic(item, "error")),
90
- ...(input.warnings ?? []).map((item) => toAdapterDiagnostic(item, "warning"))
91
- ]
92
- };
93
- }
94
- var ARK_ANALYSIS_RESULT_SCHEMA = {
95
- $schema: "https://json-schema.org/draft/2020-12/schema",
96
- $id: "https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",
97
- title: "ArkGate analysis result",
98
- type: "object",
99
- additionalProperties: false,
100
- required: ["schemaVersion", "valid", "diagnostics"],
101
- properties: {
102
- schemaVersion: { const: ARK_ANALYSIS_RESULT_SCHEMA_VERSION },
103
- valid: { type: "boolean" },
104
- diagnostics: {
105
- type: "array",
106
- items: {
107
- type: "object",
108
- additionalProperties: false,
109
- required: ["ruleId", "severity", "message", "location", "evidence"],
110
- properties: {
111
- ruleId: { type: "string", minLength: 1 },
112
- severity: { enum: ["error", "warning"] },
113
- message: { type: "string", minLength: 1 },
114
- location: {
115
- type: "object",
116
- additionalProperties: false,
117
- required: ["file", "line", "column"],
118
- properties: {
119
- file: { type: "string", minLength: 1 },
120
- line: { type: "integer", minimum: 1 },
121
- column: { type: "integer", minimum: 1 }
122
- }
123
- },
124
- evidence: {
125
- type: "object",
126
- additionalProperties: false,
127
- properties: {
128
- target: { type: "string" },
129
- fromLayer: { type: "string" },
130
- toLayer: { type: "string" },
131
- typeOnly: { type: "boolean" }
132
- }
133
- }
134
- }
135
- }
136
- }
137
- }
138
- };
139
-
140
- // src/domain/layerMatch.ts
141
- var regexpCache = /* @__PURE__ */ new Map();
142
- function escapeLiteral(ch) {
143
- return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
144
- }
145
- function normalizeGlobSeparators(pattern) {
146
- let out = "";
147
- for (let i = 0; i < pattern.length; i += 1) {
148
- const c = pattern[i];
149
- if (c === "\\" && i + 1 < pattern.length) {
150
- const next = pattern[i + 1];
151
- if ("*?{}[],".includes(next) || next === "\\") {
152
- out += "\\" + next;
153
- i += 1;
154
- continue;
155
- }
156
- out += "/";
157
- continue;
158
- }
159
- out += c;
160
- }
161
- return out;
162
- }
163
- function bracesBalanced(glob) {
164
- let depth = 0;
165
- for (let i = 0; i < glob.length; i += 1) {
166
- const c = glob[i];
167
- if (c === "\\") {
168
- i += 1;
169
- continue;
170
- }
171
- if (c === "{") depth += 1;
172
- else if (c === "}") {
173
- depth -= 1;
174
- if (depth < 0) return false;
175
- }
176
- }
177
- return depth === 0;
178
- }
179
- function globToRegExp(pattern) {
180
- const cached = regexpCache.get(pattern);
181
- if (cached) return cached;
182
- const glob = normalizeGlobSeparators(pattern);
183
- const useBraces = bracesBalanced(glob);
184
- let out = "";
185
- let braceDepth = 0;
186
- for (let i = 0; i < glob.length; i += 1) {
187
- const c = glob[i];
188
- if (c === "\\" && i + 1 < glob.length) {
189
- out += escapeLiteral(glob[i + 1]);
190
- i += 1;
191
- } else if (c === "*") {
192
- if (glob[i + 1] === "*") {
193
- if (glob[i + 2] === "/") {
194
- out += "(?:.*/)?";
195
- i += 2;
196
- } else {
197
- out += ".*";
198
- i += 1;
199
- }
200
- } else {
201
- out += "[^/]*";
202
- }
203
- } else if (c === "?") {
204
- out += "[^/]";
205
- } else if (c === "{" && useBraces) {
206
- out += "(?:";
207
- braceDepth += 1;
208
- } else if (c === "}" && useBraces && braceDepth > 0) {
209
- out += ")";
210
- braceDepth -= 1;
211
- } else if (c === "," && useBraces && braceDepth > 0) {
212
- out += "|";
213
- } else {
214
- out += escapeLiteral(c);
215
- }
216
- }
217
- const re = new RegExp(`^${out}$`);
218
- regexpCache.set(pattern, re);
219
- return re;
220
- }
221
- function patternSpecificity(pattern) {
222
- const glob = normalizeGlobSeparators(String(pattern));
223
- const beforeWildcard = glob.split("*")[0];
224
- const literalSegments = beforeWildcard.split("/").filter(Boolean).length;
225
- const literalLength = glob.replace(/\*/g, "").length;
226
- return literalSegments * 1e4 + literalLength;
227
- }
228
- function layerForRelativePath(relPath, layers) {
229
- const rel = String(relPath).split(/[/\\]/).join("/");
230
- let bestName;
231
- let bestScore = -1;
232
- for (const layer of layers ?? []) {
233
- if ((layer.exclude ?? []).some((pattern) => globToRegExp(pattern).test(rel))) {
234
- continue;
235
- }
236
- for (const pattern of layer.patterns ?? []) {
237
- if (globToRegExp(pattern).test(rel)) {
238
- const score = patternSpecificity(pattern);
239
- if (score > bestScore) {
240
- bestScore = score;
241
- bestName = layer.name;
242
- }
243
- }
244
- }
245
- }
246
- return bestName;
247
- }
248
- function sliceIdForPath(relPath, sliceFolders) {
249
- if (!sliceFolders?.length) return void 0;
250
- const parts = String(relPath).split(/[/\\]/).filter(Boolean);
251
- const folders = new Set(sliceFolders.map((s) => String(s).toLowerCase()));
252
- for (let i = 0; i < parts.length - 1; i += 1) {
253
- if (folders.has(parts[i].toLowerCase())) {
254
- return `${parts[i]}/${parts[i + 1]}`;
255
- }
256
- }
257
- return void 0;
258
- }
259
- function inferSliceFoldersFromPatterns(patterns) {
260
- const out = /* @__PURE__ */ new Set();
261
- for (const pattern of patterns ?? []) {
262
- const glob = normalizeGlobSeparators(String(pattern));
263
- const parts = glob.split("/").filter(Boolean);
264
- for (let i = 0; i < parts.length; i += 1) {
265
- const part = parts[i];
266
- if ((part === "**" || part === "*") && i > 0) {
267
- const prev = parts[i - 1];
268
- if (prev && !prev.includes("*") && !prev.includes("{") && !prev.includes("}")) {
269
- out.add(prev);
270
- }
271
- }
272
- }
273
- }
274
- return [...out];
275
- }
276
- function resolveSliceFolders(rule, layerName, layers) {
277
- if (Array.isArray(rule.sliceFolders) && rule.sliceFolders.length > 0) {
278
- return rule.sliceFolders.filter((s) => typeof s === "string" && s.length > 0);
279
- }
280
- const layer = (layers ?? []).find((l) => l.name === layerName);
281
- return inferSliceFoldersFromPatterns(layer?.patterns);
282
- }
283
- function findDeniedEdgeRule(rules, from, to, options) {
284
- for (const rule of rules ?? []) {
285
- if (rule.from !== from || rule.to !== to) continue;
286
- if (rule.allowed !== false) continue;
287
- if (rule.peerIsolation) {
288
- const fromPath = options?.fromPath;
289
- const toPath = options?.toPath;
290
- if (!fromPath || !toPath) continue;
291
- const folders = resolveSliceFolders(rule, from, options?.layers);
292
- if (folders.length === 0) continue;
293
- const fromSlice = sliceIdForPath(fromPath, folders);
294
- const toSlice = sliceIdForPath(toPath, folders);
295
- if (!fromSlice || !toSlice) continue;
296
- if (fromSlice !== toSlice) return rule;
297
- continue;
298
- }
299
- if (from === to) continue;
300
- return rule;
301
- }
302
- return void 0;
303
- }
304
-
305
- // src/domain/sourcePolicy.ts
306
- var SOURCE_POLICY_MESSAGES = {
307
- RAW_EVENT_PUBLISH: "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",
308
- PUBLISH_MISSING_SOURCE: "Strict Ark publish calls must include metadata.source."
309
- };
310
- function looksLikeArkIntent(value) {
311
- return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(
312
- value
313
- );
314
- }
315
- function classifyPublishFacts(facts) {
316
- if (!facts.publishCall) return [];
317
- const findings = [];
318
- if (facts.rawIntentName !== void 0 && looksLikeArkIntent(facts.rawIntentName) || facts.objectHasIntent) {
319
- findings.push({
320
- ruleId: "RAW_EVENT_PUBLISH",
321
- message: SOURCE_POLICY_MESSAGES.RAW_EVENT_PUBLISH
322
- });
323
- }
324
- if (facts.arkPublishCandidate && !facts.hasSource) {
325
- findings.push({
326
- ruleId: "PUBLISH_MISSING_SOURCE",
327
- message: SOURCE_POLICY_MESSAGES.PUBLISH_MISSING_SOURCE
328
- });
329
- }
330
- return findings;
331
- }
332
-
333
- // src/kernel/semanticAnalysis.ts
334
- function literalText(ts, node) {
335
- return node && ts.isStringLiteralLike(node) ? node.text : void 0;
336
- }
337
- function lineOf(sourceFile, node) {
338
- return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
339
- }
340
- function isTypeOnlyReference(ts, node) {
341
- if (ts.isImportDeclaration(node)) {
342
- const clause = node.importClause;
343
- if (!clause) return false;
344
- if (clause.isTypeOnly) return true;
345
- const named = clause.namedBindings;
346
- return Boolean(
347
- named && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((element) => element.isTypeOnly)
348
- );
349
- }
350
- if (ts.isExportDeclaration(node)) {
351
- if (node.isTypeOnly) return true;
352
- const clause = node.exportClause;
353
- return Boolean(
354
- clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly)
355
- );
356
- }
357
- return false;
358
- }
359
- function singleFileChecker(ts, sourceFile) {
360
- const options = { noLib: true, noResolve: true, target: ts.ScriptTarget.Latest };
361
- const host = ts.createCompilerHost(options, true);
362
- host.getSourceFile = (fileName) => fileName === sourceFile.fileName ? sourceFile : void 0;
363
- host.fileExists = (fileName) => fileName === sourceFile.fileName;
364
- host.readFile = (fileName) => fileName === sourceFile.fileName ? sourceFile.text : void 0;
365
- return ts.createProgram([sourceFile.fileName], options, host).getTypeChecker();
366
- }
367
- function symbolAt(checker, node) {
368
- try {
369
- return checker.getSymbolAtLocation(node);
370
- } catch {
371
- return void 0;
372
- }
373
- }
374
- function localDeclaration(ts, checker, sourceFile, node) {
375
- const shorthand = node.parent && ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
376
- let symbol;
377
- try {
378
- symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(node.parent) : symbolAt(checker, node);
379
- } catch {
380
- symbol = void 0;
381
- }
382
- return Boolean(
383
- symbol?.declarations?.some(
384
- (declaration) => declaration.getSourceFile().fileName === sourceFile.fileName
385
- )
386
- );
387
- }
388
- function extractSemanticDependencies(ts, sourceFile) {
389
- let checker;
390
- const dependencies = [];
391
- const add = (node, kind, specifier, typeOnly = false) => dependencies.push({
392
- specifier,
393
- kind,
394
- line: lineOf(sourceFile, node),
395
- typeOnly,
396
- unresolved: specifier === void 0,
397
- node
398
- });
399
- const visit = (node) => {
400
- if (ts.isImportDeclaration(node)) {
401
- add(node, "import", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
402
- } else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
403
- add(node, "export", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
404
- } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
405
- add(node, "require", literalText(ts, node.moduleReference.expression));
406
- } else if (ts.isCallExpression(node)) {
407
- const dynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
408
- const requireCall = ts.isIdentifier(node.expression) && node.expression.text === "require";
409
- const directRequire = requireCall && !localDeclaration(
410
- ts,
411
- checker ?? (checker = singleFileChecker(ts, sourceFile)),
412
- sourceFile,
413
- node.expression
414
- );
415
- if (dynamicImport || directRequire) {
416
- add(node, directRequire ? "require" : "dynamic-import", literalText(ts, node.arguments[0]));
417
- }
418
- }
419
- ts.forEachChild(node, visit);
420
- };
421
- visit(sourceFile);
422
- return dependencies;
423
- }
424
- function staticAccessPath(ts, node) {
425
- const segments = [];
426
- let current = node;
427
- while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) {
428
- if (ts.isPropertyAccessExpression(current)) segments.unshift(current.name.text);
429
- else {
430
- const property = literalText(ts, current.argumentExpression);
431
- if (property === void 0) return void 0;
432
- segments.unshift(property);
433
- }
434
- current = current.expression;
435
- }
436
- if (!ts.isIdentifier(current)) return void 0;
437
- segments.unshift(current.text);
438
- return { root: current, segments };
439
- }
440
- function runtimeIdentifierReference(ts, node) {
441
- const parent = node.parent;
442
- if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) return false;
443
- return ts.isExpressionNode(node) && !ts.isInTypeQuery(node) || ts.isShorthandPropertyAssignment(parent) && parent.name === node;
444
- }
445
- function bestForbiddenMatch(entries, segments) {
446
- const normalized = segments[0] === "globalThis" ? segments.slice(1) : segments;
447
- for (let length = normalized.length; length >= 1; length -= 1) {
448
- const candidate = normalized.slice(0, length).join(".");
449
- if (entries.has(candidate)) return candidate;
450
- }
451
- return void 0;
452
- }
453
- function collectForbiddenCapabilityUses(ts, sourceFile, forbidden) {
454
- if (forbidden.length === 0) return [];
455
- const entries = new Set(forbidden);
456
- const checker = singleFileChecker(ts, sourceFile);
457
- const aliases = /* @__PURE__ */ new Map();
458
- const topLevelNames = /* @__PURE__ */ new Set();
459
- for (const statement of sourceFile.statements) {
460
- if (ts.isVariableStatement(statement)) {
461
- for (const declaration of statement.declarationList.declarations) {
462
- if (ts.isIdentifier(declaration.name)) topLevelNames.add(declaration.name.text);
463
- }
464
- }
465
- }
466
- const resolvePath = (node) => {
467
- const path = staticAccessPath(ts, node);
468
- if (!path) return void 0;
469
- const symbol = symbolAt(checker, path.root);
470
- const alias = symbol ? aliases.get(symbol) : void 0;
471
- if (alias) return [...alias, ...path.segments.slice(1)];
472
- return localDeclaration(ts, checker, sourceFile, path.root) || topLevelNames.has(path.root.text) ? void 0 : path.segments;
473
- };
474
- for (const statement of sourceFile.statements) {
475
- if (!ts.isVariableStatement(statement)) continue;
476
- for (const declaration of statement.declarationList.declarations) {
477
- if (!declaration.initializer || !ts.isIdentifier(declaration.name)) continue;
478
- const path = resolvePath(declaration.initializer);
479
- const symbol = symbolAt(checker, declaration.name);
480
- if (!path || !symbol) continue;
481
- aliases.set(symbol, path);
482
- }
483
- }
484
- const uses = [];
485
- const seen = /* @__PURE__ */ new Set();
486
- const flag = (name, node) => {
487
- const line = lineOf(sourceFile, node);
488
- const key = `${name}:${node.getStart(sourceFile)}`;
489
- if (seen.has(key)) return;
490
- seen.add(key);
491
- uses.push({ name, line, node });
492
- };
493
- const visit = (node) => {
494
- const parentContinuesPath = node.parent && (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node;
495
- if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && !parentContinuesPath) {
496
- const path = resolvePath(node);
497
- const match = path ? bestForbiddenMatch(entries, path) : void 0;
498
- if (match) flag(match, node);
499
- } else if (ts.isIdentifier(node) && entries.has(node.text) && runtimeIdentifierReference(ts, node) && !localDeclaration(ts, checker, sourceFile, node)) {
500
- flag(node.text, node);
501
- }
502
- if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer) {
503
- const base = resolvePath(node.initializer);
504
- if (base) {
505
- for (const element of node.name.elements) {
506
- if (!ts.isIdentifier(element.name)) continue;
507
- const property = element.propertyName ? literalText(ts, element.propertyName) ?? element.propertyName.text : element.name.text;
508
- const match = bestForbiddenMatch(entries, [...base, property]);
509
- if (match) flag(match, node.initializer);
510
- }
511
- }
512
- }
513
- ts.forEachChild(node, visit);
514
- };
515
- visit(sourceFile);
516
- return uses;
517
- }
518
-
519
- // src/kernel/ai-gate/AICodeGate.ts
520
- function violation(ruleId, message, extra) {
521
- return { ruleId, code: ruleId, message, ...extra };
522
- }
523
- function lineOf2(source, index) {
524
- return source.slice(0, index).split("\n").length;
525
- }
526
- function extractQuotedStrings(source) {
527
- const matches = [];
528
- const re = /['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g;
529
- let m;
530
- while ((m = re.exec(source)) !== null) {
531
- matches.push({ value: m[1], index: m.index });
532
- }
533
- return matches;
534
- }
535
- function extractModuleSpecifiers(source) {
536
- const matches = [];
537
- const patterns = [
538
- {
539
- kind: "import",
540
- re: /\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g
541
- },
542
- {
543
- kind: "export",
544
- re: /\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g
545
- },
546
- {
547
- kind: "dynamic-import",
548
- re: /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g
549
- },
550
- {
551
- kind: "require",
552
- re: /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g
553
- }
554
- ];
555
- for (const pattern of patterns) {
556
- let match;
557
- while ((match = pattern.re.exec(source)) !== null) {
558
- const index = match.index + match[0].indexOf(match[1]);
559
- const raw = match[0];
560
- const typeOnly = pattern.kind === "import" && /\bimport\s+type\b/.test(raw) || pattern.kind === "export" && /\bexport\s+type\b/.test(raw);
561
- matches.push({ value: match[1], index, kind: pattern.kind, typeOnly });
562
- }
563
- }
564
- return matches.sort((a, b) => a.index - b.index);
565
- }
566
- function extractQuotedStringsAst(ts, source) {
567
- const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
568
- const matches = [];
569
- const visit = (node) => {
570
- if (ts.isStringLiteralLike(node)) {
571
- matches.push({ value: node.text, index: node.getStart(sourceFile) });
572
- }
573
- ts.forEachChild(node, visit);
574
- };
575
- visit(sourceFile);
576
- return matches;
577
- }
578
- function hasInfrastructureToken(specifier) {
579
- const tokens = specifier.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
580
- return [
581
- "adapter",
582
- "adapters",
583
- "infra",
584
- "infrastructure",
585
- "persistence",
586
- "repository",
587
- "repositories",
588
- "integration",
589
- "database",
590
- "db"
591
- ].some((token) => tokens.includes(token));
592
- }
593
- function isKnownInfrastructurePackage(specifier) {
594
- const normalized = specifier.toLowerCase();
595
- return ["sequelize", "prisma", "typeorm", "mongoose", "knex"].some(
596
- (name) => normalized === name || normalized.startsWith(`${name}/`)
597
- );
598
- }
599
- function layerHasInfrastructureRole(layerName) {
600
- const normalized = layerName.toLowerCase();
601
- return [
602
- "adapter",
603
- "infra",
604
- "persistence",
605
- "repository",
606
- "repositories",
607
- "integration",
608
- "database"
609
- ].some((token) => normalized.includes(token));
610
- }
611
- function tsStringLiteralText(ts, node) {
612
- return node && ts.isStringLiteralLike(node) ? node.text : void 0;
613
- }
614
- function tsPropertyName(ts, node) {
615
- if (!node) return void 0;
616
- if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) return node.text;
617
- return void 0;
618
- }
619
- function tsObjectProperty(ts, node, name) {
620
- if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
621
- return node.properties.find((property) => {
622
- if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) {
623
- return false;
624
- }
625
- return tsPropertyName(ts, property.name) === name;
626
- });
627
- }
628
- function tsObjectHasProperty(ts, node, name) {
629
- return tsObjectProperty(ts, node, name) !== void 0;
630
- }
631
- function tsObjectPropertyValue(ts, node, name) {
632
- const property = tsObjectProperty(ts, node, name);
633
- return property && ts.isPropertyAssignment(property) ? property.initializer : void 0;
634
- }
635
- function tsObjectHasMetadataSource(ts, node) {
636
- const metadata = tsObjectPropertyValue(ts, node, "metadata");
637
- return tsObjectHasProperty(ts, metadata, "source");
638
- }
639
- function tsLooksLikeIntentCreatorExpression(ts, node) {
640
- if (!node) return false;
641
- if (ts.isIdentifier(node)) return /^[A-Z]/.test(node.text);
642
- if (ts.isPropertyAccessExpression(node)) {
643
- return tsLooksLikeIntentCreatorExpression(ts, node.name);
644
- }
645
- return false;
646
- }
647
- function tsIsPublishCall(ts, node) {
648
- if (!ts.isCallExpression(node)) return false;
649
- const expression = node.expression;
650
- if (ts.isPropertyAccessExpression(expression)) {
651
- return expression.name.text === "publish";
652
- }
653
- return ts.isIdentifier(expression) && expression.text === "publish";
654
- }
655
- function tsIsArkPublishCandidate(ts, node) {
656
- if (!ts.isCallExpression(node)) return false;
657
- const firstArg = node.arguments[0];
658
- const rawIntent = tsStringLiteralText(ts, firstArg);
659
- return rawIntent !== void 0 && looksLikeArkIntent(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent") || tsLooksLikeIntentCreatorExpression(ts, firstArg);
660
- }
661
- function tsPublishHasSource(ts, node) {
662
- if (!ts.isCallExpression(node)) return false;
663
- const [firstArg, secondArg, thirdArg] = node.arguments;
664
- return tsObjectHasMetadataSource(ts, firstArg) || tsObjectHasProperty(ts, secondArg, "source") || tsObjectHasProperty(ts, thirdArg, "source");
665
- }
666
- function tsPublishSourceLiteral(ts, node) {
667
- if (!ts.isCallExpression(node)) return void 0;
668
- const [firstArg, secondArg, thirdArg] = node.arguments;
669
- const rawMetadata = tsObjectPropertyValue(ts, firstArg, "metadata");
670
- return tsStringLiteralText(ts, tsObjectPropertyValue(ts, rawMetadata, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, secondArg, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, thirdArg, "source"));
671
- }
672
- function analyzePublishAst(ts, source, context, profile) {
673
- const sourceFile = ts.createSourceFile(
674
- "generated.ts",
675
- source,
676
- ts.ScriptTarget.Latest,
677
- true
678
- );
679
- const gateContext = context;
680
- const filePath = gateContext?.filePath;
681
- const contextLayer = gateContext?.layer;
682
- const violations = [];
683
- const lineForNode = (node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
684
- const visit = (node) => {
685
- if (tsIsPublishCall(ts, node)) {
686
- const firstArg = node.arguments[0];
687
- const rawIntent = tsStringLiteralText(ts, firstArg);
688
- for (const finding of classifyPublishFacts({
689
- publishCall: true,
690
- rawIntentName: rawIntent,
691
- objectHasIntent: tsObjectHasProperty(ts, firstArg, "intent"),
692
- arkPublishCandidate: tsIsArkPublishCandidate(ts, node),
693
- hasSource: tsPublishHasSource(ts, node)
694
- })) {
695
- violations.push(
696
- violation(finding.ruleId, finding.message, { line: lineForNode(node), filePath })
697
- );
698
- }
699
- const sourceIntent = tsPublishSourceLiteral(ts, node);
700
- if (profile && contextLayer && sourceIntent && looksLikeArkIntent(sourceIntent)) {
701
- const sourceLayer = profile.resolveLayer(sourceIntent);
702
- if (sourceLayer && sourceLayer !== contextLayer) {
703
- violations.push(
704
- violation(
705
- "PUBLISH_SOURCE_LAYER_MISMATCH",
706
- `Publish source "${sourceIntent}" resolves to ${sourceLayer}, but the target file is classified as ${contextLayer}.`,
707
- {
708
- line: lineForNode(node),
709
- filePath,
710
- target: sourceIntent,
711
- fromLayer: contextLayer,
712
- toLayer: sourceLayer
713
- }
714
- )
715
- );
716
- }
717
- }
718
- }
719
- ts.forEachChild(node, visit);
720
- };
721
- visit(sourceFile);
722
- return violations;
723
- }
724
- function createAICodeGate(options = {}) {
725
- const intentNames = new Set(
726
- (options.intents || []).map((i) => typeof i === "string" ? i : i.name)
727
- );
728
- const userForbidden = options.forbiddenPatterns || [];
729
- const explicitInfraLayers = new Set(options.infrastructureLayers ?? []);
730
- const enforceAllowlist = options.enforceIntentAllowlist ?? intentNames.size > 0;
731
- return {
732
- validate(source, context) {
733
- const violations = [];
734
- const gateContext = context;
735
- const filePath = gateContext?.filePath;
736
- const contextLayer = gateContext?.layer;
737
- const semanticTypescript = options.typescript;
738
- const semanticSourceFile = semanticTypescript ? semanticTypescript.createSourceFile(
739
- filePath ?? "generated.ts",
740
- source,
741
- semanticTypescript.ScriptTarget.Latest,
742
- true
743
- ) : void 0;
744
- const semanticDependencies = semanticSourceFile ? extractSemanticDependencies(options.typescript, semanticSourceFile) : void 0;
745
- const moduleSpecifiers2 = semanticDependencies ? semanticDependencies.filter((dependency) => dependency.specifier !== void 0).map((dependency) => ({
746
- value: dependency.specifier,
747
- index: dependency.node.getStart(semanticSourceFile),
748
- kind: dependency.kind,
749
- typeOnly: dependency.typeOnly
750
- })) : extractModuleSpecifiers(source);
751
- const quotedStrings = options.typescript ? extractQuotedStringsAst(options.typescript, source) : extractQuotedStrings(source);
752
- if (options.typescript && !options.allowNonLiteralDynamicImport?.(filePath)) {
753
- for (const dependency of semanticDependencies?.filter(({ unresolved }) => unresolved) ?? []) {
754
- const isRequire = dependency.kind === "require";
755
- violations.push(
756
- violation(
757
- isRequire ? "DYNAMIC_REQUIRE_NOT_ALLOWLISTED" : "DYNAMIC_IMPORT_NOT_ALLOWLISTED",
758
- `Non-literal ${isRequire ? "require call" : "dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,
759
- { line: dependency.line, filePath }
760
- )
761
- );
762
- }
763
- }
764
- const exemptFromInfraHeuristics = contextLayer !== void 0 && (explicitInfraLayers.has(contextLayer) || layerHasInfrastructureRole(contextLayer));
765
- const infraLayerEscapeHatch = contextLayer !== void 0 ? ` If "${contextLayer}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).` : "";
766
- for (const pat of userForbidden) {
767
- if (pat instanceof RegExp) {
768
- pat.lastIndex = 0;
769
- const match = pat.exec(source);
770
- pat.lastIndex = 0;
771
- if (match) {
772
- violations.push(
773
- violation("FORBIDDEN_PATTERN", `Forbidden pattern matched: ${pat}`, {
774
- line: match.index === void 0 ? void 0 : lineOf2(source, match.index),
775
- filePath,
776
- suggestion: "Remove infrastructure imports from domain/application layers." + infraLayerEscapeHatch
777
- })
778
- );
779
- }
780
- } else if (source.includes(pat)) {
781
- violations.push(
782
- violation("FORBIDDEN_SUBSTRING", `Forbidden substring: ${pat}`, {
783
- line: lineOf2(source, source.indexOf(pat)),
784
- filePath
785
- })
786
- );
787
- }
788
- }
789
- for (const specifier of moduleSpecifiers2) {
790
- const targetHit = options.resolveImportTarget?.(specifier.value, filePath) ?? (options.resolveImportLayer ? { layer: options.resolveImportLayer(specifier.value, filePath) } : void 0);
791
- const sourceHit = typeof filePath === "string" ? options.resolveImportTarget?.(filePath) ?? (options.resolveImportLayer ? { layer: contextLayer, relPath: void 0 } : void 0) : void 0;
792
- const targetLayer = targetHit?.layer;
793
- if (targetLayer && contextLayer) {
794
- const blocked = findDeniedEdgeRule(
795
- options.architectureProfile?.rules,
796
- contextLayer,
797
- targetLayer,
798
- {
799
- fromPath: sourceHit?.relPath,
800
- toPath: targetHit?.relPath,
801
- layers: options.architectureLayers
802
- }
803
- );
804
- if (blocked) {
805
- if (specifier.typeOnly && !blocked.peerIsolation) {
806
- continue;
807
- }
808
- const peer = Boolean(blocked.peerIsolation);
809
- violations.push(
810
- violation(
811
- "LAYER_IMPORT_VIOLATION",
812
- blocked.message ?? (peer ? `Layer "${contextLayer}" must not import across slices into "${targetLayer}".` : `Layer "${contextLayer}" must not import "${targetLayer}".`),
813
- {
814
- line: lineOf2(source, specifier.index),
815
- source: specifier.value,
816
- target: specifier.value,
817
- filePath,
818
- fromLayer: contextLayer,
819
- toLayer: targetLayer,
820
- suggestion: peer ? "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.",
821
- details: {
822
- importKind: specifier.kind,
823
- peerIsolation: peer,
824
- ...specifier.typeOnly ? { typeOnly: true } : {}
825
- }
826
- }
827
- )
828
- );
829
- continue;
830
- }
831
- if (targetLayer !== contextLayer) {
832
- continue;
833
- }
834
- }
835
- if (exemptFromInfraHeuristics || specifier.typeOnly) continue;
836
- if (!hasInfrastructureToken(specifier.value) && !isKnownInfrastructurePackage(specifier.value)) {
837
- continue;
838
- }
839
- violations.push(
840
- violation(
841
- "FORBIDDEN_IMPORT",
842
- `Forbidden ${specifier.kind} target: "${specifier.value}".`,
843
- {
844
- line: lineOf2(source, specifier.index),
845
- source: specifier.value,
846
- target: specifier.value,
847
- filePath,
848
- suggestion: "Route infrastructure access through an allowed adapter or port boundary." + infraLayerEscapeHatch,
849
- details: { importKind: specifier.kind }
850
- }
851
- )
852
- );
853
- }
854
- if (options.policies) {
855
- for (const policy of options.policies) {
856
- const res = policy.check({ source, context });
857
- if (res !== true) {
858
- if (Array.isArray(res)) {
859
- for (const v of res) {
860
- violations.push(
861
- violation("POLICY_VIOLATION", v.message, {
862
- filePath,
863
- suggestion: `Fix violation of policy "${policy.name}".`
864
- })
865
- );
866
- }
867
- } else if (res === false) {
868
- violations.push(
869
- violation("POLICY_VIOLATION", `Policy ${policy.name} failed on generated code`)
870
- );
871
- } else {
872
- violations.push(
873
- violation("POLICY_VIOLATION", res.message)
874
- );
875
- }
876
- }
877
- }
878
- }
879
- if (enforceAllowlist && intentNames.size > 0) {
880
- for (const literal of quotedStrings) {
881
- if (looksLikeArkIntent(literal.value) && !intentNames.has(literal.value)) {
882
- violations.push(
883
- violation(
884
- "UNKNOWN_INTENT",
885
- `Unknown intent reference: "${literal.value}"`,
886
- {
887
- line: lineOf2(source, literal.index),
888
- filePath,
889
- target: literal.value,
890
- suggestion: `Register intent "${literal.value}" via defineIntent() or remove the reference.`
891
- }
892
- )
893
- );
894
- }
895
- }
896
- }
897
- if (options.architectureProfile && contextLayer) {
898
- for (const literal of quotedStrings) {
899
- if (!looksLikeArkIntent(literal.value)) continue;
900
- const targetLayer = options.architectureProfile.resolveLayer(literal.value);
901
- if (!targetLayer) continue;
902
- const blocked = findDeniedEdgeRule(
903
- options.architectureProfile.rules,
904
- contextLayer,
905
- targetLayer
906
- );
907
- if (blocked) {
908
- violations.push(
909
- violation(
910
- "LAYER_REFERENCE_VIOLATION",
911
- blocked.message ?? `Layer "${contextLayer}" must not reference "${targetLayer}" through "${literal.value}".`,
912
- {
913
- line: lineOf2(source, literal.index),
914
- filePath,
915
- target: literal.value,
916
- fromLayer: contextLayer,
917
- toLayer: targetLayer,
918
- suggestion: "Route the dependency through an allowed intent, port, or event.",
919
- details: { rule: blocked }
920
- }
921
- )
922
- );
923
- }
924
- }
925
- }
926
- if (options.extensions) {
927
- for (const ext of options.extensions) {
928
- try {
929
- const extViolations = ext.analyze(source, context);
930
- violations.push(...extViolations);
931
- } catch (err) {
932
- violations.push(
933
- violation(
934
- "EXTENSION_ERROR",
935
- `Extension "${ext.name}" failed: ${err instanceof Error ? err.message : String(err)}`
936
- )
937
- );
938
- }
939
- }
940
- }
941
- if (options.typescript && semanticSourceFile && contextLayer && options.forbiddenGlobals?.[contextLayer]?.length) {
942
- try {
943
- violations.push(
944
- ...collectForbiddenCapabilityUses(
945
- options.typescript,
946
- semanticSourceFile,
947
- options.forbiddenGlobals[contextLayer]
948
- ).map(
949
- (use) => violation(
950
- "FORBIDDEN_GLOBAL",
951
- `${contextLayer} must not use the ambient global "${use.name}".`,
952
- {
953
- line: use.line,
954
- filePath,
955
- target: use.name,
956
- fromLayer: contextLayer,
957
- suggestion: "Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."
958
- }
959
- )
960
- )
961
- );
962
- } catch (err) {
963
- violations.push(
964
- violation(
965
- "AST_ANALYZER_ERROR",
966
- `TypeScript AST analyzer failed: ${err instanceof Error ? err.message : String(err)}`
967
- )
968
- );
969
- }
970
- }
971
- if (options.typescript) {
972
- try {
973
- violations.push(
974
- ...analyzePublishAst(
975
- options.typescript,
976
- source,
977
- context,
978
- options.architectureProfile
979
- )
980
- );
981
- } catch (err) {
982
- violations.push(
983
- violation(
984
- "AST_ANALYZER_ERROR",
985
- `TypeScript AST analyzer failed: ${err instanceof Error ? err.message : String(err)}`
986
- )
987
- );
988
- }
989
- }
990
- return {
991
- valid: violations.length === 0,
992
- violations
993
- };
994
- }
995
- };
996
- }
997
-
998
- // src/domain/configContract.ts
999
- var ARK_CONFIG_SCHEMA_VERSION = "1.0";
1000
- var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
1001
- var DEFAULT_LAYER_NAMES = [
1002
- "DomainModel",
1003
- "ApplicationOrchestration",
1004
- "PersistenceAdapters",
1005
- "IntegrationAdapters",
1006
- "WorkflowSagaEngine",
1007
- "BackgroundJobsScheduling",
1008
- "PresentationAdapters",
1009
- "ReportingReadModels",
1010
- "ExtensibilityMetadata",
1011
- "SecurityAuditObservability",
1012
- "Kernel"
1013
- ];
1014
- var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
1015
- "PresentationAdapters->ApplicationOrchestration",
1016
- "ApplicationOrchestration->DomainModel",
1017
- "WorkflowSagaEngine->ApplicationOrchestration",
1018
- "WorkflowSagaEngine->DomainModel",
1019
- "BackgroundJobsScheduling->ApplicationOrchestration"
1020
- ]);
1021
- function createDefaultRules() {
1022
- const rules = [];
1023
- for (const from of DEFAULT_LAYER_NAMES) {
1024
- for (const to of DEFAULT_LAYER_NAMES) {
1025
- if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
1026
- rules.push({ from, to, allowed: false });
1027
- }
1028
- }
1029
- return rules;
1030
- }
1031
- var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
1032
- var stringArraySchema = {
1033
- type: "array",
1034
- items: { type: "string", minLength: 1 },
1035
- uniqueItems: true
1036
- };
1037
- var ARK_CONFIG_SCHEMA = {
1038
- $schema: "https://json-schema.org/draft/2020-12/schema",
1039
- $id: ARK_CONFIG_SCHEMA_URL,
1040
- title: "ArkGate architecture contract",
1041
- description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
1042
- type: "object",
1043
- additionalProperties: false,
1044
- required: ["$schema", "schemaVersion", "include", "layers", "rules"],
1045
- properties: {
1046
- $schema: {
1047
- type: "string",
1048
- minLength: 1,
1049
- default: ARK_CONFIG_SCHEMA_URL,
1050
- description: "Editor-facing URL or local path for this JSON Schema."
1051
- },
1052
- schemaVersion: {
1053
- type: "string",
1054
- const: ARK_CONFIG_SCHEMA_VERSION,
1055
- default: ARK_CONFIG_SCHEMA_VERSION
1056
- },
1057
- name: { type: "string", minLength: 1 },
1058
- include: { ...stringArraySchema, minItems: 1, default: ["src"] },
1059
- exclude: { ...stringArraySchema, default: [] },
1060
- excludeGenerated: { type: "boolean", default: true },
1061
- frameworkOverlay: { type: "string", minLength: 1 },
1062
- layers: {
1063
- type: "array",
1064
- default: [],
1065
- items: { $ref: "#/$defs/layer" }
1066
- },
1067
- rules: {
1068
- type: "array",
1069
- default: DEFAULT_ARK_CONFIG_RULES,
1070
- items: { $ref: "#/$defs/rule" }
1071
- },
1072
- cyclePolicy: {
1073
- type: "string",
1074
- enum: ["strict", "soft", "framework-soft", "off"],
1075
- default: "strict"
1076
- },
1077
- dynamicImportAllowlist: { ...stringArraySchema, default: [] },
1078
- safety: {
1079
- $ref: "#/$defs/safety",
1080
- default: {
1081
- maxTsSuppressions: 0,
1082
- maxAnyCasts: 0,
1083
- allowInMemory: false,
1084
- allowDisabledPeerIsolation: false
1085
- }
1086
- }
1087
- },
1088
- $defs: {
1089
- layer: {
1090
- type: "object",
1091
- additionalProperties: false,
1092
- required: ["name", "patterns"],
1093
- properties: {
1094
- name: { type: "string", minLength: 1 },
1095
- patterns: { ...stringArraySchema, minItems: 1 },
1096
- exclude: stringArraySchema,
1097
- intentPrefixes: stringArraySchema,
1098
- description: { type: "string", minLength: 1 },
1099
- forbiddenGlobals: stringArraySchema,
1100
- mayImportInfrastructure: { type: "boolean" },
1101
- optional: { type: "boolean" }
1102
- }
1103
- },
1104
- rule: {
1105
- type: "object",
1106
- additionalProperties: false,
1107
- required: ["from", "to", "allowed"],
1108
- properties: {
1109
- from: { type: "string", minLength: 1 },
1110
- to: { type: "string", minLength: 1 },
1111
- allowed: { type: "boolean" },
1112
- message: { type: "string", minLength: 1 },
1113
- peerIsolation: { type: "boolean" },
1114
- sliceFolders: { ...stringArraySchema, minItems: 1 }
1115
- }
1116
- },
1117
- safety: {
1118
- type: "object",
1119
- additionalProperties: false,
1120
- properties: {
1121
- maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
1122
- maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
1123
- allowInMemory: { type: "boolean", default: false },
1124
- allowDisabledPeerIsolation: { type: "boolean", default: false }
1125
- }
1126
- }
1127
- }
1128
- };
1129
- var ArkConfigValidationError = class extends Error {
1130
- issues;
1131
- source;
1132
- constructor(source, issues) {
1133
- super(
1134
- `Invalid ArkGate config (${source}):
1135
- ${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`
1136
- );
1137
- this.name = "ArkConfigValidationError";
1138
- this.source = source;
1139
- this.issues = issues;
1140
- }
1141
- };
1142
- function isObject(value) {
1143
- return value !== null && typeof value === "object" && !Array.isArray(value);
1144
- }
1145
- function propertyPath(parent, key) {
1146
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
1147
- }
1148
- function valueType(value) {
1149
- if (value === null) return "null";
1150
- if (Array.isArray(value)) return "array";
1151
- return typeof value;
1152
- }
1153
- function resolveSchemaRef(ref, root) {
1154
- const prefix = "#/$defs/";
1155
- if (!ref.startsWith(prefix)) return void 0;
1156
- return root.$defs[ref.slice(prefix.length)];
1157
- }
1158
- function validateNode(value, schema, path, root, issues) {
1159
- if (schema.$ref) {
1160
- const referenced = resolveSchemaRef(schema.$ref, root);
1161
- if (!referenced) {
1162
- issues.push({ path, message: `schema reference ${schema.$ref} cannot be resolved` });
1163
- return;
1164
- }
1165
- validateNode(value, referenced, path, root, issues);
1166
- return;
1167
- }
1168
- if (schema.const !== void 0 && !Object.is(value, schema.const)) {
1169
- issues.push({ path, message: `must equal ${JSON.stringify(schema.const)}` });
1170
- return;
1171
- }
1172
- if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
1173
- issues.push({ path, message: `must be one of ${schema.enum.map(String).join(", ")}` });
1174
- return;
1175
- }
1176
- if (schema.type === "object") {
1177
- if (!isObject(value)) {
1178
- issues.push({ path, message: `must be an object; received ${valueType(value)}` });
1179
- return;
1180
- }
1181
- const properties = schema.properties ?? {};
1182
- for (const key of schema.required ?? []) {
1183
- if (value[key] === void 0) {
1184
- issues.push({ path: propertyPath(path, key), message: "is required" });
1185
- }
1186
- }
1187
- if (schema.additionalProperties === false) {
1188
- for (const key of Object.keys(value)) {
1189
- if (!(key in properties)) {
1190
- issues.push({ path: propertyPath(path, key), message: "unknown field" });
1191
- }
1192
- }
1193
- }
1194
- for (const [key, childSchema] of Object.entries(properties)) {
1195
- if (value[key] !== void 0) {
1196
- validateNode(value[key], childSchema, propertyPath(path, key), root, issues);
1197
- }
1198
- }
1199
- return;
1200
- }
1201
- if (schema.type === "array") {
1202
- if (!Array.isArray(value)) {
1203
- issues.push({ path, message: `must be an array; received ${valueType(value)}` });
1204
- return;
1205
- }
1206
- if (schema.minItems !== void 0 && value.length < schema.minItems) {
1207
- issues.push({ path, message: `must contain at least ${schema.minItems} item(s)` });
1208
- }
1209
- if (schema.uniqueItems) {
1210
- const serialized = value.map((entry) => JSON.stringify(entry));
1211
- if (new Set(serialized).size !== serialized.length) {
1212
- issues.push({ path, message: "must not contain duplicate items" });
1213
- }
1214
- }
1215
- if (schema.items) {
1216
- value.forEach(
1217
- (entry, index) => validateNode(entry, schema.items, `${path}[${index}]`, root, issues)
1218
- );
1219
- }
1220
- return;
1221
- }
1222
- if (schema.type === "string") {
1223
- if (typeof value !== "string") {
1224
- issues.push({ path, message: `must be a string; received ${valueType(value)}` });
1225
- return;
1226
- }
1227
- if (schema.minLength !== void 0 && value.length < schema.minLength) {
1228
- issues.push({ path, message: `must contain at least ${schema.minLength} character(s)` });
1229
- }
1230
- return;
1231
- }
1232
- if (schema.type === "boolean") {
1233
- if (typeof value !== "boolean") {
1234
- issues.push({ path, message: `must be a boolean; received ${valueType(value)}` });
1235
- }
1236
- return;
1237
- }
1238
- if (schema.type === "integer") {
1239
- if (!Number.isInteger(value)) {
1240
- issues.push({ path, message: `must be an integer; received ${valueType(value)}` });
1241
- return;
1242
- }
1243
- if (schema.minimum !== void 0 && value < schema.minimum) {
1244
- issues.push({ path, message: `must be at least ${schema.minimum}` });
1245
- }
1246
- }
1247
- }
1248
- function defaultedConfig(input) {
1249
- return {
1250
- ...input,
1251
- $schema: input.$schema === void 0 ? ARK_CONFIG_SCHEMA_URL : input.$schema,
1252
- schemaVersion: input.schemaVersion === void 0 ? ARK_CONFIG_SCHEMA_VERSION : input.schemaVersion,
1253
- include: input.include === void 0 ? ["src"] : input.include,
1254
- layers: input.layers === void 0 ? [] : input.layers,
1255
- rules: input.rules === void 0 ? DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule })) : input.rules
1256
- };
1257
- }
1258
- function migrateArkConfig(input, source = "ark.config.json") {
1259
- if (!isObject(input)) {
1260
- throw new ArkConfigValidationError(source, [
1261
- { path: "$", message: `must be an object; received ${valueType(input)}` }
1262
- ]);
1263
- }
1264
- const migratedFrom = input.schemaVersion === void 0 ? "unversioned" : null;
1265
- if (input.schemaVersion !== void 0 && input.schemaVersion !== ARK_CONFIG_SCHEMA_VERSION) {
1266
- throw new ArkConfigValidationError(source, [
1267
- {
1268
- path: "$.schemaVersion",
1269
- message: `unsupported version ${JSON.stringify(input.schemaVersion)}; expected ${ARK_CONFIG_SCHEMA_VERSION}`
1270
- }
1271
- ]);
1272
- }
1273
- return { candidate: defaultedConfig(input), migratedFrom };
1274
- }
1275
- function loadArkConfigContract(input, source = "ark.config.json") {
1276
- const { candidate, migratedFrom } = migrateArkConfig(input, source);
1277
- const issues = [];
1278
- validateNode(
1279
- candidate,
1280
- ARK_CONFIG_SCHEMA,
1281
- "$",
1282
- ARK_CONFIG_SCHEMA,
1283
- issues
1284
- );
1285
- if (issues.length > 0) throw new ArkConfigValidationError(source, issues);
1286
- return { config: candidate, migratedFrom };
1287
- }
1288
- function parseArkConfigJson(json, source = "ark.config.json") {
1289
- let input;
1290
- try {
1291
- input = JSON.parse(json);
1292
- } catch (error) {
1293
- throw new ArkConfigValidationError(source, [
1294
- {
1295
- path: "$",
1296
- message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
1297
- }
1298
- ]);
1299
- }
1300
- return loadArkConfigContract(input, source);
1301
- }
1302
- function withArkConfigMetadata(config) {
1303
- const result = {
1304
- $schema: typeof config.$schema === "string" && config.$schema.length > 0 ? config.$schema : ARK_CONFIG_SCHEMA_URL,
1305
- schemaVersion: ARK_CONFIG_SCHEMA_VERSION
1306
- };
1307
- for (const [key, value] of Object.entries(config)) {
1308
- if (key !== "$schema" && key !== "schemaVersion") result[key] = value;
1309
- }
1310
- return result;
1311
- }
1312
-
1313
- // src/kernel/layers/ArchitectureProfile.ts
1314
- function normalizePrefix(prefix) {
1315
- return prefix.endsWith(".") ? prefix : `${prefix}.`;
1316
- }
1317
- function byLongestPrefix(a, b) {
1318
- const maxA = a.prefixes.length ? Math.max(...a.prefixes.map((p) => p.length)) : 0;
1319
- const maxB = b.prefixes.length ? Math.max(...b.prefixes.map((p) => p.length)) : 0;
1320
- return maxB - maxA;
1321
- }
1322
- function createArchitectureProfile(options) {
1323
- const layers = options.layers.map((layer) => ({
1324
- ...layer,
1325
- prefixes: layer.prefixes.map(normalizePrefix)
1326
- }));
1327
- const sortedLayers = [...layers].sort(byLongestPrefix);
1328
- const rules = [...options.rules ?? []];
1329
- return {
1330
- name: options.name,
1331
- layers,
1332
- rules,
1333
- resolveLayer(name) {
1334
- return layers.find((layer) => layer.match?.(name))?.name ?? sortedLayers.find(
1335
- (layer) => layer.prefixes.some((prefix) => name.startsWith(prefix))
1336
- )?.name;
1337
- }
1338
- };
1339
- }
1340
- function createArchitectureProfileFromArkConfig(config, options = {}) {
1341
- return createArchitectureProfile({
1342
- name: options.name ?? config.name ?? "ark.config.json",
1343
- layers: config.layers.map((layer, index) => ({
1344
- name: layer.name,
1345
- prefixes: layer.intentPrefixes ?? [],
1346
- description: layer.description,
1347
- order: index + 1
1348
- })),
1349
- rules: config.rules ?? []
1350
- });
1351
- }
1352
- var elevenLayerProfileLayers = [
1353
- {
1354
- name: "DomainModel",
1355
- prefixes: ["Domain"],
1356
- description: "Rich domain model, business rules, and domain events.",
1357
- order: 1
1358
- },
1359
- {
1360
- name: "ApplicationOrchestration",
1361
- prefixes: ["Application"],
1362
- description: "Use cases and command orchestration.",
1363
- order: 2
1364
- },
1365
- {
1366
- name: "PersistenceAdapters",
1367
- prefixes: ["Adapter.Persistence", "Adapter.Repository"],
1368
- description: "Database, repository, and storage adapters.",
1369
- order: 3
1370
- },
1371
- {
1372
- name: "IntegrationAdapters",
1373
- prefixes: ["Adapter.Integration", "Adapter.External"],
1374
- description: "External systems, APIs, and integration adapters.",
1375
- order: 4
1376
- },
1377
- {
1378
- name: "WorkflowSagaEngine",
1379
- prefixes: ["Workflow"],
1380
- description: "Sagas, workflows, and long-running processes.",
1381
- order: 5
1382
- },
1383
- {
1384
- name: "BackgroundJobsScheduling",
1385
- prefixes: ["Job"],
1386
- description: "Background jobs, scheduled work, and async processors.",
1387
- order: 6
1388
- },
1389
- {
1390
- name: "PresentationAdapters",
1391
- prefixes: ["Presentation", "Adapter.Presentation", "Adapter.Api"],
1392
- description: "API, UI, controller, and presentation adapters.",
1393
- order: 7
1394
- },
1395
- {
1396
- name: "ReportingReadModels",
1397
- prefixes: ["Reporting"],
1398
- description: "Read models, projections, and reporting surfaces.",
1399
- order: 8
1400
- },
1401
- {
1402
- name: "ExtensibilityMetadata",
1403
- prefixes: ["Metadata"],
1404
- description: "Metadata, extensions, and schema contracts.",
1405
- order: 9
1406
- },
1407
- {
1408
- name: "SecurityAuditObservability",
1409
- prefixes: ["Security", "Audit", "Observability"],
1410
- description: "Security, audit, and observability concerns.",
1411
- order: 10
1412
- },
1413
- {
1414
- name: "Kernel",
1415
- prefixes: ["Kernel"],
1416
- description: "Ark-owned governance and kernel signals.",
1417
- order: 11
1418
- }
1419
- ];
1420
- var elevenLayerProfile = createArchitectureProfile({
1421
- name: "Ark 11-layer Hexagonal Event-Driven Profile",
1422
- layers: elevenLayerProfileLayers,
1423
- rules: DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule }))
1424
- });
1425
- var defaultElevenLayerDirectories = {
1426
- DomainModel: ["domain"],
1427
- ApplicationOrchestration: ["application", "app"],
1428
- PersistenceAdapters: [
1429
- "adapters/persistence",
1430
- "adapters/repository",
1431
- "repositories",
1432
- "infra/persistence"
1433
- ],
1434
- IntegrationAdapters: ["adapters/integration", "adapters/external", "integrations"],
1435
- WorkflowSagaEngine: ["workflows", "sagas"],
1436
- BackgroundJobsScheduling: ["jobs", "schedules"],
1437
- PresentationAdapters: ["presentation", "adapters/presentation", "adapters/api"],
1438
- ReportingReadModels: ["reporting", "read-models", "projections"],
1439
- ExtensibilityMetadata: ["metadata", "extensions"],
1440
- SecurityAuditObservability: ["security", "audit", "observability"],
1441
- Kernel: ["kernel"]
1442
- };
1443
- function createElevenLayerArkConfig(options = {}) {
1444
- const rootDir = options.rootDir ?? "src";
1445
- const optional = options.optionalLayers ?? true;
1446
- const prefix = rootDir === "." ? "" : `${rootDir}/`;
1447
- return withArkConfigMetadata({
1448
- include: options.include ?? [rootDir],
1449
- layers: elevenLayerProfile.layers.map((layer) => ({
1450
- name: layer.name,
1451
- patterns: (defaultElevenLayerDirectories[layer.name] ?? [layer.name]).map(
1452
- (directory) => `${prefix}${directory}/**`
1453
- ),
1454
- intentPrefixes: layer.prefixes,
1455
- optional
1456
- })),
1457
- rules: [...elevenLayerProfile.rules]
1458
- });
1459
- }
1460
-
1461
- // src/domain/analysis.ts
1462
- var ANALYSIS_IR_SCHEMA_VERSION = "1.0";
1463
- function deterministicHash(value) {
1464
- let hash = 2166136261;
1465
- for (let index = 0; index < value.length; index += 1) {
1466
- hash ^= value.charCodeAt(index);
1467
- hash = Math.imul(hash, 16777619);
1468
- }
1469
- return `fnv1a-${(hash >>> 0).toString(16).padStart(8, "0")}`;
1470
- }
1471
- function stableSerialize(value) {
1472
- if (value === null || typeof value !== "object") return JSON.stringify(value);
1473
- if (Array.isArray(value)) return `[${value.map(stableSerialize).join(",")}]`;
1474
- const object = value;
1475
- return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(object[key])}`).join(",")}}`;
1476
- }
1477
-
1478
- // src/kernel/analysis.ts
1479
- function loadContract(input, source) {
1480
- const loaded = typeof input === "string" ? parseArkConfigJson(input, source) : loadArkConfigContract(input, source);
1481
- return { ...loaded, policyHash: deterministicHash(stableSerialize(loaded.config)) };
1482
- }
1483
- function normalizePath(value) {
1484
- return value.replace(/\\/g, "/").replace(/^\.\//, "");
1485
- }
1486
- function isIdentifierCharacter(value) {
1487
- return value !== void 0 && /[A-Za-z0-9_$]/.test(value);
1488
- }
1489
- function skipWhitespace(source, index) {
1490
- while (index < source.length && /\s/.test(source[index])) index += 1;
1491
- return index;
1492
- }
1493
- function readString(source, index) {
1494
- const quote = source[index];
1495
- if (quote !== "'" && quote !== '"') return void 0;
1496
- const start = index;
1497
- let value = "";
1498
- for (index += 1; index < source.length; index += 1) {
1499
- const current = source[index];
1500
- if (current === quote) {
1501
- return { value, offset: start, excerpt: source.slice(start, index + 1) };
1502
- }
1503
- if (current === "\\" && index + 1 < source.length) {
1504
- value += source[index + 1];
1505
- index += 1;
1506
- } else {
1507
- value += current;
1508
- }
1509
- }
1510
- return void 0;
1511
- }
1512
- function isWordAt(source, word, index) {
1513
- return source.startsWith(word, index) && !isIdentifierCharacter(source[index - 1]) && !isIdentifierCharacter(source[index + word.length]);
1514
- }
1515
- function specifierAfterImport(source, index) {
1516
- index = skipWhitespace(source, index + "import".length);
1517
- if (source[index] === "(") return readString(source, skipWhitespace(source, index + 1));
1518
- return specifierInStaticStatement(source, index, true);
1519
- }
1520
- function specifierAfterExport(source, index) {
1521
- return specifierInStaticStatement(source, index + "export".length, false);
1522
- }
1523
- function specifierInStaticStatement(source, index, allowDirectSpecifier) {
1524
- for (; index < source.length; index += 1) {
1525
- if (source[index] === ";") return void 0;
1526
- if (isWordAt(source, "from", index)) {
1527
- return readString(source, skipWhitespace(source, index + "from".length));
1528
- }
1529
- if (allowDirectSpecifier && (source[index] === "'" || source[index] === '"')) {
1530
- return readString(source, index);
1531
- }
1532
- if (index > 0 && (isWordAt(source, "import", index) || isWordAt(source, "export", index))) {
1533
- return void 0;
1534
- }
1535
- }
1536
- return void 0;
1537
- }
1538
- function moduleSpecifiers(source) {
1539
- const result = [];
1540
- for (let index = 0; index < source.length; index += 1) {
1541
- const current = source[index];
1542
- if (current === "/" && source[index + 1] === "/") {
1543
- index = source.indexOf("\n", index + 2);
1544
- if (index < 0) break;
1545
- continue;
1546
- }
1547
- if (current === "/" && source[index + 1] === "*") {
1548
- const end = source.indexOf("*/", index + 2);
1549
- if (end < 0) break;
1550
- index = end + 1;
1551
- continue;
1552
- }
1553
- if (current === "'" || current === '"' || current === "`") {
1554
- const string = readString(source, index);
1555
- if (string) index = string.offset + string.excerpt.length - 1;
1556
- continue;
1557
- }
1558
- const specifier = isWordAt(source, "import", index) ? specifierAfterImport(source, index) : isWordAt(source, "export", index) ? specifierAfterExport(source, index) : void 0;
1559
- if (specifier) result.push(specifier);
1560
- }
1561
- return result;
1562
- }
1563
- function importEdges(file, files) {
1564
- const edges = [];
1565
- for (const moduleSpecifier of moduleSpecifiers(file.content)) {
1566
- const specifier = moduleSpecifier.value;
1567
- if (!specifier.startsWith(".")) continue;
1568
- const line = file.content.slice(0, moduleSpecifier.offset).split("\n").length;
1569
- const evidence = {
1570
- kind: "import",
1571
- file: file.path,
1572
- line,
1573
- excerpt: moduleSpecifier.excerpt
1574
- };
1575
- const target = resolveSpecifier(file.path, specifier, files);
1576
- edges.push({
1577
- from: file.path,
1578
- specifier,
1579
- to: target?.path ?? null,
1580
- resolution: target ? "resolved" : "unresolved",
1581
- fromLayer: file.layer,
1582
- toLayer: target?.layer ?? null,
1583
- evidence
1584
- });
1585
- }
1586
- return edges;
1587
- }
1588
- function resolveSpecifier(from, specifier, files) {
1589
- const segments = from.split("/");
1590
- segments.pop();
1591
- for (const segment of specifier.split("/")) {
1592
- if (segment === "." || segment === "") continue;
1593
- if (segment === "..") segments.pop();
1594
- else segments.push(segment);
1595
- }
1596
- const base = segments.join("/");
1597
- for (const candidate of [base, `${base}.ts`, `${base}.tsx`, `${base}.mts`, `${base}.cts`, `${base}/index.ts`, `${base}/index.tsx`]) {
1598
- const found = files.get(candidate);
1599
- if (found) return found;
1600
- }
1601
- return void 0;
1602
- }
1603
- function violationsFor(edges, config) {
1604
- const violations = [];
1605
- for (const edge of edges) {
1606
- if (!edge.to || !edge.fromLayer || !edge.toLayer) continue;
1607
- const rule = findDeniedEdgeRule(config.rules, edge.fromLayer, edge.toLayer, {
1608
- fromPath: edge.from,
1609
- toPath: edge.to,
1610
- layers: config.layers
1611
- });
1612
- if (!rule) continue;
1613
- violations.push({
1614
- ruleId: `layer-dependency:${rule.from}->${rule.to}`,
1615
- message: rule.message ?? `${rule.from} must not depend on ${rule.to}.`,
1616
- edge,
1617
- evidence: edge.evidence
1618
- });
1619
- }
1620
- return violations;
1621
- }
1622
- function analyzeProject(input) {
1623
- const files = input.files.map((inputFile) => {
1624
- const path = normalizePath(inputFile.path);
1625
- return {
1626
- path,
1627
- content: inputFile.content,
1628
- contentHash: deterministicHash(inputFile.content),
1629
- layer: layerForRelativePath(path, input.contract.config.layers) ?? null
1630
- };
1631
- }).sort((left, right) => left.path.localeCompare(right.path));
1632
- const fileByPath = new Map(files.map((file) => [file.path, file]));
1633
- const edges = files.flatMap((file) => importEdges(file, fileByPath));
1634
- const capabilityUses = [];
1635
- const violations = violationsFor(edges, input.contract.config);
1636
- return {
1637
- ir: {
1638
- schemaVersion: ANALYSIS_IR_SCHEMA_VERSION,
1639
- policyHash: input.contract.policyHash,
1640
- compilerOptionsHash: deterministicHash(stableSerialize(input.compilerOptions ?? {})),
1641
- files,
1642
- layers: input.contract.config.layers.map((layer) => layer.name),
1643
- edges,
1644
- capabilityUses,
1645
- violations
1646
- }
1647
- };
1648
- }
1649
- function analyzeChange(input) {
1650
- const files = new Map(input.files.map((file) => [normalizePath(file.path), file]));
1651
- for (const change of input.changes) {
1652
- const path = normalizePath(change.path);
1653
- if ("delete" in change && change.delete) files.delete(path);
1654
- else if ("content" in change) files.set(path, { path, content: change.content });
1655
- }
1656
- return analyzeProject({
1657
- contract: input.contract,
1658
- files: [...files.values()],
1659
- compilerOptions: input.compilerOptions
1660
- });
1661
- }
1662
- function explainViolation(violation2) {
1663
- const location = `${violation2.evidence.file}:${violation2.evidence.line}`;
1664
- if (!violation2.edge) return `${violation2.ruleId} at ${location}: ${violation2.message}`;
1665
- const target = violation2.edge.to ?? violation2.edge.specifier;
1666
- return `${violation2.ruleId} at ${location}: ${violation2.edge.from} imports ${target}. ${violation2.message}`;
1667
- }
1668
- function detectArchitectureCycles(graph) {
1669
- let index = 0;
1670
- const indices = /* @__PURE__ */ new Map();
1671
- const low = /* @__PURE__ */ new Map();
1672
- const onStack = /* @__PURE__ */ new Set();
1673
- const stack = [];
1674
- const components = [];
1675
- const connect = (file) => {
1676
- indices.set(file, index);
1677
- low.set(file, index);
1678
- index += 1;
1679
- stack.push(file);
1680
- onStack.add(file);
1681
- for (const target of [...graph.get(file) ?? []].sort()) {
1682
- if (!graph.has(target)) continue;
1683
- if (!indices.has(target)) {
1684
- connect(target);
1685
- low.set(file, Math.min(low.get(file) ?? 0, low.get(target) ?? 0));
1686
- } else if (onStack.has(target)) {
1687
- low.set(file, Math.min(low.get(file) ?? 0, indices.get(target) ?? 0));
1688
- }
1689
- }
1690
- if (low.get(file) !== indices.get(file)) return;
1691
- const component = [];
1692
- let member;
1693
- do {
1694
- member = stack.pop();
1695
- if (member === void 0) break;
1696
- onStack.delete(member);
1697
- component.push(member);
1698
- } while (member !== file);
1699
- if (component.length > 1) components.push(component.sort());
1700
- };
1701
- for (const file of [...graph.keys()].sort()) {
1702
- if (!indices.has(file)) connect(file);
1703
- }
1704
- return components.sort((left, right) => left[0].localeCompare(right[0])).map((members) => ({
1705
- ruleId: "CIRCULAR_DEPENDENCY",
1706
- file: members[0],
1707
- line: 1,
1708
- target: members.join(" \u2192 "),
1709
- message: `Circular dependency among ${members.length} files: ${members.join(" \u2192 ")} \u2192 ${members[0]}.`,
1710
- cycleKind: "value"
1711
- }));
1712
- }
1713
- function evaluateArchitectureGraph(input) {
1714
- const violations = input.contentViolations.map((violation2) => ({ ...violation2 }));
1715
- const warnings = (input.warnings ?? []).map((warning) => ({ ...warning }));
1716
- const graph = new Map(
1717
- input.files.map((file) => [file, /* @__PURE__ */ new Set()])
1718
- );
1719
- for (const edge of input.edges) {
1720
- if (edge.to && edge.to !== edge.from && !edge.typeOnly && graph.has(edge.from)) {
1721
- graph.get(edge.from)?.add(edge.to);
1722
- }
1723
- if (!edge.to || !edge.toLayer) continue;
1724
- const rule = findDeniedEdgeRule(input.rules, edge.fromLayer, edge.toLayer, {
1725
- fromPath: edge.from,
1726
- toPath: edge.to,
1727
- layers: input.config.layers
1728
- });
1729
- if (!rule) continue;
1730
- const peerIsolation = Boolean(rule.peerIsolation);
1731
- violations.push({
1732
- ruleId: "LAYER_IMPORT_VIOLATION",
1733
- file: edge.from,
1734
- line: edge.line,
1735
- fromLayer: edge.fromLayer,
1736
- toLayer: edge.toLayer,
1737
- target: edge.to,
1738
- ...edge.typeOnly ? { typeOnly: true } : {},
1739
- ...edge.targetTypeOnlyExports ? { targetTypeOnlyExports: true } : {},
1740
- ...edge.sourcePureTypeModule ? { sourcePureTypeModule: true } : {},
1741
- ...edge.namedBindingsTypeOnly ? { namedBindingsTypeOnly: true } : {},
1742
- ...!peerIsolation && edge.portProofEligible ? { portProofEligible: true } : {},
1743
- ...edge.kind ? { edgeKind: edge.kind } : {},
1744
- ...peerIsolation ? { peerIsolation: true } : {},
1745
- message: rule.message ?? (peerIsolation ? `${edge.fromLayer} must not ${edge.kind} another slice of ${edge.toLayer} (${edge.from} \u2192 ${edge.to}). Extract shared code or use events/ports across slices.` : `${edge.fromLayer} must not ${edge.kind} ${edge.toLayer}.`)
1746
- });
1747
- }
1748
- const cyclePolicy = String(input.config.cyclePolicy ?? "strict").toLowerCase();
1749
- if (cyclePolicy !== "off") {
1750
- const cycles = detectArchitectureCycles(graph);
1751
- if (cyclePolicy === "soft" || cyclePolicy === "framework-soft") {
1752
- warnings.push(
1753
- ...cycles.map((cycle) => ({
1754
- ...cycle,
1755
- message: `${cycle.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,
1756
- failsStrict: false
1757
- }))
1758
- );
1759
- } else {
1760
- violations.push(...cycles);
1761
- }
1762
- }
1763
- return { violations, warnings, safety: input.safety };
1764
- }
1765
- function configWarning(ruleId, message, extra = {}) {
1766
- return { ruleId, message, ...extra };
1767
- }
1768
- function collectAnalysisConfigWarnings(input) {
1769
- const { config, rules, files, manifest } = input;
1770
- const warnings = [];
1771
- if (config.dynamicImportAllowlist !== void 0 && (!Array.isArray(config.dynamicImportAllowlist) || config.dynamicImportAllowlist.some((entry) => typeof entry !== "string"))) {
1772
- warnings.push(
1773
- configWarning(
1774
- "CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST",
1775
- "dynamicImportAllowlist must be an array of file globs."
1776
- )
1777
- );
1778
- }
1779
- if (config.safety !== void 0 && (config.safety === null || typeof config.safety !== "object" || Array.isArray(config.safety))) {
1780
- warnings.push(configWarning("CONFIG_INVALID_SAFETY", "safety must be an object."));
1781
- } else if (config.safety) {
1782
- for (const key of ["maxTsSuppressions", "maxAnyCasts"]) {
1783
- const value = config.safety[key];
1784
- if (value !== void 0 && (!Number.isInteger(value) || value < 0)) {
1785
- warnings.push(
1786
- configWarning(
1787
- "CONFIG_INVALID_SAFETY_THRESHOLD",
1788
- `safety.${key} must be a non-negative integer.`
1789
- )
1790
- );
1791
- }
1792
- }
1793
- }
1794
- const layers = Array.isArray(config.layers) ? config.layers : [];
1795
- const manifestLayers = Array.isArray(manifest?.architecture?.layers) ? manifest.architecture.layers : [];
1796
- const knownLayers = /* @__PURE__ */ new Set([
1797
- ...layers.map((layer) => layer.name).filter(Boolean),
1798
- ...manifestLayers.map((layer) => layer.name).filter((name) => Boolean(name))
1799
- ]);
1800
- if (layers.length === 0) {
1801
- warnings.push(
1802
- configWarning(
1803
- "CONFIG_NO_LAYERS",
1804
- "No file layers are configured; ark-check cannot classify files for import-boundary enforcement."
1805
- )
1806
- );
1807
- }
1808
- const seenLayers = /* @__PURE__ */ new Set();
1809
- const duplicateLayers = /* @__PURE__ */ new Set();
1810
- for (const layer of layers) {
1811
- if (!layer.name) {
1812
- warnings.push(configWarning("CONFIG_LAYER_WITHOUT_NAME", "A configured layer is missing a name."));
1813
- continue;
1814
- }
1815
- if (seenLayers.has(layer.name)) duplicateLayers.add(layer.name);
1816
- seenLayers.add(layer.name);
1817
- if (layer.forbiddenGlobals !== void 0 && (!Array.isArray(layer.forbiddenGlobals) || layer.forbiddenGlobals.some((entry) => typeof entry !== "string"))) {
1818
- warnings.push(
1819
- configWarning(
1820
- "CONFIG_INVALID_FORBIDDEN_GLOBALS",
1821
- `Layer "${layer.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,
1822
- { layer: layer.name }
1823
- )
1824
- );
1825
- }
1826
- const patterns = Array.isArray(layer.patterns) ? layer.patterns : [];
1827
- if (patterns.length === 0) {
1828
- warnings.push(
1829
- configWarning(
1830
- "CONFIG_LAYER_WITHOUT_PATTERNS",
1831
- `Layer "${layer.name}" has no file patterns and will never classify files.`,
1832
- { layer: layer.name }
1833
- )
1834
- );
1835
- continue;
1836
- }
1837
- for (const pattern of patterns) {
1838
- let expression;
1839
- try {
1840
- expression = globToRegExp(pattern);
1841
- } catch (error) {
1842
- warnings.push(
1843
- configWarning(
1844
- "CONFIG_INVALID_LAYER_PATTERN",
1845
- `Layer "${layer.name}" has an invalid pattern "${pattern}": ${error instanceof Error ? error.message : String(error)}`,
1846
- { layer: layer.name, pattern }
1847
- )
1848
- );
1849
- continue;
1850
- }
1851
- if (!files.some((file) => expression.test(file)) && !layer.optional) {
1852
- warnings.push(
1853
- configWarning(
1854
- "CONFIG_LAYER_PATTERN_NO_MATCHES",
1855
- `Layer "${layer.name}" pattern "${pattern}" matched no included files.`,
1856
- { layer: layer.name, pattern, failsStrict: false }
1857
- )
1858
- );
1859
- }
1860
- }
1861
- }
1862
- for (const name of duplicateLayers) {
1863
- warnings.push(
1864
- configWarning("CONFIG_DUPLICATE_LAYER", `Layer "${name}" is configured more than once.`, {
1865
- layer: name
1866
- })
1867
- );
1868
- }
1869
- if (knownLayers.size > 0) {
1870
- for (const rule of rules ?? []) {
1871
- if (rule.from && !knownLayers.has(rule.from)) {
1872
- warnings.push(
1873
- configWarning(
1874
- "CONFIG_RULE_UNKNOWN_FROM_LAYER",
1875
- `Rule references unknown source layer "${rule.from}".`,
1876
- { fromLayer: rule.from, toLayer: rule.to }
1877
- )
1878
- );
1879
- }
1880
- if (rule.to && !knownLayers.has(rule.to)) {
1881
- warnings.push(
1882
- configWarning(
1883
- "CONFIG_RULE_UNKNOWN_TO_LAYER",
1884
- `Rule references unknown target layer "${rule.to}".`,
1885
- { fromLayer: rule.from, toLayer: rule.to }
1886
- )
1887
- );
1888
- }
1889
- }
1890
- }
1891
- const ambiguousPairs = /* @__PURE__ */ new Set();
1892
- if (layers.length > 1) {
1893
- for (const file of files) {
1894
- let topScore = -1;
1895
- let topLayers = [];
1896
- for (const layer of layers) {
1897
- for (const pattern of layer.patterns ?? []) {
1898
- if (!globToRegExp(pattern).test(file)) continue;
1899
- const score = patternSpecificity(pattern);
1900
- if (score > topScore) {
1901
- topScore = score;
1902
- topLayers = [layer.name];
1903
- } else if (score === topScore && !topLayers.includes(layer.name)) {
1904
- topLayers.push(layer.name);
1905
- }
1906
- }
1907
- }
1908
- if (topLayers.length > 1) ambiguousPairs.add([...topLayers].sort().join(" + "));
1909
- }
1910
- }
1911
- if (ambiguousPairs.size > 0) {
1912
- warnings.push(
1913
- configWarning(
1914
- "CONFIG_AMBIGUOUS_LAYERS",
1915
- `Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...ambiguousPairs].join(", ")}.`,
1916
- { pairs: [...ambiguousPairs] }
1917
- )
1918
- );
1919
- }
1920
- const unclassified = files.filter((file) => !layerForRelativePath(file, layers));
1921
- if (unclassified.length > 0) {
1922
- warnings.push(
1923
- configWarning(
1924
- "CONFIG_UNCLASSIFIED_FILES",
1925
- `${unclassified.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,
1926
- { count: unclassified.length, samples: unclassified.slice(0, 5) }
1927
- )
1928
- );
1929
- }
1930
- return warnings;
1931
- }
1932
- // Annotate the CommonJS export names for ESM import in node:
1933
- 0 && (module.exports = {
1934
- ANALYSIS_IR_SCHEMA_VERSION,
1935
- ARK_ANALYSIS_RESULT_SCHEMA,
1936
- ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
1937
- ARK_CONFIG_SCHEMA,
1938
- ARK_CONFIG_SCHEMA_VERSION,
1939
- analyzeChange,
1940
- analyzeProject,
1941
- collectAnalysisConfigWarnings,
1942
- collectForbiddenCapabilityUses,
1943
- createAICodeGate,
1944
- createAdapterResult,
1945
- createArchitectureProfile,
1946
- createArchitectureProfileFromArkConfig,
1947
- createElevenLayerArkConfig,
1948
- detectArchitectureCycles,
1949
- deterministicHash,
1950
- elevenLayerProfile,
1951
- evaluateArchitectureGraph,
1952
- explainViolation,
1953
- extractSemanticDependencies,
1954
- loadArkConfigContract,
1955
- loadContract,
1956
- parseArkConfigJson,
1957
- stableSerialize,
1958
- toAdapterDiagnostic,
1959
- version
1960
- });
1
+ "use strict";var ge=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,t)=>{for(var n in t)ge(e,n,{get:t[n],enumerable:!0})},ot=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rt(t))!it.call(e,i)&&i!==n&&ge(e,i,{get:()=>t[i],enumerable:!(r=nt(t,i))||r.enumerable});return e};var st=e=>ot(ge({},"__esModule",{value:!0}),e);var zt={};at(zt,{ANALYSIS_IR_SCHEMA_VERSION:()=>ae,ARK_ANALYSIS_RESULT_SCHEMA:()=>_e,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>$e,ARK_CONFIG_SCHEMA:()=>ne,ARK_CONFIG_SCHEMA_VERSION:()=>Be,POLICY_DELTA_SCHEMA_VERSION:()=>qe,analyzeArchitectureConvergence:()=>Y,analyzeChange:()=>Le,analyzePolicyDelta:()=>Ze,analyzeProject:()=>fe,classifyArkPolicyDelta:()=>ce,collectAnalysisConfigWarnings:()=>tt,collectForbiddenCapabilityUses:()=>V,createAICodeGate:()=>xe,createAdapterResult:()=>ve,createArchitectureProfile:()=>z,createArchitectureProfileFromArkConfig:()=>Se,createElevenLayerArkConfig:()=>ke,detectArchitectureCycles:()=>we,deterministicHash:()=>P,elevenLayerProfile:()=>K,evaluateArchitectureGraph:()=>Pe,explainViolation:()=>Xe,extractSemanticDependencies:()=>H,loadArkConfigContract:()=>B,loadContract:()=>de,parseArkConfigJson:()=>ie,policyDeltaAcknowledgementMatches:()=>le,preflightChange:()=>et,stableSerialize:()=>L,toAdapterDiagnostic:()=>Q,version:()=>Re});module.exports=st(zt);var Re="3.2.0";var $e="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Oe(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ct(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==="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 Q(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"?"warning":t,i={...E(e.target)?{target:E(e.target)}:{},...E(e.fromLayer)?{fromLayer:E(e.fromLayer)}:{},...E(e.toLayer)?{toLayer:E(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:r,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:Oe(e.line,1),column:Oe(e.column,1)},evidence:i,nextAction:E(e.nextAction)??ct(n,i,e)}}function ve(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>Q(t,"error")),...(e.warnings??[]).map(t=>Q(t,"warning"))]}}var _e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","valid","diagnostics"],properties:{schemaVersion:{const:"1.1"},valid:{type:"boolean"},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"}}},nextAction:{type:"string",minLength:1}}}}}};var Ne=new Map;function Me(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ye(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=r}return t}function lt(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 F(e){let t=Ne.get(e);if(t)return t;let n=ye(e),r=lt(n),i="",a=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(i+=Me(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(i+="(?:.*/)?",c+=2):(i+=".*",c+=1):i+="[^/]*":d==="?"?i+="[^/]":d==="{"&&r?(i+="(?:",a+=1):d==="}"&&r&&a>0?(i+=")",a-=1):d===","&&r&&a>0?i+="|":i+=Me(d)}let s=new RegExp(`^${i}$`);return Ne.set(e,s),s}function he(e){let t=ye(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return r*1e4+i}function X(e,t){let n=String(e).split(/[/\\]/).join("/"),r,i=-1;for(let a of t??[])if(!(a.exclude??[]).some(s=>F(s).test(n))){for(let s of a.patterns??[])if(F(s).test(n)){let c=he(s);c>i&&(i=c,r=a.name)}}return r}function De(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(r.has(n[i].toLowerCase()))return`${n[i]}/${n[i+1]}`}function dt(e){let t=new Set;for(let n of e??[]){let i=ye(String(n)).split("/").filter(Boolean);for(let a=0;a<i.length;a+=1){let s=i[a];if((s==="**"||s==="*")&&a>0){let c=i[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function pt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let r=(n??[]).find(i=>i.name===t);return dt(r?.patterns)}function v(e,t,n,r){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let a=r?.fromPath,s=r?.toPath;if(!a||!s)continue;let c=pt(i,t,r?.layers);if(c.length===0)continue;let d=De(a,c),u=De(s,c);if(!d||!u)continue;if(d!==u)return i;continue}if(t!==n)return i}}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."};function O(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Ae(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&O(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 _(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function He(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Te(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function Ve(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=i=>i===t.fileName?t:void 0,r.fileExists=i=>i===t.fileName,r.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Ce(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function be(e,t,n,r){let i=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=i?t.getShorthandAssignmentValueSymbol(r.parent):Ce(t,r)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function H(e,t){let n,r=[],i=(s,c,d,u=!1)=>r.push({specifier:d,kind:c,line:He(t,s),typeOnly:u,unresolved:d===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))i(s,"import",_(e,s.moduleSpecifier),Te(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)i(s,"export",_(e,s.moduleSpecifier),Te(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))i(s,"require",_(e,s.moduleReference.expression));else if(e.isCallExpression(s)){let c=s.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!be(e,n??(n=Ve(e,t)),t,s.expression);(c||u)&&i(s,u?"require":"dynamic-import",_(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),r}function ft(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let i=_(e,r.argumentExpression);if(i===void 0)return;n.unshift(i)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ut(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 Fe(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let i=n.slice(0,r).join(".");if(e.has(i))return i}}function V(e,t,n){if(n.length===0)return[];let r=new Set(n),i=Ve(e,t),a=new Map,s=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&s.add(l.name.text);let c=o=>{let l=ft(e,o);if(!l)return;let f=Ce(i,l.root),y=f?a.get(f):void 0;return y?[...y,...l.segments.slice(1)]:be(e,i,t,l.root)||s.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 f=c(l.initializer),y=Ce(i,l.name);!f||!y||a.set(y,f)}let d=[],u=new Set,g=(o,l)=>{let f=He(t,l),y=`${o}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:o,line:f,node:l}))},h=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 f=c(o),y=f?Fe(r,f):void 0;y&&g(y,o)}else e.isIdentifier(o)&&r.has(o.text)&&ut(e,o)&&!be(e,i,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let f=c(o.initializer);if(f)for(let y of o.name.elements){if(!e.isIdentifier(y.name))continue;let k=y.propertyName?_(e,y.propertyName)??y.propertyName.text:y.name.text,b=Fe(r,[...f,k]);b&&g(b,o.initializer)}}e.forEachChild(o,h)};return h(t),d}function A(e,t,n){return{ruleId:e,code:e,message:t,...n}}function N(e,t){return e.slice(0,t).split(`
2
+ `).length}function gt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function yt(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 r of n){let i;for(;(i=r.re.exec(e))!==null;){let a=i.index+i[0].indexOf(i[1]),s=i[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(s)||r.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:i[1],index:a,kind:r.kind,typeOnly:c})}}return t.sort((r,i)=>r.index-i.index)}function ht(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],i=a=>{e.isStringLiteralLike(a)&&r.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,i)};return i(n),r}function mt(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 At(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function Ct(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function G(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function bt(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function je(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:bt(e,r.name)===n)}function U(e,t,n){return je(e,t,n)!==void 0}function j(e,t,n){let r=je(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function xt(e,t){let n=j(e,t,"metadata");return U(e,n,"source")}function Ge(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ge(e,t.name):!1:!1}function It(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 St(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=G(e,n);return r!==void 0&&O(r)||U(e,n,"intent")||Ge(e,n)}function kt(e,t){if(!e.isCallExpression(t))return!1;let[n,r,i]=t.arguments;return xt(e,n)||U(e,r,"source")||U(e,i,"source")}function Et(e,t){if(!e.isCallExpression(t))return;let[n,r,i]=t.arguments,a=j(e,n,"metadata");return G(e,j(e,a,"source"))??G(e,j(e,r,"source"))??G(e,j(e,i,"source"))}function Lt(e,t,n,r){let i=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,c=a?.layer,d=[],u=h=>i.getLineAndCharacterOfPosition(h.getStart(i)).line+1,g=h=>{if(It(e,h)){let o=h.arguments[0],l=G(e,o);for(let y of Ae({publishCall:!0,rawIntentName:l,objectHasIntent:U(e,o,"intent"),arkPublishCandidate:St(e,h),hasSource:kt(e,h)}))d.push(A(y.ruleId,y.message,{line:u(h),filePath:s}));let f=Et(e,h);if(r&&c&&f&&O(f)){let y=r.resolveLayer(f);y&&y!==c&&d.push(A("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${y}, but the target file is classified as ${c}.`,{line:u(h),filePath:s,target:f,fromLayer:c,toLayer:y}))}}e.forEachChild(h,g)};return g(i),d}function xe(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),i=e.enforceIntentAllowlist??t.size>0;return{validate(a,s){let c=[],d=s,u=d?.filePath,g=d?.layer,h=e.typescript,o=h?h.createSourceFile(u??"generated.ts",a,h.ScriptTarget.Latest,!0):void 0,l=o?H(e.typescript,o):void 0,f=l?l.filter(p=>p.specifier!==void 0).map(p=>({value:p.specifier,index:p.node.getStart(o),kind:p.kind,typeOnly:p.typeOnly})):yt(a),y=e.typescript?ht(e.typescript,a):gt(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let p of l?.filter(({unresolved:m})=>m)??[]){let m=p.kind==="require";c.push(A(m?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${m?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:p.line,filePath:u}))}let k=g!==void 0&&(r.has(g)||Ct(g)),b=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 p of n)if(p instanceof RegExp){p.lastIndex=0;let m=p.exec(a);p.lastIndex=0,m&&c.push(A("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${p}`,{line:m.index===void 0?void 0:N(a,m.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else a.includes(p)&&c.push(A("FORBIDDEN_SUBSTRING",`Forbidden substring: ${p}`,{line:N(a,a.indexOf(p)),filePath:u}));for(let p of f){let m=e.resolveImportTarget?.(p.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(p.value,u)}:void 0),R=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,$=m?.layer;if($&&g){let Z=v(e.architectureProfile?.rules,g,$,{fromPath:R?.relPath,toPath:m?.relPath,layers:e.architectureLayers});if(Z){if(p.typeOnly&&!Z.peerIsolation)continue;let ue=!!Z.peerIsolation;c.push(A("LAYER_IMPORT_VIOLATION",Z.message??(ue?`Layer "${g}" must not import across slices into "${$}".`:`Layer "${g}" must not import "${$}".`),{line:N(a,p.index),source:p.value,target:p.value,filePath:u,fromLayer:g,toLayer:$,suggestion:ue?"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:p.kind,peerIsolation:ue,...p.typeOnly?{typeOnly:!0}:{}}}));continue}if($!==g)continue}k||p.typeOnly||!mt(p.value)&&!At(p.value)||c.push(A("FORBIDDEN_IMPORT",`Forbidden ${p.kind} target: "${p.value}".`,{line:N(a,p.index),source:p.value,target:p.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:p.kind}}))}if(e.policies)for(let p of e.policies){let m=p.check({source:a,context:s});if(m!==!0)if(Array.isArray(m))for(let R of m)c.push(A("POLICY_VIOLATION",R.message,{filePath:u,suggestion:`Fix violation of policy "${p.name}".`}));else m===!1?c.push(A("POLICY_VIOLATION",`Policy ${p.name} failed on generated code`)):c.push(A("POLICY_VIOLATION",m.message))}if(i&&t.size>0)for(let p of y)O(p.value)&&!t.has(p.value)&&c.push(A("UNKNOWN_INTENT",`Unknown intent reference: "${p.value}"`,{line:N(a,p.index),filePath:u,target:p.value,suggestion:`Register intent "${p.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let p of y){if(!O(p.value))continue;let m=e.architectureProfile.resolveLayer(p.value);if(!m)continue;let R=v(e.architectureProfile.rules,g,m);R&&c.push(A("LAYER_REFERENCE_VIOLATION",R.message??`Layer "${g}" must not reference "${m}" through "${p.value}".`,{line:N(a,p.index),filePath:u,target:p.value,fromLayer:g,toLayer:m,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:R}}))}if(e.extensions)for(let p of e.extensions)try{let m=p.analyze(a,s);c.push(...m)}catch(m){c.push(A("EXTENSION_ERROR",`Extension "${p.name}" failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{c.push(...V(e.typescript,o,e.forbiddenGlobals[g]).map(p=>A("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${p.name}".`,{line:p.line,filePath:u,target:p.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript)try{c.push(...Lt(e.typescript,a,s,e.architectureProfile))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}return{valid:c.length===0,violations:c}}}}var Be="1.0",te="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ue=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],wt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Pt(){let e=[];for(let t of Ue)for(let n of Ue)t===n||wt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var re=Pt();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ne={$schema:"https://json-schema.org/draft/2020-12/schema",$id:te,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:te,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:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:re,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},forbiddenGlobals:w,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:{...w,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}}}}},D=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
+ ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ke(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ie(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function M(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Rt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ee(e,t,n,r,i){if(t.$ref){let a=Rt(t.$ref,r);if(!a){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ee(e,a,n,r,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ke(e)){i.push({path:n,message:`must be an object; received ${M(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&i.push({path:Ie(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||i.push({path:Ie(n,s),message:"unknown field"});for(let[s,c]of Object.entries(a))e[s]!==void 0&&ee(e[s],c,Ie(n,s),r,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${M(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(s=>JSON.stringify(s));new Set(a).size!==a.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,s)=>ee(a,t.items,`${n}[${s}]`,r,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${M(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${M(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${M(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Ot(e){return{...e,$schema:e.$schema===void 0?te: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?re.map(t=>({...t})):e.rules}}function $t(e,t="ark.config.json"){if(!Ke(e))throw new D(t,[{path:"$",message:`must be an object; received ${M(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new D(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Ot(e),migratedFrom:n}}function B(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=$t(e,t),i=[];if(ee(n,ne,"$",ne,i),i.length>0)throw new D(t,i);return{config:n,migratedFrom:r}}function ie(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new D(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return B(n,t)}function ze(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:te,schemaVersion:"1.0"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function vt(e){return e.endsWith(".")?e:`${e}.`}function _t(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(i=>i.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(i=>i.length)):0)-n}function z(e){let t=e.layers.map(i=>({...i,prefixes:i.prefixes.map(vt)})),n=[...t].sort(_t),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(i){return t.find(a=>a.match?.(i))?.name??n.find(a=>a.prefixes.some(s=>i.startsWith(s)))?.name}}}function Se(e,t={}){return z({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Nt=[{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}],K=z({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Nt,rules:re.map(e=>({...e}))}),Mt={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 ke(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ze({include:e.include??[t],layers:K.layers.map(i=>({name:i.name,patterns:(Mt[i.name]??[i.name]).map(a=>`${r}${a}/**`),intentPrefixes:i.prefixes,optional:n})),rules:[...K.rules]})}var ae="1.0";function P(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 L(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(L).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${L(t[n])}`).join(",")}}`}var qe="1.0";function C(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 I(e){return[...new Set(e??[])].sort()}function T(e,t,n,r,i){let a=I(n),s=I(r),c=new Set(a),d=new Set(s),u=s.filter(h=>!c.has(h)),g=a.filter(h=>!d.has(h));u.length===0&&g.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:a,after:s}),g.length>0&&C(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:a,after:s}))}function oe(e,t,n,r,i,a,s){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?i:i==="strengthening"?"weakening":"strengthening",message:r?a:s,before:n,after:r})}function se(e,t){let n=new Map,r=new Set;for(let i of e){let a=t(i);n.has(a)?r.add(a):n.set(a,i)}return{values:n,duplicates:[...r].sort()}}function Dt(e,t,n){let r=se(t,a=>a.name),i=se(n,a=>a.name);(r.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let s=r.values.get(a),c=i.values.get(a),d=`$.layers[${a}]`;if(!s&&c){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(s&&!c){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}!s||!c||(T(e,`${d}.patterns`,s.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."}),T(e,`${d}.exclude`,s.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."}),T(e,`${d}.forbiddenGlobals`,s.forbiddenGlobals,c.forbiddenGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),I(s.intentPrefixes).join("\0")!==I(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:I(s.intentPrefixes),after:I(c.intentPrefixes)}),oe(e,`${d}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),oe(e,`${d}.optional`,s.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 Tt(e,t,n){let r=s=>`${s.from}->${s.to}`,i=se(t,r),a=se(n,r);(i.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:a.duplicates});for(let s of[...new Set([...i.values.keys(),...a.values.keys()])].sort()){let c=i.values.get(s),d=a.values.get(s),u=`$.rules[${s}]`;if(!c&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(c&&!d){c.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!d)continue;c.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:d.allowed});let g=c.peerIsolation===!0,h=d.peerIsolation===!0;if(g!==h){let o=c.from===c.to&&d.from===d.to;C(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:o?h?"strengthening":"weakening":"judgment-required",message:o?h?"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:h})}I(c.sliceFolders).join("\0")!==I(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:I(c.sliceFolders),after:I(d.sliceFolders)})}}function Ft(e,t,n){let r=t.safety??{},i=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=r[a]??0,c=i[a]??0;s!==c&&C(e,{kind:c>s?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:c>s?"weakening":"strengthening",message:c>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:c})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])oe(e,`$.safety.${a}`,r[a]===!0,i[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Ht(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 ce(e,t){let n=[];T(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),T(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."}),T(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."}),oe(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let s=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(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}),Dt(n,e.layers,t.layers),Tt(n,e.rules,t.rules),Ft(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:"1.0",classification:Ht(n),findings:n}}function le(e,t){if(!e||e.schemaVersion!=="1.0"||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=I(e.findingIds),r=I(t.findingIds);return n.length===r.length&&n.every((i,a)=>i===r[a])}function S(e){return`${e.from}->${e.to}`}function q(e,t,n,r="dependency"){return{id:`${e}:${r}:${S(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${S(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${S(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${S(t)} from the candidate, then preflight again.`}:{}}}function Y(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),r=new Map(e.changes.map(o=>[o.path,o])),i=new Map(e.changeMap.map.dependencies.map(o=>[S(o),o])),a=new Map(e.baseDependencies.map(o=>[S(o),o])),s=new Map(e.candidateDependencies.map(o=>[S(o),o]));for(let o of[...n.values()].sort((l,f)=>l.path.localeCompare(f.path))){let l=r.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[...r.values()].sort((l,f)=>l.path.localeCompare(f.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[...i.values()].sort((l,f)=>S(l).localeCompare(S(f)))){if(s.has(S(o))){t.push(q("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};s.has(S(l))?(c.add(S(l)),t.push(q("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(q("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[o,l]of[...s].sort(([f],[y])=>f.localeCompare(y)))a.has(o)||i.has(o)||c.has(o)||!d.has(l.from)&&!d.has(l.to)||t.push({...q("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...a].sort(([f],[y])=>f.localeCompare(y)))s.has(o)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...q("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 h={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:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}function Ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function de(e,t){let n=typeof e=="string"?ie(e,t):B(e,t);return{...n,policyHash:P(L(n.config))}}function Ze(e){let t=de(e.baseConfig,e.baseSource??"base ark.config.json"),n=de(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=ce(t.config,n.config),i=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=i.length>0,s=a&&le(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:i,requiresAcknowledgement:a,acknowledged:s,valid:!a||s}}function J(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 We(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function Ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function pe(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,i="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:i,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=a}}function W(e,t,n){return e.startsWith(t,n)&&!We(e[n-1])&&!We(e[n+t.length])}function Vt(e,t){return t=Ee(e,t+6),e[t]==="("?pe(e,Ee(e,t+1)):Qe(e,t,!0)}function jt(e,t){return Qe(e,t+6,!1)}function Qe(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(W(e,"from",t))return pe(e,Ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return pe(e,t);if(t>0&&(W(e,"import",t)||W(e,"export",t)))return}}function Gt(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
+ `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="'"||r==='"'||r==="`"){let a=pe(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let i=W(e,"import",n)?Vt(e,n):W(e,"export",n)?jt(e,n):void 0;i&&t.push(i)}return t}function Ut(e,t){let n=[];for(let r of Gt(e.content)){let i=r.value;if(!i.startsWith("."))continue;let a=e.content.slice(0,r.offset).split(`
6
+ `).length,s={kind:"import",file:e.path,line:a,excerpt:r.excerpt},c=Bt(e.path,i,t);n.push({from:e.path,specifier:i,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:s})}return n}function Bt(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let i=r.join("/");for(let a of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let s=n.get(a);if(s)return s}}function Kt(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let i=v(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:r,evidence:r.evidence})}return n}function fe(e){let t=e.files.map(s=>{let c=J(s.path);return{path:c,content:s.content,contentHash:P(s.content),layer:X(c,e.contract.config.layers)??null}}).sort((s,c)=>s.path.localeCompare(c.path)),n=new Map(t.map(s=>[s.path,s])),r=t.flatMap(s=>Ut(s,n)),i=[],a=Kt(r,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:P(L(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(s=>s.name),edges:r,capabilityUses:i,violations:a}}}function Le(e){let t=new Map(e.files.map(n=>[J(n.path),n]));for(let n of e.changes){let r=J(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return fe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Xe(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function we(e){let t=0,n=new Map,r=new Map,i=new Set,a=[],s=[],c=d=>{n.set(d,t),r.set(d,t),t+=1,a.push(d),i.add(d);for(let h of[...e.get(d)??[]].sort())e.has(h)&&(n.has(h)?i.has(h)&&r.set(d,Math.min(r.get(d)??0,n.get(h)??0)):(c(h),r.set(d,Math.min(r.get(d)??0,r.get(h)??0))));if(r.get(d)!==n.get(d))return;let u=[],g;do{if(g=a.pop(),g===void 0)break;i.delete(g),u.push(g)}while(g!==d);u.length>1&&s.push(u.sort())};for(let d of[...e.keys()].sort())n.has(d)||c(d);return s.sort((d,u)=>d[0].localeCompare(u[0])).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Pe(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let s=v(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!s)continue;let c=!!s.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...c?{peerIsolation:!0}:{},message:s.message??(c?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let a=we(r);i==="soft"||i==="framework-soft"?n.push(...a.map(s=>({...s,message:`${s.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function Je(e){return P(L(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function et(e){let t=fe(e),n=new Map(t.ir.files.map(o=>[o.path,o])),r=[],i=new Set,a=[];for(let o of e.changes){let l=o.path.replace(/\\/g,"/"),f=J(o.path);if(!f||f===".."||f.startsWith("../")||l.startsWith("/")||/^[A-Za-z]:\//.test(l)||l.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(f)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}i.add(f),"delete"in o&&o.delete&&!n.has(f)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),r.push("delete"in o&&o.delete?{path:f,delete:!0}:{path:f,content:"content"in o?o.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let s=Le({...e,changes:r}),c=new Map(s.ir.files.map(o=>[o.path,o])),d=Pe({config:e.contract.config,rules:e.contract.config.rules,files:s.ir.files.map(o=>o.path),contentViolations:[],edges:s.ir.edges.filter(o=>!!o.fromLayer).map(o=>({from:o.from,fromLayer:o.fromLayer,...o.to?{to:o.to}:{},...o.toLayer?{toLayer:o.toLayer}:{},line:o.evidence.line,kind:"import"}))}),u=r.map(o=>{let l=J(o.path),f=n.get(l),y=c.get(l);return{path:l,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((o,l)=>o.path.localeCompare(l.path)),g=[...a,...d.violations].map(o=>({...o,nextAction:Ye(o)})),h=e.changeMap?Y({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:g.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:Je(t.ir.files),candidateTreeHash:Je(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:u,violations:g,warnings:d.warnings}}function x(e,t,n={}){return{ruleId:e,message:t,...n}}function tt(e){let{config:t,rules:n,files:r,manifest:i}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(x("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(x("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[l];f!==void 0&&(!Number.isInteger(f)||f<0)&&a.push(x("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],d=new Set([...s.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);s.length===0&&a.push(x("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,g=new Set;for(let l of s){if(!l.name){a.push(x("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&g.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(y=>typeof y!="string"))&&a.push(x("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let f=Array.isArray(l.patterns)?l.patterns:[];if(f.length===0){a.push(x("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let y of f){let k;try{k=F(y)}catch(b){a.push(x("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${y}": ${b instanceof Error?b.message:String(b)}`,{layer:l.name,pattern:y}));continue}!r.some(b=>k.test(b))&&!l.optional&&a.push(x("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${y}" matched no included files.`,{layer:l.name,pattern:y,failsStrict:!1}))}}for(let l of g)a.push(x("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(d.size>0)for(let l of n??[])l.from&&!d.has(l.from)&&a.push(x("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!d.has(l.to)&&a.push(x("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let h=new Set;if(s.length>1)for(let l of r){let f=-1,y=[];for(let k of s)for(let b of k.patterns??[]){if(!F(b).test(l))continue;let p=he(b);p>f?(f=p,y=[k.name]):p===f&&!y.includes(k.name)&&y.push(k.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&a.push(x("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let o=r.filter(l=>!X(l,s));return o.length>0&&a.push(x("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),a}0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,stableSerialize,toAdapterDiagnostic,version});