arkgate 2.12.0 → 3.0.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 (88) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +90 -51
  3. package/bin/ark-check.mjs +156 -39
  4. package/bin/ark-mcp.mjs +119 -6
  5. package/bin/ark-shared.mjs +216 -129
  6. package/bin/ark.mjs +134 -34
  7. package/bin/lib/adapter-contract.mjs +93 -0
  8. package/bin/lib/agent-gates.mjs +13 -0
  9. package/bin/lib/analysis-engine.mjs +1171 -0
  10. package/bin/lib/architecture-scan.mjs +84 -127
  11. package/bin/lib/ci-and-commands.mjs +40 -3
  12. package/bin/lib/codex-home.mjs +7 -0
  13. package/bin/lib/config-contract.mjs +331 -0
  14. package/bin/lib/config-warnings.mjs +7 -205
  15. package/bin/lib/doctor-plan.mjs +43 -16
  16. package/bin/lib/enforcement-profiles.mjs +97 -0
  17. package/bin/lib/field-install.mjs +67 -10
  18. package/bin/lib/gate-files.mjs +42 -3
  19. package/bin/lib/graph-cycles.mjs +4 -54
  20. package/bin/lib/hook-templates.mjs +33 -1
  21. package/bin/lib/host-support-matrix.mjs +83 -0
  22. package/bin/lib/install-migrate.mjs +99 -30
  23. package/bin/lib/mcp-adoption.mjs +35 -3
  24. package/bin/lib/open-html.mjs +75 -0
  25. package/bin/lib/presets.mjs +45 -4
  26. package/bin/lib/safety-diagnostics.mjs +36 -15
  27. package/bin/lib/scan-files.mjs +12 -1
  28. package/bin/lib/skill-install.mjs +72 -1
  29. package/bin/lib/source-policy.mjs +36 -0
  30. package/bin/lib/start-preview.mjs +271 -0
  31. package/bin/lib/ts-resolve.mjs +13 -3
  32. package/bin/lib/weakest-link.mjs +417 -0
  33. package/bin/lib/write-path-capabilities.mjs +186 -0
  34. package/bin/lib/write-path-detect.mjs +62 -99
  35. package/compat/nestjs.cjs +2 -0
  36. package/compat/nestjs.d.ts +2 -0
  37. package/compat/nestjs.js +1 -0
  38. package/compat/runtime.cjs +2 -0
  39. package/compat/runtime.d.ts +2 -0
  40. package/compat/runtime.js +1 -0
  41. package/dist/configContract-BxSIwVRo.d.cts +259 -0
  42. package/dist/configContract-BxSIwVRo.d.ts +259 -0
  43. package/dist/eslint/index.cjs +500 -61
  44. package/dist/eslint/index.d.cts +36 -20
  45. package/dist/eslint/index.d.ts +36 -20
  46. package/dist/eslint/index.js +500 -61
  47. package/dist/index.cjs +1349 -2741
  48. package/dist/index.d.cts +449 -483
  49. package/dist/index.d.ts +449 -483
  50. package/dist/index.js +1325 -2687
  51. package/docs/agent-guide.md +58 -34
  52. package/docs/ai-gates.md +79 -21
  53. package/docs/configuration.md +97 -0
  54. package/docs/enthusiast/README.md +3 -3
  55. package/docs/enthusiast/how-to-agent-gates.md +7 -3
  56. package/docs/migrate-from-ark-runtime-kernel.md +5 -3
  57. package/docs/package-surface.md +19 -19
  58. package/docs/production-hardening.md +31 -5
  59. package/docs/threat-model.md +65 -0
  60. package/docs/typescript-support.md +30 -3
  61. package/package.json +46 -11
  62. package/schemas/ark.analysis-result.schema.json +91 -0
  63. package/schemas/ark.config.schema.json +750 -0
  64. package/server.json +2 -2
  65. package/templates/hooks/pre-commit-ark +37 -0
  66. package/templates/skills/ark-architect.md +3 -2
  67. package/templates/skills/ark-coverage.md +2 -2
  68. package/templates/skills/ark-runtime.md +8 -5
  69. package/templates/skills/ark-upgrade.md +36 -16
  70. package/tests/fixtures/ts-consumer/ark.config.json +2 -0
  71. package/dist/eslint/index.cjs.map +0 -1
  72. package/dist/eslint/index.js.map +0 -1
  73. package/dist/index.cjs.map +0 -1
  74. package/dist/index.js.map +0 -1
  75. package/dist/nestjs/index.cjs +0 -2498
  76. package/dist/nestjs/index.cjs.map +0 -1
  77. package/dist/nestjs/index.d.cts +0 -22
  78. package/dist/nestjs/index.d.ts +0 -22
  79. package/dist/nestjs/index.js +0 -2474
  80. package/dist/nestjs/index.js.map +0 -1
  81. package/dist/runtime/index.cjs +0 -3352
  82. package/dist/runtime/index.cjs.map +0 -1
  83. package/dist/runtime/index.d.cts +0 -2
  84. package/dist/runtime/index.d.ts +0 -2
  85. package/dist/runtime/index.js +0 -3270
  86. package/dist/runtime/index.js.map +0 -1
  87. package/dist/types-BZ17b9i5.d.cts +0 -1068
  88. package/dist/types-BZ17b9i5.d.ts +0 -1068
package/dist/index.js CHANGED
@@ -1,668 +1,96 @@
1
1
  // src/version.ts
2
- var version = "2.12.0";
2
+ var version = "3.0.0";
3
3
 
4
- // src/kernel/intent/IntentRegistry.ts
5
- var IntentRegistry = class {
6
- intents = /* @__PURE__ */ new Map();
7
- dependencies = /* @__PURE__ */ new Map();
8
- productions = /* @__PURE__ */ new Map();
9
- /**
10
- * Define/register a new intent.
11
- *
12
- * @param name - Semantic intent name following the convention (Domain.*, Application.*, etc.)
13
- * @param options - Optional relationship declarations
14
- * @throws Error if an intent with the same name is already registered
15
- */
16
- define(name, options) {
17
- if (this.intents.has(name)) {
18
- throw new Error(
19
- `Intent "${name}" is already registered. Intent names must be unique within a registry.`
20
- );
21
- }
22
- const fn = (payload) => ({
23
- intent: name,
24
- payload,
25
- metadata: {
26
- occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
27
- source: "unknown"
28
- }
29
- });
30
- Object.defineProperty(fn, "name", {
31
- value: name,
32
- enumerable: true,
33
- configurable: false,
34
- writable: false
35
- });
36
- const creator = fn;
37
- this.intents.set(name, creator);
38
- if (options?.dependsOn) {
39
- for (const dep of options.dependsOn) {
40
- this.declareDependency(name, dep);
41
- }
42
- }
43
- if (options?.produces) {
44
- for (const prod of options.produces) {
45
- this.declareProduction(name, prod);
46
- }
47
- }
48
- return creator;
49
- }
50
- /**
51
- * Declare that one intent depends on / relates to another.
52
- * This information is used by the DependencyGraph (future iterations) and for policy checks.
53
- *
54
- * @param from - The source intent (e.g. an Application operation)
55
- * @param to - The target intent it depends on (e.g. a Domain event or concept)
56
- */
57
- declareDependency(from, to) {
58
- if (!this.dependencies.has(from)) {
59
- this.dependencies.set(from, /* @__PURE__ */ new Set());
60
- }
61
- this.dependencies.get(from).add(to);
62
- }
63
- /**
64
- * Declare that one intent produces / emits another (e.g. use case → domain event).
65
- */
66
- declareProduction(from, to) {
67
- if (!this.productions.has(from)) {
68
- this.productions.set(from, /* @__PURE__ */ new Set());
69
- }
70
- this.productions.get(from).add(to);
71
- }
72
- /**
73
- * Retrieve a previously defined intent creator by name.
74
- */
75
- get(name) {
76
- return this.intents.get(name);
77
- }
78
- /**
79
- * List all registered intent creators.
80
- */
81
- list() {
82
- return Array.from(this.intents.values());
83
- }
84
- /**
85
- * Get all declared dependencies for a given intent.
86
- */
87
- getDependencies(intentName) {
88
- const deps = this.dependencies.get(intentName);
89
- return deps ? Array.from(deps) : [];
90
- }
91
- /**
92
- * Get all intents produced / emitted by a given intent.
93
- */
94
- getProductions(intentName) {
95
- const prods = this.productions.get(intentName);
96
- return prods ? Array.from(prods) : [];
97
- }
98
- /**
99
- * Get all declared relationships (useful for graph generation).
100
- */
101
- getAllRelationships() {
102
- const result = [];
103
- for (const [from, tos] of this.dependencies.entries()) {
104
- for (const to of tos) {
105
- result.push({ from, to, kind: "dependsOn" });
106
- }
107
- }
108
- for (const [from, tos] of this.productions.entries()) {
109
- for (const to of tos) {
110
- result.push({ from, to, kind: "produces" });
111
- }
112
- }
113
- return result;
114
- }
115
- /**
116
- * Check if an intent name has been registered.
117
- */
118
- has(name) {
119
- return this.intents.has(name);
120
- }
121
- /**
122
- * Clear the registry. Primarily useful for tests.
123
- */
124
- clear() {
125
- this.intents.clear();
126
- this.dependencies.clear();
127
- this.productions.clear();
128
- }
129
- };
130
-
131
- // src/kernel/intent/defineIntent.ts
132
- var defaultRegistry = new IntentRegistry();
133
- function defineIntent(name, options) {
134
- return defaultRegistry.define(name, options);
135
- }
136
- function createIntentRegistry() {
137
- return new IntentRegistry();
138
- }
139
- var defaultIntentRegistry = defaultRegistry;
140
-
141
- // src/kernel/intent/validateIntentName.ts
142
- var ALLOWED_PREFIXES = [
143
- "Domain.",
144
- "Application.",
145
- "Adapter.",
146
- "Workflow.",
147
- "Job.",
148
- "Presentation.",
149
- "Reporting.",
150
- "Metadata.",
151
- "Security.",
152
- "Audit.",
153
- "Observability.",
154
- "Kernel."
155
- ];
156
- function validateIntentName(name) {
157
- if (!name || typeof name !== "string") {
158
- return { valid: false, reason: "Intent name must be a non-empty string" };
159
- }
160
- if (!ALLOWED_PREFIXES.some((p) => name.startsWith(p))) {
161
- return {
162
- valid: false,
163
- reason: `Intent "${name}" must start with one of: ${ALLOWED_PREFIXES.join(", ")}`
164
- };
165
- }
166
- const rest = name.slice(name.indexOf(".") + 1);
167
- if (!rest || !/^[A-Za-z][A-Za-z0-9_.]*$/.test(rest)) {
168
- return {
169
- valid: false,
170
- reason: `Intent "${name}" has an invalid segment after the layer prefix`
171
- };
172
- }
173
- return { valid: true };
174
- }
175
-
176
- // src/kernel/policy/PolicyViolationError.ts
177
- var PolicyViolationError = class extends Error {
178
- violations;
179
- constructor(violations) {
180
- const messages = violations.map((v) => `- ${v.policyName}: ${v.message}`).join("\n");
181
- super(`Hard policy violation(s) detected:
182
- ${messages}`);
183
- this.name = "PolicyViolationError";
184
- this.violations = violations;
185
- }
186
- };
187
-
188
- // src/kernel/policy/PolicyEngine.ts
189
- var PolicyEngine = class {
190
- policies = [];
191
- constructor(initialPolicies = []) {
192
- for (const policy of initialPolicies) {
193
- this.add(policy);
194
- }
195
- }
196
- /**
197
- * Adds a policy to the engine.
198
- */
199
- add(policy) {
200
- if (this.policies.some((p) => p.name === policy.name)) {
201
- throw new Error(`Policy "${policy.name}" is already registered in this engine.`);
202
- }
203
- this.policies.push(policy);
204
- }
205
- /**
206
- * Returns all registered policies.
207
- */
208
- getPolicies() {
209
- return [...this.policies];
210
- }
211
- /**
212
- * Evaluates all policies against the provided context.
213
- */
214
- evaluate(context) {
215
- const violations = [];
216
- for (const policy of this.policies) {
217
- const result = policy.check(context);
218
- if (result === true) {
219
- continue;
220
- }
221
- if (result === false) {
222
- violations.push({
223
- policyName: policy.name,
224
- severity: policy.severity,
225
- message: `Policy "${policy.name}" was violated.`
226
- });
227
- continue;
228
- }
229
- if (Array.isArray(result)) {
230
- for (const v of result) {
231
- violations.push({
232
- policyName: policy.name,
233
- severity: policy.severity,
234
- message: v.message,
235
- details: v.details
236
- });
237
- }
238
- } else {
239
- violations.push({
240
- policyName: policy.name,
241
- severity: policy.severity,
242
- message: result.message,
243
- details: result.details
244
- });
245
- }
246
- }
247
- const hardViolations = violations.filter((v) => v.severity === "hard");
248
- const softViolations = violations.filter((v) => v.severity === "soft");
249
- return {
250
- passed: violations.length === 0,
251
- violations,
252
- hardViolations,
253
- softViolations
254
- };
255
- }
256
- /**
257
- * Enforces all policies.
258
- *
259
- * - Soft violations are collected and can be observed (returned or logged).
260
- * - Hard violations cause an error to be thrown (by default).
261
- *
262
- * @returns Evaluation result (including any soft violations)
263
- * @throws Error if any hard policy is violated
264
- */
265
- enforce(context) {
266
- const result = this.evaluate(context);
267
- if (result.hardViolations.length > 0) {
268
- throw new PolicyViolationError(result.hardViolations);
269
- }
270
- return result;
271
- }
272
- /**
273
- * Clears all registered policies.
274
- */
275
- clear() {
276
- this.policies.length = 0;
277
- }
278
- };
279
-
280
- // src/kernel/policy/definePolicy.ts
281
- function definePolicy(options) {
282
- const severity = options.severity ?? "soft";
283
- const policy = {
284
- name: options.name,
285
- severity,
286
- tags: options.tags,
287
- owner: options.owner,
288
- version: options.version,
289
- rationale: options.rationale,
290
- enforcementMode: options.enforcementMode,
291
- deprecated: options.deprecated,
292
- replacedBy: options.replacedBy,
293
- check: options.check
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 } : {}
294
20
  };
