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