arkgate 2.13.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +53 -36
  3. package/bin/ark-check.mjs +72 -6
  4. package/bin/ark-mcp.mjs +108 -1
  5. package/bin/ark-shared.mjs +204 -149
  6. package/bin/ark.mjs +90 -25
  7. package/bin/lib/adapter-contract.mjs +93 -0
  8. package/bin/lib/agent-gates.mjs +1 -0
  9. package/bin/lib/analysis-engine.mjs +1171 -0
  10. package/bin/lib/architecture-scan.mjs +84 -135
  11. package/bin/lib/ci-and-commands.mjs +51 -15
  12. package/bin/lib/config-warnings.mjs +7 -205
  13. package/bin/lib/design-smells.mjs +434 -0
  14. package/bin/lib/doctor-plan.mjs +149 -16
  15. package/bin/lib/field-install.mjs +67 -10
  16. package/bin/lib/gate-files.mjs +42 -3
  17. package/bin/lib/graph-cycles.mjs +4 -54
  18. package/bin/lib/hook-templates.mjs +33 -1
  19. package/bin/lib/host-support-matrix.mjs +7 -1
  20. package/bin/lib/install-migrate.mjs +54 -16
  21. package/bin/lib/presets.mjs +42 -2
  22. package/bin/lib/safety-diagnostics.mjs +18 -17
  23. package/bin/lib/scan-files.mjs +12 -1
  24. package/bin/lib/skill-install.mjs +8 -1
  25. package/bin/lib/source-policy.mjs +36 -0
  26. package/bin/lib/start-preview.mjs +271 -0
  27. package/bin/lib/ts-resolve.mjs +11 -2
  28. package/bin/lib/write-path-capabilities.mjs +4 -0
  29. package/compat/nestjs.cjs +2 -0
  30. package/compat/nestjs.d.ts +2 -0
  31. package/compat/nestjs.js +1 -0
  32. package/compat/runtime.cjs +2 -0
  33. package/compat/runtime.d.ts +2 -0
  34. package/compat/runtime.js +1 -0
  35. package/dist/configContract-BxSIwVRo.d.cts +259 -0
  36. package/dist/configContract-BxSIwVRo.d.ts +259 -0
  37. package/dist/eslint/index.cjs +125 -48
  38. package/dist/eslint/index.d.cts +7 -1
  39. package/dist/eslint/index.d.ts +7 -1
  40. package/dist/eslint/index.js +125 -48
  41. package/dist/index.cjs +1248 -3302
  42. package/dist/index.d.cts +359 -483
  43. package/dist/index.d.ts +359 -483
  44. package/dist/index.js +1231 -3248
  45. package/docs/agent-guide.md +34 -16
  46. package/docs/ai-gates.md +30 -7
  47. package/docs/brownfield-adoption.md +52 -1
  48. package/docs/migrate-from-ark-runtime-kernel.md +2 -3
  49. package/docs/package-surface.md +10 -13
  50. package/docs/production-hardening.md +17 -4
  51. package/docs/typescript-support.md +27 -0
  52. package/package.json +33 -11
  53. package/schemas/ark.analysis-result.schema.json +91 -0
  54. package/server.json +2 -2
  55. package/templates/skills/ark-adopt.md +26 -3
  56. package/templates/skills/ark-architect.md +10 -2
  57. package/templates/skills/ark-autopilot.md +37 -20
  58. package/templates/skills/ark-contract.md +7 -0
  59. package/templates/skills/ark-coverage.md +44 -45
  60. package/templates/skills/ark-explain.md +8 -0
  61. package/templates/skills/ark-explore.md +117 -47
  62. package/templates/skills/ark-fix.md +22 -0
  63. package/templates/skills/ark-loop.md +15 -1
  64. package/templates/skills/ark-place.md +7 -0
  65. package/templates/skills/ark-think.md +24 -20
  66. package/dist/configContract-iBLxx5Tz.d.cts +0 -53
  67. package/dist/configContract-iBLxx5Tz.d.ts +0 -53
  68. package/dist/eslint/index.cjs.map +0 -1
  69. package/dist/eslint/index.js.map +0 -1
  70. package/dist/index.cjs.map +0 -1
  71. package/dist/index.js.map +0 -1
  72. package/dist/nestjs/index.cjs +0 -2606
  73. package/dist/nestjs/index.cjs.map +0 -1
  74. package/dist/nestjs/index.d.cts +0 -23
  75. package/dist/nestjs/index.d.ts +0 -23
  76. package/dist/nestjs/index.js +0 -2582
  77. package/dist/nestjs/index.js.map +0 -1
  78. package/dist/runtime/index.cjs +0 -4014
  79. package/dist/runtime/index.cjs.map +0 -1
  80. package/dist/runtime/index.d.cts +0 -3
  81. package/dist/runtime/index.d.ts +0 -3
  82. package/dist/runtime/index.js +0 -3925
  83. package/dist/runtime/index.js.map +0 -1
  84. package/dist/types-BxBwnBpC.d.cts +0 -1041
  85. package/dist/types-Wcs_l1_J.d.ts +0 -1041
