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