arkgate 2.13.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 (72) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +37 -22
  3. package/bin/ark-check.mjs +62 -4
  4. package/bin/ark-mcp.mjs +108 -1
  5. package/bin/ark-shared.mjs +204 -149
  6. package/bin/ark.mjs +90 -25
  7. package/bin/lib/adapter-contract.mjs +93 -0
  8. package/bin/lib/agent-gates.mjs +1 -0
  9. package/bin/lib/analysis-engine.mjs +1171 -0
  10. package/bin/lib/architecture-scan.mjs +84 -135
  11. package/bin/lib/ci-and-commands.mjs +31 -0
  12. package/bin/lib/config-warnings.mjs +7 -205
  13. package/bin/lib/field-install.mjs +67 -10
  14. package/bin/lib/gate-files.mjs +42 -3
  15. package/bin/lib/graph-cycles.mjs +4 -54
  16. package/bin/lib/hook-templates.mjs +33 -1
  17. package/bin/lib/host-support-matrix.mjs +7 -1
  18. package/bin/lib/install-migrate.mjs +54 -16
  19. package/bin/lib/presets.mjs +42 -2
  20. package/bin/lib/safety-diagnostics.mjs +18 -17
  21. package/bin/lib/scan-files.mjs +12 -1
  22. package/bin/lib/skill-install.mjs +8 -1
  23. package/bin/lib/source-policy.mjs +36 -0
  24. package/bin/lib/start-preview.mjs +271 -0
  25. package/bin/lib/ts-resolve.mjs +11 -2
  26. package/bin/lib/write-path-capabilities.mjs +4 -0
  27. package/compat/nestjs.cjs +2 -0
  28. package/compat/nestjs.d.ts +2 -0
  29. package/compat/nestjs.js +1 -0
  30. package/compat/runtime.cjs +2 -0
  31. package/compat/runtime.d.ts +2 -0
  32. package/compat/runtime.js +1 -0
  33. package/dist/configContract-BxSIwVRo.d.cts +259 -0
  34. package/dist/configContract-BxSIwVRo.d.ts +259 -0
  35. package/dist/eslint/index.cjs +125 -48
  36. package/dist/eslint/index.d.cts +7 -1
  37. package/dist/eslint/index.d.ts +7 -1
  38. package/dist/eslint/index.js +125 -48
  39. package/dist/index.cjs +1248 -3302
  40. package/dist/index.d.cts +359 -483
  41. package/dist/index.d.ts +359 -483
  42. package/dist/index.js +1231 -3248
  43. package/docs/agent-guide.md +28 -16
  44. package/docs/ai-gates.md +30 -7
  45. package/docs/migrate-from-ark-runtime-kernel.md +2 -3
  46. package/docs/package-surface.md +8 -13
  47. package/docs/production-hardening.md +17 -4
  48. package/docs/typescript-support.md +27 -0
  49. package/package.json +33 -11
  50. package/schemas/ark.analysis-result.schema.json +91 -0
  51. package/server.json +2 -2
  52. package/templates/skills/ark-architect.md +3 -2
  53. package/dist/configContract-iBLxx5Tz.d.cts +0 -53
  54. package/dist/configContract-iBLxx5Tz.d.ts +0 -53
  55. package/dist/eslint/index.cjs.map +0 -1
  56. package/dist/eslint/index.js.map +0 -1
  57. package/dist/index.cjs.map +0 -1
  58. package/dist/index.js.map +0 -1
  59. package/dist/nestjs/index.cjs +0 -2606
  60. package/dist/nestjs/index.cjs.map +0 -1
  61. package/dist/nestjs/index.d.cts +0 -23
  62. package/dist/nestjs/index.d.ts +0 -23
  63. package/dist/nestjs/index.js +0 -2582
  64. package/dist/nestjs/index.js.map +0 -1
  65. package/dist/runtime/index.cjs +0 -4014
  66. package/dist/runtime/index.cjs.map +0 -1
  67. package/dist/runtime/index.d.cts +0 -3
  68. package/dist/runtime/index.d.ts +0 -3
  69. package/dist/runtime/index.js +0 -3925
  70. package/dist/runtime/index.js.map +0 -1
  71. package/dist/types-BxBwnBpC.d.cts +0 -1041
  72. package/dist/types-Wcs_l1_J.d.ts +0 -1041