@@ -0,0 +1,1171 @@
1
+ // GENERATED from src/kernel/analysis.ts by scripts/generate-analysis-engine.mjs.
2
+ // Do not edit this file directly.
3
+ // src/domain/analysis.ts
4
+ var ANALYSIS_IR_SCHEMA_VERSION = "1.0";
5
+ function deterministicHash(value) {
6
+ let hash = 2166136261;
7
+ for (let index = 0; index < value.length; index += 1) {
8
+ hash ^= value.charCodeAt(index);
9
+ hash = Math.imul(hash, 16777619);
10
+ }
11
+ return `fnv1a-${(hash >>> 0).toString(16).padStart(8, "0")}`;
12
+ }
13
+ function stableSerialize(value) {
14
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
15
+ if (Array.isArray(value)) return `[${value.map(stableSerialize).join(",")}]`;
16
+ const object = value;
17
+ return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(object[key])}`).join(",")}}`;
18
+ }
19
+
20
+ // src/domain/configContract.ts
21
+ var ARK_CONFIG_SCHEMA_VERSION = "1.0";
22
+ var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
23
+ var DEFAULT_LAYER_NAMES = [
24
+ "DomainModel",
25
+ "ApplicationOrchestration",
26
+ "PersistenceAdapters",
27
+ "IntegrationAdapters",
28
+ "WorkflowSagaEngine",
29
+ "BackgroundJobsScheduling",
30
+ "PresentationAdapters",
31
+ "ReportingReadModels",
32
+ "ExtensibilityMetadata",
33
+ "SecurityAuditObservability",
34
+ "Kernel"
35
+ ];
36
+ var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
37
+ "PresentationAdapters->ApplicationOrchestration",
38
+ "ApplicationOrchestration->DomainModel",
39
+ "WorkflowSagaEngine->ApplicationOrchestration",
40
+ "WorkflowSagaEngine->DomainModel",
41
+ "BackgroundJobsScheduling->ApplicationOrchestration"
42
+ ]);
43
+ function createDefaultRules() {
44
+ const rules = [];
45
+ for (const from of DEFAULT_LAYER_NAMES) {
46
+ for (const to of DEFAULT_LAYER_NAMES) {
47
+ if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
48
+ rules.push({ from, to, allowed: false });
49
+ }
50
+ }
51
+ return rules;
52
+ }
53
+ var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
54
+ var stringArraySchema = {
55
+ type: "array",
56
+ items: { type: "string", minLength: 1 },
57
+ uniqueItems: true
58
+ };
59
+ var ARK_CONFIG_SCHEMA = {
60
+ $schema: "https://json-schema.org/draft/2020-12/schema",
61
+ $id: ARK_CONFIG_SCHEMA_URL,
62
+ title: "ArkGate architecture contract",
63
+ description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
64
+ type: "object",
65
+ additionalProperties: false,
66
+ required: ["$schema", "schemaVersion", "include", "layers", "rules"],
67
+ properties: {
68
+ $schema: {
69
+ type: "string",
70
+ minLength: 1,
71
+ default: ARK_CONFIG_SCHEMA_URL,
72
+ description: "Editor-facing URL or local path for this JSON Schema."
73
+ },
74
+ schemaVersion: {
75
+ type: "string",
76
+ const: ARK_CONFIG_SCHEMA_VERSION,
77
+ default: ARK_CONFIG_SCHEMA_VERSION
78
+ },
79
+ name: { type: "string", minLength: 1 },
80
+ include: { ...stringArraySchema, minItems: 1, default: ["src"] },
81
+ exclude: { ...stringArraySchema, default: [] },
82
+ excludeGenerated: { type: "boolean", default: true },
83
+ frameworkOverlay: { type: "string", minLength: 1 },
84
+ layers: {
85
+ type: "array",
86
+ default: [],
87
+ items: { $ref: "#/$defs/layer" }
88
+ },
89
+ rules: {
90
+ type: "array",
91
+ default: DEFAULT_ARK_CONFIG_RULES,
92
+ items: { $ref: "#/$defs/rule" }
93
+ },
94
+ cyclePolicy: {
95
+ type: "string",
96
+ enum: ["strict", "soft", "framework-soft", "off"],
97
+ default: "strict"
98
+ },
99
+ dynamicImportAllowlist: { ...stringArraySchema, default: [] },
100
+ safety: {
101
+ $ref: "#/$defs/safety",
102
+ default: {
103
+ maxTsSuppressions: 0,
104
+ maxAnyCasts: 0,
105
+ allowInMemory: false,
106
+ allowDisabledPeerIsolation: false
107
+ }
108
+ }
109
+ },
110
+ $defs: {
111
+ layer: {
112
+ type: "object",
113
+ additionalProperties: false,
114
+ required: ["name", "patterns"],
115
+ properties: {
116
+ name: { type: "string", minLength: 1 },
117
+ patterns: { ...stringArraySchema, minItems: 1 },
118
+ exclude: stringArraySchema,
119
+ intentPrefixes: stringArraySchema,
120
+ description: { type: "string", minLength: 1 },
121
+ forbiddenGlobals: stringArraySchema,
122
+ mayImportInfrastructure: { type: "boolean" },
123
+ optional: { type: "boolean" }
124
+ }
125
+ },
126
+ rule: {
127
+ type: "object",
128
+ additionalProperties: false,
129
+ required: ["from", "to", "allowed"],
130
+ properties: {
131
+ from: { type: "string", minLength: 1 },
132
+ to: { type: "string", minLength: 1 },
133
+ allowed: { type: "boolean" },
134
+ message: { type: "string", minLength: 1 },
135
+ peerIsolation: { type: "boolean" },
136
+ sliceFolders: { ...stringArraySchema, minItems: 1 }
137
+ }
138
+ },
139
+ safety: {
140
+ type: "object",
141
+ additionalProperties: false,
142
+ properties: {
143
+ maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
144
+ maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
145
+ allowInMemory: { type: "boolean", default: false },
146
+ allowDisabledPeerIsolation: { type: "boolean", default: false }
147
+ }
148
+ }
149
+ }
150
+ };
151
+ var ArkConfigValidationError = class extends Error {
152
+ issues;
153
+ source;
154
+ constructor(source, issues) {
155
+ super(
156
+ `Invalid ArkGate config (${source}):
157
+ ${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`
158
+ );
159
+ this.name = "ArkConfigValidationError";
160
+ this.source = source;
161
+ this.issues = issues;
162
+ }
163
+ };
164
+ function isObject(value) {
165
+ return value !== null && typeof value === "object" && !Array.isArray(value);
166
+ }
167
+ function propertyPath(parent, key) {
168
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
169
+ }
170
+ function valueType(value) {
171
+ if (value === null) return "null";
172
+ if (Array.isArray(value)) return "array";
173
+ return typeof value;
174
+ }
175
+ function resolveSchemaRef(ref, root) {
176
+ const prefix = "#/$defs/";
177
+ if (!ref.startsWith(prefix)) return void 0;
178
+ return root.$defs[ref.slice(prefix.length)];
179
+ }
180
+ function validateNode(value, schema, path, root, issues) {
181
+ if (schema.$ref) {
182
+ const referenced = resolveSchemaRef(schema.$ref, root);
183
+ if (!referenced) {
184
+ issues.push({ path, message: `schema reference ${schema.$ref} cannot be resolved` });
185
+ return;
186
+ }
187
+ validateNode(value, referenced, path, root, issues);
188
+ return;
189
+ }
190
+ if (schema.const !== void 0 && !Object.is(value, schema.const)) {
191
+ issues.push({ path, message: `must equal ${JSON.stringify(schema.const)}` });
192
+ return;
193
+ }
194
+ if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
195
+ issues.push({ path, message: `must be one of ${schema.enum.map(String).join(", ")}` });
196
+ return;
197
+ }
198
+ if (schema.type === "object") {
199
+ if (!isObject(value)) {
200
+ issues.push({ path, message: `must be an object; received ${valueType(value)}` });
201
+ return;
202
+ }
203
+ const properties = schema.properties ?? {};
204
+ for (const key of schema.required ?? []) {
205
+ if (value[key] === void 0) {
206
+ issues.push({ path: propertyPath(path, key), message: "is required" });
207
+ }
208
+ }
209
+ if (schema.additionalProperties === false) {
210
+ for (const key of Object.keys(value)) {
211
+ if (!(key in properties)) {
212
+ issues.push({ path: propertyPath(path, key), message: "unknown field" });
213
+ }
214
+ }
215
+ }
216
+ for (const [key, childSchema] of Object.entries(properties)) {
217
+ if (value[key] !== void 0) {
218
+ validateNode(value[key], childSchema, propertyPath(path, key), root, issues);
219
+ }
220
+ }
221
+ return;
222
+ }
223
+ if (schema.type === "array") {
224
+ if (!Array.isArray(value)) {
225
+ issues.push({ path, message: `must be an array; received ${valueType(value)}` });
226
+ return;
227
+ }
228
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
229
+ issues.push({ path, message: `must contain at least ${schema.minItems} item(s)` });
230
+ }
231
+ if (schema.uniqueItems) {
232
+ const serialized = value.map((entry) => JSON.stringify(entry));
233
+ if (new Set(serialized).size !== serialized.length) {
234
+ issues.push({ path, message: "must not contain duplicate items" });
235
+ }
236
+ }
237
+ if (schema.items) {
238
+ value.forEach(
239
+ (entry, index) => validateNode(entry, schema.items, `${path}[${index}]`, root, issues)
240
+ );
241
+ }
242
+ return;
243
+ }
244
+ if (schema.type === "string") {
245
+ if (typeof value !== "string") {
246
+ issues.push({ path, message: `must be a string; received ${valueType(value)}` });
247
+ return;
248
+ }
249
+ if (schema.minLength !== void 0 && value.length < schema.minLength) {
250
+ issues.push({ path, message: `must contain at least ${schema.minLength} character(s)` });
251
+ }
252
+ return;
253
+ }
254
+ if (schema.type === "boolean") {
255
+ if (typeof value !== "boolean") {
256
+ issues.push({ path, message: `must be a boolean; received ${valueType(value)}` });
257
+ }
258
+ return;
259
+ }
260
+ if (schema.type === "integer") {
261
+ if (!Number.isInteger(value)) {
262
+ issues.push({ path, message: `must be an integer; received ${valueType(value)}` });
263
+ return;
264
+ }
265
+ if (schema.minimum !== void 0 && value < schema.minimum) {
266
+ issues.push({ path, message: `must be at least ${schema.minimum}` });
267
+ }
268
+ }
269
+ }
270
+ function defaultedConfig(input) {
271
+ return {
272
+ ...input,
273
+ $schema: input.$schema === void 0 ? ARK_CONFIG_SCHEMA_URL : input.$schema,
274
+ schemaVersion: input.schemaVersion === void 0 ? ARK_CONFIG_SCHEMA_VERSION : input.schemaVersion,
275
+ include: input.include === void 0 ? ["src"] : input.include,
276
+ layers: input.layers === void 0 ? [] : input.layers,
277
+ rules: input.rules === void 0 ? DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule })) : input.rules
278
+ };
279
+ }
280
+ function migrateArkConfig(input, source = "ark.config.json") {
281
+ if (!isObject(input)) {
282
+ throw new ArkConfigValidationError(source, [
283
+ { path: "$", message: `must be an object; received ${valueType(input)}` }
284
+ ]);
285
+ }
286
+ const migratedFrom = input.schemaVersion === void 0 ? "unversioned" : null;
287
+ if (input.schemaVersion !== void 0 && input.schemaVersion !== ARK_CONFIG_SCHEMA_VERSION) {
288
+ throw new ArkConfigValidationError(source, [
289
+ {
290
+ path: "$.schemaVersion",
291
+ message: `unsupported version ${JSON.stringify(input.schemaVersion)}; expected ${ARK_CONFIG_SCHEMA_VERSION}`
292
+ }
293
+ ]);
294
+ }
295
+ return { candidate: defaultedConfig(input), migratedFrom };
296
+ }
297
+ function loadArkConfigContract(input, source = "ark.config.json") {
298
+ const { candidate, migratedFrom } = migrateArkConfig(input, source);
299
+ const issues = [];
300
+ validateNode(
301
+ candidate,
302
+ ARK_CONFIG_SCHEMA,
303
+ "$",
304
+ ARK_CONFIG_SCHEMA,
305
+ issues
306
+ );
307
+ if (issues.length > 0) throw new ArkConfigValidationError(source, issues);
308
+ return { config: candidate, migratedFrom };
309
+ }
310
+ function parseArkConfigJson(json, source = "ark.config.json") {
311
+ let input;
312
+ try {
313
+ input = JSON.parse(json);
314
+ } catch (error) {
315
+ throw new ArkConfigValidationError(source, [
316
+ {
317
+ path: "$",
318
+ message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
319
+ }
320
+ ]);
321
+ }
322
+ return loadArkConfigContract(input, source);
323
+ }
324
+
325
+ // src/domain/layerMatch.ts
326
+ var regexpCache = /* @__PURE__ */ new Map();
327
+ function escapeLiteral(ch) {
328
+ return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
329
+ }
330
+ function normalizeGlobSeparators(pattern) {
331
+ let out = "";
332
+ for (let i = 0; i < pattern.length; i += 1) {
333
+ const c = pattern[i];
334
+ if (c === "\\" && i + 1 < pattern.length) {
335
+ const next = pattern[i + 1];
336
+ if ("*?{}[],".includes(next) || next === "\\") {
337
+ out += "\\" + next;
338
+ i += 1;
339
+ continue;
340
+ }
341
+ out += "/";
342
+ continue;
343
+ }
344
+ out += c;
345
+ }
346
+ return out;
347
+ }
348
+ function bracesBalanced(glob) {
349
+ let depth = 0;
350
+ for (let i = 0; i < glob.length; i += 1) {
351
+ const c = glob[i];
352
+ if (c === "\\") {
353
+ i += 1;
354
+ continue;
355
+ }
356
+ if (c === "{") depth += 1;
357
+ else if (c === "}") {
358
+ depth -= 1;
359
+ if (depth < 0) return false;
360
+ }
361
+ }
362
+ return depth === 0;
363
+ }
364
+ function globToRegExp(pattern) {
365
+ const cached = regexpCache.get(pattern);
366
+ if (cached) return cached;
367
+ const glob = normalizeGlobSeparators(pattern);
368
+ const useBraces = bracesBalanced(glob);
369
+ let out = "";
370
+ let braceDepth = 0;
371
+ for (let i = 0; i < glob.length; i += 1) {
372
+ const c = glob[i];
373
+ if (c === "\\" && i + 1 < glob.length) {
374
+ out += escapeLiteral(glob[i + 1]);
375
+ i += 1;
376
+ } else if (c === "*") {
377
+ if (glob[i + 1] === "*") {
378
+ if (glob[i + 2] === "/") {
379
+ out += "(?:.*/)?";
380
+ i += 2;
381
+ } else {
382
+ out += ".*";
383
+ i += 1;
384
+ }
385
+ } else {
386
+ out += "[^/]*";
387
+ }
388
+ } else if (c === "?") {
389
+ out += "[^/]";
390
+ } else if (c === "{" && useBraces) {
391
+ out += "(?:";
392
+ braceDepth += 1;
393
+ } else if (c === "}" && useBraces && braceDepth > 0) {
394
+ out += ")";
395
+ braceDepth -= 1;
396
+ } else if (c === "," && useBraces && braceDepth > 0) {
397
+ out += "|";
398
+ } else {
399
+ out += escapeLiteral(c);
400
+ }
401
+ }
402
+ const re = new RegExp(`^${out}$`);
403
+ regexpCache.set(pattern, re);
404
+ return re;
405
+ }
406
+ function patternSpecificity(pattern) {
407
+ const glob = normalizeGlobSeparators(String(pattern));
408
+ const beforeWildcard = glob.split("*")[0];
409
+ const literalSegments = beforeWildcard.split("/").filter(Boolean).length;
410
+ const literalLength = glob.replace(/\*/g, "").length;
411
+ return literalSegments * 1e4 + literalLength;
412
+ }
413
+ function layerForRelativePath(relPath, layers) {
414
+ const rel = String(relPath).split(/[/\\]/).join("/");
415
+ let bestName;
416
+ let bestScore = -1;
417
+ for (const layer of layers ?? []) {
418
+ if ((layer.exclude ?? []).some((pattern) => globToRegExp(pattern).test(rel))) {
419
+ continue;
420
+ }
421
+ for (const pattern of layer.patterns ?? []) {
422
+ if (globToRegExp(pattern).test(rel)) {
423
+ const score = patternSpecificity(pattern);
424
+ if (score > bestScore) {
425
+ bestScore = score;
426
+ bestName = layer.name;
427
+ }
428
+ }
429
+ }
430
+ }
431
+ return bestName;
432
+ }
433
+ function sliceIdForPath(relPath, sliceFolders) {
434
+ if (!sliceFolders?.length) return void 0;
435
+ const parts = String(relPath).split(/[/\\]/).filter(Boolean);
436
+ const folders = new Set(sliceFolders.map((s) => String(s).toLowerCase()));
437
+ for (let i = 0; i < parts.length - 1; i += 1) {
438
+ if (folders.has(parts[i].toLowerCase())) {
439
+ return `${parts[i]}/${parts[i + 1]}`;
440
+ }
441
+ }
442
+ return void 0;
443
+ }
444
+ function inferSliceFoldersFromPatterns(patterns) {
445
+ const out = /* @__PURE__ */ new Set();
446
+ for (const pattern of patterns ?? []) {
447
+ const glob = normalizeGlobSeparators(String(pattern));
448
+ const parts = glob.split("/").filter(Boolean);
449
+ for (let i = 0; i < parts.length; i += 1) {
450
+ const part = parts[i];
451
+ if ((part === "**" || part === "*") && i > 0) {
452
+ const prev = parts[i - 1];
453
+ if (prev && !prev.includes("*") && !prev.includes("{") && !prev.includes("}")) {
454
+ out.add(prev);
455
+ }
456
+ }
457
+ }
458
+ }
459
+ return [...out];
460
+ }
461
+ function resolveSliceFolders(rule, layerName, layers) {
462
+ if (Array.isArray(rule.sliceFolders) && rule.sliceFolders.length > 0) {
463
+ return rule.sliceFolders.filter((s) => typeof s === "string" && s.length > 0);
464
+ }
465
+ const layer = (layers ?? []).find((l) => l.name === layerName);
466
+ return inferSliceFoldersFromPatterns(layer?.patterns);
467
+ }
468
+ function findDeniedEdgeRule(rules, from, to, options) {
469
+ for (const rule of rules ?? []) {
470
+ if (rule.from !== from || rule.to !== to) continue;
471
+ if (rule.allowed !== false) continue;
472
+ if (rule.peerIsolation) {
473
+ const fromPath = options?.fromPath;
474
+ const toPath = options?.toPath;
475
+ if (!fromPath || !toPath) continue;
476
+ const folders = resolveSliceFolders(rule, from, options?.layers);
477
+ if (folders.length === 0) continue;
478
+ const fromSlice = sliceIdForPath(fromPath, folders);
479
+ const toSlice = sliceIdForPath(toPath, folders);
480
+ if (!fromSlice || !toSlice) continue;
481
+ if (fromSlice !== toSlice) return rule;
482
+ continue;
483
+ }
484
+ if (from === to) continue;
485
+ return rule;
486
+ }
487
+ return void 0;
488
+ }
489
+
490
+ // src/kernel/semanticAnalysis.ts
491
+ function literalText(ts, node) {
492
+ return node && ts.isStringLiteralLike(node) ? node.text : void 0;
493
+ }
494
+ function lineOf(sourceFile, node) {
495
+ return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
496
+ }
497
+ function isTypeOnlyReference(ts, node) {
498
+ if (ts.isImportDeclaration(node)) {
499
+ const clause = node.importClause;
500
+ if (!clause) return false;
501
+ if (clause.isTypeOnly) return true;
502
+ const named = clause.namedBindings;
503
+ return Boolean(
504
+ named && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((element) => element.isTypeOnly)
505
+ );
506
+ }
507
+ if (ts.isExportDeclaration(node)) {
508
+ if (node.isTypeOnly) return true;
509
+ const clause = node.exportClause;
510
+ return Boolean(
511
+ clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly)
512
+ );
513
+ }
514
+ return false;
515
+ }
516
+ function singleFileChecker(ts, sourceFile) {
517
+ const options = { noLib: true, noResolve: true, target: ts.ScriptTarget.Latest };
518
+ const host = ts.createCompilerHost(options, true);
519
+ host.getSourceFile = (fileName) => fileName === sourceFile.fileName ? sourceFile : void 0;
520
+ host.fileExists = (fileName) => fileName === sourceFile.fileName;
521
+ host.readFile = (fileName) => fileName === sourceFile.fileName ? sourceFile.text : void 0;
522
+ return ts.createProgram([sourceFile.fileName], options, host).getTypeChecker();
523
+ }
524
+ function symbolAt(checker, node) {
525
+ try {
526
+ return checker.getSymbolAtLocation(node);
527
+ } catch {
528
+ return void 0;
529
+ }
530
+ }
531
+ function localDeclaration(ts, checker, sourceFile, node) {
532
+ const shorthand = node.parent && ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
533
+ let symbol;
534
+ try {
535
+ symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(node.parent) : symbolAt(checker, node);
536
+ } catch {
537
+ symbol = void 0;
538
+ }
539
+ return Boolean(
540
+ symbol?.declarations?.some(
541
+ (declaration) => declaration.getSourceFile().fileName === sourceFile.fileName
542
+ )
543
+ );
544
+ }
545
+ function extractSemanticDependencies(ts, sourceFile) {
546
+ let checker;
547
+ const dependencies = [];
548
+ const add = (node, kind, specifier, typeOnly = false) => dependencies.push({
549
+ specifier,
550
+ kind,
551
+ line: lineOf(sourceFile, node),
552
+ typeOnly,
553
+ unresolved: specifier === void 0,
554
+ node
555
+ });
556
+ const visit = (node) => {
557
+ if (ts.isImportDeclaration(node)) {
558
+ add(node, "import", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
559
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
560
+ add(node, "export", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
561
+ } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
562
+ add(node, "require", literalText(ts, node.moduleReference.expression));
563
+ } else if (ts.isCallExpression(node)) {
564
+ const dynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
565
+ const requireCall = ts.isIdentifier(node.expression) && node.expression.text === "require";
566
+ const directRequire = requireCall && !localDeclaration(
567
+ ts,
568
+ checker ?? (checker = singleFileChecker(ts, sourceFile)),
569
+ sourceFile,
570
+ node.expression
571
+ );
572
+ if (dynamicImport || directRequire) {
573
+ add(node, directRequire ? "require" : "dynamic-import", literalText(ts, node.arguments[0]));
574
+ }
575
+ }
576
+ ts.forEachChild(node, visit);
577
+ };
578
+ visit(sourceFile);
579
+ return dependencies;
580
+ }
581
+ function staticAccessPath(ts, node) {
582
+ const segments = [];
583
+ let current = node;
584
+ while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) {
585
+ if (ts.isPropertyAccessExpression(current)) segments.unshift(current.name.text);
586
+ else {
587
+ const property = literalText(ts, current.argumentExpression);
588
+ if (property === void 0) return void 0;
589
+ segments.unshift(property);
590
+ }
591
+ current = current.expression;
592
+ }
593
+ if (!ts.isIdentifier(current)) return void 0;
594
+ segments.unshift(current.text);
595
+ return { root: current, segments };
596
+ }
597
+ function runtimeIdentifierReference(ts, node) {
598
+ const parent = node.parent;
599
+ if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) return false;
600
+ return ts.isExpressionNode(node) && !ts.isInTypeQuery(node) || ts.isShorthandPropertyAssignment(parent) && parent.name === node;
601
+ }
602
+ function bestForbiddenMatch(entries, segments) {
603
+ const normalized = segments[0] === "globalThis" ? segments.slice(1) : segments;
604
+ for (let length = normalized.length; length >= 1; length -= 1) {
605
+ const candidate = normalized.slice(0, length).join(".");
606
+ if (entries.has(candidate)) return candidate;
607
+ }
608
+ return void 0;
609
+ }
610
+ function collectForbiddenCapabilityUses(ts, sourceFile, forbidden) {
611
+ if (forbidden.length === 0) return [];
612
+ const entries = new Set(forbidden);
613
+ const checker = singleFileChecker(ts, sourceFile);
614
+ const aliases = /* @__PURE__ */ new Map();
615
+ const topLevelNames = /* @__PURE__ */ new Set();
616
+ for (const statement of sourceFile.statements) {
617
+ if (ts.isVariableStatement(statement)) {
618
+ for (const declaration of statement.declarationList.declarations) {
619
+ if (ts.isIdentifier(declaration.name)) topLevelNames.add(declaration.name.text);
620
+ }
621
+ }
622
+ }
623
+ const resolvePath = (node) => {
624
+ const path = staticAccessPath(ts, node);
625
+ if (!path) return void 0;
626
+ const symbol = symbolAt(checker, path.root);
627
+ const alias = symbol ? aliases.get(symbol) : void 0;
628
+ if (alias) return [...alias, ...path.segments.slice(1)];
629
+ return localDeclaration(ts, checker, sourceFile, path.root) || topLevelNames.has(path.root.text) ? void 0 : path.segments;
630
+ };
631
+ for (const statement of sourceFile.statements) {
632
+ if (!ts.isVariableStatement(statement)) continue;
633
+ for (const declaration of statement.declarationList.declarations) {
634
+ if (!declaration.initializer || !ts.isIdentifier(declaration.name)) continue;
635
+ const path = resolvePath(declaration.initializer);
636
+ const symbol = symbolAt(checker, declaration.name);
637
+ if (!path || !symbol) continue;
638
+ aliases.set(symbol, path);
639
+ }
640
+ }
641
+ const uses = [];
642
+ const seen = /* @__PURE__ */ new Set();
643
+ const flag = (name, node) => {
644
+ const line = lineOf(sourceFile, node);
645
+ const key = `${name}:${node.getStart(sourceFile)}`;
646
+ if (seen.has(key)) return;
647
+ seen.add(key);
648
+ uses.push({ name, line, node });
649
+ };
650
+ const visit = (node) => {
651
+ const parentContinuesPath = node.parent && (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node;
652
+ if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && !parentContinuesPath) {
653
+ const path = resolvePath(node);
654
+ const match = path ? bestForbiddenMatch(entries, path) : void 0;
655
+ if (match) flag(match, node);
656
+ } else if (ts.isIdentifier(node) && entries.has(node.text) && runtimeIdentifierReference(ts, node) && !localDeclaration(ts, checker, sourceFile, node)) {
657
+ flag(node.text, node);
658
+ }
659
+ if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer) {
660
+ const base = resolvePath(node.initializer);
661
+ if (base) {
662
+ for (const element of node.name.elements) {
663
+ if (!ts.isIdentifier(element.name)) continue;
664
+ const property = element.propertyName ? literalText(ts, element.propertyName) ?? element.propertyName.text : element.name.text;
665
+ const match = bestForbiddenMatch(entries, [...base, property]);
666
+ if (match) flag(match, node.initializer);
667
+ }
668
+ }
669
+ }
670
+ ts.forEachChild(node, visit);
671
+ };
672
+ visit(sourceFile);
673
+ return uses;
674
+ }
675
+
676
+ // src/domain/sourcePolicy.ts
677
+ var SOURCE_POLICY_MESSAGES = {
678
+ RAW_EVENT_PUBLISH: "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",
679
+ PUBLISH_MISSING_SOURCE: "Strict Ark publish calls must include metadata.source."
680
+ };
681
+ function looksLikeArkIntent(value) {
682
+ return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(
683
+ value
684
+ );
685
+ }
686
+ function classifyPublishFacts(facts) {
687
+ if (!facts.publishCall) return [];
688
+ const findings = [];
689
+ if (facts.rawIntentName !== void 0 && looksLikeArkIntent(facts.rawIntentName) || facts.objectHasIntent) {
690
+ findings.push({
691
+ ruleId: "RAW_EVENT_PUBLISH",
692
+ message: SOURCE_POLICY_MESSAGES.RAW_EVENT_PUBLISH
693
+ });
694
+ }
695
+ if (facts.arkPublishCandidate && !facts.hasSource) {
696
+ findings.push({
697
+ ruleId: "PUBLISH_MISSING_SOURCE",
698
+ message: SOURCE_POLICY_MESSAGES.PUBLISH_MISSING_SOURCE
699
+ });
700
+ }
701
+ return findings;
702
+ }
703
+
704
+ // src/kernel/analysis.ts
705
+ function loadContract(input, source) {
706
+ const loaded = typeof input === "string" ? parseArkConfigJson(input, source) : loadArkConfigContract(input, source);
707
+ return { ...loaded, policyHash: deterministicHash(stableSerialize(loaded.config)) };
708
+ }
709
+ function normalizePath(value) {
710
+ return value.replace(/\\/g, "/").replace(/^\.\//, "");
711
+ }
712
+ function isIdentifierCharacter(value) {
713
+ return value !== void 0 && /[A-Za-z0-9_$]/.test(value);
714
+ }
715
+ function skipWhitespace(source, index) {
716
+ while (index < source.length && /\s/.test(source[index])) index += 1;
717
+ return index;
718
+ }
719
+ function readString(source, index) {
720
+ const quote = source[index];
721
+ if (quote !== "'" && quote !== '"') return void 0;
722
+ const start = index;
723
+ let value = "";
724
+ for (index += 1; index < source.length; index += 1) {
725
+ const current = source[index];
726
+ if (current === quote) {
727
+ return { value, offset: start, excerpt: source.slice(start, index + 1) };
728
+ }
729
+ if (current === "\\" && index + 1 < source.length) {
730
+ value += source[index + 1];
731
+ index += 1;
732
+ } else {
733
+ value += current;
734
+ }
735
+ }
736
+ return void 0;
737
+ }
738
+ function isWordAt(source, word, index) {
739
+ return source.startsWith(word, index) && !isIdentifierCharacter(source[index - 1]) && !isIdentifierCharacter(source[index + word.length]);
740
+ }
741
+ function specifierAfterImport(source, index) {
742
+ index = skipWhitespace(source, index + "import".length);
743
+ if (source[index] === "(") return readString(source, skipWhitespace(source, index + 1));
744
+ return specifierInStaticStatement(source, index, true);
745
+ }
746
+ function specifierAfterExport(source, index) {
747
+ return specifierInStaticStatement(source, index + "export".length, false);
748
+ }
749
+ function specifierInStaticStatement(source, index, allowDirectSpecifier) {
750
+ for (; index < source.length; index += 1) {
751
+ if (source[index] === ";") return void 0;
752
+ if (isWordAt(source, "from", index)) {
753
+ return readString(source, skipWhitespace(source, index + "from".length));
754
+ }
755
+ if (allowDirectSpecifier && (source[index] === "'" || source[index] === '"')) {
756
+ return readString(source, index);
757
+ }
758
+ if (index > 0 && (isWordAt(source, "import", index) || isWordAt(source, "export", index))) {
759
+ return void 0;
760
+ }
761
+ }
762
+ return void 0;
763
+ }
764
+ function moduleSpecifiers(source) {
765
+ const result = [];
766
+ for (let index = 0; index < source.length; index += 1) {
767
+ const current = source[index];
768
+ if (current === "/" && source[index + 1] === "/") {
769
+ index = source.indexOf("\n", index + 2);
770
+ if (index < 0) break;
771
+ continue;
772
+ }
773
+ if (current === "/" && source[index + 1] === "*") {
774
+ const end = source.indexOf("*/", index + 2);
775
+ if (end < 0) break;
776
+ index = end + 1;
777
+ continue;
778
+ }
779
+ if (current === "'" || current === '"' || current === "`") {
780
+ const string = readString(source, index);
781
+ if (string) index = string.offset + string.excerpt.length - 1;
782
+ continue;
783
+ }
784
+ const specifier = isWordAt(source, "import", index) ? specifierAfterImport(source, index) : isWordAt(source, "export", index) ? specifierAfterExport(source, index) : void 0;
785
+ if (specifier) result.push(specifier);
786
+ }
787
+ return result;
788
+ }
789
+ function importEdges(file, files) {
790
+ const edges = [];
791
+ for (const moduleSpecifier of moduleSpecifiers(file.content)) {
792
+ const specifier = moduleSpecifier.value;
793
+ if (!specifier.startsWith(".")) continue;
794
+ const line = file.content.slice(0, moduleSpecifier.offset).split("\n").length;
795
+ const evidence = {
796
+ kind: "import",
797
+ file: file.path,
798
+ line,
799
+ excerpt: moduleSpecifier.excerpt
800
+ };
801
+ const target = resolveSpecifier(file.path, specifier, files);
802
+ edges.push({
803
+ from: file.path,
804
+ specifier,
805
+ to: target?.path ?? null,
806
+ resolution: target ? "resolved" : "unresolved",
807
+ fromLayer: file.layer,
808
+ toLayer: target?.layer ?? null,
809
+ evidence
810
+ });
811
+ }
812
+ return edges;
813
+ }
814
+ function resolveSpecifier(from, specifier, files) {
815
+ const segments = from.split("/");
816
+ segments.pop();
817
+ for (const segment of specifier.split("/")) {
818
+ if (segment === "." || segment === "") continue;
819
+ if (segment === "..") segments.pop();
820
+ else segments.push(segment);
821
+ }
822
+ const base = segments.join("/");
823
+ for (const candidate of [base, `${base}.ts`, `${base}.tsx`, `${base}.mts`, `${base}.cts`, `${base}/index.ts`, `${base}/index.tsx`]) {
824
+ const found = files.get(candidate);
825
+ if (found) return found;
826
+ }
827
+ return void 0;
828
+ }
829
+ function violationsFor(edges, config) {
830
+ const violations = [];
831
+ for (const edge of edges) {
832
+ if (!edge.to || !edge.fromLayer || !edge.toLayer) continue;
833
+ const rule = findDeniedEdgeRule(config.rules, edge.fromLayer, edge.toLayer, {
834
+ fromPath: edge.from,
835
+ toPath: edge.to,
836
+ layers: config.layers
837
+ });
838
+ if (!rule) continue;
839
+ violations.push({
840
+ ruleId: `layer-dependency:${rule.from}->${rule.to}`,
841
+ message: rule.message ?? `${rule.from} must not depend on ${rule.to}.`,
842
+ edge,
843
+ evidence: edge.evidence
844
+ });
845
+ }
846
+ return violations;
847
+ }
848
+ function analyzeProject(input) {
849
+ const files = input.files.map((inputFile) => {
850
+ const path = normalizePath(inputFile.path);
851
+ return {
852
+ path,
853
+ content: inputFile.content,
854
+ contentHash: deterministicHash(inputFile.content),
855
+ layer: layerForRelativePath(path, input.contract.config.layers) ?? null
856
+ };
857
+ }).sort((left, right) => left.path.localeCompare(right.path));
858
+ const fileByPath = new Map(files.map((file) => [file.path, file]));
859
+ const edges = files.flatMap((file) => importEdges(file, fileByPath));
860
+ const capabilityUses = [];
861
+ const violations = violationsFor(edges, input.contract.config);
862
+ return {
863
+ ir: {
864
+ schemaVersion: ANALYSIS_IR_SCHEMA_VERSION,
865
+ policyHash: input.contract.policyHash,
866
+ compilerOptionsHash: deterministicHash(stableSerialize(input.compilerOptions ?? {})),
867
+ files,
868
+ layers: input.contract.config.layers.map((layer) => layer.name),
869
+ edges,
870
+ capabilityUses,
871
+ violations
872
+ }
873
+ };
874
+ }
875
+ function analyzeChange(input) {
876
+ const files = new Map(input.files.map((file) => [normalizePath(file.path), file]));
877
+ for (const change of input.changes) {
878
+ const path = normalizePath(change.path);
879
+ if ("delete" in change && change.delete) files.delete(path);
880
+ else if ("content" in change) files.set(path, { path, content: change.content });
881
+ }
882
+ return analyzeProject({
883
+ contract: input.contract,
884
+ files: [...files.values()],
885
+ compilerOptions: input.compilerOptions
886
+ });
887
+ }
888
+ function explainViolation(violation) {
889
+ const location = `${violation.evidence.file}:${violation.evidence.line}`;
890
+ if (!violation.edge) return `${violation.ruleId} at ${location}: ${violation.message}`;
891
+ const target = violation.edge.to ?? violation.edge.specifier;
892
+ return `${violation.ruleId} at ${location}: ${violation.edge.from} imports ${target}. ${violation.message}`;
893
+ }
894
+ function detectArchitectureCycles(graph) {
895
+ let index = 0;
896
+ const indices = /* @__PURE__ */ new Map();
897
+ const low = /* @__PURE__ */ new Map();
898
+ const onStack = /* @__PURE__ */ new Set();
899
+ const stack = [];
900
+ const components = [];
901
+ const connect = (file) => {
902
+ indices.set(file, index);
903
+ low.set(file, index);
904
+ index += 1;
905
+ stack.push(file);
906
+ onStack.add(file);
907
+ for (const target of [...graph.get(file) ?? []].sort()) {
908
+ if (!graph.has(target)) continue;
909
+ if (!indices.has(target)) {
910
+ connect(target);
911
+ low.set(file, Math.min(low.get(file) ?? 0, low.get(target) ?? 0));
912
+ } else if (onStack.has(target)) {
913
+ low.set(file, Math.min(low.get(file) ?? 0, indices.get(target) ?? 0));
914
+ }
915
+ }
916
+ if (low.get(file) !== indices.get(file)) return;
917
+ const component = [];
918
+ let member;
919
+ do {
920
+ member = stack.pop();
921
+ if (member === void 0) break;
922
+ onStack.delete(member);
923
+ component.push(member);
924
+ } while (member !== file);
925
+ if (component.length > 1) components.push(component.sort());
926
+ };
927
+ for (const file of [...graph.keys()].sort()) {
928
+ if (!indices.has(file)) connect(file);
929
+ }
930
+ return components.sort((left, right) => left[0].localeCompare(right[0])).map((members) => ({
931
+ ruleId: "CIRCULAR_DEPENDENCY",
932
+ file: members[0],
933
+ line: 1,
934
+ target: members.join(" \u2192 "),
935
+ message: `Circular dependency among ${members.length} files: ${members.join(" \u2192 ")} \u2192 ${members[0]}.`,
936
+ cycleKind: "value"
937
+ }));
938
+ }
939
+ function evaluateArchitectureGraph(input) {
940
+ const violations = input.contentViolations.map((violation) => ({ ...violation }));
941
+ const warnings = (input.warnings ?? []).map((warning) => ({ ...warning }));
942
+ const graph = new Map(
943
+ input.files.map((file) => [file, /* @__PURE__ */ new Set()])
944
+ );
945
+ for (const edge of input.edges) {
946
+ if (edge.to && edge.to !== edge.from && !edge.typeOnly && graph.has(edge.from)) {
947
+ graph.get(edge.from)?.add(edge.to);
948
+ }
949
+ if (!edge.to || !edge.toLayer) continue;
950
+ const rule = findDeniedEdgeRule(input.rules, edge.fromLayer, edge.toLayer, {
951
+ fromPath: edge.from,
952
+ toPath: edge.to,
953
+ layers: input.config.layers
954
+ });
955
+ if (!rule) continue;
956
+ const peerIsolation = Boolean(rule.peerIsolation);
957
+ violations.push({
958
+ ruleId: "LAYER_IMPORT_VIOLATION",
959
+ file: edge.from,
960
+ line: edge.line,
961
+ fromLayer: edge.fromLayer,
962
+ toLayer: edge.toLayer,
963
+ target: edge.to,
964
+ ...edge.typeOnly ? { typeOnly: true } : {},
965
+ ...edge.targetTypeOnlyExports ? { targetTypeOnlyExports: true } : {},
966
+ ...edge.sourcePureTypeModule ? { sourcePureTypeModule: true } : {},
967
+ ...edge.namedBindingsTypeOnly ? { namedBindingsTypeOnly: true } : {},
968
+ ...!peerIsolation && edge.portProofEligible ? { portProofEligible: true } : {},
969
+ ...edge.kind ? { edgeKind: edge.kind } : {},
970
+ ...peerIsolation ? { peerIsolation: true } : {},
971
+ 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}.`)
972
+ });
973
+ }
974
+ const cyclePolicy = String(input.config.cyclePolicy ?? "strict").toLowerCase();
975
+ if (cyclePolicy !== "off") {
976
+ const cycles = detectArchitectureCycles(graph);
977
+ if (cyclePolicy === "soft" || cyclePolicy === "framework-soft") {
978
+ warnings.push(
979
+ ...cycles.map((cycle) => ({
980
+ ...cycle,
981
+ message: `${cycle.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,
982
+ failsStrict: false
983
+ }))
984
+ );
985
+ } else {
986
+ violations.push(...cycles);
987
+ }
988
+ }
989
+ return { violations, warnings, safety: input.safety };
990
+ }
991
+ function configWarning(ruleId, message, extra = {}) {
992
+ return { ruleId, message, ...extra };
993
+ }
994
+ function collectAnalysisConfigWarnings(input) {
995
+ const { config, rules, files, manifest } = input;
996
+ const warnings = [];
997
+ if (config.dynamicImportAllowlist !== void 0 && (!Array.isArray(config.dynamicImportAllowlist) || config.dynamicImportAllowlist.some((entry) => typeof entry !== "string"))) {
998
+ warnings.push(
999
+ configWarning(
1000
+ "CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST",
1001
+ "dynamicImportAllowlist must be an array of file globs."
1002
+ )
1003
+ );
1004
+ }
1005
+ if (config.safety !== void 0 && (config.safety === null || typeof config.safety !== "object" || Array.isArray(config.safety))) {
1006
+ warnings.push(configWarning("CONFIG_INVALID_SAFETY", "safety must be an object."));
1007
+ } else if (config.safety) {
1008
+ for (const key of ["maxTsSuppressions", "maxAnyCasts"]) {
1009
+ const value = config.safety[key];
1010
+ if (value !== void 0 && (!Number.isInteger(value) || value < 0)) {
1011
+ warnings.push(
1012
+ configWarning(
1013
+ "CONFIG_INVALID_SAFETY_THRESHOLD",
1014
+ `safety.${key} must be a non-negative integer.`
1015
+ )
1016
+ );
1017
+ }
1018
+ }
1019
+ }
1020
+ const layers = Array.isArray(config.layers) ? config.layers : [];
1021
+ const manifestLayers = Array.isArray(manifest?.architecture?.layers) ? manifest.architecture.layers : [];
1022
+ const knownLayers = /* @__PURE__ */ new Set([
1023
+ ...layers.map((layer) => layer.name).filter(Boolean),
1024
+ ...manifestLayers.map((layer) => layer.name).filter((name) => Boolean(name))
1025
+ ]);
1026
+ if (layers.length === 0) {
1027
+ warnings.push(
1028
+ configWarning(
1029
+ "CONFIG_NO_LAYERS",
1030
+ "No file layers are configured; ark-check cannot classify files for import-boundary enforcement."
1031
+ )
1032
+ );
1033
+ }
1034
+ const seenLayers = /* @__PURE__ */ new Set();
1035
+ const duplicateLayers = /* @__PURE__ */ new Set();
1036
+ for (const layer of layers) {
1037
+ if (!layer.name) {
1038
+ warnings.push(configWarning("CONFIG_LAYER_WITHOUT_NAME", "A configured layer is missing a name."));
1039
+ continue;
1040
+ }
1041
+ if (seenLayers.has(layer.name)) duplicateLayers.add(layer.name);
1042
+ seenLayers.add(layer.name);
1043
+ if (layer.forbiddenGlobals !== void 0 && (!Array.isArray(layer.forbiddenGlobals) || layer.forbiddenGlobals.some((entry) => typeof entry !== "string"))) {
1044
+ warnings.push(
1045
+ configWarning(
1046
+ "CONFIG_INVALID_FORBIDDEN_GLOBALS",
1047
+ `Layer "${layer.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,
1048
+ { layer: layer.name }
1049
+ )
1050
+ );
1051
+ }
1052
+ const patterns = Array.isArray(layer.patterns) ? layer.patterns : [];
1053
+ if (patterns.length === 0) {
1054
+ warnings.push(
1055
+ configWarning(
1056
+ "CONFIG_LAYER_WITHOUT_PATTERNS",
1057
+ `Layer "${layer.name}" has no file patterns and will never classify files.`,
1058
+ { layer: layer.name }
1059
+ )
1060
+ );
1061
+ continue;
1062
+ }
1063
+ for (const pattern of patterns) {
1064
+ let expression;
1065
+ try {
1066
+ expression = globToRegExp(pattern);
1067
+ } catch (error) {
1068
+ warnings.push(
1069
+ configWarning(
1070
+ "CONFIG_INVALID_LAYER_PATTERN",
1071
+ `Layer "${layer.name}" has an invalid pattern "${pattern}": ${error instanceof Error ? error.message : String(error)}`,
1072
+ { layer: layer.name, pattern }
1073
+ )
1074
+ );
1075
+ continue;
1076
+ }
1077
+ if (!files.some((file) => expression.test(file)) && !layer.optional) {
1078
+ warnings.push(
1079
+ configWarning(
1080
+ "CONFIG_LAYER_PATTERN_NO_MATCHES",
1081
+ `Layer "${layer.name}" pattern "${pattern}" matched no included files.`,
1082
+ { layer: layer.name, pattern, failsStrict: false }
1083
+ )
1084
+ );
1085
+ }
1086
+ }
1087
+ }
1088
+ for (const name of duplicateLayers) {
1089
+ warnings.push(
1090
+ configWarning("CONFIG_DUPLICATE_LAYER", `Layer "${name}" is configured more than once.`, {
1091
+ layer: name
1092
+ })
1093
+ );
1094
+ }
1095
+ if (knownLayers.size > 0) {
1096
+ for (const rule of rules ?? []) {
1097
+ if (rule.from && !knownLayers.has(rule.from)) {
1098
+ warnings.push(
1099
+ configWarning(
1100
+ "CONFIG_RULE_UNKNOWN_FROM_LAYER",
1101
+ `Rule references unknown source layer "${rule.from}".`,
1102
+ { fromLayer: rule.from, toLayer: rule.to }
1103
+ )
1104
+ );
1105
+ }
1106
+ if (rule.to && !knownLayers.has(rule.to)) {
1107
+ warnings.push(
1108
+ configWarning(
1109
+ "CONFIG_RULE_UNKNOWN_TO_LAYER",
1110
+ `Rule references unknown target layer "${rule.to}".`,
1111
+ { fromLayer: rule.from, toLayer: rule.to }
1112
+ )
1113
+ );
1114
+ }
1115
+ }
1116
+ }
1117
+ const ambiguousPairs = /* @__PURE__ */ new Set();
1118
+ if (layers.length > 1) {
1119
+ for (const file of files) {
1120
+ let topScore = -1;
1121
+ let topLayers = [];
1122
+ for (const layer of layers) {
1123
+ for (const pattern of layer.patterns ?? []) {
1124
+ if (!globToRegExp(pattern).test(file)) continue;
1125
+ const score = patternSpecificity(pattern);
1126
+ if (score > topScore) {
1127
+ topScore = score;
1128
+ topLayers = [layer.name];
1129
+ } else if (score === topScore && !topLayers.includes(layer.name)) {
1130
+ topLayers.push(layer.name);
1131
+ }
1132
+ }
1133
+ }
1134
+ if (topLayers.length > 1) ambiguousPairs.add([...topLayers].sort().join(" + "));
1135
+ }
1136
+ }
1137
+ if (ambiguousPairs.size > 0) {
1138
+ warnings.push(
1139
+ configWarning(
1140
+ "CONFIG_AMBIGUOUS_LAYERS",
1141
+ `Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...ambiguousPairs].join(", ")}.`,
1142
+ { pairs: [...ambiguousPairs] }
1143
+ )
1144
+ );
1145
+ }
1146
+ const unclassified = files.filter((file) => !layerForRelativePath(file, layers));
1147
+ if (unclassified.length > 0) {
1148
+ warnings.push(
1149
+ configWarning(
1150
+ "CONFIG_UNCLASSIFIED_FILES",
1151
+ `${unclassified.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,
1152
+ { count: unclassified.length, samples: unclassified.slice(0, 5) }
1153
+ )
1154
+ );
1155
+ }
1156
+ return warnings;
1157
+ }
1158
+ export {
1159
+ SOURCE_POLICY_MESSAGES,
1160
+ analyzeChange,
1161
+ analyzeProject,
1162
+ classifyPublishFacts,
1163
+ collectAnalysisConfigWarnings,
1164
+ collectForbiddenCapabilityUses,
1165
+ detectArchitectureCycles,
1166
+ evaluateArchitectureGraph,
1167
+ explainViolation,
1168
+ extractSemanticDependencies,
1169
+ loadContract,
1170
+ looksLikeArkIntent
1171
+ };