295
- return policy;
296
- }
297
-
298
- // src/kernel/policy/builtins.ts
299
- function defaultLayerOf(name) {
300
- const dot = name.indexOf(".");
301
- return dot >= 0 ? name.slice(0, dot) : name;
302
- }
303
- function resolveLayer(name, options) {
304
- return options.resolveLayer?.(name) ?? defaultLayerOf(name);
305
- }
306
- function matchesRule(fromLayer, toLayer, rule) {
307
- return fromLayer === rule.from && toLayer === rule.to;
308
- }
309
- function defineLayerPolicy(options) {
310
- const name = options.name ?? "Layer isolation";
311
- const severity = options.severity ?? "hard";
312
- return definePolicy({
313
- name,
21
+ return {
22
+ ruleId,
314
23
  severity,
315
- tags: ["layer"],
316
- check: (ctx) => {
317
- const edges = [
318
- ...(ctx.edges ?? []).filter((e) => e.kind === "declared" || e.kind === "produces").map((e) => ({ from: e.from, to: e.to })),
319
- ...(ctx.relationships ?? []).filter((r) => r.kind === "dependsOn").map((r) => ({ from: r.from, to: r.to }))
320
- ];
321
- const violations = [];
322
- for (const edge of edges) {
323
- const fromLayer = resolveLayer(edge.from, options);
324
- const toLayer = resolveLayer(edge.to, options);
325
- for (const rule of options.rules) {
326
- if (!rule.allowed && matchesRule(fromLayer, toLayer, rule)) {
327
- violations.push({
328
- policyName: name,
329
- severity,
330
- message: rule.message ?? `Layer violation: ${edge.from} (${fromLayer}) must not relate to ${edge.to} (${toLayer})`
331
- });
332
- }
333
- }
334
- }
335
- return violations.length > 0 ? violations : true;
336
- }
337
- });
338
- }
339
- function isLayerPolicy(policy) {
340
- return policy.tags?.includes("layer") ?? false;
341
- }
342
- var architecturalPolicies = {
343
- /**
344
- * @deprecated Use cleanArchitectureMatrix() for full layer rules.
345
- * Blocks Domain → Adapter declared dependencies only.
346
- */
347
- layerIsolation() {
348
- return architecturalPolicies.cleanArchitectureMatrix();
349
- },
350
- /**
351
- * Clean-architecture dependency matrix (declared dependsOn / declared edges only).
352
- * Does not block observed event flows (Domain events consumed by Application).
353
- */
354
- cleanArchitectureMatrix() {
355
- return defineLayerPolicy({
356
- name: "Clean architecture matrix",
357
- severity: "hard",
358
- rules: [
359
- { from: "Domain", to: "Adapter", allowed: false },
360
- { from: "Domain", to: "Application", allowed: false },
361
- { from: "Adapter", to: "Application", allowed: false },
362
- { from: "Adapter", to: "Domain", allowed: false }
363
- ]
364
- });
365
- }
366
- };
367
- function defineArchitectureProfilePolicy(profile, options = {}) {
368
- return defineLayerPolicy({
369
- name: options.name ?? `${profile.name} layer policy`,
370
- severity: options.severity ?? "hard",
371
- rules: profile.rules,
372
- resolveLayer: profile.resolveLayer
373
- });
374
- }
375
-
376
- // src/kernel/event-bus/policyContext.ts
377
- function buildPublishPolicyContext(options) {
378
- return (event) => ({
379
- event,
380
- relationships: options.intentRegistry?.getAllRelationships(),
381
- edges: options.dependencyGraph?.getEdges()
382
- });
383
- }
384
- function definePublishPolicy(options) {
385
- return definePolicy(options);
386
- }
387
-
388
- // src/kernel/event-bus/errors.ts
389
- var UnregisteredIntentError = class extends Error {
390
- intentName;
391
- constructor(intentName) {
392
- super(
393
- `Intent "${intentName}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`
394
- );
395
- this.name = "UnregisteredIntentError";
396
- this.intentName = intentName;
397
- }
398
- };
399
- var InvalidIntentNameError = class extends Error {
400
- intentName;
401
- reason;
402
- constructor(intentName, reason) {
403
- super(`Invalid intent name "${intentName}": ${reason}`);
404
- this.name = "InvalidIntentNameError";
405
- this.intentName = intentName;
406
- this.reason = reason;
407
- }
408
- };
409
- var LayerPolicyContextError = class extends Error {
410
- constructor() {
411
- super(
412
- "Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."
413
- );
414
- this.name = "LayerPolicyContextError";
415
- }
416
- };
417
- var EventContractViolationError = class extends Error {
418
- intentName;
419
- issues;
420
- constructor(intentName, issues) {
421
- super(
422
- `Event contract violation for "${intentName}". Register a matching event contract/version or fix the payload before publishing.`
423
- );
424
- this.name = "EventContractViolationError";
425
- this.intentName = intentName;
426
- this.issues = issues;
427
- }
428
- };
429
- var UnknownEventSourceError = class extends Error {
430
- intentName;
431
- source;
432
- constructor(intentName, source) {
433
- super(
434
- source ? `Event "${intentName}" metadata.source "${source}" is not registered. Register the producer intent or publish from a known source.` : `Event "${intentName}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`
435
- );
436
- this.name = "UnknownEventSourceError";
437
- this.intentName = intentName;
438
- this.source = source;
439
- }
440
- };
441
- var SourceMetadataOverrideError = class extends Error {
442
- boundSource;
443
- attemptedSource;
444
- constructor(boundSource, attemptedSource) {
445
- super(
446
- `Source-bound publisher for "${boundSource}" cannot publish with metadata.source "${attemptedSource}". Create a publisher for the intended source instead.`
447
- );
448
- this.name = "SourceMetadataOverrideError";
449
- this.boundSource = boundSource;
450
- this.attemptedSource = attemptedSource;
451
- }
452
- };
453
- var ObservedLayerFlowViolationError = class extends Error {
454
- source;
455
- intentName;
456
- fromLayer;
457
- toLayer;
458
- constructor(source, intentName, fromLayer, toLayer, message) {
459
- super(
460
- message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${intentName}" (${toLayer}). Route this through an allowed layer or adjust the architecture profile rule.`
461
- );
462
- this.name = "ObservedLayerFlowViolationError";
463
- this.source = source;
464
- this.intentName = intentName;
465
- this.fromLayer = fromLayer;
466
- this.toLayer = toLayer;
467
- }
468
- };
469
-
470
- // src/kernel/event-bus/publishGuards.ts
471
- function assertIntentAllowed(intentName, options) {
472
- if (!options.strictRegistry && !options.validateIntentNaming) {
473
- return;
474
- }
475
- if (options.validateIntentNaming) {
476
- const validation = validateIntentName(intentName);
477
- if (!validation.valid) {
478
- throw new InvalidIntentNameError(intentName, validation.reason);
479
- }
480
- }
481
- if (options.strictRegistry && options.intentRegistry && !options.intentRegistry.has(intentName)) {
482
- throw new UnregisteredIntentError(intentName);
483
- }
484
- }
485
- function assertSourceAllowed(event, options) {
486
- if (!options.requireKnownSource) return;
487
- if (!event.metadata.source || event.metadata.source === "unknown") {
488
- throw new UnknownEventSourceError(event.intent);
489
- }
490
- if (options.intentRegistry && !options.intentRegistry.has(event.metadata.source)) {
491
- throw new UnknownEventSourceError(event.intent, event.metadata.source);
492
- }
493
- }
494
- function assertContractAllowed(event, options) {
495
- if (!options.eventContracts) return;
496
- const result = options.eventContracts.validate(event);
497
- if (!result.ok && (options.strictEventContracts || result.contract)) {
498
- throw new EventContractViolationError(event.intent, result.issues);
499
- }
500
- }
501
-
502
- // src/kernel/event-bus/payloadPatch.ts
503
- function isPlainRecord(value) {
504
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
505
- return false;
506
- }
507
- const proto = Object.getPrototypeOf(value);
508
- return proto === Object.prototype || proto === null;
509
- }
510
- function clonePatchValue(value) {
511
- if (Array.isArray(value)) return value.map(clonePatchValue);
512
- if (isPlainRecord(value)) {
513
- return Object.fromEntries(
514
- Object.entries(value).map(([key, child]) => [key, clonePatchValue(child)])
515
- );
516
- }
517
- return value;
518
- }
519
- function mergeRecordPatch(target, patch, path = "payload") {
520
- const next = { ...target };
521
- for (const [key, value] of Object.entries(patch)) {
522
- const childPath = `${path}.${key}`;
523
- if (!(key in next) || next[key] === void 0) {
524
- next[key] = clonePatchValue(value);
525
- continue;
526
- }
527
- if (isPlainRecord(next[key]) && isPlainRecord(value)) {
528
- next[key] = mergeRecordPatch(next[key], value, childPath);
529
- continue;
530
- }
531
- if (Array.isArray(next[key]) && Array.isArray(value)) {
532
- next[key] = mergeArrayPatch(next[key], value, childPath);
533
- continue;
534
- }
535
- throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
536
- }
537
- return next;
538
- }
539
- function mergeArrayPatch(target, patch, path = "payload") {
540
- const next = [...target];
541
- patch.forEach((value, index) => {
542
- const childPath = `${path}[${index}]`;
543
- if (index >= next.length || next[index] === void 0) {
544
- next[index] = clonePatchValue(value);
545
- return;
546
- }
547
- if (isPlainRecord(next[index]) && isPlainRecord(value)) {
548
- next[index] = mergeRecordPatch(next[index], value, childPath);
549
- return;
550
- }
551
- if (Array.isArray(next[index]) && Array.isArray(value)) {
552
- next[index] = mergeArrayPatch(next[index], value, childPath);
553
- return;
554
- }
555
- throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
556
- });
557
- return next;
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
+ };
558
32
  }
559
- function applyPayloadPatch(payload, patch) {
560
- if (Array.isArray(patch)) {
561
- if (payload === void 0) return clonePatchValue(patch);
562
- if (!Array.isArray(payload)) {
563
- throw new Error("Array interceptor patch requires an array payload.");
564
- }
565
- return mergeArrayPatch(payload, patch);
566
- }
567
- if (payload === void 0) return clonePatchValue(patch);
568
- if (!isPlainRecord(payload)) {
569
- throw new Error("Object interceptor patch requires an object payload.");
570
- }
571
- return mergeRecordPatch(payload, patch);
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
+ };
572
42
  }
573
-
574
- // src/kernel/event-bus/publishInterceptors.ts
575
- async function applyInterceptors(event, deps) {
576
- if (event.metadata.allowInterception === false) {
577
- return event;
578
- }
579
- const matching = [...deps.interceptorsForIntent(event.intent)];
580
- let current = event;
581
- for (const registration of matching) {
582
- const patches = [];
583
- try {
584
- await Promise.resolve(
585
- registration.interceptor({
586
- event: current,
587
- intercept: (patch) => {
588
- patches.push(patch);
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
+ }
589
82
  }
590
- })
591
- );
592
- if (patches.length === 0) {
593
- continue;
594
- }
595
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
596
- let candidate = {
597
- ...current,
598
- metadata: {
599
- ...current.metadata,
600
- interceptions: [
601
- ...current.metadata.interceptions ?? [],
602
- { interceptorId: registration.interceptorId, timestamp }
603
- ]
604
83
  }
605
- };
606
- for (const patch of patches) {
607
- candidate = {
608
- ...candidate,
609
- payload: applyPayloadPatch(candidate.payload, patch),
610
- metadata: { ...candidate.metadata }
611
- };
612
84
  }
613
- assertContractAllowed(candidate, {
614
- eventContracts: deps.eventContracts,
615
- strictEventContracts: deps.strictEventContracts
616
- });
617
- current = candidate;
618
- registration.lastInterceptedAt = timestamp;
619
- deps.appendTrace({
620
- type: "event.intercepted",
621
- timestamp,
622
- intent: current.intent,
623
- correlationId: current.metadata.correlationId,
624
- traceId: current.metadata.traceId,
625
- spanId: current.metadata.spanId,
626
- details: {
627
- registrationId: registration.registrationId,
628
- interceptorId: registration.interceptorId,
629
- patchesApplied: patches.length
630
- }
631
- });
632
- await deps.recordAudit("event.intercepted", current, {
633
- registrationId: registration.registrationId,
634
- interceptorId: registration.interceptorId,
635
- patchesApplied: patches.length
636
- });
637
- } catch (err) {
638
- await recordInterceptorError(registration, current, err, deps);
639
85
  }
640
86
  }
641
- return current;
642
- }
643
- async function recordInterceptorError(interceptor, event, error, deps) {
644
- const message = error instanceof Error ? error.message : String(error);
645
- deps.appendTrace({
646
- type: "interceptor.error",
647
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
648
- intent: event.intent,
649
- correlationId: event.metadata.correlationId,
650
- traceId: event.metadata.traceId,
651
- spanId: event.metadata.spanId,
652
- details: {
653
- registrationId: interceptor.registrationId,
654
- interceptorId: interceptor.interceptorId,
655
- error: message
656
- }
657
- });
658
- await deps.recordAudit("interceptor.error", event, {
659
- registrationId: interceptor.registrationId,
660
- interceptorId: interceptor.interceptorId,
661
- error: message
662
- });
663
- }
87
+ };
664
88
 
665
89
  // src/domain/layerMatch.ts