@@ -1,2606 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var __decorateClass = (decorators, target, key, kind) => {
20
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
- if (decorator = decorators[i])
23
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
- if (kind && result) __defProp(target, key, result);
25
- return result;
26
- };
27
-
28
- // src/nestjs/index.ts
29
- var nestjs_exports = {};
30
- __export(nestjs_exports, {
31
- ARK_KERNEL: () => ARK_KERNEL,
32
- ArkModule: () => ArkModule,
33
- InjectArk: () => InjectArk
34
- });
35
- module.exports = __toCommonJS(nestjs_exports);
36
- var import_common = require("@nestjs/common");
37
-
38
- // src/kernel/audit/AuditTrail.ts
39
- var auditSequence = 0;
40
- function createAuditId() {
41
- auditSequence += 1;
42
- return `audit-${Date.now()}-${auditSequence}`;
43
- }
44
- function matchesQuery(record, query) {
45
- if (query.type && record.type !== query.type) return false;
46
- if (query.intent && record.intent !== query.intent) return false;
47
- if (query.correlationId && record.correlationId !== query.correlationId) return false;
48
- if (query.subject && record.subject !== query.subject) return false;
49
- if (query.since && record.timestamp < query.since) return false;
50
- if (query.until && record.timestamp > query.until) return false;
51
- return true;
52
- }
53
- var InMemoryAuditStore = class {
54
- constructor(maxRecords) {
55
- this.maxRecords = maxRecords;
56
- }
57
- maxRecords;
58
- records = [];
59
- append(record) {
60
- this.records.push(record);
61
- if (this.maxRecords !== void 0 && this.records.length > this.maxRecords) {
62
- this.records.splice(0, this.records.length - this.maxRecords);
63
- }
64
- }
65
- query(query = {}) {
66
- const records = this.records.filter((record) => matchesQuery(record, query));
67
- return query.limit === void 0 ? [...records] : records.slice(-query.limit);
68
- }
69
- clear() {
70
- this.records.length = 0;
71
- }
72
- };
73
- var AuditTrailImpl = class {
74
- constructor(store) {
75
- this.store = store;
76
- }
77
- store;
78
- async record(input) {
79
- const record = {
80
- id: createAuditId(),
81
- timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
82
- type: input.type,
83
- source: input.source,
84
- actor: input.actor,
85
- intent: input.intent,
86
- correlationId: input.correlationId,
87
- causationId: input.causationId,
88
- subject: input.subject,
89
- details: input.details
90
- };
91
- await this.store.append(record);
92
- return record;
93
- }
94
- async query(query) {
95
- return this.store.query(query);
96
- }
97
- async clear() {
98
- await this.store.clear();
99
- }
100
- };
101
- function createAuditTrail(options = {}) {
102
- return new AuditTrailImpl(
103
- options.store ?? new InMemoryAuditStore(options.maxRecords)
104
- );
105
- }
106
-
107
- // src/kernel/policy/PolicyViolationError.ts
108
- var PolicyViolationError = class extends Error {
109
- violations;
110
- constructor(violations) {
111
- const messages = violations.map((v) => `- ${v.policyName}: ${v.message}`).join("\n");
112
- super(`Hard policy violation(s) detected:
113
- ${messages}`);
114
- this.name = "PolicyViolationError";
115
- this.violations = violations;
116
- }
117
- };
118
-
119
- // src/kernel/policy/PolicyEngine.ts
120
- var PolicyEngine = class {
121
- policies = [];
122
- constructor(initialPolicies = []) {
123
- for (const policy of initialPolicies) {
124
- this.add(policy);
125
- }
126
- }
127
- /**
128
- * Adds a policy to the engine.
129
- */
130
- add(policy) {
131
- if (this.policies.some((p) => p.name === policy.name)) {
132
- throw new Error(`Policy "${policy.name}" is already registered in this engine.`);
133
- }
134
- this.policies.push(policy);
135
- }
136
- /**
137
- * Returns all registered policies.
138
- */
139
- getPolicies() {
140
- return [...this.policies];
141
- }
142
- /**
143
- * Evaluates all policies against the provided context.
144
- */
145
- evaluate(context) {
146
- const violations = [];
147
- for (const policy of this.policies) {
148
- const result = policy.check(context);
149
- if (result === true) {
150
- continue;
151
- }
152
- if (result === false) {
153
- violations.push({
154
- policyName: policy.name,
155
- severity: policy.severity,
156
- message: `Policy "${policy.name}" was violated.`
157
- });
158
- continue;
159
- }
160
- if (Array.isArray(result)) {
161
- for (const v of result) {
162
- violations.push({
163
- policyName: policy.name,
164
- severity: policy.severity,
165
- message: v.message,
166
- details: v.details
167
- });
168
- }
169
- } else {
170
- violations.push({
171
- policyName: policy.name,
172
- severity: policy.severity,
173
- message: result.message,
174
- details: result.details
175
- });
176
- }
177
- }
178
- const hardViolations = violations.filter((v) => v.severity === "hard");
179
- const softViolations = violations.filter((v) => v.severity === "soft");
180
- return {
181
- passed: violations.length === 0,
182
- violations,
183
- hardViolations,
184
- softViolations
185
- };
186
- }
187
- /**
188
- * Enforces all policies.
189
- *
190
- * - Soft violations are collected and can be observed (returned or logged).
191
- * - Hard violations cause an error to be thrown (by default).
192
- *
193
- * @returns Evaluation result (including any soft violations)
194
- * @throws Error if any hard policy is violated
195
- */
196
- enforce(context) {
197
- const result = this.evaluate(context);
198
- if (result.hardViolations.length > 0) {
199
- throw new PolicyViolationError(result.hardViolations);
200
- }
201
- return result;
202
- }
203
- /**
204
- * Clears all registered policies.
205
- */
206
- clear() {
207
- this.policies.length = 0;
208
- }
209
- };
210
-
211
- // src/kernel/policy/definePolicy.ts
212
- function definePolicy(options) {
213
- const severity = options.severity ?? "soft";
214
- const policy = {
215
- name: options.name,
216
- severity,
217
- tags: options.tags,
218
- owner: options.owner,
219
- version: options.version,
220
- rationale: options.rationale,
221
- enforcementMode: options.enforcementMode,
222
- deprecated: options.deprecated,
223
- replacedBy: options.replacedBy,
224
- check: options.check
225
- };
226
- return policy;
227
- }
228
-
229
- // src/kernel/policy/builtins.ts
230
- function defaultLayerOf(name) {
231
- const dot = name.indexOf(".");
232
- return dot >= 0 ? name.slice(0, dot) : name;
233
- }
234
- function resolveLayer(name, options) {
235
- return options.resolveLayer?.(name) ?? defaultLayerOf(name);
236
- }
237
- function matchesRule(fromLayer, toLayer, rule) {
238
- return fromLayer === rule.from && toLayer === rule.to;
239
- }
240
- function defineLayerPolicy(options) {
241
- const name = options.name ?? "Layer isolation";
242
- const severity = options.severity ?? "hard";
243
- return definePolicy({
244
- name,
245
- severity,
246
- tags: ["layer"],
247
- check: (ctx) => {
248
- const edges = [
249
- ...(ctx.edges ?? []).filter((e) => e.kind === "declared" || e.kind === "produces").map((e) => ({ from: e.from, to: e.to })),
250
- ...(ctx.relationships ?? []).filter((r) => r.kind === "dependsOn").map((r) => ({ from: r.from, to: r.to }))
251
- ];
252
- const violations = [];
253
- for (const edge of edges) {
254
- const fromLayer = resolveLayer(edge.from, options);
255
- const toLayer = resolveLayer(edge.to, options);
256
- for (const rule of options.rules) {
257
- if (!rule.allowed && matchesRule(fromLayer, toLayer, rule)) {
258
- violations.push({
259
- policyName: name,
260
- severity,
261
- message: rule.message ?? `Layer violation: ${edge.from} (${fromLayer}) must not relate to ${edge.to} (${toLayer})`
262
- });
263
- }
264
- }
265
- }
266
- return violations.length > 0 ? violations : true;
267
- }
268
- });
269
- }
270
- function isLayerPolicy(policy) {
271
- return policy.tags?.includes("layer") ?? false;
272
- }
273
- function defineArchitectureProfilePolicy(profile, options = {}) {
274
- return defineLayerPolicy({
275
- name: options.name ?? `${profile.name} layer policy`,
276
- severity: options.severity ?? "hard",
277
- rules: profile.rules,
278
- resolveLayer: profile.resolveLayer
279
- });
280
- }
281
-
282
- // src/kernel/event-bus/policyContext.ts
283
- function buildPublishPolicyContext(options) {
284
- return (event) => ({
285
- event,
286
- relationships: options.intentRegistry?.getAllRelationships(),
287
- edges: options.dependencyGraph?.getEdges()
288
- });
289
- }
290
-
291
- // src/kernel/event-bus/errors.ts
292
- var UnregisteredIntentError = class extends Error {
293
- intentName;
294
- constructor(intentName) {
295
- super(
296
- `Intent "${intentName}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`
297
- );
298
- this.name = "UnregisteredIntentError";
299
- this.intentName = intentName;
300
- }
301
- };
302
- var InvalidIntentNameError = class extends Error {
303
- intentName;
304
- reason;
305
- constructor(intentName, reason) {
306
- super(`Invalid intent name "${intentName}": ${reason}`);
307
- this.name = "InvalidIntentNameError";
308
- this.intentName = intentName;
309
- this.reason = reason;
310
- }
311
- };
312
- var LayerPolicyContextError = class extends Error {
313
- constructor() {
314
- super(
315
- "Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."
316
- );
317
- this.name = "LayerPolicyContextError";
318
- }
319
- };
320
- var EventContractViolationError = class extends Error {
321
- intentName;
322
- issues;
323
- constructor(intentName, issues) {
324
- super(
325
- `Event contract violation for "${intentName}". Register a matching event contract/version or fix the payload before publishing.`
326
- );
327
- this.name = "EventContractViolationError";
328
- this.intentName = intentName;
329
- this.issues = issues;
330
- }
331
- };
332
- var UnknownEventSourceError = class extends Error {
333
- intentName;
334
- source;
335
- constructor(intentName, source) {
336
- super(
337
- 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.`
338
- );
339
- this.name = "UnknownEventSourceError";
340
- this.intentName = intentName;
341
- this.source = source;
342
- }
343
- };
344
- var SourceMetadataOverrideError = class extends Error {
345
- boundSource;
346
- attemptedSource;
347
- constructor(boundSource, attemptedSource) {
348
- super(
349
- `Source-bound publisher for "${boundSource}" cannot publish with metadata.source "${attemptedSource}". Create a publisher for the intended source instead.`
350
- );
351
- this.name = "SourceMetadataOverrideError";
352
- this.boundSource = boundSource;
353
- this.attemptedSource = attemptedSource;
354
- }
355
- };
356
- var ObservedLayerFlowViolationError = class extends Error {
357
- source;
358
- intentName;
359
- fromLayer;
360
- toLayer;
361
- constructor(source, intentName, fromLayer, toLayer, message) {
362
- super(
363
- message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${intentName}" (${toLayer}). Route this through an allowed layer or adjust the architecture profile rule.`
364
- );
365
- this.name = "ObservedLayerFlowViolationError";
366
- this.source = source;
367
- this.intentName = intentName;
368
- this.fromLayer = fromLayer;
369
- this.toLayer = toLayer;
370
- }
371
- };
372
-
373
- // src/kernel/intent/validateIntentName.ts
374
- var ALLOWED_PREFIXES = [
375
- "Domain.",
376
- "Application.",
377
- "Adapter.",
378
- "Workflow.",
379
- "Job.",
380
- "Presentation.",
381
- "Reporting.",
382
- "Metadata.",
383
- "Security.",
384
- "Audit.",
385
- "Observability.",
386
- "Kernel."
387
- ];
388
- function validateIntentName(name) {
389
- if (!name || typeof name !== "string") {
390
- return { valid: false, reason: "Intent name must be a non-empty string" };
391
- }
392
- if (!ALLOWED_PREFIXES.some((p) => name.startsWith(p))) {
393
- return {
394
- valid: false,
395
- reason: `Intent "${name}" must start with one of: ${ALLOWED_PREFIXES.join(", ")}`
396
- };
397
- }
398
- const rest = name.slice(name.indexOf(".") + 1);
399
- if (!rest || !/^[A-Za-z][A-Za-z0-9_.]*$/.test(rest)) {
400
- return {
401
- valid: false,
402
- reason: `Intent "${name}" has an invalid segment after the layer prefix`
403
- };
404
- }
405
- return { valid: true };
406
- }
407
-
408
- // src/kernel/event-bus/publishGuards.ts
409
- function assertIntentAllowed(intentName, options) {
410
- if (!options.strictRegistry && !options.validateIntentNaming) {
411
- return;
412
- }
413
- if (options.validateIntentNaming) {
414
- const validation = validateIntentName(intentName);
415
- if (!validation.valid) {
416
- throw new InvalidIntentNameError(intentName, validation.reason);
417
- }
418
- }
419
- if (options.strictRegistry && options.intentRegistry && !options.intentRegistry.has(intentName)) {
420
- throw new UnregisteredIntentError(intentName);
421
- }
422
- }
423
- function assertSourceAllowed(event, options) {
424
- if (!options.requireKnownSource) return;
425
- if (!event.metadata.source || event.metadata.source === "unknown") {
426
- throw new UnknownEventSourceError(event.intent);
427
- }
428
- if (options.intentRegistry && !options.intentRegistry.has(event.metadata.source)) {
429
- throw new UnknownEventSourceError(event.intent, event.metadata.source);
430
- }
431
- }
432
- function assertContractAllowed(event, options) {
433
- if (!options.eventContracts) return;
434
- const result = options.eventContracts.validate(event);
435
- if (!result.ok && (options.strictEventContracts || result.contract)) {
436
- throw new EventContractViolationError(event.intent, result.issues);
437
- }
438
- }
439
-
440
- // src/kernel/event-bus/payloadPatch.ts
441
- function isPlainRecord(value) {
442
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
443
- return false;
444
- }
445
- const proto = Object.getPrototypeOf(value);
446
- return proto === Object.prototype || proto === null;
447
- }
448
- function clonePatchValue(value) {
449
- if (Array.isArray(value)) return value.map(clonePatchValue);
450
- if (isPlainRecord(value)) {
451
- return Object.fromEntries(
452
- Object.entries(value).map(([key, child]) => [key, clonePatchValue(child)])
453
- );
454
- }
455
- return value;
456
- }
457
- function mergeRecordPatch(target, patch, path = "payload") {
458
- const next = { ...target };
459
- for (const [key, value] of Object.entries(patch)) {
460
- const childPath = `${path}.${key}`;
461
- if (!(key in next) || next[key] === void 0) {
462
- next[key] = clonePatchValue(value);
463
- continue;
464
- }
465
- if (isPlainRecord(next[key]) && isPlainRecord(value)) {
466
- next[key] = mergeRecordPatch(next[key], value, childPath);
467
- continue;
468
- }
469
- if (Array.isArray(next[key]) && Array.isArray(value)) {
470
- next[key] = mergeArrayPatch(next[key], value, childPath);
471
- continue;
472
- }
473
- throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
474
- }
475
- return next;
476
- }
477
- function mergeArrayPatch(target, patch, path = "payload") {
478
- const next = [...target];
479
- patch.forEach((value, index) => {
480
- const childPath = `${path}[${index}]`;
481
- if (index >= next.length || next[index] === void 0) {
482
- next[index] = clonePatchValue(value);
483
- return;
484
- }
485
- if (isPlainRecord(next[index]) && isPlainRecord(value)) {
486
- next[index] = mergeRecordPatch(next[index], value, childPath);
487
- return;
488
- }
489
- if (Array.isArray(next[index]) && Array.isArray(value)) {
490
- next[index] = mergeArrayPatch(next[index], value, childPath);
491
- return;
492
- }
493
- throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
494
- });
495
- return next;
496
- }
497
- function applyPayloadPatch(payload, patch) {
498
- if (Array.isArray(patch)) {
499
- if (payload === void 0) return clonePatchValue(patch);
500
- if (!Array.isArray(payload)) {
501
- throw new Error("Array interceptor patch requires an array payload.");
502
- }
503
- return mergeArrayPatch(payload, patch);
504
- }
505
- if (payload === void 0) return clonePatchValue(patch);
506
- if (!isPlainRecord(payload)) {
507
- throw new Error("Object interceptor patch requires an object payload.");
508
- }
509
- return mergeRecordPatch(payload, patch);
510
- }
511
-
512
- // src/kernel/event-bus/publishInterceptors.ts
513
- async function applyInterceptors(event, deps) {
514
- if (event.metadata.allowInterception === false) {
515
- return event;
516
- }
517
- const matching = [...deps.interceptorsForIntent(event.intent)];
518
- let current = event;
519
- for (const registration of matching) {
520
- const patches = [];
521
- try {
522
- await Promise.resolve(
523
- registration.interceptor({
524
- event: current,
525
- intercept: (patch) => {
526
- patches.push(patch);
527
- }
528
- })
529
- );
530
- if (patches.length === 0) {
531
- continue;
532
- }
533
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
534
- let candidate = {
535
- ...current,
536
- metadata: {
537
- ...current.metadata,
538
- interceptions: [
539
- ...current.metadata.interceptions ?? [],
540
- { interceptorId: registration.interceptorId, timestamp }
541
- ]
542
- }
543
- };
544
- for (const patch of patches) {
545
- candidate = {
546
- ...candidate,
547
- payload: applyPayloadPatch(candidate.payload, patch),
548
- metadata: { ...candidate.metadata }
549
- };
550
- }
551
- assertContractAllowed(candidate, {
552
- eventContracts: deps.eventContracts,
553
- strictEventContracts: deps.strictEventContracts
554
- });
555
- current = candidate;
556
- registration.lastInterceptedAt = timestamp;
557
- deps.appendTrace({
558
- type: "event.intercepted",
559
- timestamp,
560
- intent: current.intent,
561
- correlationId: current.metadata.correlationId,
562
- traceId: current.metadata.traceId,
563
- spanId: current.metadata.spanId,
564
- details: {
565
- registrationId: registration.registrationId,
566
- interceptorId: registration.interceptorId,
567
- patchesApplied: patches.length
568
- }
569
- });
570
- await deps.recordAudit("event.intercepted", current, {
571
- registrationId: registration.registrationId,
572
- interceptorId: registration.interceptorId,
573
- patchesApplied: patches.length
574
- });
575
- } catch (err) {
576
- await recordInterceptorError(registration, current, err, deps);
577
- }
578
- }
579
- return current;
580
- }
581
- async function recordInterceptorError(interceptor, event, error, deps) {
582
- const message = error instanceof Error ? error.message : String(error);
583
- deps.appendTrace({
584
- type: "interceptor.error",
585
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
586
- intent: event.intent,
587
- correlationId: event.metadata.correlationId,
588
- traceId: event.metadata.traceId,
589
- spanId: event.metadata.spanId,
590
- details: {
591
- registrationId: interceptor.registrationId,
592
- interceptorId: interceptor.interceptorId,
593
- error: message
594
- }
595
- });
596
- await deps.recordAudit("interceptor.error", event, {
597
- registrationId: interceptor.registrationId,
598
- interceptorId: interceptor.interceptorId,
599
- error: message
600
- });
601
- }
602
-
603
- // src/domain/layerMatch.ts
604
- function normalizeGlobSeparators(pattern) {
605
- let out = "";
606
- for (let i = 0; i < pattern.length; i += 1) {
607
- const c = pattern[i];
608
- if (c === "\\" && i + 1 < pattern.length) {
609
- const next = pattern[i + 1];
610
- if ("*?{}[],".includes(next) || next === "\\") {
611
- out += "\\" + next;
612
- i += 1;
613
- continue;
614
- }
615
- out += "/";
616
- continue;
617
- }
618
- out += c;
619
- }
620
- return out;
621
- }
622
- function sliceIdForPath(relPath, sliceFolders) {
623
- if (!sliceFolders?.length) return void 0;
624
- const parts = String(relPath).split(/[/\\]/).filter(Boolean);
625
- const folders = new Set(sliceFolders.map((s) => String(s).toLowerCase()));
626
- for (let i = 0; i < parts.length - 1; i += 1) {
627
- if (folders.has(parts[i].toLowerCase())) {
628
- return `${parts[i]}/${parts[i + 1]}`;
629
- }
630
- }
631
- return void 0;
632
- }
633
- function inferSliceFoldersFromPatterns(patterns) {
634
- const out = /* @__PURE__ */ new Set();
635
- for (const pattern of patterns ?? []) {
636
- const glob = normalizeGlobSeparators(String(pattern));
637
- const parts = glob.split("/").filter(Boolean);
638
- for (let i = 0; i < parts.length; i += 1) {
639
- const part = parts[i];
640
- if ((part === "**" || part === "*") && i > 0) {
641
- const prev = parts[i - 1];
642
- if (prev && !prev.includes("*") && !prev.includes("{") && !prev.includes("}")) {
643
- out.add(prev);
644
- }
645
- }
646
- }
647
- }
648
- return [...out];
649
- }
650
- function resolveSliceFolders(rule, layerName, layers) {
651
- if (Array.isArray(rule.sliceFolders) && rule.sliceFolders.length > 0) {
652
- return rule.sliceFolders.filter((s) => typeof s === "string" && s.length > 0);
653
- }
654
- const layer = (layers ?? []).find((l) => l.name === layerName);
655
- return inferSliceFoldersFromPatterns(layer?.patterns);
656
- }
657
- function findDeniedEdgeRule(rules, from, to, options) {
658
- for (const rule of rules ?? []) {
659
- if (rule.from !== from || rule.to !== to) continue;
660
- if (rule.allowed !== false) continue;
661
- if (rule.peerIsolation) {
662
- const fromPath = options?.fromPath;
663
- const toPath = options?.toPath;
664
- if (!fromPath || !toPath) continue;
665
- const folders = resolveSliceFolders(rule, from, options?.layers);
666
- if (folders.length === 0) continue;
667
- const fromSlice = sliceIdForPath(fromPath, folders);
668
- const toSlice = sliceIdForPath(toPath, folders);
669
- if (!fromSlice || !toSlice) continue;
670
- if (fromSlice !== toSlice) return rule;
671
- continue;
672
- }
673
- if (from === to) continue;
674
- return rule;
675
- }
676
- return void 0;
677
- }
678
-
679
- // src/kernel/event-bus/observedLayerFlow.ts
680
- async function assertObservedLayerFlowAllowed(event, deps) {
681
- if (deps.mode === "off" || !deps.architectureProfile) {
682
- return;
683
- }
684
- const source = event.metadata.source;
685
- if (!source || source === "unknown") return;
686
- const profile = deps.architectureProfile;
687
- const fromLayer = profile.resolveLayer(source);
688
- const toLayer = profile.resolveLayer(event.intent);
689
- if (!fromLayer || !toLayer) return;
690
- const blocked = findDeniedEdgeRule(profile.rules, fromLayer, toLayer);
691
- if (!blocked) return;
692
- const severity = deps.mode;
693
- const message = blocked.message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${event.intent}" (${toLayer}).`;
694
- const details = {
695
- source,
696
- intent: event.intent,
697
- fromLayer,
698
- toLayer,
699
- severity,
700
- message,
701
- rule: blocked
702
- };
703
- deps.appendTrace({
704
- type: "layer.observedViolation",
705
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
706
- intent: event.intent,
707
- correlationId: event.metadata.correlationId,
708
- traceId: event.metadata.traceId,
709
- spanId: event.metadata.spanId,
710
- details
711
- });
712
- await deps.recordAudit("layer.observedViolation", event, details);
713
- if (severity === "hard") {
714
- throw new ObservedLayerFlowViolationError(
715
- source,
716
- event.intent,
717
- fromLayer,
718
- toLayer,
719
- message
720
- );
721
- }
722
- }
723
-
724
- // src/kernel/event-bus/publishPolicy.ts
725
- async function enforcePublishPolicy(event, deps) {
726
- const ctx = deps.getPolicyContext(event);
727
- let policyResult;
728
- try {
729
- policyResult = deps.policyEngine.enforce(ctx);
730
- } catch (err) {
731
- if (err instanceof PolicyViolationError) {
732
- deps.appendTrace({
733
- type: "policy.hardViolation",
734
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
735
- intent: event.intent,
736
- correlationId: event.metadata.correlationId,
737
- traceId: event.metadata.traceId,
738
- spanId: event.metadata.spanId,
739
- details: { violations: err.violations }
740
- });
741
- await deps.recordAudit("policy.hardViolation", event, {
742
- violations: err.violations
743
- });
744
- }
745
- throw err;
746
- }
747
- if (policyResult.softViolations.length > 0) {
748
- deps.appendTrace({
749
- type: "policy.softViolation",
750
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
751
- intent: event.intent,
752
- correlationId: event.metadata.correlationId,
753
- traceId: event.metadata.traceId,
754
- spanId: event.metadata.spanId,
755
- details: { violations: policyResult.softViolations }
756
- });
757
- await deps.recordAudit("policy.softViolation", event, {
758
- violations: policyResult.softViolations
759
- });
760
- if (deps.onSoftViolation) {
761
- await deps.safeHook(
762
- () => deps.onSoftViolation(policyResult, event),
763
- "onSoftViolation",
764
- event
765
- );
766
- }
767
- }
768
- }
769
-
770
- // src/kernel/event-bus/publishRecording.ts
771
- function appendHistory(buffers, record) {
772
- buffers.history.push(record);
773
- if (buffers.maxHistorySize !== void 0 && buffers.history.length > buffers.maxHistorySize) {
774
- buffers.history.splice(0, buffers.history.length - buffers.maxHistorySize);
775
- }
776
- }
777
- function appendTrace(buffers, record) {
778
- buffers.trace.push(record);
779
- if (buffers.maxHistorySize !== void 0 && buffers.trace.length > buffers.maxHistorySize) {
780
- buffers.trace.splice(0, buffers.trace.length - buffers.maxHistorySize);
781
- }
782
- for (const sink of buffers.traceSinks) {
783
- try {
784
- sink(record);
785
- } catch {
786
- }
787
- }
788
- }
789
- async function recordAudit(buffers, type, event, details) {
790
- if (!buffers.auditTrail) return;
791
- try {
792
- await buffers.auditTrail.record({
793
- type,
794
- source: event.metadata.source,
795
- intent: event.intent,
796
- correlationId: event.metadata.correlationId,
797
- causationId: event.metadata.causationId,
798
- subject: event.intent,
799
- details
800
- });
801
- } catch (err) {
802
- appendTrace(buffers, {
803
- type: "hook.error",
804
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
805
- intent: event.intent,
806
- correlationId: event.metadata.correlationId,
807
- traceId: event.metadata.traceId,
808
- spanId: event.metadata.spanId,
809
- details: {
810
- hook: "auditTrail",
811
- error: err instanceof Error ? err.message : String(err)
812
- }
813
- });
814
- }
815
- }
816
- async function recordRawPublishDiagnostic(buffers, event) {
817
- const details = {
818
- intent: event.intent,
819
- source: event.metadata.source,
820
- suggestion: "Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."
821
- };
822
- appendTrace(buffers, {
823
- type: "event.rawPublish",
824
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
825
- intent: event.intent,
826
- correlationId: event.metadata.correlationId,
827
- traceId: event.metadata.traceId,
828
- spanId: event.metadata.spanId,
829
- details
830
- });
831
- await recordAudit(buffers, "event.rawPublish", event, details);
832
- }
833
- async function recordSuccessfulPublish(buffers, event, subscribersNotified) {
834
- const record = {
835
- event,
836
- publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
837
- subscribersNotified
838
- };
839
- appendHistory(buffers, record);
840
- await buffers.outbox?.enqueue(event);
841
- appendTrace(buffers, {
842
- type: "event.published",
843
- timestamp: record.publishedAt,
844
- intent: event.intent,
845
- correlationId: event.metadata.correlationId,
846
- traceId: event.metadata.traceId,
847
- spanId: event.metadata.spanId,
848
- details: { subscribersNotified }
849
- });
850
- await recordAudit(buffers, "event.published", event, {
851
- subscribersNotified
852
- });
853
- return record;
854
- }
855
- function enrichMetadata(base, extra, instanceId) {
856
- return {
857
- ...base,
858
- ...extra,
859
- occurredAt: extra.occurredAt || base.occurredAt || (/* @__PURE__ */ new Date()).toISOString(),
860
- source: extra.source || base.source || "unknown",
861
- kernelInstanceId: extra.kernelInstanceId ?? base.kernelInstanceId ?? instanceId,
862
- eventVersion: extra.eventVersion ?? base.eventVersion,
863
- schemaVersion: extra.schemaVersion ?? base.schemaVersion,
864
- allowInterception: extra.allowInterception ?? base.allowInterception,
865
- interceptions: extra.interceptions ?? base.interceptions,
866
- correlationId: extra.correlationId ?? base.correlationId,
867
- causationId: extra.causationId ?? base.causationId,
868
- traceId: extra.traceId ?? base.traceId,
869
- spanId: extra.spanId ?? base.spanId,
870
- parentSpanId: extra.parentSpanId ?? base.parentSpanId
871
- };
872
- }
873
-
874
- // src/kernel/event-bus/EventBus.ts
875
- var interceptorSequence = 0;
876
- function nextInterceptorRegistrationId() {
877
- interceptorSequence += 1;
878
- return `interceptor-${Date.now()}-${interceptorSequence}`;
879
- }
880
- var EventBusImpl = class {
881
- subscriptions = [];
882
- subscriptionsByIntent = /* @__PURE__ */ new Map();
883
- interceptors = [];
884
- interceptorsByIntent = /* @__PURE__ */ new Map();
885
- recording;
886
- onPublish;
887
- onSoftViolation;
888
- onHandlerError;
889
- eventContracts;
890
- strictEventContracts;
891
- requireKnownSource;
892
- architectureProfile;
893
- enforceObservedLayerFlowMode;
894
- rethrowHandlerErrors;
895
- policyEngine;
896
- getPolicyContext;
897
- intentRegistry;
898
- dependencyGraph;
899
- strictRegistry;
900
- validateIntentNaming;
901
- constructor(options = {}) {
902
- this.onPublish = options.onPublish;
903
- this.onSoftViolation = options.onSoftViolation;
904
- this.onHandlerError = options.onHandlerError;
905
- this.eventContracts = options.eventContracts;
906
- this.strictEventContracts = options.strictEventContracts ?? false;
907
- this.requireKnownSource = options.requireKnownSource ?? false;
908
- this.architectureProfile = options.architectureProfile;
909
- this.enforceObservedLayerFlowMode = options.enforceObservedLayerFlow ?? "off";
910
- this.rethrowHandlerErrors = options.rethrowHandlerErrors ?? false;
911
- this.intentRegistry = options.intentRegistry;
912
- this.dependencyGraph = options.dependencyGraph;
913
- this.strictRegistry = options.strictRegistry ?? options.intentRegistry !== void 0;
914
- this.validateIntentNaming = options.validateIntentNaming ?? this.strictRegistry;
915
- this.recording = {
916
- history: [],
917
- trace: [],
918
- maxHistorySize: options.maxHistorySize,
919
- traceSinks: [...options.traceSinks ?? []],
920
- auditTrail: options.auditTrail,
921
- outbox: options.outbox,
922
- instanceId: options.instanceId
923
- };
924
- if (options.policyEngine) {
925
- this.policyEngine = options.policyEngine;
926
- } else if (options.policies && options.policies.length > 0) {
927
- this.policyEngine = new PolicyEngine(options.policies);
928
- }
929
- const allPolicies = this.policyEngine?.getPolicies() ?? options.policies ?? [];
930
- if (allPolicies.some(isLayerPolicy) && !options.intentRegistry && !options.dependencyGraph && !options.getPolicyContext) {
931
- throw new LayerPolicyContextError();
932
- }
933
- if (options.getPolicyContext) {
934
- this.getPolicyContext = options.getPolicyContext;
935
- } else if (options.intentRegistry || options.dependencyGraph) {
936
- this.getPolicyContext = buildPublishPolicyContext({
937
- intentRegistry: options.intentRegistry,
938
- dependencyGraph: options.dependencyGraph
939
- });
940
- } else {
941
- this.getPolicyContext = (event) => ({ event });
942
- }
943
- }
944
- async publish(eventOrCreator, payloadOrMeta, metadata) {
945
- let event;
946
- const rawPublish = typeof eventOrCreator !== "function";
947
- if (!rawPublish) {
948
- const creator = eventOrCreator;
949
- const payload = payloadOrMeta;
950
- const extraMeta = metadata ?? {};
951
- const created = creator(payload);
952
- event = {
953
- ...created,
954
- metadata: enrichMetadata(
955
- created.metadata,
956
- extraMeta,
957
- this.recording.instanceId
958
- )
959
- };
960
- } else {
961
- const rawEvent = eventOrCreator;
962
- const extraMeta = metadata ?? payloadOrMeta ?? {};
963
- event = {
964
- ...rawEvent,
965
- metadata: enrichMetadata(
966
- rawEvent.metadata,
967
- extraMeta,
968
- this.recording.instanceId
969
- )
970
- };
971
- }
972
- if (rawPublish && this.strictRegistry) {
973
- await recordRawPublishDiagnostic(this.recording, event);
974
- }
975
- assertIntentAllowed(event.intent, {
976
- strictRegistry: this.strictRegistry,
977
- validateIntentNaming: this.validateIntentNaming,
978
- intentRegistry: this.intentRegistry
979
- });
980
- assertSourceAllowed(event, {
981
- requireKnownSource: this.requireKnownSource,
982
- intentRegistry: this.intentRegistry
983
- });
984
- assertContractAllowed(event, {
985
- eventContracts: this.eventContracts,
986
- strictEventContracts: this.strictEventContracts
987
- });
988
- event = await applyInterceptors(event, {
989
- interceptorsForIntent: (intent) => this.interceptorsByIntent.get(intent) ?? [],
990
- eventContracts: this.eventContracts,
991
- strictEventContracts: this.strictEventContracts,
992
- appendTrace: (r) => this.appendTrace(r),
993
- recordAudit: (type, e, details) => this.recordAudit(type, e, details)
994
- });
995
- assertContractAllowed(event, {
996
- eventContracts: this.eventContracts,
997
- strictEventContracts: this.strictEventContracts
998
- });
999
- await assertObservedLayerFlowAllowed(event, {
1000
- mode: this.enforceObservedLayerFlowMode,
1001
- architectureProfile: this.architectureProfile,
1002
- appendTrace: (r) => this.appendTrace(r),
1003
- recordAudit: (type, e, details) => this.recordAudit(type, e, details)
1004
- });
1005
- this.dependencyGraph?.registerEventFlow(event.metadata.source, event.intent);
1006
- const matching = [...this.subscriptionsByIntent.get(event.intent) ?? []];
1007
- if (this.policyEngine) {
1008
- await enforcePublishPolicy(event, {
1009
- policyEngine: this.policyEngine,
1010
- getPolicyContext: this.getPolicyContext,
1011
- appendTrace: (r) => this.appendTrace(r),
1012
- recordAudit: (type, e, details) => this.recordAudit(type, e, details),
1013
- onSoftViolation: this.onSoftViolation,
1014
- safeHook: (fn, name, e) => this.safeHook(fn, name, e)
1015
- });
1016
- }
1017
- await recordSuccessfulPublish(
1018
- this.recording,
1019
- event,
1020
- matching.length
1021
- );
1022
- await Promise.all(
1023
- matching.map((sub) => this.invokeHandler(sub, event))
1024
- );
1025
- if (this.onPublish) {
1026
- await this.safeHook(
1027
- () => this.onPublish(event),
1028
- "onPublish",
1029
- event
1030
- );
1031
- }
1032
- }
1033
- createPublisher(source) {
1034
- const sourceName = typeof source === "string" ? source : source.name;
1035
- assertIntentAllowed(sourceName, {
1036
- strictRegistry: this.strictRegistry,
1037
- validateIntentNaming: this.validateIntentNaming,
1038
- intentRegistry: this.intentRegistry
1039
- });
1040
- return {
1041
- source: sourceName,
1042
- publish: async (intent, payload, metadata = {}) => {
1043
- if (metadata.source && metadata.source !== sourceName) {
1044
- throw new SourceMetadataOverrideError(sourceName, metadata.source);
1045
- }
1046
- await this.publish(intent, payload, {
1047
- ...metadata,
1048
- source: sourceName
1049
- });
1050
- }
1051
- };
1052
- }
1053
- subscribe(intent, handler) {
1054
- const intentName = typeof intent === "string" ? intent : intent.name;
1055
- assertIntentAllowed(intentName, {
1056
- strictRegistry: this.strictRegistry,
1057
- validateIntentNaming: this.validateIntentNaming,
1058
- intentRegistry: this.intentRegistry
1059
- });
1060
- const sub = {
1061
- intentName,
1062
- handler
1063
- };
1064
- this.subscriptions.push(sub);
1065
- const subscriptionsForIntent = this.subscriptionsByIntent.get(intentName) ?? [];
1066
- subscriptionsForIntent.push(sub);
1067
- this.subscriptionsByIntent.set(intentName, subscriptionsForIntent);
1068
- return () => {
1069
- const idx = this.subscriptions.indexOf(sub);
1070
- if (idx >= 0) this.subscriptions.splice(idx, 1);
1071
- const byIntent = this.subscriptionsByIntent.get(intentName);
1072
- if (!byIntent) return;
1073
- const intentIdx = byIntent.indexOf(sub);
1074
- if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
1075
- if (byIntent.length === 0) this.subscriptionsByIntent.delete(intentName);
1076
- };
1077
- }
1078
- registerInterceptor(intent, interceptor, interceptorId) {
1079
- const intentName = typeof intent === "string" ? intent : intent.name;
1080
- assertIntentAllowed(intentName, {
1081
- strictRegistry: this.strictRegistry,
1082
- validateIntentNaming: this.validateIntentNaming,
1083
- intentRegistry: this.intentRegistry
1084
- });
1085
- const registration = {
1086
- registrationId: nextInterceptorRegistrationId(),
1087
- interceptorId: interceptorId ?? intentName,
1088
- intentName,
1089
- interceptor,
1090
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1091
- };
1092
- this.interceptors.push(registration);
1093
- const interceptorsForIntent = this.interceptorsByIntent.get(intentName) ?? [];
1094
- interceptorsForIntent.push(registration);
1095
- this.interceptorsByIntent.set(intentName, interceptorsForIntent);
1096
- return registration.registrationId;
1097
- }
1098
- unregisterInterceptor(registrationId) {
1099
- const interceptor = this.interceptors.find(
1100
- (candidate) => candidate.registrationId === registrationId
1101
- );
1102
- if (!interceptor) return false;
1103
- const idx = this.interceptors.indexOf(interceptor);
1104
- if (idx >= 0) this.interceptors.splice(idx, 1);
1105
- const byIntent = this.interceptorsByIntent.get(interceptor.intentName);
1106
- if (byIntent) {
1107
- const intentIdx = byIntent.indexOf(interceptor);
1108
- if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
1109
- if (byIntent.length === 0) this.interceptorsByIntent.delete(interceptor.intentName);
1110
- }
1111
- return true;
1112
- }
1113
- listInterceptors(intent) {
1114
- return this.interceptors.filter((interceptor) => !intent || interceptor.intentName === intent).map((interceptor) => ({
1115
- registrationId: interceptor.registrationId,
1116
- interceptorId: interceptor.interceptorId,
1117
- intent: interceptor.intentName,
1118
- createdAt: interceptor.createdAt,
1119
- lastInterceptedAt: interceptor.lastInterceptedAt
1120
- }));
1121
- }
1122
- getHistory() {
1123
- return [...this.recording.history];
1124
- }
1125
- clearHistory() {
1126
- this.recording.history.length = 0;
1127
- }
1128
- getTrace() {
1129
- return [...this.recording.trace];
1130
- }
1131
- clearTrace() {
1132
- this.recording.trace.length = 0;
1133
- }
1134
- appendTrace(record) {
1135
- appendTrace(this.recording, record);
1136
- }
1137
- async recordAudit(type, event, details) {
1138
- await recordAudit(this.recording, type, event, details);
1139
- }
1140
- async invokeHandler(sub, event) {
1141
- try {
1142
- await Promise.resolve(sub.handler(event));
1143
- } catch (err) {
1144
- this.appendTrace({
1145
- type: "handler.error",
1146
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1147
- intent: event.intent,
1148
- correlationId: event.metadata.correlationId,
1149
- traceId: event.metadata.traceId,
1150
- spanId: event.metadata.spanId,
1151
- details: { error: err instanceof Error ? err.message : String(err) }
1152
- });
1153
- await this.recordAudit("handler.error", event, {
1154
- handlerIntent: sub.intentName,
1155
- error: err instanceof Error ? err.message : String(err)
1156
- });
1157
- if (this.onHandlerError) {
1158
- await this.safeHook(
1159
- () => this.onHandlerError(err, event, sub.intentName),
1160
- "onHandlerError",
1161
- event
1162
- );
1163
- }
1164
- if (this.rethrowHandlerErrors) {
1165
- throw err;
1166
- }
1167
- }
1168
- }
1169
- async safeHook(fn, hookName, event) {
1170
- try {
1171
- await Promise.resolve(fn());
1172
- } catch (err) {
1173
- this.appendTrace({
1174
- type: "hook.error",
1175
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1176
- intent: event.intent,
1177
- correlationId: event.metadata.correlationId,
1178
- traceId: event.metadata.traceId,
1179
- spanId: event.metadata.spanId,
1180
- details: {
1181
- hook: hookName,
1182
- error: err instanceof Error ? err.message : String(err)
1183
- }
1184
- });
1185
- await this.recordAudit("hook.error", event, {
1186
- hook: hookName,
1187
- error: err instanceof Error ? err.message : String(err)
1188
- });
1189
- }
1190
- }
1191
- };
1192
- function createEventBus(options) {
1193
- return new EventBusImpl(options);
1194
- }
1195
-
1196
- // src/kernel/event-contracts/EventContractRegistry.ts
1197
- function formatStandardSchemaPath(path) {
1198
- if (!path || path.length === 0) return void 0;
1199
- return path.map(
1200
- (segment) => typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment)
1201
- ).join(".");
1202
- }
1203
- function actualType(value) {
1204
- if (Array.isArray(value)) return "array";
1205
- if (value === null) return "object";
1206
- const type = typeof value;
1207
- if (type === "string" || type === "number" || type === "boolean" || type === "object") {
1208
- return type;
1209
- }
1210
- return "unknown";
1211
- }
1212
- function formatPath(parent, field) {
1213
- return parent ? `${parent}.${field}` : field;
1214
- }
1215
- function validateSchemaField(value, fieldSchema, path, contract, issues) {
1216
- const valueType = actualType(value);
1217
- if (fieldSchema.type !== "unknown" && valueType !== fieldSchema.type) {
1218
- issues.push({
1219
- intent: contract.intent,
1220
- version: contract.version,
1221
- field: path,
1222
- message: `Expected ${fieldSchema.type}, received ${valueType}.`
1223
- });
1224
- return;
1225
- }
1226
- if (fieldSchema.enum && !fieldSchema.enum.some((allowed) => Object.is(allowed, value))) {
1227
- issues.push({
1228
- intent: contract.intent,
1229
- version: contract.version,
1230
- field: path,
1231
- message: "Value is not allowed by event contract enum."
1232
- });
1233
- }
1234
- if (fieldSchema.type === "object" && fieldSchema.fields) {
1235
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
1236
- issues.push({
1237
- intent: contract.intent,
1238
- version: contract.version,
1239
- field: path,
1240
- message: "Nested object field must be a non-array object."
1241
- });
1242
- return;
1243
- }
1244
- validateObjectSchema(
1245
- value,
1246
- fieldSchema.fields,
1247
- contract,
1248
- issues,
1249
- path
1250
- );
1251
- }
1252
- if (fieldSchema.type === "array" && fieldSchema.items && Array.isArray(value)) {
1253
- value.forEach((item, index) => {
1254
- validateSchemaField(
1255
- item,
1256
- fieldSchema.items,
1257
- `${path}[${index}]`,
1258
- contract,
1259
- issues
1260
- );
1261
- });
1262
- }
1263
- }
1264
- function validateObjectSchema(payload, schema, contract, issues, parentPath) {
1265
- for (const [field, fieldSchema] of Object.entries(schema)) {
1266
- const path = formatPath(parentPath, field);
1267
- const value = payload[field];
1268
- if (value === void 0) {
1269
- if (fieldSchema.required) {
1270
- issues.push({
1271
- intent: contract.intent,
1272
- version: contract.version,
1273
- field: path,
1274
- message: "Required field is missing."
1275
- });
1276
- }
1277
- continue;
1278
- }
1279
- validateSchemaField(value, fieldSchema, path, contract, issues);
1280
- }
1281
- }
1282
- var EventContractRegistryImpl = class {
1283
- contracts = /* @__PURE__ */ new Map();
1284
- register(contract) {
1285
- const key = this.key(contract.intent, contract.version);
1286
- if (this.contracts.has(key)) {
1287
- throw new Error(`Event contract "${key}" is already registered.`);
1288
- }
1289
- this.contracts.set(key, { allowAdditionalFields: true, ...contract });
1290
- }
1291
- get(intent, version2) {
1292
- if (version2) return this.contracts.get(this.key(intent, version2));
1293
- return this.list(intent).at(-1);
1294
- }
1295
- list(intent) {
1296
- return Array.from(this.contracts.values()).filter(
1297
- (contract) => !intent || contract.intent === intent
1298
- );
1299
- }
1300
- validate(event) {
1301
- const version2 = event.metadata.eventVersion;
1302
- const contract = this.get(event.intent, version2);
1303
- const issues = [];
1304
- if (!contract) {
1305
- return {
1306
- ok: false,
1307
- issues: [
1308
- {
1309
- intent: event.intent,
1310
- version: version2,
1311
- message: version2 ? `No event contract registered for version "${version2}".` : "No event contract registered for intent."
1312
- }
1313
- ]
1314
- };
1315
- }
1316
- if (contract.deprecated) {
1317
- issues.push({
1318
- intent: event.intent,
1319
- version: contract.version,
1320
- message: typeof contract.deprecated === "string" ? contract.deprecated : "Event contract is deprecated."
1321
- });
1322
- }
1323
- const payload = event.payload != null && typeof event.payload === "object" ? event.payload : void 0;
1324
- if (contract.schema) {
1325
- if (!payload) {
1326
- issues.push({
1327
- intent: event.intent,
1328
- version: contract.version,
1329
- message: "Payload must be an object for schema validation."
1330
- });
1331
- } else {
1332
- validateObjectSchema(payload, contract.schema, contract, issues);
1333
- if (contract.allowAdditionalFields === false) {
1334
- for (const field of Object.keys(payload)) {
1335
- if (!contract.schema[field]) {
1336
- issues.push({
1337
- intent: event.intent,
1338
- version: contract.version,
1339
- field,
1340
- message: "Additional field is not allowed by event contract."
1341
- });
1342
- }
1343
- }
1344
- }
1345
- }
1346
- }
1347
- if (contract.standardSchema) {
1348
- const result = contract.standardSchema["~standard"].validate(event.payload);
1349
- if (result instanceof Promise) {
1350
- issues.push({
1351
- intent: event.intent,
1352
- version: contract.version,
1353
- message: "Standard Schema validator returned a Promise; event contract validation is synchronous."
1354
- });
1355
- } else if (result.issues) {
1356
- for (const issue of result.issues) {
1357
- issues.push({
1358
- intent: event.intent,
1359
- version: contract.version,
1360
- field: formatStandardSchemaPath(issue.path),
1361
- message: issue.message
1362
- });
1363
- }
1364
- }
1365
- }
1366
- return { ok: issues.length === 0, contract, issues };
1367
- }
1368
- clear() {
1369
- this.contracts.clear();
1370
- }
1371
- key(intent, version2) {
1372
- return `${intent}@${version2}`;
1373
- }
1374
- };
1375
- function createEventContractRegistry() {
1376
- return new EventContractRegistryImpl();
1377
- }
1378
-
1379
- // src/kernel/graph/DependencyGraph.ts
1380
- var DependencyGraphImpl = class {
1381
- nodes = /* @__PURE__ */ new Map();
1382
- edges = [];
1383
- registerDependency(from, to, kind = "declared") {
1384
- this.ensureNode(from);
1385
- this.ensureNode(to);
1386
- this.addEdge({ from, to, kind });
1387
- }
1388
- registerEventFlow(producer, consumer) {
1389
- this.ensureNode(producer);
1390
- this.ensureNode(consumer);
1391
- this.addEdge({ from: producer, to: consumer, kind: "observed" });
1392
- }
1393
- getNodes() {
1394
- return Array.from(this.nodes.values());
1395
- }
1396
- getEdges() {
1397
- return [...this.edges];
1398
- }
1399
- toJSON() {
1400
- return {
1401
- nodes: this.getNodes(),
1402
- edges: this.getEdges()
1403
- };
1404
- }
1405
- toMermaid() {
1406
- let out = "flowchart TD\n";
1407
- for (const edge of this.edges) {
1408
- const label = edge.kind ? `|${edge.kind}|` : "";
1409
- out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
1410
- `;
1411
- }
1412
- const connected = new Set(
1413
- this.edges.flatMap((e) => [e.from, e.to])
1414
- );
1415
- for (const node of this.nodes.keys()) {
1416
- if (!connected.has(node)) {
1417
- out += ` ${this.safeId(node)}
1418
- `;
1419
- }
1420
- }
1421
- return out.trim();
1422
- }
1423
- toLayerMermaid(profile) {
1424
- const nodesByLayer = /* @__PURE__ */ new Map();
1425
- for (const node of this.nodes.keys()) {
1426
- const layer = profile.resolveLayer(node) ?? "Unclassified";
1427
- const current = nodesByLayer.get(layer) ?? [];
1428
- current.push(node);
1429
- nodesByLayer.set(layer, current);
1430
- }
1431
- let out = "flowchart TD\n";
1432
- for (const layer of profile.layers) {
1433
- const nodes = nodesByLayer.get(layer.name) ?? [];
1434
- if (nodes.length === 0) continue;
1435
- out += ` subgraph ${this.safeId(layer.name)}[${layer.name}]
1436
- `;
1437
- for (const node of nodes) {
1438
- out += ` ${this.safeId(node)}[${node}]
1439
- `;
1440
- }
1441
- out += " end\n";
1442
- }
1443
- const unclassified = nodesByLayer.get("Unclassified") ?? [];
1444
- if (unclassified.length > 0) {
1445
- out += " subgraph Unclassified[Unclassified]\n";
1446
- for (const node of unclassified) {
1447
- out += ` ${this.safeId(node)}[${node}]
1448
- `;
1449
- }
1450
- out += " end\n";
1451
- }
1452
- for (const edge of this.edges) {
1453
- const label = edge.kind ? `|${edge.kind}|` : "";
1454
- out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
1455
- `;
1456
- }
1457
- return out.trim();
1458
- }
1459
- detectViolations(rules = []) {
1460
- const violations = [];
1461
- const cycles = this.findSimpleCycles();
1462
- if (cycles.length > 0) {
1463
- violations.push(`Cycle detected: ${cycles.map((c) => c.join("->")).join(", ")}`);
1464
- }
1465
- for (const rule of rules) {
1466
- try {
1467
- const res = rule(this.edges);
1468
- if (res && res.length) violations.push(...res);
1469
- } catch (e) {
1470
- violations.push(`Rule error: ${e.message}`);
1471
- }
1472
- }
1473
- return violations;
1474
- }
1475
- ensureNode(id) {
1476
- if (!this.nodes.has(id)) {
1477
- this.nodes.set(id, { id });
1478
- }
1479
- }
1480
- addEdge(edge) {
1481
- const exists = this.edges.some(
1482
- (e) => e.from === edge.from && e.to === edge.to && e.kind === edge.kind
1483
- );
1484
- if (!exists) {
1485
- this.edges.push(edge);
1486
- }
1487
- }
1488
- // Very naive cycle detection for small graphs
1489
- findSimpleCycles() {
1490
- const graph = /* @__PURE__ */ new Map();
1491
- for (const e of this.edges) {
1492
- if (!graph.has(e.from)) graph.set(e.from, []);
1493
- graph.get(e.from).push(e.to);
1494
- }
1495
- const cycles = [];
1496
- const visited = /* @__PURE__ */ new Set();
1497
- const stack = [];
1498
- const dfs = (node) => {
1499
- visited.add(node);
1500
- stack.push(node);
1501
- for (const nei of graph.get(node) || []) {
1502
- if (!visited.has(nei)) {
1503
- dfs(nei);
1504
- } else if (stack.includes(nei)) {
1505
- const cycleStart = stack.indexOf(nei);
1506
- const cycle = stack.slice(cycleStart).concat(nei);
1507
- cycles.push(cycle);
1508
- }
1509
- }
1510
- stack.pop();
1511
- };
1512
- for (const node of graph.keys()) {
1513
- if (!visited.has(node)) dfs(node);
1514
- }
1515
- const unique = new Set(cycles.map((c) => c.join("->")));
1516
- return Array.from(unique).map((s) => s.split("->"));
1517
- }
1518
- safeId(id) {
1519
- return id.replace(/[^a-zA-Z0-9_]/g, "_");
1520
- }
1521
- };
1522
- function createDependencyGraph() {
1523
- return new DependencyGraphImpl();
1524
- }
1525
-
1526
- // src/kernel/graph/sync.ts
1527
- function syncRegistryToGraph(registry, graph, options = {}) {
1528
- const requireRegistered = options.requireRegisteredTargets ?? false;
1529
- for (const rel of registry.getAllRelationships()) {
1530
- if (requireRegistered && !registry.has(rel.to)) {
1531
- continue;
1532
- }
1533
- if (rel.kind === "dependsOn") {
1534
- graph.registerDependency(rel.from, rel.to, "declared");
1535
- } else {
1536
- graph.registerDependency(rel.from, rel.to, "produces");
1537
- }
1538
- }
1539
- }
1540
-
1541
- // src/kernel/intent/IntentRegistry.ts
1542
- var IntentRegistry = class {
1543
- intents = /* @__PURE__ */ new Map();
1544
- dependencies = /* @__PURE__ */ new Map();
1545
- productions = /* @__PURE__ */ new Map();
1546
- /**
1547
- * Define/register a new intent.
1548
- *
1549
- * @param name - Semantic intent name following the convention (Domain.*, Application.*, etc.)
1550
- * @param options - Optional relationship declarations
1551
- * @throws Error if an intent with the same name is already registered
1552
- */
1553
- define(name, options) {
1554
- if (this.intents.has(name)) {
1555
- throw new Error(
1556
- `Intent "${name}" is already registered. Intent names must be unique within a registry.`
1557
- );
1558
- }
1559
- const fn = (payload) => ({
1560
- intent: name,
1561
- payload,
1562
- metadata: {
1563
- occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1564
- source: "unknown"
1565
- }
1566
- });
1567
- Object.defineProperty(fn, "name", {
1568
- value: name,
1569
- enumerable: true,
1570
- configurable: false,
1571
- writable: false
1572
- });
1573
- const creator = fn;
1574
- this.intents.set(name, creator);
1575
- if (options?.dependsOn) {
1576
- for (const dep of options.dependsOn) {
1577
- this.declareDependency(name, dep);
1578
- }
1579
- }
1580
- if (options?.produces) {
1581
- for (const prod of options.produces) {
1582
- this.declareProduction(name, prod);
1583
- }
1584
- }
1585
- return creator;
1586
- }
1587
- /**
1588
- * Declare that one intent depends on / relates to another.
1589
- * This information is used by the DependencyGraph (future iterations) and for policy checks.
1590
- *
1591
- * @param from - The source intent (e.g. an Application operation)
1592
- * @param to - The target intent it depends on (e.g. a Domain event or concept)
1593
- */
1594
- declareDependency(from, to) {
1595
- if (!this.dependencies.has(from)) {
1596
- this.dependencies.set(from, /* @__PURE__ */ new Set());
1597
- }
1598
- this.dependencies.get(from).add(to);
1599
- }
1600
- /**
1601
- * Declare that one intent produces / emits another (e.g. use case → domain event).
1602
- */
1603
- declareProduction(from, to) {
1604
- if (!this.productions.has(from)) {
1605
- this.productions.set(from, /* @__PURE__ */ new Set());
1606
- }
1607
- this.productions.get(from).add(to);
1608
- }
1609
- /**
1610
- * Retrieve a previously defined intent creator by name.
1611
- */
1612
- get(name) {
1613
- return this.intents.get(name);
1614
- }
1615
- /**
1616
- * List all registered intent creators.
1617
- */
1618
- list() {
1619
- return Array.from(this.intents.values());
1620
- }
1621
- /**
1622
- * Get all declared dependencies for a given intent.
1623
- */
1624
- getDependencies(intentName) {
1625
- const deps = this.dependencies.get(intentName);
1626
- return deps ? Array.from(deps) : [];
1627
- }
1628
- /**
1629
- * Get all intents produced / emitted by a given intent.
1630
- */
1631
- getProductions(intentName) {
1632
- const prods = this.productions.get(intentName);
1633
- return prods ? Array.from(prods) : [];
1634
- }
1635
- /**
1636
- * Get all declared relationships (useful for graph generation).
1637
- */
1638
- getAllRelationships() {
1639
- const result = [];
1640
- for (const [from, tos] of this.dependencies.entries()) {
1641
- for (const to of tos) {
1642
- result.push({ from, to, kind: "dependsOn" });
1643
- }
1644
- }
1645
- for (const [from, tos] of this.productions.entries()) {
1646
- for (const to of tos) {
1647
- result.push({ from, to, kind: "produces" });
1648
- }
1649
- }
1650
- return result;
1651
- }
1652
- /**
1653
- * Check if an intent name has been registered.
1654
- */
1655
- has(name) {
1656
- return this.intents.has(name);
1657
- }
1658
- /**
1659
- * Clear the registry. Primarily useful for tests.
1660
- */
1661
- clear() {
1662
- this.intents.clear();
1663
- this.dependencies.clear();
1664
- this.productions.clear();
1665
- }
1666
- };
1667
-
1668
- // src/kernel/intent/defineIntent.ts
1669
- var defaultRegistry = new IntentRegistry();
1670
- function createIntentRegistry() {
1671
- return new IntentRegistry();
1672
- }
1673
-
1674
- // src/domain/configContract.ts
1675
- var ARK_CONFIG_SCHEMA_VERSION = "1.0";
1676
- var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
1677
- var DEFAULT_LAYER_NAMES = [
1678
- "DomainModel",
1679
- "ApplicationOrchestration",
1680
- "PersistenceAdapters",
1681
- "IntegrationAdapters",
1682
- "WorkflowSagaEngine",
1683
- "BackgroundJobsScheduling",
1684
- "PresentationAdapters",
1685
- "ReportingReadModels",
1686
- "ExtensibilityMetadata",
1687
- "SecurityAuditObservability",
1688
- "Kernel"
1689
- ];
1690
- var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
1691
- "PresentationAdapters->ApplicationOrchestration",
1692
- "ApplicationOrchestration->DomainModel",
1693
- "WorkflowSagaEngine->ApplicationOrchestration",
1694
- "WorkflowSagaEngine->DomainModel",
1695
- "BackgroundJobsScheduling->ApplicationOrchestration"
1696
- ]);
1697
- function createDefaultRules() {
1698
- const rules = [];
1699
- for (const from of DEFAULT_LAYER_NAMES) {
1700
- for (const to of DEFAULT_LAYER_NAMES) {
1701
- if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
1702
- rules.push({ from, to, allowed: false });
1703
- }
1704
- }
1705
- return rules;
1706
- }
1707
- var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
1708
- var stringArraySchema = {
1709
- type: "array",
1710
- items: { type: "string", minLength: 1 },
1711
- uniqueItems: true
1712
- };
1713
- var ARK_CONFIG_SCHEMA = {
1714
- $schema: "https://json-schema.org/draft/2020-12/schema",
1715
- $id: ARK_CONFIG_SCHEMA_URL,
1716
- title: "ArkGate architecture contract",
1717
- description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
1718
- type: "object",
1719
- additionalProperties: false,
1720
- required: ["$schema", "schemaVersion", "include", "layers", "rules"],
1721
- properties: {
1722
- $schema: {
1723
- type: "string",
1724
- minLength: 1,
1725
- default: ARK_CONFIG_SCHEMA_URL,
1726
- description: "Editor-facing URL or local path for this JSON Schema."
1727
- },
1728
- schemaVersion: {
1729
- type: "string",
1730
- const: ARK_CONFIG_SCHEMA_VERSION,
1731
- default: ARK_CONFIG_SCHEMA_VERSION
1732
- },
1733
- name: { type: "string", minLength: 1 },
1734
- include: { ...stringArraySchema, minItems: 1, default: ["src"] },
1735
- exclude: { ...stringArraySchema, default: [] },
1736
- excludeGenerated: { type: "boolean", default: true },
1737
- frameworkOverlay: { type: "string", minLength: 1 },
1738
- layers: {
1739
- type: "array",
1740
- default: [],
1741
- items: { $ref: "#/$defs/layer" }
1742
- },
1743
- rules: {
1744
- type: "array",
1745
- default: DEFAULT_ARK_CONFIG_RULES,
1746
- items: { $ref: "#/$defs/rule" }
1747
- },
1748
- cyclePolicy: {
1749
- type: "string",
1750
- enum: ["strict", "soft", "framework-soft", "off"],
1751
- default: "strict"
1752
- },
1753
- dynamicImportAllowlist: { ...stringArraySchema, default: [] },
1754
- safety: {
1755
- $ref: "#/$defs/safety",
1756
- default: {
1757
- maxTsSuppressions: 0,
1758
- maxAnyCasts: 0,
1759
- allowInMemory: false,
1760
- allowDisabledPeerIsolation: false
1761
- }
1762
- }
1763
- },
1764
- $defs: {
1765
- layer: {
1766
- type: "object",
1767
- additionalProperties: false,
1768
- required: ["name", "patterns"],
1769
- properties: {
1770
- name: { type: "string", minLength: 1 },
1771
- patterns: { ...stringArraySchema, minItems: 1 },
1772
- exclude: stringArraySchema,
1773
- intentPrefixes: stringArraySchema,
1774
- description: { type: "string", minLength: 1 },
1775
- forbiddenGlobals: stringArraySchema,
1776
- mayImportInfrastructure: { type: "boolean" },
1777
- optional: { type: "boolean" }
1778
- }
1779
- },
1780
- rule: {
1781
- type: "object",
1782
- additionalProperties: false,
1783
- required: ["from", "to", "allowed"],
1784
- properties: {
1785
- from: { type: "string", minLength: 1 },
1786
- to: { type: "string", minLength: 1 },
1787
- allowed: { type: "boolean" },
1788
- message: { type: "string", minLength: 1 },
1789
- peerIsolation: { type: "boolean" },
1790
- sliceFolders: { ...stringArraySchema, minItems: 1 }
1791
- }
1792
- },
1793
- safety: {
1794
- type: "object",
1795
- additionalProperties: false,
1796
- properties: {
1797
- maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
1798
- maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
1799
- allowInMemory: { type: "boolean", default: false },
1800
- allowDisabledPeerIsolation: { type: "boolean", default: false }
1801
- }
1802
- }
1803
- }
1804
- };
1805
-
1806
- // src/kernel/layers/ArchitectureProfile.ts
1807
- function normalizePrefix(prefix) {
1808
- return prefix.endsWith(".") ? prefix : `${prefix}.`;
1809
- }
1810
- function byLongestPrefix(a, b) {
1811
- const maxA = a.prefixes.length ? Math.max(...a.prefixes.map((p) => p.length)) : 0;
1812
- const maxB = b.prefixes.length ? Math.max(...b.prefixes.map((p) => p.length)) : 0;
1813
- return maxB - maxA;
1814
- }
1815
- function createArchitectureProfile(options) {
1816
- const layers = options.layers.map((layer) => ({
1817
- ...layer,
1818
- prefixes: layer.prefixes.map(normalizePrefix)
1819
- }));
1820
- const sortedLayers = [...layers].sort(byLongestPrefix);
1821
- const rules = [...options.rules ?? []];
1822
- return {
1823
- name: options.name,
1824
- layers,
1825
- rules,
1826
- resolveLayer(name) {
1827
- return layers.find((layer) => layer.match?.(name))?.name ?? sortedLayers.find(
1828
- (layer) => layer.prefixes.some((prefix) => name.startsWith(prefix))
1829
- )?.name;
1830
- }
1831
- };
1832
- }
1833
- var elevenLayerProfileLayers = [
1834
- {
1835
- name: "DomainModel",
1836
- prefixes: ["Domain"],
1837
- description: "Rich domain model, business rules, and domain events.",
1838
- order: 1
1839
- },
1840
- {
1841
- name: "ApplicationOrchestration",
1842
- prefixes: ["Application"],
1843
- description: "Use cases and command orchestration.",
1844
- order: 2
1845
- },
1846
- {
1847
- name: "PersistenceAdapters",
1848
- prefixes: ["Adapter.Persistence", "Adapter.Repository"],
1849
- description: "Database, repository, and storage adapters.",
1850
- order: 3
1851
- },
1852
- {
1853
- name: "IntegrationAdapters",
1854
- prefixes: ["Adapter.Integration", "Adapter.External"],
1855
- description: "External systems, APIs, and integration adapters.",
1856
- order: 4
1857
- },
1858
- {
1859
- name: "WorkflowSagaEngine",
1860
- prefixes: ["Workflow"],
1861
- description: "Sagas, workflows, and long-running processes.",
1862
- order: 5
1863
- },
1864
- {
1865
- name: "BackgroundJobsScheduling",
1866
- prefixes: ["Job"],
1867
- description: "Background jobs, scheduled work, and async processors.",
1868
- order: 6
1869
- },
1870
- {
1871
- name: "PresentationAdapters",
1872
- prefixes: ["Presentation", "Adapter.Presentation", "Adapter.Api"],
1873
- description: "API, UI, controller, and presentation adapters.",
1874
- order: 7
1875
- },
1876
- {
1877
- name: "ReportingReadModels",
1878
- prefixes: ["Reporting"],
1879
- description: "Read models, projections, and reporting surfaces.",
1880
- order: 8
1881
- },
1882
- {
1883
- name: "ExtensibilityMetadata",
1884
- prefixes: ["Metadata"],
1885
- description: "Metadata, extensions, and schema contracts.",
1886
- order: 9
1887
- },
1888
- {
1889
- name: "SecurityAuditObservability",
1890
- prefixes: ["Security", "Audit", "Observability"],
1891
- description: "Security, audit, and observability concerns.",
1892
- order: 10
1893
- },
1894
- {
1895
- name: "Kernel",
1896
- prefixes: ["Kernel"],
1897
- description: "Ark-owned governance and kernel signals.",
1898
- order: 11
1899
- }
1900
- ];
1901
- var elevenLayerProfile = createArchitectureProfile({
1902
- name: "Ark 11-layer Hexagonal Event-Driven Profile",
1903
- layers: elevenLayerProfileLayers,
1904
- rules: DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule }))
1905
- });
1906
-
1907
- // src/kernel/manifest/constants.ts
1908
- var MANIFEST_SCHEMA_VERSION = "1.0";
1909
-
1910
- // src/version.ts
1911
- var version = "2.13.0";
1912
-
1913
- // src/kernel/manifest/createArkManifest.ts
1914
- function policyId(name) {
1915
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1916
- }
1917
- var ArkManifestImpl = class {
1918
- constructor(data) {
1919
- this.data = data;
1920
- }
1921
- data;
1922
- toJSON() {
1923
- return { ...this.data };
1924
- }
1925
- };
1926
- function createArkManifest(options = {}) {
1927
- const registry = options.registry;
1928
- const policyEngine = options.policyEngine;
1929
- const metadata = options.metadata;
1930
- const graph = options.graph;
1931
- const profile = options.profile;
1932
- const projections = options.projections;
1933
- const eventContracts = options.eventContracts;
1934
- const observability = options.observability;
1935
- const intents = registry ? registry.list().map((creator) => ({
1936
- name: creator.name,
1937
- dependencies: registry.getDependencies(creator.name),
1938
- productions: registry.getProductions(creator.name)
1939
- })) : [];
1940
- const relationships = registry ? registry.getAllRelationships() : [];
1941
- const policies = policyEngine ? policyEngine.getPolicies().map((p) => ({
1942
- id: policyId(p.name),
1943
- name: p.name,
1944
- severity: p.severity,
1945
- tags: p.tags ? [...p.tags] : void 0,
1946
- owner: p.owner,
1947
- version: p.version,
1948
- rationale: p.rationale,
1949
- enforcementMode: p.enforcementMode,
1950
- deprecated: p.deprecated,
1951
- replacedBy: p.replacedBy,
1952
- description: p.tags?.includes("layer") ? "Enforces clean-architecture layer dependency rules on declared relationships." : void 0
1953
- })) : [];
1954
- const entities = metadata ? metadata.toJSON() : [];
1955
- const graphData = graph ? graph.toJSON() : { nodes: [], edges: [] };
1956
- const entityIntents = entities.filter((e) => (e.emits?.length ?? 0) > 0 || (e.consumes?.length ?? 0) > 0).map((e) => ({
1957
- entity: e.name,
1958
- emits: e.emits,
1959
- consumes: e.consumes
1960
- }));
1961
- const projectionData = projections ? projections.list().map((projection) => ({
1962
- name: projection.name,
1963
- sourceIntents: projection.sourceIntents,
1964
- checkpoint: projections.getCheckpoint(projection.name)
1965
- })) : [];
1966
- const data = {
1967
- schemaVersion: MANIFEST_SCHEMA_VERSION,
1968
- version,
1969
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1970
- intents,
1971
- relationships,
1972
- policies,
1973
- entities,
1974
- graph: graphData,
1975
- architecture: profile ? {
1976
- profile: profile.name,
1977
- layers: profile.layers,
1978
- rules: profile.rules
1979
- } : void 0,
1980
- projections: projectionData,
1981
- eventContracts: eventContracts?.list() ?? [],
1982
- observability: observability?.report(),
1983
- links: { entityIntents }
1984
- };
1985
- return new ArkManifestImpl(data);
1986
- }
1987
-
1988
- // src/kernel/metadata/MetadataRegistry.ts
1989
- var MetadataRegistryImpl = class {
1990
- entities = /* @__PURE__ */ new Map();
1991
- entity(name, meta, options = {}) {
1992
- if (this.entities.has(name) && !options.allowOverwrite) {
1993
- throw new Error(`Entity metadata "${name}" is already registered.`);
1994
- }
1995
- const full = { name, fields: {}, ...meta };
1996
- this.entities.set(name, full);
1997
- return full;
1998
- }
1999
- getEntity(name) {
2000
- return this.entities.get(name);
2001
- }
2002
- listEntities() {
2003
- return Array.from(this.entities.values());
2004
- }
2005
- findEntitiesByIntent(intentName) {
2006
- return this.listEntities().filter(
2007
- (entity) => entity.emits?.includes(intentName) || entity.consumes?.includes(intentName)
2008
- );
2009
- }
2010
- validate() {
2011
- const issues = [];
2012
- for (const entity of this.entities.values()) {
2013
- if (!entity.name.trim()) {
2014
- issues.push({ entity: entity.name, message: "Entity name is required." });
2015
- }
2016
- for (const [fieldName, field] of Object.entries(entity.fields)) {
2017
- if (!fieldName.trim()) {
2018
- issues.push({ entity: entity.name, field: fieldName, message: "Field name is required." });
2019
- }
2020
- if (!field.type || typeof field.type !== "string") {
2021
- issues.push({
2022
- entity: entity.name,
2023
- field: fieldName,
2024
- message: "Field type must be a non-empty string."
2025
- });
2026
- }
2027
- if (field.relation && !this.entities.has(field.relation.entity)) {
2028
- issues.push({
2029
- entity: entity.name,
2030
- field: fieldName,
2031
- message: `Related entity "${field.relation.entity}" is not registered.`
2032
- });
2033
- }
2034
- }
2035
- }
2036
- return { ok: issues.length === 0, issues };
2037
- }
2038
- toJSON() {
2039
- return this.listEntities();
2040
- }
2041
- };
2042
- function createMetadataRegistry() {
2043
- return new MetadataRegistryImpl();
2044
- }
2045
-
2046
- // src/kernel/observability/ObservabilityReporter.ts
2047
- function flowKey(flow) {
2048
- return `${flow.from}->${flow.to}`;
2049
- }
2050
- function uniqueFlows(flows) {
2051
- const seen = /* @__PURE__ */ new Set();
2052
- const result = [];
2053
- for (const flow of flows) {
2054
- const key = flowKey(flow);
2055
- if (seen.has(key)) continue;
2056
- seen.add(key);
2057
- result.push(flow);
2058
- }
2059
- return result;
2060
- }
2061
- function difference(left, right) {
2062
- const rightKeys = new Set(right.map(flowKey));
2063
- return left.filter((flow) => !rightKeys.has(flowKey(flow)));
2064
- }
2065
- function createObservabilityReporter(options) {
2066
- const registry = options.registry;
2067
- const eventBus = options.eventBus;
2068
- const graph = options.graph;
2069
- return {
2070
- report() {
2071
- const declaredFromRegistry = registry ? registry.getAllRelationships().filter((relationship) => relationship.kind === "produces").map((relationship) => ({
2072
- from: relationship.from,
2073
- to: relationship.to
2074
- })) : [];
2075
- const declaredFromGraph = declaredFromRegistry.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "produces").map((edge) => ({ from: edge.from, to: edge.to }));
2076
- const observedFromHistory = eventBus?.getHistory().map((record) => ({
2077
- from: record.event.metadata.source,
2078
- to: record.event.intent
2079
- })) ?? [];
2080
- const observedFromGraph = observedFromHistory.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "observed").map((edge) => ({ from: edge.from, to: edge.to }));
2081
- const declaredProductions = uniqueFlows([
2082
- ...declaredFromRegistry,
2083
- ...declaredFromGraph
2084
- ]);
2085
- const observedProductions = uniqueFlows([
2086
- ...observedFromHistory,
2087
- ...observedFromGraph
2088
- ]);
2089
- const unknownSources = observedProductions.filter(
2090
- (flow) => !flow.from || flow.from === "unknown"
2091
- );
2092
- const unregisteredObservedSources = registry ? Array.from(
2093
- new Set(
2094
- observedProductions.map((flow) => flow.from).filter(
2095
- (source) => source && source !== "unknown" && !registry.has(source)
2096
- )
2097
- )
2098
- ) : [];
2099
- const unregisteredObservedIntents = registry ? Array.from(
2100
- new Set(
2101
- observedProductions.map((flow) => flow.to).filter((intent) => !registry.has(intent))
2102
- )
2103
- ) : [];
2104
- const observedIntentNames = new Set(
2105
- observedProductions.flatMap((flow) => [flow.from, flow.to])
2106
- );
2107
- const registeredButNeverObserved = registry ? registry.list().map((intent) => intent.name).filter((intent) => !observedIntentNames.has(intent)) : [];
2108
- return {
2109
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2110
- declaredProductions,
2111
- observedProductions,
2112
- declaredButUnobserved: difference(declaredProductions, observedProductions),
2113
- observedButUndeclared: difference(
2114
- observedProductions.filter((flow) => flow.from !== "unknown"),
2115
- declaredProductions
2116
- ),
2117
- unknownSources,
2118
- unregisteredObservedSources,
2119
- unregisteredObservedIntents,
2120
- registeredButNeverObserved
2121
- };
2122
- }
2123
- };
2124
- }
2125
-
2126
- // src/kernel/outbox/InMemoryOutboxStore.ts
2127
- var outboxSequence = 0;
2128
- function nextOutboxId() {
2129
- outboxSequence += 1;
2130
- return `outbox-${Date.now()}-${outboxSequence}`;
2131
- }
2132
- function cloneRecord(record) {
2133
- return {
2134
- ...record,
2135
- event: {
2136
- ...record.event,
2137
- metadata: { ...record.event.metadata }
2138
- }
2139
- };
2140
- }
2141
- var InMemoryOutboxStore = class {
2142
- records = /* @__PURE__ */ new Map();
2143
- async enqueue(event) {
2144
- const now = (/* @__PURE__ */ new Date()).toISOString();
2145
- const record = {
2146
- id: nextOutboxId(),
2147
- event,
2148
- status: "pending",
2149
- attempts: 0,
2150
- createdAt: now,
2151
- updatedAt: now
2152
- };
2153
- this.records.set(record.id, record);
2154
- return cloneRecord(record);
2155
- }
2156
- async markDispatched(id) {
2157
- const record = this.records.get(id);
2158
- if (!record) return;
2159
- record.status = "dispatched";
2160
- record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2161
- }
2162
- async markFailed(id, error) {
2163
- const record = this.records.get(id);
2164
- if (!record) return;
2165
- record.status = "failed";
2166
- record.attempts += 1;
2167
- record.error = error instanceof Error ? error.message : String(error);
2168
- record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2169
- }
2170
- async list(status) {
2171
- return Array.from(this.records.values()).filter((record) => !status || record.status === status).map(cloneRecord);
2172
- }
2173
- async clear() {
2174
- this.records.clear();
2175
- }
2176
- };
2177
-
2178
- // src/kernel/projections/ProjectionRegistry.ts
2179
- var InMemoryReadModelStore = class {
2180
- states = /* @__PURE__ */ new Map();
2181
- load(name) {
2182
- return this.states.get(name);
2183
- }
2184
- save(name, state) {
2185
- this.states.set(name, state);
2186
- }
2187
- clear(name) {
2188
- if (name) {
2189
- this.states.delete(name);
2190
- } else {
2191
- this.states.clear();
2192
- }
2193
- }
2194
- };
2195
- function initialState(definition) {
2196
- return typeof definition.initialState === "function" ? definition.initialState() : definition.initialState;
2197
- }
2198
- var ProjectionRegistryImpl = class {
2199
- definitions = /* @__PURE__ */ new Map();
2200
- checkpoints = /* @__PURE__ */ new Map();
2201
- store;
2202
- auditTrail;
2203
- constructor(options = {}) {
2204
- this.store = options.store ?? new InMemoryReadModelStore();
2205
- this.auditTrail = options.auditTrail;
2206
- }
2207
- register(definition) {
2208
- if (this.definitions.has(definition.name)) {
2209
- throw new Error(`Projection "${definition.name}" is already registered.`);
2210
- }
2211
- this.definitions.set(definition.name, definition);
2212
- this.checkpoints.set(definition.name, {
2213
- projection: definition.name,
2214
- appliedCount: 0
2215
- });
2216
- }
2217
- list() {
2218
- return Array.from(this.definitions.values());
2219
- }
2220
- async apply(event) {
2221
- const applied = [];
2222
- for (const definition of this.definitions.values()) {
2223
- if (!definition.sourceIntents.includes(event.intent)) continue;
2224
- const current = await this.store.load(definition.name) ?? initialState(definition);
2225
- const next = await definition.project(event, current);
2226
- await this.store.save(definition.name, next);
2227
- const previous = this.checkpoints.get(definition.name);
2228
- this.checkpoints.set(definition.name, {
2229
- projection: definition.name,
2230
- appliedCount: (previous?.appliedCount ?? 0) + 1,
2231
- lastIntent: event.intent,
2232
- lastCorrelationId: event.metadata.correlationId,
2233
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2234
- });
2235
- await this.auditTrail?.record({
2236
- type: "projection.applied",
2237
- source: "Kernel.ProjectionRegistry",
2238
- intent: event.intent,
2239
- correlationId: event.metadata.correlationId,
2240
- causationId: event.metadata.causationId,
2241
- subject: definition.name,
2242
- details: { projection: definition.name }
2243
- });
2244
- applied.push(definition.name);
2245
- }
2246
- return applied;
2247
- }
2248
- async getState(name) {
2249
- return this.store.load(name);
2250
- }
2251
- getCheckpoint(name) {
2252
- return this.checkpoints.get(name);
2253
- }
2254
- getCheckpoints() {
2255
- return Array.from(this.checkpoints.values());
2256
- }
2257
- async clear() {
2258
- await this.store.clear();
2259
- for (const definition of this.definitions.values()) {
2260
- this.checkpoints.set(definition.name, {
2261
- projection: definition.name,
2262
- appliedCount: 0
2263
- });
2264
- }
2265
- }
2266
- };
2267
- function createProjectionRegistry(options) {
2268
- return new ProjectionRegistryImpl(options);
2269
- }
2270
-
2271
- // src/kernel/workflow/Saga.ts
2272
- var workflowSequence = 0;
2273
- function createWorkflowId(prefix) {
2274
- workflowSequence += 1;
2275
- return `${prefix}-${Date.now()}-${workflowSequence}`;
2276
- }
2277
- function errorMessage(error) {
2278
- return error instanceof Error ? error.message : String(error);
2279
- }
2280
- function sleep(ms) {
2281
- return new Promise((resolve) => {
2282
- setTimeout(resolve, ms);
2283
- });
2284
- }
2285
- async function withTimeout(operation, timeoutMs, stepName) {
2286
- const controller = new AbortController();
2287
- if (timeoutMs === void 0) return operation(controller.signal);
2288
- let timeout;
2289
- const timeoutPromise = new Promise((_, reject) => {
2290
- timeout = setTimeout(() => {
2291
- const error = new Error(`Workflow step "${stepName}" timed out after ${timeoutMs}ms.`);
2292
- controller.abort(error);
2293
- reject(error);
2294
- }, timeoutMs);
2295
- });
2296
- try {
2297
- return await Promise.race([operation(controller.signal), timeoutPromise]);
2298
- } finally {
2299
- if (timeout) clearTimeout(timeout);
2300
- }
2301
- }
2302
- var InMemoryWorkflowStore = class {
2303
- snapshots = /* @__PURE__ */ new Map();
2304
- save(snapshot) {
2305
- this.snapshots.set(snapshot.id, { ...snapshot, context: { ...snapshot.context } });
2306
- }
2307
- get(id) {
2308
- const snapshot = this.snapshots.get(id);
2309
- return snapshot ? { ...snapshot, context: { ...snapshot.context } } : void 0;
2310
- }
2311
- list(workflowName) {
2312
- return Array.from(this.snapshots.values()).filter((snapshot) => !workflowName || snapshot.workflowName === workflowName).map((snapshot) => ({ ...snapshot, context: { ...snapshot.context } }));
2313
- }
2314
- clear() {
2315
- this.snapshots.clear();
2316
- }
2317
- };
2318
- var WorkflowEngineImpl = class {
2319
- constructor(bus, options = {}) {
2320
- this.bus = bus;
2321
- this.options = options;
2322
- this.store = options.store ?? new InMemoryWorkflowStore();
2323
- }
2324
- bus;
2325
- options;
2326
- definitions = /* @__PURE__ */ new Map();
2327
- store;
2328
- register(definition) {
2329
- if (this.definitions.has(definition.name)) {
2330
- throw new Error(`Workflow "${definition.name}" is already registered.`);
2331
- }
2332
- const names = /* @__PURE__ */ new Set();
2333
- for (const step of definition.steps) {
2334
- if (names.has(step.name)) {
2335
- throw new Error(
2336
- `Workflow "${definition.name}" has duplicate step name "${step.name}".`
2337
- );
2338
- }
2339
- names.add(step.name);
2340
- }
2341
- this.definitions.set(definition.name, definition);
2342
- if (definition.startOn) {
2343
- const trigger = definition.startOn;
2344
- this.bus.subscribe(trigger.intent, async (event) => {
2345
- await this.start(definition.name, trigger.mapEventToPayload(event));
2346
- });
2347
- }
2348
- }
2349
- async start(workflowName, initialPayload, options = {}) {
2350
- const definition = this.definitions.get(workflowName);
2351
- if (!definition) {
2352
- throw new Error(`Workflow "${workflowName}" is not registered.`);
2353
- }
2354
- const now = (/* @__PURE__ */ new Date()).toISOString();
2355
- const snapshot = {
2356
- id: options.id ?? createWorkflowId(workflowName),
2357
- workflowName,
2358
- status: "running",
2359
- context: { ...initialPayload },
2360
- completedSteps: [],
2361
- attempts: {},
2362
- startedAt: now,
2363
- updatedAt: now
2364
- };
2365
- await this.store.save(snapshot);
2366
- await this.audit("workflow.started", snapshot, { workflowName });
2367
- try {
2368
- for (const step of definition.steps) {
2369
- await this.runStep(snapshot, step);
2370
- }
2371
- snapshot.status = "completed";
2372
- snapshot.currentStep = void 0;
2373
- snapshot.completedAt = (/* @__PURE__ */ new Date()).toISOString();
2374
- snapshot.updatedAt = snapshot.completedAt;
2375
- await this.store.save(snapshot);
2376
- await this.audit("workflow.completed", snapshot, { workflowName });
2377
- return { ...snapshot, context: { ...snapshot.context } };
2378
- } catch (err) {
2379
- await this.compensate(snapshot, definition.steps, err);
2380
- snapshot.status = "failed";
2381
- snapshot.currentStep = void 0;
2382
- snapshot.error = errorMessage(err);
2383
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2384
- await this.store.save(snapshot);
2385
- await this.audit("workflow.failed", snapshot, {
2386
- workflowName,
2387
- error: snapshot.error,
2388
- failedStep: snapshot.failedStep
2389
- });
2390
- throw err;
2391
- }
2392
- }
2393
- async get(id) {
2394
- return this.store.get(id);
2395
- }
2396
- async list(workflowName) {
2397
- return this.store.list(workflowName);
2398
- }
2399
- async runStep(snapshot, step) {
2400
- const retry = step.retry ?? this.options.defaultRetry ?? { attempts: 1 };
2401
- const maxAttempts = Math.max(1, retry.attempts);
2402
- snapshot.currentStep = step.name;
2403
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2404
- await this.store.save(snapshot);
2405
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
2406
- snapshot.attempts[step.name] = attempt;
2407
- await this.store.save(snapshot);
2408
- let result;
2409
- try {
2410
- result = await withTimeout(
2411
- (signal) => Promise.resolve(step.execute(snapshot.context, this.bus, signal)),
2412
- step.timeoutMs,
2413
- step.name
2414
- );
2415
- } catch (err) {
2416
- if (attempt < maxAttempts) {
2417
- if (retry.delayMs) await sleep(retry.delayMs);
2418
- continue;
2419
- }
2420
- snapshot.failedStep = step.name;
2421
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2422
- await this.store.save(snapshot);
2423
- await this.audit("workflow.step.failed", snapshot, {
2424
- step: step.name,
2425
- attempt,
2426
- error: errorMessage(err)
2427
- });
2428
- throw err;
2429
- }
2430
- if (result) Object.assign(snapshot.context, result);
2431
- snapshot.completedSteps.push(step.name);
2432
- snapshot.currentStep = void 0;
2433
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2434
- await this.store.save(snapshot);
2435
- await this.audit("workflow.step.completed", snapshot, {
2436
- step: step.name,
2437
- attempt
2438
- });
2439
- return;
2440
- }
2441
- throw new Error(`Workflow step "${step.name}" did not complete.`);
2442
- }
2443
- async compensate(snapshot, steps, error) {
2444
- snapshot.status = "compensating";
2445
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2446
- await this.store.save(snapshot);
2447
- const completed = steps.filter(
2448
- (step) => snapshot.completedSteps.includes(step.name)
2449
- );
2450
- for (let index = completed.length - 1; index >= 0; index -= 1) {
2451
- const step = completed[index];
2452
- if (!step.compensate) continue;
2453
- try {
2454
- await Promise.resolve(step.compensate(snapshot.context, this.bus, error));
2455
- await this.audit("workflow.compensation.completed", snapshot, {
2456
- step: step.name
2457
- });
2458
- } catch (compensationError) {
2459
- await this.audit("workflow.step.failed", snapshot, {
2460
- step: step.name,
2461
- compensation: true,
2462
- error: errorMessage(compensationError)
2463
- });
2464
- }
2465
- }
2466
- }
2467
- async audit(type, snapshot, details) {
2468
- await this.options.auditTrail?.record({
2469
- type,
2470
- source: "Kernel.WorkflowEngine",
2471
- subject: snapshot.id,
2472
- details
2473
- });
2474
- }
2475
- };
2476
- function createWorkflowEngine(bus, options) {
2477
- return new WorkflowEngineImpl(bus, options);
2478
- }
2479
-
2480
- // src/kernel/runtime/createArkKernel.ts
2481
- var DEFAULT_MAX_HISTORY_SIZE = 1e3;
2482
- var kernelSequence = 0;
2483
- function nextKernelInstanceId() {
2484
- kernelSequence += 1;
2485
- return `ark-kernel-${Date.now()}-${kernelSequence}`;
2486
- }
2487
- function createArkKernel(options = {}) {
2488
- const strict = options.strict ?? true;
2489
- const instanceId = options.instanceId ?? nextKernelInstanceId();
2490
- const profile = options.profile ?? elevenLayerProfile;
2491
- const maxHistorySize = options.maxHistorySize ?? DEFAULT_MAX_HISTORY_SIZE;
2492
- const registry = createIntentRegistry();
2493
- const graph = createDependencyGraph();
2494
- const metadata = options.metadata ?? createMetadataRegistry();
2495
- const auditTrail = options.auditTrail ?? createAuditTrail({ maxRecords: maxHistorySize });
2496
- const eventContracts = options.eventContracts ?? createEventContractRegistry();
2497
- const outbox = options.outbox ?? new InMemoryOutboxStore();
2498
- const projections = options.projections ?? createProjectionRegistry({ auditTrail });
2499
- const policyEngine = new PolicyEngine([
2500
- defineArchitectureProfilePolicy(profile),
2501
- ...options.policies ?? []
2502
- ]);
2503
- const syncGraph = () => {
2504
- syncRegistryToGraph(registry, graph, { requireRegisteredTargets: true });
2505
- };
2506
- const eventBus = createEventBus({
2507
- intentRegistry: registry,
2508
- dependencyGraph: graph,
2509
- policyEngine,
2510
- strictRegistry: true,
2511
- validateIntentNaming: true,
2512
- auditTrail,
2513
- eventContracts,
2514
- strictEventContracts: options.strictEventContracts ?? strict,
2515
- requireKnownSource: options.requireKnownSource ?? true,
2516
- architectureProfile: profile,
2517
- enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? (strict ? "hard" : "off"),
2518
- outbox,
2519
- instanceId,
2520
- maxHistorySize,
2521
- onPublish: options.autoApplyProjections === false ? void 0 : async (event) => {
2522
- await projections.apply(event);
2523
- }
2524
- });
2525
- const workflowEngine = createWorkflowEngine(eventBus, { auditTrail });
2526
- const observability = createObservabilityReporter({
2527
- registry,
2528
- eventBus,
2529
- graph
2530
- });
2531
- return {
2532
- instanceId,
2533
- profile,
2534
- registry,
2535
- graph,
2536
- metadata,
2537
- auditTrail,
2538
- eventContracts,
2539
- outbox,
2540
- projections,
2541
- policyEngine,
2542
- eventBus,
2543
- workflowEngine,
2544
- observability,
2545
- publisher(source) {
2546
- return eventBus.createPublisher(source);
2547
- },
2548
- syncGraph,
2549
- manifest() {
2550
- syncGraph();
2551
- return createArkManifest({
2552
- registry,
2553
- policyEngine,
2554
- metadata,
2555
- graph,
2556
- profile,
2557
- projections,
2558
- eventContracts,
2559
- observability
2560
- });
2561
- }
2562
- };
2563
- }
2564
-
2565
- // src/nestjs/index.ts
2566
- var ARK_KERNEL = /* @__PURE__ */ Symbol("ARK_KERNEL");
2567
- var InjectArk = () => (0, import_common.Inject)(ARK_KERNEL);
2568
- var ArkModule = class {
2569
- /**
2570
- * Registers a global Ark kernel. Pass an existing kernel to share one across
2571
- * processes/tests, or options to create a fresh strict kernel.
2572
- */
2573
- static forRoot(kernelOrOptions) {
2574
- const kernel = kernelOrOptions && "registry" in kernelOrOptions ? kernelOrOptions : createArkKernel(kernelOrOptions);
2575
- return {
2576
- module: ArkModule,
2577
- global: true,
2578
- providers: [{ provide: ARK_KERNEL, useValue: kernel }],
2579
- exports: [ARK_KERNEL]
2580
- };
2581
- }
2582
- static forRootAsync(options) {
2583
- return {
2584
- module: ArkModule,
2585
- global: true,
2586
- providers: [
2587
- {
2588
- provide: ARK_KERNEL,
2589
- useFactory: options.useFactory,
2590
- inject: options.inject ?? []
2591
- }
2592
- ],
2593
- exports: [ARK_KERNEL]
2594
- };
2595
- }
2596
- };
2597
- ArkModule = __decorateClass([
2598
- (0, import_common.Module)({})
2599
- ], ArkModule);
2600
- // Annotate the CommonJS export names for ESM import in node:
2601
- 0 && (module.exports = {
2602
- ARK_KERNEL,
2603
- ArkModule,
2604
- InjectArk
2605
- });
2606
- //# sourceMappingURL=index.cjs.map