90
+ var regexpCache = /* @__PURE__ */ new Map();
91
+ function escapeLiteral(ch) {
92
+ return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
93
+ }
666
94
  function normalizeGlobSeparators(pattern) {
667
95
  let out = "";
668
96
  for (let i = 0; i < pattern.length; i += 1) {
@@ -681,6 +109,91 @@ function normalizeGlobSeparators(pattern) {
681
109
  }
682
110
  return out;
683
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
+ }
684
197
  function sliceIdForPath(relPath, sliceFolders) {
685
198
  if (!sliceFolders?.length) return void 0;
686
199
  const parts = String(relPath).split(/[/\\]/).filter(Boolean);
@@ -738,1407 +251,225 @@ function findDeniedEdgeRule(rules, from, to, options) {
738
251
  return void 0;
739
252
  }
740
253
 
741
- // src/kernel/event-bus/observedLayerFlow.ts
742
- async function assertObservedLayerFlowAllowed(event, deps) {
743
- if (deps.mode === "off" || !deps.architectureProfile) {
744
- return;
745
- }
746
- const source = event.metadata.source;
747
- if (!source || source === "unknown") return;
748
- const profile = deps.architectureProfile;
749
- const fromLayer = profile.resolveLayer(source);
750
- const toLayer = profile.resolveLayer(event.intent);
751
- if (!fromLayer || !toLayer) return;
752
- const blocked = findDeniedEdgeRule(profile.rules, fromLayer, toLayer);
753
- if (!blocked) return;
754
- const severity = deps.mode;
755
- const message = blocked.message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${event.intent}" (${toLayer}).`;
756
- const details = {
757
- source,
758
- intent: event.intent,
759
- fromLayer,
760
- toLayer,
761
- severity,
762
- message,
763
- rule: blocked
764
- };
765
- deps.appendTrace({
766
- type: "layer.observedViolation",
767
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
768
- intent: event.intent,
769
- correlationId: event.metadata.correlationId,
770
- traceId: event.metadata.traceId,
771
- spanId: event.metadata.spanId,
772
- details
773
- });
774
- await deps.recordAudit("layer.observedViolation", event, details);
775
- if (severity === "hard") {
776
- throw new ObservedLayerFlowViolationError(
777
- source,
778
- event.intent,
779
- fromLayer,
780
- toLayer,
781
- message
782
- );
783
- }
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
+ );
784
263
  }
785
-
786
- // src/kernel/event-bus/publishPolicy.ts
787
- async function enforcePublishPolicy(event, deps) {
788
- const ctx = deps.getPolicyContext(event);
789
- let policyResult;
790
- try {
791
- policyResult = deps.policyEngine.enforce(ctx);
792
- } catch (err) {
793
- if (err instanceof PolicyViolationError) {
794
- deps.appendTrace({
795
- type: "policy.hardViolation",
796
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
797
- intent: event.intent,
798
- correlationId: event.metadata.correlationId,
799
- traceId: event.metadata.traceId,
800
- spanId: event.metadata.spanId,
801
- details: { violations: err.violations }
802
- });
803
- await deps.recordAudit("policy.hardViolation", event, {
804
- violations: err.violations
805
- });
806
- }
807
- throw err;
808
- }
809
- if (policyResult.softViolations.length > 0) {
810
- deps.appendTrace({
811
- type: "policy.softViolation",
812
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
813
- intent: event.intent,
814
- correlationId: event.metadata.correlationId,
815
- traceId: event.metadata.traceId,
816
- spanId: event.metadata.spanId,
817
- details: { violations: policyResult.softViolations }
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
818
271
  });
819
- await deps.recordAudit("policy.softViolation", event, {
820
- violations: policyResult.softViolations
272
+ }
273
+ if (facts.arkPublishCandidate && !facts.hasSource) {
274
+ findings.push({
275
+ ruleId: "PUBLISH_MISSING_SOURCE",
276
+ message: SOURCE_POLICY_MESSAGES.PUBLISH_MISSING_SOURCE
821
277
  });
822
- if (deps.onSoftViolation) {
823
- await deps.safeHook(
824
- () => deps.onSoftViolation(policyResult, event),
825
- "onSoftViolation",
826
- event
827
- );
828
- }
829
278
  }
279
+ return findings;
830
280
  }
831
281
 
832
- // src/kernel/event-bus/publishRecording.ts
833
- function appendHistory(buffers, record) {
834
- buffers.history.push(record);
835
- if (buffers.maxHistorySize !== void 0 && buffers.history.length > buffers.maxHistorySize) {
836
- buffers.history.splice(0, buffers.history.length - buffers.maxHistorySize);
837
- }
282
+ // src/kernel/semanticAnalysis.ts
283
+ function literalText(ts, node) {
284
+ return node && ts.isStringLiteralLike(node) ? node.text : void 0;
838
285
  }
839
- function appendTrace(buffers, record) {
840
- buffers.trace.push(record);
841
- if (buffers.maxHistorySize !== void 0 && buffers.trace.length > buffers.maxHistorySize) {
842
- buffers.trace.splice(0, buffers.trace.length - buffers.maxHistorySize);
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
+ );
843
298
  }
844
- for (const sink of buffers.traceSinks) {
845
- try {
846
- sink(record);
847
- } catch {
848
- }
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
+ );
849
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();
850
315
  }
851
- async function recordAudit(buffers, type, event, details) {
852
- if (!buffers.auditTrail) return;
316
+ function symbolAt(checker, node) {
853
317
  try {
854
- await buffers.auditTrail.record({
855
- type,
856
- source: event.metadata.source,
857
- intent: event.intent,
858
- correlationId: event.metadata.correlationId,
859
- causationId: event.metadata.causationId,
860
- subject: event.intent,
861
- details
862
- });
863
- } catch (err) {
864
- appendTrace(buffers, {
865
- type: "hook.error",
866
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
867
- intent: event.intent,
868
- correlationId: event.metadata.correlationId,
869
- traceId: event.metadata.traceId,
870
- spanId: event.metadata.spanId,
871
- details: {
872
- hook: "auditTrail",
873
- error: err instanceof Error ? err.message : String(err)
874
- }
875
- });
318
+ return checker.getSymbolAtLocation(node);
319
+ } catch {
320
+ return void 0;
876
321
  }
877
322
  }
878
- async function recordRawPublishDiagnostic(buffers, event) {
879
- const details = {
880
- intent: event.intent,
881
- source: event.metadata.source,
882
- suggestion: "Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."
883
- };
884
- appendTrace(buffers, {
885
- type: "event.rawPublish",
886
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
887
- intent: event.intent,
888
- correlationId: event.metadata.correlationId,
889
- traceId: event.metadata.traceId,
890
- spanId: event.metadata.spanId,
891
- details
892
- });
893
- await recordAudit(buffers, "event.rawPublish", event, details);
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
+ );
894
336
  }
895
- async function recordSuccessfulPublish(buffers, event, subscribersNotified) {
896
- const record = {
897
- event,
898
- publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
899
- subscribersNotified
900
- };
901
- appendHistory(buffers, record);
902
- await buffers.outbox?.enqueue(event);
903
- appendTrace(buffers, {
904
- type: "event.published",
905
- timestamp: record.publishedAt,
906
- intent: event.intent,
907
- correlationId: event.metadata.correlationId,
908
- traceId: event.metadata.traceId,
909
- spanId: event.metadata.spanId,
910
- details: { subscribersNotified }
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
911
347
  });
912
- await recordAudit(buffers, "event.published", event, {
913
- subscribersNotified
914
- });
915
- return record;
916
- }
917
- function enrichMetadata(base, extra, instanceId) {
918
- return {
919
- ...base,
920
- ...extra,
921
- occurredAt: extra.occurredAt || base.occurredAt || (/* @__PURE__ */ new Date()).toISOString(),
922
- source: extra.source || base.source || "unknown",
923
- kernelInstanceId: extra.kernelInstanceId ?? base.kernelInstanceId ?? instanceId,
924
- eventVersion: extra.eventVersion ?? base.eventVersion,
925
- schemaVersion: extra.schemaVersion ?? base.schemaVersion,
926
- allowInterception: extra.allowInterception ?? base.allowInterception,
927
- interceptions: extra.interceptions ?? base.interceptions,
928
- correlationId: extra.correlationId ?? base.correlationId,
929
- causationId: extra.causationId ?? base.causationId,
930
- traceId: extra.traceId ?? base.traceId,
931
- spanId: extra.spanId ?? base.spanId,
932
- parentSpanId: extra.parentSpanId ?? base.parentSpanId
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);
933
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;
934
401
  }
935
-
936
- // src/kernel/event-bus/EventBus.ts
937
- var interceptorSequence = 0;
938
- function nextInterceptorRegistrationId() {
939
- interceptorSequence += 1;
940
- return `interceptor-${Date.now()}-${interceptorSequence}`;
941
- }
942
- var EventBusImpl = class {
943
- subscriptions = [];
944
- subscriptionsByIntent = /* @__PURE__ */ new Map();
945
- interceptors = [];
946
- interceptorsByIntent = /* @__PURE__ */ new Map();
947
- recording;
948
- onPublish;
949
- onSoftViolation;
950
- onHandlerError;
951
- eventContracts;
952
- strictEventContracts;
953
- requireKnownSource;
954
- architectureProfile;
955
- enforceObservedLayerFlowMode;
956
- rethrowHandlerErrors;
957
- policyEngine;
958
- getPolicyContext;
959
- intentRegistry;
960
- dependencyGraph;
961
- strictRegistry;
962
- validateIntentNaming;
963
- constructor(options = {}) {
964
- this.onPublish = options.onPublish;
965
- this.onSoftViolation = options.onSoftViolation;
966
- this.onHandlerError = options.onHandlerError;
967
- this.eventContracts = options.eventContracts;
968
- this.strictEventContracts = options.strictEventContracts ?? false;
969
- this.requireKnownSource = options.requireKnownSource ?? false;
970
- this.architectureProfile = options.architectureProfile;
971
- this.enforceObservedLayerFlowMode = options.enforceObservedLayerFlow ?? "off";
972
- this.rethrowHandlerErrors = options.rethrowHandlerErrors ?? false;
973
- this.intentRegistry = options.intentRegistry;
974
- this.dependencyGraph = options.dependencyGraph;
975
- this.strictRegistry = options.strictRegistry ?? options.intentRegistry !== void 0;
976
- this.validateIntentNaming = options.validateIntentNaming ?? this.strictRegistry;
977
- this.recording = {
978
- history: [],
979
- trace: [],
980
- maxHistorySize: options.maxHistorySize,
981
- traceSinks: [...options.traceSinks ?? []],
982
- auditTrail: options.auditTrail,
983
- outbox: options.outbox,
984
- instanceId: options.instanceId
985
- };
986
- if (options.policyEngine) {
987
- this.policyEngine = options.policyEngine;
988
- } else if (options.policies && options.policies.length > 0) {
989
- this.policyEngine = new PolicyEngine(options.policies);
990
- }
991
- const allPolicies = this.policyEngine?.getPolicies() ?? options.policies ?? [];
992
- if (allPolicies.some(isLayerPolicy) && !options.intentRegistry && !options.dependencyGraph && !options.getPolicyContext) {
993
- throw new LayerPolicyContextError();
994
- }
995
- if (options.getPolicyContext) {
996
- this.getPolicyContext = options.getPolicyContext;
997
- } else if (options.intentRegistry || options.dependencyGraph) {
998
- this.getPolicyContext = buildPublishPolicyContext({
999
- intentRegistry: options.intentRegistry,
1000
- dependencyGraph: options.dependencyGraph
1001
- });
1002
- } else {
1003
- this.getPolicyContext = (event) => ({ event });
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
+ }
1004
413
  }
1005
414
  }
1006
- async publish(eventOrCreator, payloadOrMeta, metadata) {
1007
- let event;
1008
- const rawPublish = typeof eventOrCreator !== "function";
1009
- if (!rawPublish) {
1010
- const creator = eventOrCreator;
1011
- const payload = payloadOrMeta;
1012
- const extraMeta = metadata ?? {};
1013
- const created = creator(payload);
1014
- event = {
1015
- ...created,
1016
- metadata: enrichMetadata(
1017
- created.metadata,
1018
- extraMeta,
1019
- this.recording.instanceId
1020
- )
1021
- };
1022
- } else {
1023
- const rawEvent = eventOrCreator;
1024
- const extraMeta = metadata ?? payloadOrMeta ?? {};
1025
- event = {
1026
- ...rawEvent,
1027
- metadata: enrichMetadata(
1028
- rawEvent.metadata,
1029
- extraMeta,
1030
- this.recording.instanceId
1031
- )
1032
- };
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);
1033
431
  }
1034
- if (rawPublish && this.strictRegistry) {
1035
- await recordRawPublishDiagnostic(this.recording, event);
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
+ }
1036
461
  }
1037
- assertIntentAllowed(event.intent, {
1038
- strictRegistry: this.strictRegistry,
1039
- validateIntentNaming: this.validateIntentNaming,
1040
- intentRegistry: this.intentRegistry
1041
- });
1042
- assertSourceAllowed(event, {
1043
- requireKnownSource: this.requireKnownSource,
1044
- intentRegistry: this.intentRegistry
1045
- });
1046
- assertContractAllowed(event, {
1047
- eventContracts: this.eventContracts,
1048
- strictEventContracts: this.strictEventContracts
1049
- });
1050
- event = await applyInterceptors(event, {
1051
- interceptorsForIntent: (intent) => this.interceptorsByIntent.get(intent) ?? [],
1052
- eventContracts: this.eventContracts,
1053
- strictEventContracts: this.strictEventContracts,
1054
- appendTrace: (r) => this.appendTrace(r),
1055
- recordAudit: (type, e, details) => this.recordAudit(type, e, details)
1056
- });
1057
- assertContractAllowed(event, {
1058
- eventContracts: this.eventContracts,
1059
- strictEventContracts: this.strictEventContracts
1060
- });
1061
- await assertObservedLayerFlowAllowed(event, {
1062
- mode: this.enforceObservedLayerFlowMode,
1063
- architectureProfile: this.architectureProfile,
1064
- appendTrace: (r) => this.appendTrace(r),
1065
- recordAudit: (type, e, details) => this.recordAudit(type, e, details)
1066
- });
1067
- this.dependencyGraph?.registerEventFlow(event.metadata.source, event.intent);
1068
- const matching = [...this.subscriptionsByIntent.get(event.intent) ?? []];
1069
- if (this.policyEngine) {
1070
- await enforcePublishPolicy(event, {
1071
- policyEngine: this.policyEngine,
1072
- getPolicyContext: this.getPolicyContext,
1073
- appendTrace: (r) => this.appendTrace(r),
1074
- recordAudit: (type, e, details) => this.recordAudit(type, e, details),
1075
- onSoftViolation: this.onSoftViolation,
1076
- safeHook: (fn, name, e) => this.safeHook(fn, name, e)
1077
- });
1078
- }
1079
- await recordSuccessfulPublish(
1080
- this.recording,
1081
- event,
1082
- matching.length
1083
- );
1084
- await Promise.all(
1085
- matching.map((sub) => this.invokeHandler(sub, event))
1086
- );
1087
- if (this.onPublish) {
1088
- await this.safeHook(
1089
- () => this.onPublish(event),
1090
- "onPublish",
1091
- event
1092
- );
1093
- }
1094
- }
1095
- createPublisher(source) {
1096
- const sourceName = typeof source === "string" ? source : source.name;
1097
- assertIntentAllowed(sourceName, {
1098
- strictRegistry: this.strictRegistry,
1099
- validateIntentNaming: this.validateIntentNaming,
1100
- intentRegistry: this.intentRegistry
1101
- });
1102
- return {
1103
- source: sourceName,
1104
- publish: async (intent, payload, metadata = {}) => {
1105
- if (metadata.source && metadata.source !== sourceName) {
1106
- throw new SourceMetadataOverrideError(sourceName, metadata.source);
1107
- }
1108
- await this.publish(intent, payload, {
1109
- ...metadata,
1110
- source: sourceName
1111
- });
1112
- }
1113
- };
1114
- }
1115
- subscribe(intent, handler) {
1116
- const intentName = typeof intent === "string" ? intent : intent.name;
1117
- assertIntentAllowed(intentName, {
1118
- strictRegistry: this.strictRegistry,
1119
- validateIntentNaming: this.validateIntentNaming,
1120
- intentRegistry: this.intentRegistry
1121
- });
1122
- const sub = {
1123
- intentName,
1124
- handler
1125
- };
1126
- this.subscriptions.push(sub);
1127
- const subscriptionsForIntent = this.subscriptionsByIntent.get(intentName) ?? [];
1128
- subscriptionsForIntent.push(sub);
1129
- this.subscriptionsByIntent.set(intentName, subscriptionsForIntent);
1130
- return () => {
1131
- const idx = this.subscriptions.indexOf(sub);
1132
- if (idx >= 0) this.subscriptions.splice(idx, 1);
1133
- const byIntent = this.subscriptionsByIntent.get(intentName);
1134
- if (!byIntent) return;
1135
- const intentIdx = byIntent.indexOf(sub);
1136
- if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
1137
- if (byIntent.length === 0) this.subscriptionsByIntent.delete(intentName);
1138
- };
1139
- }
1140
- registerInterceptor(intent, interceptor, interceptorId) {
1141
- const intentName = typeof intent === "string" ? intent : intent.name;
1142
- assertIntentAllowed(intentName, {
1143
- strictRegistry: this.strictRegistry,
1144
- validateIntentNaming: this.validateIntentNaming,
1145
- intentRegistry: this.intentRegistry
1146
- });
1147
- const registration = {
1148
- registrationId: nextInterceptorRegistrationId(),
1149
- interceptorId: interceptorId ?? intentName,
1150
- intentName,
1151
- interceptor,
1152
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1153
- };
1154
- this.interceptors.push(registration);
1155
- const interceptorsForIntent = this.interceptorsByIntent.get(intentName) ?? [];
1156
- interceptorsForIntent.push(registration);
1157
- this.interceptorsByIntent.set(intentName, interceptorsForIntent);
1158
- return registration.registrationId;
1159
- }
1160
- unregisterInterceptor(registrationId) {
1161
- const interceptor = this.interceptors.find(
1162
- (candidate) => candidate.registrationId === registrationId
1163
- );
1164
- if (!interceptor) return false;
1165
- const idx = this.interceptors.indexOf(interceptor);
1166
- if (idx >= 0) this.interceptors.splice(idx, 1);
1167
- const byIntent = this.interceptorsByIntent.get(interceptor.intentName);
1168
- if (byIntent) {
1169
- const intentIdx = byIntent.indexOf(interceptor);
1170
- if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
1171
- if (byIntent.length === 0) this.interceptorsByIntent.delete(interceptor.intentName);
1172
- }
1173
- return true;
1174
- }
1175
- listInterceptors(intent) {
1176
- return this.interceptors.filter((interceptor) => !intent || interceptor.intentName === intent).map((interceptor) => ({
1177
- registrationId: interceptor.registrationId,
1178
- interceptorId: interceptor.interceptorId,
1179
- intent: interceptor.intentName,
1180
- createdAt: interceptor.createdAt,
1181
- lastInterceptedAt: interceptor.lastInterceptedAt
1182
- }));
1183
- }
1184
- getHistory() {
1185
- return [...this.recording.history];
1186
- }
1187
- clearHistory() {
1188
- this.recording.history.length = 0;
1189
- }
1190
- getTrace() {
1191
- return [...this.recording.trace];
1192
- }
1193
- clearTrace() {
1194
- this.recording.trace.length = 0;
1195
- }
1196
- appendTrace(record) {
1197
- appendTrace(this.recording, record);
1198
- }
1199
- async recordAudit(type, event, details) {
1200
- await recordAudit(this.recording, type, event, details);
1201
- }
1202
- async invokeHandler(sub, event) {
1203
- try {
1204
- await Promise.resolve(sub.handler(event));
1205
- } catch (err) {
1206
- this.appendTrace({
1207
- type: "handler.error",
1208
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1209
- intent: event.intent,
1210
- correlationId: event.metadata.correlationId,
1211
- traceId: event.metadata.traceId,
1212
- spanId: event.metadata.spanId,
1213
- details: { error: err instanceof Error ? err.message : String(err) }
1214
- });
1215
- await this.recordAudit("handler.error", event, {
1216
- handlerIntent: sub.intentName,
1217
- error: err instanceof Error ? err.message : String(err)
1218
- });
1219
- if (this.onHandlerError) {
1220
- await this.safeHook(
1221
- () => this.onHandlerError(err, event, sub.intentName),
1222
- "onHandlerError",
1223
- event
1224
- );
1225
- }
1226
- if (this.rethrowHandlerErrors) {
1227
- throw err;
1228
- }
1229
- }
1230
- }
1231
- async safeHook(fn, hookName, event) {
1232
- try {
1233
- await Promise.resolve(fn());
1234
- } catch (err) {
1235
- this.appendTrace({
1236
- type: "hook.error",
1237
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1238
- intent: event.intent,
1239
- correlationId: event.metadata.correlationId,
1240
- traceId: event.metadata.traceId,
1241
- spanId: event.metadata.spanId,
1242
- details: {
1243
- hook: hookName,
1244
- error: err instanceof Error ? err.message : String(err)
1245
- }
1246
- });
1247
- await this.recordAudit("hook.error", event, {
1248
- hook: hookName,
1249
- error: err instanceof Error ? err.message : String(err)
1250
- });
1251
- }
1252
- }
1253
- };
1254
- function createEventBus(options) {
1255
- return new EventBusImpl(options);
1256
- }
1257
-
1258
- // src/kernel/event-contracts/EventContractRegistry.ts
1259
- function formatStandardSchemaPath(path) {
1260
- if (!path || path.length === 0) return void 0;
1261
- return path.map(
1262
- (segment) => typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment)
1263
- ).join(".");
1264
- }
1265
- function actualType(value) {
1266
- if (Array.isArray(value)) return "array";
1267
- if (value === null) return "object";
1268
- const type = typeof value;
1269
- if (type === "string" || type === "number" || type === "boolean" || type === "object") {
1270
- return type;
1271
- }
1272
- return "unknown";
1273
- }
1274
- function formatPath(parent, field) {
1275
- return parent ? `${parent}.${field}` : field;
1276
- }
1277
- function validateSchemaField(value, fieldSchema, path, contract, issues) {
1278
- const valueType = actualType(value);
1279
- if (fieldSchema.type !== "unknown" && valueType !== fieldSchema.type) {
1280
- issues.push({
1281
- intent: contract.intent,
1282
- version: contract.version,
1283
- field: path,
1284
- message: `Expected ${fieldSchema.type}, received ${valueType}.`
1285
- });
1286
- return;
1287
- }
1288
- if (fieldSchema.enum && !fieldSchema.enum.some((allowed) => Object.is(allowed, value))) {
1289
- issues.push({
1290
- intent: contract.intent,
1291
- version: contract.version,
1292
- field: path,
1293
- message: "Value is not allowed by event contract enum."
1294
- });
1295
- }
1296
- if (fieldSchema.type === "object" && fieldSchema.fields) {
1297
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
1298
- issues.push({
1299
- intent: contract.intent,
1300
- version: contract.version,
1301
- field: path,
1302
- message: "Nested object field must be a non-array object."
1303
- });
1304
- return;
1305
- }
1306
- validateObjectSchema(
1307
- value,
1308
- fieldSchema.fields,
1309
- contract,
1310
- issues,
1311
- path
1312
- );
1313
- }
1314
- if (fieldSchema.type === "array" && fieldSchema.items && Array.isArray(value)) {
1315
- value.forEach((item, index) => {
1316
- validateSchemaField(
1317
- item,
1318
- fieldSchema.items,
1319
- `${path}[${index}]`,
1320
- contract,
1321
- issues
1322
- );
1323
- });
1324
- }
1325
- }
1326
- function validateObjectSchema(payload, schema, contract, issues, parentPath) {
1327
- for (const [field, fieldSchema] of Object.entries(schema)) {
1328
- const path = formatPath(parentPath, field);
1329
- const value = payload[field];
1330
- if (value === void 0) {
1331
- if (fieldSchema.required) {
1332
- issues.push({
1333
- intent: contract.intent,
1334
- version: contract.version,
1335
- field: path,
1336
- message: "Required field is missing."
1337
- });
1338
- }
1339
- continue;
1340
- }
1341
- validateSchemaField(value, fieldSchema, path, contract, issues);
1342
- }
1343
- }
1344
- var EventContractRegistryImpl = class {
1345
- contracts = /* @__PURE__ */ new Map();
1346
- register(contract) {
1347
- const key = this.key(contract.intent, contract.version);
1348
- if (this.contracts.has(key)) {
1349
- throw new Error(`Event contract "${key}" is already registered.`);
1350
- }
1351
- this.contracts.set(key, { allowAdditionalFields: true, ...contract });
1352
- }
1353
- get(intent, version2) {
1354
- if (version2) return this.contracts.get(this.key(intent, version2));
1355
- return this.list(intent).at(-1);
1356
- }
1357
- list(intent) {
1358
- return Array.from(this.contracts.values()).filter(
1359
- (contract) => !intent || contract.intent === intent
1360
- );
1361
- }
1362
- validate(event) {
1363
- const version2 = event.metadata.eventVersion;
1364
- const contract = this.get(event.intent, version2);
1365
- const issues = [];
1366
- if (!contract) {
1367
- return {
1368
- ok: false,
1369
- issues: [
1370
- {
1371
- intent: event.intent,
1372
- version: version2,
1373
- message: version2 ? `No event contract registered for version "${version2}".` : "No event contract registered for intent."
1374
- }
1375
- ]
1376
- };
1377
- }
1378
- if (contract.deprecated) {
1379
- issues.push({
1380
- intent: event.intent,
1381
- version: contract.version,
1382
- message: typeof contract.deprecated === "string" ? contract.deprecated : "Event contract is deprecated."
1383
- });
1384
- }
1385
- const payload = event.payload != null && typeof event.payload === "object" ? event.payload : void 0;
1386
- if (contract.schema) {
1387
- if (!payload) {
1388
- issues.push({
1389
- intent: event.intent,
1390
- version: contract.version,
1391
- message: "Payload must be an object for schema validation."
1392
- });
1393
- } else {
1394
- validateObjectSchema(payload, contract.schema, contract, issues);
1395
- if (contract.allowAdditionalFields === false) {
1396
- for (const field of Object.keys(payload)) {
1397
- if (!contract.schema[field]) {
1398
- issues.push({
1399
- intent: event.intent,
1400
- version: contract.version,
1401
- field,
1402
- message: "Additional field is not allowed by event contract."
1403
- });
1404
- }
1405
- }
1406
- }
1407
- }
1408
- }
1409
- if (contract.standardSchema) {
1410
- const result = contract.standardSchema["~standard"].validate(event.payload);
1411
- if (result instanceof Promise) {
1412
- issues.push({
1413
- intent: event.intent,
1414
- version: contract.version,
1415
- message: "Standard Schema validator returned a Promise; event contract validation is synchronous."
1416
- });
1417
- } else if (result.issues) {
1418
- for (const issue of result.issues) {
1419
- issues.push({
1420
- intent: event.intent,
1421
- version: contract.version,
1422
- field: formatStandardSchemaPath(issue.path),
1423
- message: issue.message
1424
- });
1425
- }
1426
- }
1427
- }
1428
- return { ok: issues.length === 0, contract, issues };
1429
- }
1430
- clear() {
1431
- this.contracts.clear();
1432
- }
1433
- key(intent, version2) {
1434
- return `${intent}@${version2}`;
1435
- }
1436
- };
1437
- function createEventContractRegistry() {
1438
- return new EventContractRegistryImpl();
1439
- }
1440
-
1441
- // src/kernel/outbox/InMemoryOutboxStore.ts
1442
- var outboxSequence = 0;
1443
- function nextOutboxId() {
1444
- outboxSequence += 1;
1445
- return `outbox-${Date.now()}-${outboxSequence}`;
1446
- }
1447
- function cloneRecord(record) {
1448
- return {
1449
- ...record,
1450
- event: {
1451
- ...record.event,
1452
- metadata: { ...record.event.metadata }
1453
- }
1454
- };
1455
- }
1456
- var InMemoryOutboxStore = class {
1457
- records = /* @__PURE__ */ new Map();
1458
- async enqueue(event) {
1459
- const now = (/* @__PURE__ */ new Date()).toISOString();
1460
- const record = {
1461
- id: nextOutboxId(),
1462
- event,
1463
- status: "pending",
1464
- attempts: 0,
1465
- createdAt: now,
1466
- updatedAt: now
1467
- };
1468
- this.records.set(record.id, record);
1469
- return cloneRecord(record);
1470
- }
1471
- async markDispatched(id) {
1472
- const record = this.records.get(id);
1473
- if (!record) return;
1474
- record.status = "dispatched";
1475
- record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1476
- }
1477
- async markFailed(id, error) {
1478
- const record = this.records.get(id);
1479
- if (!record) return;
1480
- record.status = "failed";
1481
- record.attempts += 1;
1482
- record.error = error instanceof Error ? error.message : String(error);
1483
- record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1484
- }
1485
- async list(status) {
1486
- return Array.from(this.records.values()).filter((record) => !status || record.status === status).map(cloneRecord);
1487
- }
1488
- async clear() {
1489
- this.records.clear();
1490
- }
1491
- };
1492
-
1493
- // src/kernel/observability/ObservabilityReporter.ts
1494
- function flowKey(flow) {
1495
- return `${flow.from}->${flow.to}`;
1496
- }
1497
- function uniqueFlows(flows) {
1498
- const seen = /* @__PURE__ */ new Set();
1499
- const result = [];
1500
- for (const flow of flows) {
1501
- const key = flowKey(flow);
1502
- if (seen.has(key)) continue;
1503
- seen.add(key);
1504
- result.push(flow);
1505
- }
1506
- return result;
1507
- }
1508
- function difference(left, right) {
1509
- const rightKeys = new Set(right.map(flowKey));
1510
- return left.filter((flow) => !rightKeys.has(flowKey(flow)));
1511
- }
1512
- function createObservabilityReporter(options) {
1513
- const registry = options.registry;
1514
- const eventBus = options.eventBus;
1515
- const graph = options.graph;
1516
- return {
1517
- report() {
1518
- const declaredFromRegistry = registry ? registry.getAllRelationships().filter((relationship) => relationship.kind === "produces").map((relationship) => ({
1519
- from: relationship.from,
1520
- to: relationship.to
1521
- })) : [];
1522
- const declaredFromGraph = declaredFromRegistry.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "produces").map((edge) => ({ from: edge.from, to: edge.to }));
1523
- const observedFromHistory = eventBus?.getHistory().map((record) => ({
1524
- from: record.event.metadata.source,
1525
- to: record.event.intent
1526
- })) ?? [];
1527
- const observedFromGraph = observedFromHistory.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "observed").map((edge) => ({ from: edge.from, to: edge.to }));
1528
- const declaredProductions = uniqueFlows([
1529
- ...declaredFromRegistry,
1530
- ...declaredFromGraph
1531
- ]);
1532
- const observedProductions = uniqueFlows([
1533
- ...observedFromHistory,
1534
- ...observedFromGraph
1535
- ]);
1536
- const unknownSources = observedProductions.filter(
1537
- (flow) => !flow.from || flow.from === "unknown"
1538
- );
1539
- const unregisteredObservedSources = registry ? Array.from(
1540
- new Set(
1541
- observedProductions.map((flow) => flow.from).filter(
1542
- (source) => source && source !== "unknown" && !registry.has(source)
1543
- )
1544
- )
1545
- ) : [];
1546
- const unregisteredObservedIntents = registry ? Array.from(
1547
- new Set(
1548
- observedProductions.map((flow) => flow.to).filter((intent) => !registry.has(intent))
1549
- )
1550
- ) : [];
1551
- const observedIntentNames = new Set(
1552
- observedProductions.flatMap((flow) => [flow.from, flow.to])
1553
- );
1554
- const registeredButNeverObserved = registry ? registry.list().map((intent) => intent.name).filter((intent) => !observedIntentNames.has(intent)) : [];
1555
- return {
1556
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1557
- declaredProductions,
1558
- observedProductions,
1559
- declaredButUnobserved: difference(declaredProductions, observedProductions),
1560
- observedButUndeclared: difference(
1561
- observedProductions.filter((flow) => flow.from !== "unknown"),
1562
- declaredProductions
1563
- ),
1564
- unknownSources,
1565
- unregisteredObservedSources,
1566
- unregisteredObservedIntents,
1567
- registeredButNeverObserved
1568
- };
1569
- }
1570
- };
1571
- }
1572
-
1573
- // src/kernel/testing/ArkTestHarness.ts
1574
- function createArkTestHarness(kernel) {
1575
- return {
1576
- events(intent) {
1577
- return kernel.eventBus.getHistory().map((record) => record.event).filter((event) => !intent || event.intent === intent);
1578
- },
1579
- traces(type) {
1580
- return kernel.eventBus.getTrace().filter((record) => !type || record.type === type);
1581
- },
1582
- audit(query) {
1583
- return kernel.auditTrail.query(query);
1584
- },
1585
- outbox(status) {
1586
- return kernel.outbox.list(status);
1587
- },
1588
- observability() {
1589
- kernel.syncGraph();
1590
- return kernel.observability.report();
1591
- },
1592
- async snapshot() {
1593
- return {
1594
- events: this.events(),
1595
- traces: this.traces(),
1596
- audit: await this.audit(),
1597
- outbox: await this.outbox(),
1598
- observability: this.observability()
1599
- };
1600
- },
1601
- async clear() {
1602
- kernel.eventBus.clearHistory();
1603
- kernel.eventBus.clearTrace();
1604
- await kernel.auditTrail.clear();
1605
- await kernel.outbox.clear();
1606
- }
1607
- };
1608
- }
1609
-
1610
- // src/kernel/audit/AuditTrail.ts
1611
- var auditSequence = 0;
1612
- function createAuditId() {
1613
- auditSequence += 1;
1614
- return `audit-${Date.now()}-${auditSequence}`;
1615
- }
1616
- function matchesQuery(record, query) {
1617
- if (query.type && record.type !== query.type) return false;
1618
- if (query.intent && record.intent !== query.intent) return false;
1619
- if (query.correlationId && record.correlationId !== query.correlationId) return false;
1620
- if (query.subject && record.subject !== query.subject) return false;
1621
- if (query.since && record.timestamp < query.since) return false;
1622
- if (query.until && record.timestamp > query.until) return false;
1623
- return true;
1624
- }
1625
- var InMemoryAuditStore = class {
1626
- constructor(maxRecords) {
1627
- this.maxRecords = maxRecords;
1628
- }
1629
- maxRecords;
1630
- records = [];
1631
- append(record) {
1632
- this.records.push(record);
1633
- if (this.maxRecords !== void 0 && this.records.length > this.maxRecords) {
1634
- this.records.splice(0, this.records.length - this.maxRecords);
1635
- }
1636
- }
1637
- query(query = {}) {
1638
- const records = this.records.filter((record) => matchesQuery(record, query));
1639
- return query.limit === void 0 ? [...records] : records.slice(-query.limit);
1640
- }
1641
- clear() {
1642
- this.records.length = 0;
1643
- }
1644
- };
1645
- var AuditTrailImpl = class {
1646
- constructor(store) {
1647
- this.store = store;
1648
- }
1649
- store;
1650
- async record(input) {
1651
- const record = {
1652
- id: createAuditId(),
1653
- timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
1654
- type: input.type,
1655
- source: input.source,
1656
- actor: input.actor,
1657
- intent: input.intent,
1658
- correlationId: input.correlationId,
1659
- causationId: input.causationId,
1660
- subject: input.subject,
1661
- details: input.details
1662
- };
1663
- await this.store.append(record);
1664
- return record;
1665
- }
1666
- async query(query) {
1667
- return this.store.query(query);
1668
- }
1669
- async clear() {
1670
- await this.store.clear();
1671
- }
1672
- };
1673
- function createAuditTrail(options = {}) {
1674
- return new AuditTrailImpl(
1675
- options.store ?? new InMemoryAuditStore(options.maxRecords)
1676
- );
1677
- }
1678
-
1679
- // src/kernel/graph/DependencyGraph.ts
1680
- var DependencyGraphImpl = class {
1681
- nodes = /* @__PURE__ */ new Map();
1682
- edges = [];
1683
- registerDependency(from, to, kind = "declared") {
1684
- this.ensureNode(from);
1685
- this.ensureNode(to);
1686
- this.addEdge({ from, to, kind });
1687
- }
1688
- registerEventFlow(producer, consumer) {
1689
- this.ensureNode(producer);
1690
- this.ensureNode(consumer);
1691
- this.addEdge({ from: producer, to: consumer, kind: "observed" });
1692
- }
1693
- getNodes() {
1694
- return Array.from(this.nodes.values());
1695
- }
1696
- getEdges() {
1697
- return [...this.edges];
1698
- }
1699
- toJSON() {
1700
- return {
1701
- nodes: this.getNodes(),
1702
- edges: this.getEdges()
1703
- };
1704
- }
1705
- toMermaid() {
1706
- let out = "flowchart TD\n";
1707
- for (const edge of this.edges) {
1708
- const label = edge.kind ? `|${edge.kind}|` : "";
1709
- out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
1710
- `;
1711
- }
1712
- const connected = new Set(
1713
- this.edges.flatMap((e) => [e.from, e.to])
1714
- );
1715
- for (const node of this.nodes.keys()) {
1716
- if (!connected.has(node)) {
1717
- out += ` ${this.safeId(node)}
1718
- `;
1719
- }
1720
- }
1721
- return out.trim();
1722
- }
1723
- toLayerMermaid(profile) {
1724
- const nodesByLayer = /* @__PURE__ */ new Map();
1725
- for (const node of this.nodes.keys()) {
1726
- const layer = profile.resolveLayer(node) ?? "Unclassified";
1727
- const current = nodesByLayer.get(layer) ?? [];
1728
- current.push(node);
1729
- nodesByLayer.set(layer, current);
1730
- }
1731
- let out = "flowchart TD\n";
1732
- for (const layer of profile.layers) {
1733
- const nodes = nodesByLayer.get(layer.name) ?? [];
1734
- if (nodes.length === 0) continue;
1735
- out += ` subgraph ${this.safeId(layer.name)}[${layer.name}]
1736
- `;
1737
- for (const node of nodes) {
1738
- out += ` ${this.safeId(node)}[${node}]
1739
- `;
1740
- }
1741
- out += " end\n";
1742
- }
1743
- const unclassified = nodesByLayer.get("Unclassified") ?? [];
1744
- if (unclassified.length > 0) {
1745
- out += " subgraph Unclassified[Unclassified]\n";
1746
- for (const node of unclassified) {
1747
- out += ` ${this.safeId(node)}[${node}]
1748
- `;
1749
- }
1750
- out += " end\n";
1751
- }
1752
- for (const edge of this.edges) {
1753
- const label = edge.kind ? `|${edge.kind}|` : "";
1754
- out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
1755
- `;
1756
- }
1757
- return out.trim();
1758
- }
1759
- detectViolations(rules = []) {
1760
- const violations = [];
1761
- const cycles = this.findSimpleCycles();
1762
- if (cycles.length > 0) {
1763
- violations.push(`Cycle detected: ${cycles.map((c) => c.join("->")).join(", ")}`);
1764
- }
1765
- for (const rule of rules) {
1766
- try {
1767
- const res = rule(this.edges);
1768
- if (res && res.length) violations.push(...res);
1769
- } catch (e) {
1770
- violations.push(`Rule error: ${e.message}`);
1771
- }
1772
- }
1773
- return violations;
1774
- }
1775
- ensureNode(id) {
1776
- if (!this.nodes.has(id)) {
1777
- this.nodes.set(id, { id });
1778
- }
1779
- }
1780
- addEdge(edge) {
1781
- const exists = this.edges.some(
1782
- (e) => e.from === edge.from && e.to === edge.to && e.kind === edge.kind
1783
- );
1784
- if (!exists) {
1785
- this.edges.push(edge);
1786
- }
1787
- }
1788
- // Very naive cycle detection for small graphs
1789
- findSimpleCycles() {
1790
- const graph = /* @__PURE__ */ new Map();
1791
- for (const e of this.edges) {
1792
- if (!graph.has(e.from)) graph.set(e.from, []);
1793
- graph.get(e.from).push(e.to);
1794
- }
1795
- const cycles = [];
1796
- const visited = /* @__PURE__ */ new Set();
1797
- const stack = [];
1798
- const dfs = (node) => {
1799
- visited.add(node);
1800
- stack.push(node);
1801
- for (const nei of graph.get(node) || []) {
1802
- if (!visited.has(nei)) {
1803
- dfs(nei);
1804
- } else if (stack.includes(nei)) {
1805
- const cycleStart = stack.indexOf(nei);
1806
- const cycle = stack.slice(cycleStart).concat(nei);
1807
- cycles.push(cycle);
1808
- }
1809
- }
1810
- stack.pop();
1811
- };
1812
- for (const node of graph.keys()) {
1813
- if (!visited.has(node)) dfs(node);
1814
- }
1815
- const unique = new Set(cycles.map((c) => c.join("->")));
1816
- return Array.from(unique).map((s) => s.split("->"));
1817
- }
1818
- safeId(id) {
1819
- return id.replace(/[^a-zA-Z0-9_]/g, "_");
1820
- }
1821
- };
1822
- function createDependencyGraph() {
1823
- return new DependencyGraphImpl();
1824
- }
1825
-
1826
- // src/kernel/graph/sync.ts
1827
- function syncRegistryToGraph(registry, graph, options = {}) {
1828
- const requireRegistered = options.requireRegisteredTargets ?? false;
1829
- for (const rel of registry.getAllRelationships()) {
1830
- if (requireRegistered && !registry.has(rel.to)) {
1831
- continue;
1832
- }
1833
- if (rel.kind === "dependsOn") {
1834
- graph.registerDependency(rel.from, rel.to, "declared");
1835
- } else {
1836
- graph.registerDependency(rel.from, rel.to, "produces");
1837
- }
1838
- }
1839
- }
1840
-
1841
- // src/kernel/layers/ArchitectureProfile.ts
1842
- function normalizePrefix(prefix) {
1843
- return prefix.endsWith(".") ? prefix : `${prefix}.`;
1844
- }
1845
- function byLongestPrefix(a, b) {
1846
- const maxA = a.prefixes.length ? Math.max(...a.prefixes.map((p) => p.length)) : 0;
1847
- const maxB = b.prefixes.length ? Math.max(...b.prefixes.map((p) => p.length)) : 0;
1848
- return maxB - maxA;
1849
- }
1850
- function flowKey2(from, to) {
1851
- return `${from}->${to}`;
1852
- }
1853
- function createStrictDenyRules(layers, allowedFlows) {
1854
- const allowed = new Set(allowedFlows.map((flow) => flowKey2(flow.from, flow.to)));
1855
- const rules = [];
1856
- for (const from of layers) {
1857
- for (const to of layers) {
1858
- if (from.name === to.name) continue;
1859
- if (allowed.has(flowKey2(from.name, to.name))) continue;
1860
- rules.push({ from: from.name, to: to.name, allowed: false });
1861
- }
1862
- }
1863
- return rules;
1864
- }
1865
- function createArchitectureProfile(options) {
1866
- const layers = options.layers.map((layer) => ({
1867
- ...layer,
1868
- prefixes: layer.prefixes.map(normalizePrefix)
1869
- }));
1870
- const sortedLayers = [...layers].sort(byLongestPrefix);
1871
- const rules = [...options.rules ?? []];
1872
- return {
1873
- name: options.name,
1874
- layers,
1875
- rules,
1876
- resolveLayer(name) {
1877
- return layers.find((layer) => layer.match?.(name))?.name ?? sortedLayers.find(
1878
- (layer) => layer.prefixes.some((prefix) => name.startsWith(prefix))
1879
- )?.name;
1880
- }
1881
- };
1882
- }
1883
- function createArchitectureProfileFromArkConfig(config, options = {}) {
1884
- return createArchitectureProfile({
1885
- name: options.name ?? config.name ?? "ark.config.json",
1886
- layers: config.layers.map((layer, index) => ({
1887
- name: layer.name,
1888
- prefixes: layer.intentPrefixes ?? [],
1889
- description: layer.description,
1890
- order: index + 1
1891
- })),
1892
- rules: config.rules ?? []
1893
- });
1894
- }
1895
- var elevenLayerProfileLayers = [
1896
- {
1897
- name: "DomainModel",
1898
- prefixes: ["Domain"],
1899
- description: "Rich domain model, business rules, and domain events.",
1900
- order: 1
1901
- },
1902
- {
1903
- name: "ApplicationOrchestration",
1904
- prefixes: ["Application"],
1905
- description: "Use cases and command orchestration.",
1906
- order: 2
1907
- },
1908
- {
1909
- name: "PersistenceAdapters",
1910
- prefixes: ["Adapter.Persistence", "Adapter.Repository"],
1911
- description: "Database, repository, and storage adapters.",
1912
- order: 3
1913
- },
1914
- {
1915
- name: "IntegrationAdapters",
1916
- prefixes: ["Adapter.Integration", "Adapter.External"],
1917
- description: "External systems, APIs, and integration adapters.",
1918
- order: 4
1919
- },
1920
- {
1921
- name: "WorkflowSagaEngine",
1922
- prefixes: ["Workflow"],
1923
- description: "Sagas, workflows, and long-running processes.",
1924
- order: 5
1925
- },
1926
- {
1927
- name: "BackgroundJobsScheduling",
1928
- prefixes: ["Job"],
1929
- description: "Background jobs, scheduled work, and async processors.",
1930
- order: 6
1931
- },
1932
- {
1933
- name: "PresentationAdapters",
1934
- prefixes: ["Presentation", "Adapter.Presentation", "Adapter.Api"],
1935
- description: "API, UI, controller, and presentation adapters.",
1936
- order: 7
1937
- },
1938
- {
1939
- name: "ReportingReadModels",
1940
- prefixes: ["Reporting"],
1941
- description: "Read models, projections, and reporting surfaces.",
1942
- order: 8
1943
- },
1944
- {
1945
- name: "ExtensibilityMetadata",
1946
- prefixes: ["Metadata"],
1947
- description: "Metadata, extensions, and schema contracts.",
1948
- order: 9
1949
- },
1950
- {
1951
- name: "SecurityAuditObservability",
1952
- prefixes: ["Security", "Audit", "Observability"],
1953
- description: "Security, audit, and observability concerns.",
1954
- order: 10
1955
- },
1956
- {
1957
- name: "Kernel",
1958
- prefixes: ["Kernel"],
1959
- description: "Ark-owned governance and kernel signals.",
1960
- order: 11
1961
- }
1962
- ];
1963
- var elevenLayerAllowedFlows = [
1964
- { from: "PresentationAdapters", to: "ApplicationOrchestration" },
1965
- { from: "ApplicationOrchestration", to: "DomainModel" },
1966
- { from: "WorkflowSagaEngine", to: "ApplicationOrchestration" },
1967
- { from: "WorkflowSagaEngine", to: "DomainModel" },
1968
- { from: "BackgroundJobsScheduling", to: "ApplicationOrchestration" }
1969
- ];
1970
- var elevenLayerProfile = createArchitectureProfile({
1971
- name: "Ark 11-layer Hexagonal Event-Driven Profile",
1972
- layers: elevenLayerProfileLayers,
1973
- rules: createStrictDenyRules(
1974
- elevenLayerProfileLayers,
1975
- elevenLayerAllowedFlows
1976
- )
1977
- });
1978
- var defaultElevenLayerDirectories = {
1979
- DomainModel: ["domain"],
1980
- ApplicationOrchestration: ["application", "app"],
1981
- PersistenceAdapters: [
1982
- "adapters/persistence",
1983
- "adapters/repository",
1984
- "repositories",
1985
- "infra/persistence"
1986
- ],
1987
- IntegrationAdapters: ["adapters/integration", "adapters/external", "integrations"],
1988
- WorkflowSagaEngine: ["workflows", "sagas"],
1989
- BackgroundJobsScheduling: ["jobs", "schedules"],
1990
- PresentationAdapters: ["presentation", "adapters/presentation", "adapters/api"],
1991
- ReportingReadModels: ["reporting", "read-models", "projections"],
1992
- ExtensibilityMetadata: ["metadata", "extensions"],
1993
- SecurityAuditObservability: ["security", "audit", "observability"],
1994
- Kernel: ["kernel"]
1995
- };
1996
- function createElevenLayerArkConfig(options = {}) {
1997
- const rootDir = options.rootDir ?? "src";
1998
- const optional = options.optionalLayers ?? true;
1999
- const prefix = rootDir === "." ? "" : `${rootDir}/`;
2000
- return {
2001
- include: options.include ?? [rootDir],
2002
- layers: elevenLayerProfile.layers.map((layer) => ({
2003
- name: layer.name,
2004
- patterns: (defaultElevenLayerDirectories[layer.name] ?? [layer.name]).map(
2005
- (directory) => `${prefix}${directory}/**`
2006
- ),
2007
- intentPrefixes: layer.prefixes,
2008
- optional
2009
- })),
2010
- rules: [...elevenLayerProfile.rules]
2011
- };
2012
- }
2013
-
2014
- // src/kernel/metadata/MetadataRegistry.ts
2015
- var MetadataRegistryImpl = class {
2016
- entities = /* @__PURE__ */ new Map();
2017
- entity(name, meta, options = {}) {
2018
- if (this.entities.has(name) && !options.allowOverwrite) {
2019
- throw new Error(`Entity metadata "${name}" is already registered.`);
2020
- }
2021
- const full = { name, fields: {}, ...meta };
2022
- this.entities.set(name, full);
2023
- return full;
2024
- }
2025
- getEntity(name) {
2026
- return this.entities.get(name);
2027
- }
2028
- listEntities() {
2029
- return Array.from(this.entities.values());
2030
- }
2031
- findEntitiesByIntent(intentName) {
2032
- return this.listEntities().filter(
2033
- (entity) => entity.emits?.includes(intentName) || entity.consumes?.includes(intentName)
2034
- );
2035
- }
2036
- validate() {
2037
- const issues = [];
2038
- for (const entity of this.entities.values()) {
2039
- if (!entity.name.trim()) {
2040
- issues.push({ entity: entity.name, message: "Entity name is required." });
2041
- }
2042
- for (const [fieldName, field] of Object.entries(entity.fields)) {
2043
- if (!fieldName.trim()) {
2044
- issues.push({ entity: entity.name, field: fieldName, message: "Field name is required." });
2045
- }
2046
- if (!field.type || typeof field.type !== "string") {
2047
- issues.push({
2048
- entity: entity.name,
2049
- field: fieldName,
2050
- message: "Field type must be a non-empty string."
2051
- });
2052
- }
2053
- if (field.relation && !this.entities.has(field.relation.entity)) {
2054
- issues.push({
2055
- entity: entity.name,
2056
- field: fieldName,
2057
- message: `Related entity "${field.relation.entity}" is not registered.`
2058
- });
2059
- }
2060
- }
2061
- }
2062
- return { ok: issues.length === 0, issues };
2063
- }
2064
- toJSON() {
2065
- return this.listEntities();
2066
- }
2067
- };
2068
- function createMetadataRegistry() {
2069
- return new MetadataRegistryImpl();
2070
- }
2071
-
2072
- // src/kernel/adapters/ports.ts
2073
- function definePort(name, options = {}) {
2074
- return {
2075
- name,
2076
- ownerLayer: options.ownerLayer,
2077
- intent: options.intent,
2078
- allowedAdapters: options.allowedAdapters ? [...options.allowedAdapters] : void 0
2079
- };
2080
- }
2081
- function createAdapter(port, impl, requiredKeysOrOptions, adapterOptions = {}) {
2082
- const options = Array.isArray(requiredKeysOrOptions) ? { ...adapterOptions, requiredKeys: requiredKeysOrOptions } : { ...requiredKeysOrOptions ?? {} };
2083
- const requiredKeys = options.requiredKeys;
2084
- if (requiredKeys && requiredKeys.length > 0) {
2085
- const missing = requiredKeys.filter((k) => !hasMember(impl, k));
2086
- if (missing.length > 0) {
2087
- throw new Error(
2088
- `Adapter for port "${port.name}" is missing required members: ${missing.join(", ")}`
2089
- );
2090
- }
2091
- }
2092
- const adapter = {
2093
- name: options.name,
2094
- layer: options.layer,
2095
- intent: options.intent,
2096
- port,
2097
- impl
2098
- };
2099
- const governance = checkAdapterGovernance(adapter);
2100
- if (!governance.ok) {
2101
- throw new Error(governance.issues.map((issue) => issue.message).join("\n"));
2102
- }
2103
- return adapter;
2104
- }
2105
- function checkContract(impl, requiredKeys = []) {
2106
- const missing = requiredKeys.filter((k) => !hasMember(impl, k));
2107
- return missing.length === 0 ? { ok: true } : { ok: false, missing };
2108
- }
2109
- function checkAdapterGovernance(adapter) {
2110
- const allowed = adapter.port.allowedAdapters ?? [];
2111
- if (allowed.length === 0) {
2112
- return { ok: true, issues: [] };
2113
- }
2114
- const adapterNames = [adapter.name, adapter.intent].filter(
2115
- (value) => typeof value === "string" && value.length > 0
2116
- );
2117
- const matched = adapterNames.some((name) => allowed.includes(name));
2118
- if (matched) {
2119
- return { ok: true, issues: [] };
2120
- }
2121
- return {
2122
- ok: false,
2123
- issues: [
2124
- {
2125
- ruleId: "ADAPTER_NOT_ALLOWED_FOR_PORT",
2126
- port: adapter.port.name,
2127
- adapter: adapter.name ?? adapter.intent,
2128
- message: `Adapter "${adapter.name ?? adapter.intent ?? "unknown"}" is not allowed for port "${adapter.port.name}".`
2129
- }
2130
- ]
462
+ ts.forEachChild(node, visit);
2131
463
  };
2132
- }
2133
- function hasMember(value, key) {
2134
- return value != null && (typeof value === "object" || typeof value === "function") && key in value;
464
+ visit(sourceFile);
465
+ return uses;
2135
466
  }
2136
467
 
2137
468
  // src/kernel/ai-gate/AICodeGate.ts
2138
469
  function violation(ruleId, message, extra) {
2139
470
  return { ruleId, code: ruleId, message, ...extra };
2140
471
  }
2141
- function lineOf(source, index) {
472
+ function lineOf2(source, index) {
2142
473
  return source.slice(0, index).split("\n").length;
2143
474
  }
2144
475
  function extractQuotedStrings(source) {
@@ -2181,63 +512,6 @@ function extractModuleSpecifiers(source) {
2181
512
  }
2182
513
  return matches.sort((a, b) => a.index - b.index);
2183
514
  }
2184
- function extractModuleSpecifiersAst(ts, source) {
2185
- const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2186
- const matches = [];
2187
- const push = (node, value, kind, typeOnly = false) => {
2188
- matches.push({
2189
- value,
2190
- index: node.getStart(sourceFile),
2191
- kind,
2192
- typeOnly
2193
- });
2194
- };
2195
- const visit = (node) => {
2196
- if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
2197
- const clause = node.importClause;
2198
- const namedBindings = clause?.namedBindings;
2199
- const specifiersOnly = clause && !clause.name && namedBindings && ts.isNamedImports(namedBindings) && namedBindings.elements.length > 0 && namedBindings.elements.every((element) => element.isTypeOnly === true);
2200
- push(
2201
- node.moduleSpecifier,
2202
- node.moduleSpecifier.text,
2203
- "import",
2204
- Boolean(clause?.isTypeOnly || specifiersOnly)
2205
- );
2206
- } else if (ts.isExportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
2207
- const clause = node.exportClause;
2208
- const specifiersOnly = clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly === true);
2209
- push(
2210
- node.moduleSpecifier,
2211
- node.moduleSpecifier.text,
2212
- "export",
2213
- Boolean(node.isTypeOnly || specifiersOnly)
2214
- );
2215
- } else if (ts.isCallExpression(node) && node.arguments.length === 1) {
2216
- const argument = node.arguments[0];
2217
- const value = tsStringLiteralText(ts, argument);
2218
- if (value !== void 0 && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
2219
- push(argument, value, "dynamic-import");
2220
- } else if (value !== void 0 && ts.isIdentifier(node.expression) && node.expression.text === "require") {
2221
- push(argument, value, "require");
2222
- }
2223
- }
2224
- ts.forEachChild(node, visit);
2225
- };
2226
- visit(sourceFile);
2227
- return matches.sort((a, b) => a.index - b.index);
2228
- }
2229
- function nonLiteralDynamicImportLines(ts, source) {
2230
- const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2231
- const lines = [];
2232
- const visit = (node) => {
2233
- if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && (!node.arguments[0] || !ts.isStringLiteralLike(node.arguments[0]))) {
2234
- lines.push(sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1);
2235
- }
2236
- ts.forEachChild(node, visit);
2237
- };
2238
- visit(sourceFile);
2239
- return lines;
2240
- }
2241
515
  function extractQuotedStringsAst(ts, source) {
2242
516
  const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2243
517
  const matches = [];
@@ -2250,9 +524,6 @@ function extractQuotedStringsAst(ts, source) {
2250
524
  visit(sourceFile);
2251
525
  return matches;
2252
526
  }
2253
- function looksLikeIntentName(s) {
2254
- return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(s);
2255
- }
2256
527
  function hasInfrastructureToken(specifier) {
2257
528
  const tokens = specifier.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2258
529
  return [
@@ -2334,7 +605,7 @@ function tsIsArkPublishCandidate(ts, node) {
2334
605
  if (!ts.isCallExpression(node)) return false;
2335
606
  const firstArg = node.arguments[0];
2336
607
  const rawIntent = tsStringLiteralText(ts, firstArg);
2337
- return rawIntent !== void 0 && looksLikeIntentName(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent") || tsLooksLikeIntentCreatorExpression(ts, firstArg);
608
+ return rawIntent !== void 0 && looksLikeArkIntent(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent") || tsLooksLikeIntentCreatorExpression(ts, firstArg);
2338
609
  }
2339
610
  function tsPublishHasSource(ts, node) {
2340
611
  if (!ts.isCallExpression(node)) return false;
@@ -2347,33 +618,6 @@ function tsPublishSourceLiteral(ts, node) {
2347
618
  const rawMetadata = tsObjectPropertyValue(ts, firstArg, "metadata");
2348
619
  return tsStringLiteralText(ts, tsObjectPropertyValue(ts, rawMetadata, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, secondArg, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, thirdArg, "source"));
2349
620
  }
2350
- function analyzeForbiddenGlobals(ts, source, filePath, layer, forbidden) {
2351
- const entries = new Set(forbidden);
2352
- if (entries.size === 0) return [];
2353
- const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2354
- const violations = [];
2355
- const flag = (name, node) => violations.push(
2356
- violation("FORBIDDEN_GLOBAL", `${layer} must not use the ambient global "${name}".`, {
2357
- line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
2358
- filePath,
2359
- target: name,
2360
- fromLayer: layer,
2361
- suggestion: "Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."
2362
- })
2363
- );
2364
- const visit = (node) => {
2365
- if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
2366
- const dotted = `${node.expression.text}.${node.name.text}`;
2367
- if (entries.has(dotted)) flag(dotted, node);
2368
- else if (entries.has(node.expression.text)) flag(node.expression.text, node);
2369
- } else if ((ts.isCallExpression(node) || ts.isNewExpression(node)) && node.expression && ts.isIdentifier(node.expression) && entries.has(node.expression.text)) {
2370
- flag(node.expression.text, node);
2371
- }
2372
- ts.forEachChild(node, visit);
2373
- };
2374
- visit(sourceFile);
2375
- return violations;
2376
- }
2377
621
  function analyzePublishAst(ts, source, context, profile) {
2378
622
  const sourceFile = ts.createSourceFile(
2379
623
  "generated.ts",
@@ -2390,24 +634,19 @@ function analyzePublishAst(ts, source, context, profile) {
2390
634
  if (tsIsPublishCall(ts, node)) {
2391
635
  const firstArg = node.arguments[0];
2392
636
  const rawIntent = tsStringLiteralText(ts, firstArg);
2393
- if (rawIntent && looksLikeIntentName(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent")) {
2394
- violations.push(
2395
- violation("RAW_EVENT_PUBLISH", "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.", {
2396
- line: lineForNode(node),
2397
- filePath
2398
- })
2399
- );
2400
- }
2401
- if (tsIsArkPublishCandidate(ts, node) && !tsPublishHasSource(ts, node)) {
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
+ })) {
2402
644
  violations.push(
2403
- violation("PUBLISH_MISSING_SOURCE", "Strict Ark publish calls must include metadata.source.", {
2404
- line: lineForNode(node),
2405
- filePath
2406
- })
645
+ violation(finding.ruleId, finding.message, { line: lineForNode(node), filePath })
2407
646
  );
2408
647
  }
2409
648
  const sourceIntent = tsPublishSourceLiteral(ts, node);
2410
- if (profile && contextLayer && sourceIntent && looksLikeIntentName(sourceIntent)) {
649
+ if (profile && contextLayer && sourceIntent && looksLikeArkIntent(sourceIntent)) {
2411
650
  const sourceLayer = profile.resolveLayer(sourceIntent);
2412
651
  if (sourceLayer && sourceLayer !== contextLayer) {
2413
652
  violations.push(
@@ -2444,15 +683,29 @@ function createAICodeGate(options = {}) {
2444
683
  const gateContext = context;
2445
684
  const filePath = gateContext?.filePath;
2446
685
  const contextLayer = gateContext?.layer;
2447
- const moduleSpecifiers = options.typescript ? extractModuleSpecifiersAst(options.typescript, source) : extractModuleSpecifiers(source);
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);
2448
700
  const quotedStrings = options.typescript ? extractQuotedStringsAst(options.typescript, source) : extractQuotedStrings(source);
2449
701
  if (options.typescript && !options.allowNonLiteralDynamicImport?.(filePath)) {
2450
- for (const line of nonLiteralDynamicImportLines(options.typescript, source)) {
702
+ for (const dependency of semanticDependencies?.filter(({ unresolved }) => unresolved) ?? []) {
703
+ const isRequire = dependency.kind === "require";
2451
704
  violations.push(
2452
705
  violation(
2453
- "DYNAMIC_IMPORT_NOT_ALLOWLISTED",
2454
- "Non-literal dynamic import cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.",
2455
- { line, filePath }
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 }
2456
709
  )
2457
710
  );
2458
711
  }
@@ -2467,7 +720,7 @@ function createAICodeGate(options = {}) {
2467
720
  if (match) {
2468
721
  violations.push(
2469
722
  violation("FORBIDDEN_PATTERN", `Forbidden pattern matched: ${pat}`, {
2470
- line: match.index === void 0 ? void 0 : lineOf(source, match.index),
723
+ line: match.index === void 0 ? void 0 : lineOf2(source, match.index),
2471
724
  filePath,
2472
725
  suggestion: "Remove infrastructure imports from domain/application layers." + infraLayerEscapeHatch
2473
726
  })
@@ -2476,13 +729,13 @@ function createAICodeGate(options = {}) {
2476
729
  } else if (source.includes(pat)) {
2477
730
  violations.push(
2478
731
  violation("FORBIDDEN_SUBSTRING", `Forbidden substring: ${pat}`, {
2479
- line: lineOf(source, source.indexOf(pat)),
732
+ line: lineOf2(source, source.indexOf(pat)),
2480
733
  filePath
2481
734
  })
2482
735
  );
2483
736
  }
2484
737
  }
2485
- for (const specifier of moduleSpecifiers) {
738
+ for (const specifier of moduleSpecifiers2) {
2486
739
  const targetHit = options.resolveImportTarget?.(specifier.value, filePath) ?? (options.resolveImportLayer ? { layer: options.resolveImportLayer(specifier.value, filePath) } : void 0);
2487
740
  const sourceHit = typeof filePath === "string" ? options.resolveImportTarget?.(filePath) ?? (options.resolveImportLayer ? { layer: contextLayer, relPath: void 0 } : void 0) : void 0;
2488
741
  const targetLayer = targetHit?.layer;
@@ -2507,7 +760,7 @@ function createAICodeGate(options = {}) {
2507
760
  "LAYER_IMPORT_VIOLATION",
2508
761
  blocked.message ?? (peer ? `Layer "${contextLayer}" must not import across slices into "${targetLayer}".` : `Layer "${contextLayer}" must not import "${targetLayer}".`),
2509
762
  {
2510
- line: lineOf(source, specifier.index),
763
+ line: lineOf2(source, specifier.index),
2511
764
  source: specifier.value,
2512
765
  target: specifier.value,
2513
766
  filePath,
@@ -2537,7 +790,7 @@ function createAICodeGate(options = {}) {
2537
790
  "FORBIDDEN_IMPORT",
2538
791
  `Forbidden ${specifier.kind} target: "${specifier.value}".`,
2539
792
  {
2540
- line: lineOf(source, specifier.index),
793
+ line: lineOf2(source, specifier.index),
2541
794
  source: specifier.value,
2542
795
  target: specifier.value,
2543
796
  filePath,
@@ -2574,13 +827,13 @@ function createAICodeGate(options = {}) {
2574
827
  }
2575
828
  if (enforceAllowlist && intentNames.size > 0) {
2576
829
  for (const literal of quotedStrings) {
2577
- if (looksLikeIntentName(literal.value) && !intentNames.has(literal.value)) {
830
+ if (looksLikeArkIntent(literal.value) && !intentNames.has(literal.value)) {
2578
831
  violations.push(
2579
832
  violation(
2580
833
  "UNKNOWN_INTENT",
2581
834
  `Unknown intent reference: "${literal.value}"`,
2582
835
  {
2583
- line: lineOf(source, literal.index),
836
+ line: lineOf2(source, literal.index),
2584
837
  filePath,
2585
838
  target: literal.value,
2586
839
  suggestion: `Register intent "${literal.value}" via defineIntent() or remove the reference.`
@@ -2592,7 +845,7 @@ function createAICodeGate(options = {}) {
2592
845
  }
2593
846
  if (options.architectureProfile && contextLayer) {
2594
847
  for (const literal of quotedStrings) {
2595
- if (!looksLikeIntentName(literal.value)) continue;
848
+ if (!looksLikeArkIntent(literal.value)) continue;
2596
849
  const targetLayer = options.architectureProfile.resolveLayer(literal.value);
2597
850
  if (!targetLayer) continue;
2598
851
  const blocked = findDeniedEdgeRule(
@@ -2606,7 +859,7 @@ function createAICodeGate(options = {}) {
2606
859
  "LAYER_REFERENCE_VIOLATION",
2607
860
  blocked.message ?? `Layer "${contextLayer}" must not reference "${targetLayer}" through "${literal.value}".`,
2608
861
  {
2609
- line: lineOf(source, literal.index),
862
+ line: lineOf2(source, literal.index),
2610
863
  filePath,
2611
864
  target: literal.value,
2612
865
  fromLayer: contextLayer,
@@ -2634,15 +887,25 @@ function createAICodeGate(options = {}) {
2634
887
  }
2635
888
  }
2636
889
  }
2637
- if (options.typescript && contextLayer && options.forbiddenGlobals?.[contextLayer]?.length) {
890
+ if (options.typescript && semanticSourceFile && contextLayer && options.forbiddenGlobals?.[contextLayer]?.length) {
2638
891
  try {
2639
892
  violations.push(
2640
- ...analyzeForbiddenGlobals(
893
+ ...collectForbiddenCapabilityUses(
2641
894
  options.typescript,
2642
- source,
2643
- filePath,
2644
- contextLayer,
895
+ semanticSourceFile,
2645
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
+ )
2646
909
  )
2647
910
  );
2648
911
  } catch (err) {
@@ -2680,591 +943,966 @@ function createAICodeGate(options = {}) {
2680
943
  }
2681
944
  };
2682
945
  }
2683
-
2684
- // src/kernel/projections/ProjectionRegistry.ts
2685
- var InMemoryReadModelStore = class {
2686
- states = /* @__PURE__ */ new Map();
2687
- load(name) {
2688
- return this.states.get(name);
2689
- }
2690
- save(name, state) {
2691
- this.states.set(name, state);
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
2692
1367
  }
2693
- clear(name) {
2694
- if (name) {
2695
- this.states.delete(name);
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;
2696
1455
  } else {
2697
- this.states.clear();
1456
+ value += current;
2698
1457
  }
2699
1458
  }
2700
- };
2701
- function initialState(definition) {
2702
- return typeof definition.initialState === "function" ? definition.initialState() : definition.initialState;
2703
- }
2704
- var ProjectionRegistryImpl = class {
2705
- definitions = /* @__PURE__ */ new Map();
2706
- checkpoints = /* @__PURE__ */ new Map();
2707
- store;
2708
- auditTrail;
2709
- constructor(options = {}) {
2710
- this.store = options.store ?? new InMemoryReadModelStore();
2711
- this.auditTrail = options.auditTrail;
2712
- }
2713
- register(definition) {
2714
- if (this.definitions.has(definition.name)) {
2715
- throw new Error(`Projection "${definition.name}" is already registered.`);
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));
2716
1477
  }
2717
- this.definitions.set(definition.name, definition);
2718
- this.checkpoints.set(definition.name, {
2719
- projection: definition.name,
2720
- appliedCount: 0
2721
- });
2722
- }
2723
- list() {
2724
- return Array.from(this.definitions.values());
2725
- }
2726
- async apply(event) {
2727
- const applied = [];
2728
- for (const definition of this.definitions.values()) {
2729
- if (!definition.sourceIntents.includes(event.intent)) continue;
2730
- const current = await this.store.load(definition.name) ?? initialState(definition);
2731
- const next = await definition.project(event, current);
2732
- await this.store.save(definition.name, next);
2733
- const previous = this.checkpoints.get(definition.name);
2734
- this.checkpoints.set(definition.name, {
2735
- projection: definition.name,
2736
- appliedCount: (previous?.appliedCount ?? 0) + 1,
2737
- lastIntent: event.intent,
2738
- lastCorrelationId: event.metadata.correlationId,
2739
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2740
- });
2741
- await this.auditTrail?.record({
2742
- type: "projection.applied",
2743
- source: "Kernel.ProjectionRegistry",
2744
- intent: event.intent,
2745
- correlationId: event.metadata.correlationId,
2746
- causationId: event.metadata.causationId,
2747
- subject: definition.name,
2748
- details: { projection: definition.name }
2749
- });
2750
- applied.push(definition.name);
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;
2751
1483
  }
2752
- return applied;
2753
- }
2754
- async getState(name) {
2755
- return this.store.load(name);
2756
- }
2757
- getCheckpoint(name) {
2758
- return this.checkpoints.get(name);
2759
- }
2760
- getCheckpoints() {
2761
- return Array.from(this.checkpoints.values());
2762
1484
  }
2763
- async clear() {
2764
- await this.store.clear();
2765
- for (const definition of this.definitions.values()) {
2766
- this.checkpoints.set(definition.name, {
2767
- projection: definition.name,
2768
- appliedCount: 0
2769
- });
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;
2770
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);
2771
1509
  }
2772
- };
2773
- function createProjectionRegistry(options) {
2774
- return new ProjectionRegistryImpl(options);
1510
+ return result;
2775
1511
  }
2776
-
2777
- // src/kernel/manifest/constants.ts
2778
- var MANIFEST_SCHEMA_VERSION = "1.0";
2779
-
2780
- // src/kernel/manifest/createArkManifest.ts
2781
- function policyId(name) {
2782
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
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;
2783
1536
  }
2784
- var ArkManifestImpl = class {
2785
- constructor(data) {
2786
- this.data = data;
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);
2787
1544
  }
2788
- data;
2789
- toJSON() {
2790
- return { ...this.data };
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;
2791
1549
  }
2792
- };
2793
- function createArkManifest(options = {}) {
2794
- const registry = options.registry;
2795
- const policyEngine = options.policyEngine;
2796
- const metadata = options.metadata;
2797
- const graph = options.graph;
2798
- const profile = options.profile;
2799
- const projections = options.projections;
2800
- const eventContracts = options.eventContracts;
2801
- const observability = options.observability;
2802
- const intents = registry ? registry.list().map((creator) => ({
2803
- name: creator.name,
2804
- dependencies: registry.getDependencies(creator.name),
2805
- productions: registry.getProductions(creator.name)
2806
- })) : [];
2807
- const relationships = registry ? registry.getAllRelationships() : [];
2808
- const policies = policyEngine ? policyEngine.getPolicies().map((p) => ({
2809
- id: policyId(p.name),
2810
- name: p.name,
2811
- severity: p.severity,
2812
- tags: p.tags ? [...p.tags] : void 0,
2813
- owner: p.owner,
2814
- version: p.version,
2815
- rationale: p.rationale,
2816
- enforcementMode: p.enforcementMode,
2817
- deprecated: p.deprecated,
2818
- replacedBy: p.replacedBy,
2819
- description: p.tags?.includes("layer") ? "Enforces clean-architecture layer dependency rules on declared relationships." : void 0
2820
- })) : [];
2821
- const entities = metadata ? metadata.toJSON() : [];
2822
- const graphData = graph ? graph.toJSON() : { nodes: [], edges: [] };
2823
- const entityIntents = entities.filter((e) => (e.emits?.length ?? 0) > 0 || (e.consumes?.length ?? 0) > 0).map((e) => ({
2824
- entity: e.name,
2825
- emits: e.emits,
2826
- consumes: e.consumes
2827
- }));
2828
- const projectionData = projections ? projections.list().map((projection) => ({
2829
- name: projection.name,
2830
- sourceIntents: projection.sourceIntents,
2831
- checkpoint: projections.getCheckpoint(projection.name)
2832
- })) : [];
2833
- const data = {
2834
- schemaVersion: MANIFEST_SCHEMA_VERSION,
2835
- version,
2836
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
2837
- intents,
2838
- relationships,
2839
- policies,
2840
- entities,
2841
- graph: graphData,
2842
- architecture: profile ? {
2843
- profile: profile.name,
2844
- layers: profile.layers,
2845
- rules: profile.rules
2846
- } : void 0,
2847
- projections: projectionData,
2848
- eventContracts: eventContracts?.list() ?? [],
2849
- observability: observability?.report(),
2850
- links: { entityIntents }
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
+ }
2851
1596
  };
2852
- return new ArkManifestImpl(data);
2853
1597
  }
2854
-
2855
- // src/kernel/workflow/Saga.ts
2856
- var workflowSequence = 0;
2857
- function createWorkflowId(prefix) {
2858
- workflowSequence += 1;
2859
- return `${prefix}-${Date.now()}-${workflowSequence}`;
2860
- }
2861
- function errorMessage(error) {
2862
- return error instanceof Error ? error.message : String(error);
2863
- }
2864
- function sleep(ms) {
2865
- return new Promise((resolve) => {
2866
- setTimeout(resolve, ms);
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
2867
1609
  });
2868
1610
  }
2869
- async function withTimeout(operation, timeoutMs, stepName) {
2870
- const controller = new AbortController();
2871
- if (timeoutMs === void 0) return operation(controller.signal);
2872
- let timeout;
2873
- const timeoutPromise = new Promise((_, reject) => {
2874
- timeout = setTimeout(() => {
2875
- const error = new Error(`Workflow step "${stepName}" timed out after ${timeoutMs}ms.`);
2876
- controller.abort(error);
2877
- reject(error);
2878
- }, timeoutMs);
2879
- });
2880
- try {
2881
- return await Promise.race([operation(controller.signal), timeoutPromise]);
2882
- } finally {
2883
- if (timeout) clearTimeout(timeout);
2884
- }
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
+ }));
2885
1661
  }
2886
- var InMemoryWorkflowStore = class {
2887
- snapshots = /* @__PURE__ */ new Map();
2888
- save(snapshot) {
2889
- this.snapshots.set(snapshot.id, { ...snapshot, context: { ...snapshot.context } });
2890
- }
2891
- get(id) {
2892
- const snapshot = this.snapshots.get(id);
2893
- return snapshot ? { ...snapshot, context: { ...snapshot.context } } : void 0;
2894
- }
2895
- list(workflowName) {
2896
- return Array.from(this.snapshots.values()).filter((snapshot) => !workflowName || snapshot.workflowName === workflowName).map((snapshot) => ({ ...snapshot, context: { ...snapshot.context } }));
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
+ });
2897
1696
  }
2898
- clear() {
2899
- this.snapshots.clear();
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
+ }
2900
1711
  }
2901
- };
2902
- var WorkflowEngineImpl = class {
2903
- constructor(bus, options = {}) {
2904
- this.bus = bus;
2905
- this.options = options;
2906
- this.store = options.store ?? new InMemoryWorkflowStore();
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
+ );
2907
1727
  }
2908
- bus;
2909
- options;
2910
- definitions = /* @__PURE__ */ new Map();
2911
- store;
2912
- register(definition) {
2913
- if (this.definitions.has(definition.name)) {
2914
- throw new Error(`Workflow "${definition.name}" is already registered.`);
2915
- }
2916
- const names = /* @__PURE__ */ new Set();
2917
- for (const step of definition.steps) {
2918
- if (names.has(step.name)) {
2919
- throw new Error(
2920
- `Workflow "${definition.name}" has duplicate step name "${step.name}".`
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
+ )
2921
1739
  );
2922
1740
  }
2923
- names.add(step.name);
2924
- }
2925
- this.definitions.set(definition.name, definition);
2926
- if (definition.startOn) {
2927
- const trigger = definition.startOn;
2928
- this.bus.subscribe(trigger.intent, async (event) => {
2929
- await this.start(definition.name, trigger.mapEventToPayload(event));
2930
- });
2931
1741
  }
2932
1742
  }
2933
- async start(workflowName, initialPayload, options = {}) {
2934
- const definition = this.definitions.get(workflowName);
2935
- if (!definition) {
2936
- throw new Error(`Workflow "${workflowName}" is not registered.`);
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;
2937
1763
  }
2938
- const now = (/* @__PURE__ */ new Date()).toISOString();
2939
- const snapshot = {
2940
- id: options.id ?? createWorkflowId(workflowName),
2941
- workflowName,
2942
- status: "running",
2943
- context: { ...initialPayload },
2944
- completedSteps: [],
2945
- attempts: {},
2946
- startedAt: now,
2947
- updatedAt: now
2948
- };
2949
- await this.store.save(snapshot);
2950
- await this.audit("workflow.started", snapshot, { workflowName });
2951
- try {
2952
- for (const step of definition.steps) {
2953
- await this.runStep(snapshot, step);
2954
- }
2955
- snapshot.status = "completed";
2956
- snapshot.currentStep = void 0;
2957
- snapshot.completedAt = (/* @__PURE__ */ new Date()).toISOString();
2958
- snapshot.updatedAt = snapshot.completedAt;
2959
- await this.store.save(snapshot);
2960
- await this.audit("workflow.completed", snapshot, { workflowName });
2961
- return { ...snapshot, context: { ...snapshot.context } };
2962
- } catch (err) {
2963
- await this.compensate(snapshot, definition.steps, err);
2964
- snapshot.status = "failed";
2965
- snapshot.currentStep = void 0;
2966
- snapshot.error = errorMessage(err);
2967
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2968
- await this.store.save(snapshot);
2969
- await this.audit("workflow.failed", snapshot, {
2970
- workflowName,
2971
- error: snapshot.error,
2972
- failedStep: snapshot.failedStep
2973
- });
2974
- throw err;
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
+ );
2975
1774
  }
2976
- }
2977
- async get(id) {
2978
- return this.store.get(id);
2979
- }
2980
- async list(workflowName) {
2981
- return this.store.list(workflowName);
2982
- }
2983
- async runStep(snapshot, step) {
2984
- const retry = step.retry ?? this.options.defaultRetry ?? { attempts: 1 };
2985
- const maxAttempts = Math.max(1, retry.attempts);
2986
- snapshot.currentStep = step.name;
2987
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2988
- await this.store.save(snapshot);
2989
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
2990
- snapshot.attempts[step.name] = attempt;
2991
- await this.store.save(snapshot);
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;
2992
1788
  try {
2993
- const result = await withTimeout(
2994
- (signal) => Promise.resolve(step.execute(snapshot.context, this.bus, signal)),
2995
- step.timeoutMs,
2996
- step.name
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
+ )
2997
1807
  );
2998
- if (result) Object.assign(snapshot.context, result);
2999
- snapshot.completedSteps.push(step.name);
3000
- snapshot.currentStep = void 0;
3001
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3002
- await this.store.save(snapshot);
3003
- await this.audit("workflow.step.completed", snapshot, {
3004
- step: step.name,
3005
- attempt
3006
- });
3007
- return;
3008
- } catch (err) {
3009
- if (attempt < maxAttempts) {
3010
- if (retry.delayMs) await sleep(retry.delayMs);
3011
- continue;
3012
- }
3013
- snapshot.failedStep = step.name;
3014
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3015
- await this.store.save(snapshot);
3016
- await this.audit("workflow.step.failed", snapshot, {
3017
- step: step.name,
3018
- attempt,
3019
- error: errorMessage(err)
3020
- });
3021
- throw err;
3022
1808
  }
3023
1809
  }
3024
- throw new Error(`Workflow step "${step.name}" did not complete.`);
3025
1810
  }
3026
- async compensate(snapshot, steps, error) {
3027
- snapshot.status = "compensating";
3028
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3029
- await this.store.save(snapshot);
3030
- const completed = steps.filter(
3031
- (step) => snapshot.completedSteps.includes(step.name)
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
+ })
3032
1816
  );
3033
- for (let index = completed.length - 1; index >= 0; index -= 1) {
3034
- const step = completed[index];
3035
- if (!step.compensate) continue;
3036
- try {
3037
- await Promise.resolve(step.compensate(snapshot.context, this.bus, error));
3038
- await this.audit("workflow.compensation.completed", snapshot, {
3039
- step: step.name
3040
- });
3041
- } catch (compensationError) {
3042
- await this.audit("workflow.step.failed", snapshot, {
3043
- step: step.name,
3044
- compensation: true,
3045
- error: errorMessage(compensationError)
3046
- });
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
+ );
3047
1837
  }
3048
1838
  }
3049
1839
  }
3050
- async audit(type, snapshot, details) {
3051
- await this.options.auditTrail?.record({
3052
- type,
3053
- source: "Kernel.WorkflowEngine",
3054
- subject: snapshot.id,
3055
- details
3056
- });
3057
- }
3058
- };
3059
- function createWorkflowEngine(bus, options) {
3060
- return new WorkflowEngineImpl(bus, options);
3061
- }
3062
- function createSaga(def, bus, options = {}) {
3063
- const engine = createWorkflowEngine(bus, options);
3064
- const definition = { name: def.name, steps: def.steps };
3065
- engine.register(definition);
3066
- const sagaId = options.id ?? createWorkflowId(def.name);
3067
- let status = "idle";
3068
- let completedStepNames = [];
3069
- return {
3070
- id: sagaId,
3071
- definition: def,
3072
- get status() {
3073
- return status;
3074
- },
3075
- get completedSteps() {
3076
- return [...completedStepNames];
3077
- },
3078
- async run(initialPayload) {
3079
- status = "running";
3080
- completedStepNames = [];
3081
- try {
3082
- const snapshot = await engine.start(def.name, initialPayload, { id: sagaId });
3083
- status = snapshot.status === "waiting" ? "idle" : snapshot.status;
3084
- completedStepNames = [...snapshot.completedSteps];
3085
- } catch (err) {
3086
- const snapshot = await engine.get(sagaId);
3087
- status = snapshot?.status === "waiting" ? "idle" : snapshot?.status ?? "failed";
3088
- completedStepNames = snapshot?.completedSteps ?? [];
3089
- throw err;
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
+ }
3090
1856
  }
1857
+ if (topLayers.length > 1) ambiguousPairs.add([...topLayers].sort().join(" + "));
3091
1858
  }
3092
- };
3093
- }
3094
-
3095
- // src/kernel/runtime/createArkKernel.ts
3096
- var DEFAULT_MAX_HISTORY_SIZE = 1e3;
3097
- var kernelSequence = 0;
3098
- function nextKernelInstanceId() {
3099
- kernelSequence += 1;
3100
- return `ark-kernel-${Date.now()}-${kernelSequence}`;
3101
- }
3102
- function createArkKernel(options = {}) {
3103
- const strict = options.strict ?? true;
3104
- const instanceId = options.instanceId ?? nextKernelInstanceId();
3105
- const profile = options.profile ?? elevenLayerProfile;
3106
- const maxHistorySize = options.maxHistorySize ?? DEFAULT_MAX_HISTORY_SIZE;
3107
- const registry = createIntentRegistry();
3108
- const graph = createDependencyGraph();
3109
- const metadata = options.metadata ?? createMetadataRegistry();
3110
- const auditTrail = options.auditTrail ?? createAuditTrail({ maxRecords: maxHistorySize });
3111
- const eventContracts = options.eventContracts ?? createEventContractRegistry();
3112
- const outbox = options.outbox ?? new InMemoryOutboxStore();
3113
- const projections = options.projections ?? createProjectionRegistry({ auditTrail });
3114
- const policyEngine = new PolicyEngine([
3115
- defineArchitectureProfilePolicy(profile),
3116
- ...options.policies ?? []
3117
- ]);
3118
- const syncGraph = () => {
3119
- syncRegistryToGraph(registry, graph, { requireRegisteredTargets: true });
3120
- };
3121
- const eventBus = createEventBus({
3122
- intentRegistry: registry,
3123
- dependencyGraph: graph,
3124
- policyEngine,
3125
- strictRegistry: true,
3126
- validateIntentNaming: true,
3127
- auditTrail,
3128
- eventContracts,
3129
- strictEventContracts: options.strictEventContracts ?? strict,
3130
- requireKnownSource: options.requireKnownSource ?? true,
3131
- architectureProfile: profile,
3132
- enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? (strict ? "hard" : "off"),
3133
- outbox,
3134
- instanceId,
3135
- maxHistorySize,
3136
- onPublish: options.autoApplyProjections === false ? void 0 : async (event) => {
3137
- await projections.apply(event);
3138
- }
3139
- });
3140
- const workflowEngine = createWorkflowEngine(eventBus, { auditTrail });
3141
- const observability = createObservabilityReporter({
3142
- registry,
3143
- eventBus,
3144
- graph
3145
- });
3146
- return {
3147
- instanceId,
3148
- profile,
3149
- registry,
3150
- graph,
3151
- metadata,
3152
- auditTrail,
3153
- eventContracts,
3154
- outbox,
3155
- projections,
3156
- policyEngine,
3157
- eventBus,
3158
- workflowEngine,
3159
- observability,
3160
- publisher(source) {
3161
- return eventBus.createPublisher(source);
3162
- },
3163
- syncGraph,
3164
- manifest() {
3165
- syncGraph();
3166
- return createArkManifest({
3167
- registry,
3168
- policyEngine,
3169
- metadata,
3170
- graph,
3171
- profile,
3172
- projections,
3173
- eventContracts,
3174
- observability
3175
- });
3176
- }
3177
- };
3178
- }
3179
- function createStrictArkKernel(options = {}) {
3180
- return createArkKernel({
3181
- ...options,
3182
- strict: true,
3183
- strictEventContracts: options.strictEventContracts ?? true,
3184
- requireKnownSource: options.requireKnownSource ?? true,
3185
- enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? "hard"
3186
- });
3187
- }
3188
- function createOptionsFromConfig(config, options = {}) {
3189
- const { profileName, ...kernelOptions } = options;
3190
- return {
3191
- ...kernelOptions,
3192
- profile: createArchitectureProfileFromArkConfig(config, { name: profileName })
3193
- };
3194
- }
3195
- function createArkKernelFromConfig(config, options = {}) {
3196
- return createArkKernel(createOptionsFromConfig(config, options));
3197
- }
3198
- function createStrictArkKernelFromConfig(config, options = {}) {
3199
- return createStrictArkKernel(createOptionsFromConfig(config, options));
3200
- }
3201
- function createLenientArkKernelFromConfig(config, options = {}) {
3202
- return createLenientArkKernel(createOptionsFromConfig(config, options));
3203
- }
3204
- function createLenientArkKernel(options = {}) {
3205
- return createArkKernel({
3206
- ...options,
3207
- strict: false,
3208
- strictEventContracts: options.strictEventContracts ?? false,
3209
- enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? "off"
3210
- });
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;
3211
1880
  }
3212
1881
  export {
3213
- DEFAULT_MAX_HISTORY_SIZE,
3214
- EventContractRegistryImpl,
3215
- EventContractViolationError,
3216
- InMemoryAuditStore,
3217
- InMemoryOutboxStore,
3218
- InMemoryReadModelStore,
3219
- InMemoryWorkflowStore,
3220
- IntentRegistry,
3221
- InvalidIntentNameError,
3222
- LayerPolicyContextError,
3223
- MANIFEST_SCHEMA_VERSION,
3224
- ObservedLayerFlowViolationError,
3225
- PolicyEngine,
3226
- PolicyViolationError,
3227
- SourceMetadataOverrideError,
3228
- UnknownEventSourceError,
3229
- UnregisteredIntentError,
3230
- architecturalPolicies,
3231
- buildPublishPolicyContext,
3232
- checkAdapterGovernance,
3233
- checkContract,
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,
3234
1891
  createAICodeGate,
3235
- createAdapter,
1892
+ createAdapterResult,
3236
1893
  createArchitectureProfile,
3237
1894
  createArchitectureProfileFromArkConfig,
3238
- createArkKernel,
3239
- createArkKernelFromConfig,
3240
- createArkManifest,
3241
- createArkTestHarness,
3242
- createAuditTrail,
3243
- createDependencyGraph,
3244
1895
  createElevenLayerArkConfig,
3245
- createEventBus,
3246
- createEventContractRegistry,
3247
- createIntentRegistry,
3248
- createLenientArkKernel,
3249
- createLenientArkKernelFromConfig,
3250
- createMetadataRegistry,
3251
- createObservabilityReporter,
3252
- createProjectionRegistry,
3253
- createSaga,
3254
- createStrictArkKernel,
3255
- createStrictArkKernelFromConfig,
3256
- createWorkflowEngine,
3257
- defaultIntentRegistry,
3258
- defineArchitectureProfilePolicy,
3259
- defineIntent,
3260
- defineLayerPolicy,
3261
- definePolicy,
3262
- definePort,
3263
- definePublishPolicy,
1896
+ detectArchitectureCycles,
1897
+ deterministicHash,
3264
1898
  elevenLayerProfile,
3265
- isLayerPolicy,
3266
- syncRegistryToGraph,
3267
- validateIntentName,
1899
+ evaluateArchitectureGraph,
1900
+ explainViolation,
1901
+ extractSemanticDependencies,
1902
+ loadArkConfigContract,
1903
+ loadContract,
1904
+ parseArkConfigJson,
1905
+ stableSerialize,
1906
+ toAdapterDiagnostic,
3268
1907
  version
3269
1908
  };
3270
- //# sourceMappingURL=index.js.map