ark-runtime-kernel 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1496 @@
1
+ /** Ark library version — single source of truth. */
2
+ declare const version = "1.0.0";
3
+
4
+ /**
5
+ * Core domain primitives for Ark.
6
+ * These types are the foundation for all governance concepts.
7
+ */
8
+ /**
9
+ * Semantic intent names follow a convention:
10
+ * - Domain.* for domain events and entities
11
+ * - Application.* for use-cases / orchestration
12
+ * - Adapter.* for integration points
13
+ * - Workflow.* for sagas and processes
14
+ * - Job.* for background jobs and scheduling
15
+ * - Presentation.* for UI/API adapters
16
+ * - Reporting.* for read models and projections
17
+ * - Metadata.* for extensibility contracts
18
+ * - Security.* / Audit.* / Observability.* for cross-cutting kernel concerns
19
+ * - Kernel.* for Ark-owned governance signals
20
+ */
21
+ type IntentName = `Domain.${string}` | `Application.${string}` | `Adapter.${string}` | `Workflow.${string}` | `Job.${string}` | `Presentation.${string}` | `Reporting.${string}` | `Metadata.${string}` | `Security.${string}` | `Audit.${string}` | `Observability.${string}` | `Kernel.${string}`;
22
+ type CorrelationId = string;
23
+ interface EventMetadata {
24
+ occurredAt: string;
25
+ source: string;
26
+ kernelInstanceId?: string;
27
+ eventVersion?: string;
28
+ schemaVersion?: string;
29
+ allowInterception?: boolean;
30
+ interceptions?: Array<{
31
+ interceptorId: string;
32
+ timestamp: string;
33
+ }>;
34
+ correlationId?: CorrelationId;
35
+ causationId?: string;
36
+ traceId?: string;
37
+ spanId?: string;
38
+ parentSpanId?: string;
39
+ [key: string]: unknown;
40
+ }
41
+ interface DomainEvent<Name extends IntentName = IntentName, Payload = unknown> {
42
+ intent: Name;
43
+ payload: Payload;
44
+ metadata: EventMetadata;
45
+ }
46
+
47
+ /**
48
+ * Intent-specific types for the Ark kernel.
49
+ *
50
+ * Intents provide semantic naming for every important concept in the system
51
+ * (domain events, application operations, adapters, workflows).
52
+ */
53
+
54
+ /**
55
+ * An IntentCreator is a callable that creates a strongly-typed DomainEvent
56
+ * when invoked with a payload.
57
+ *
58
+ * It also carries the semantic `name`.
59
+ *
60
+ * @example
61
+ * const OrderPlaced = defineIntent<'Domain.Order.OrderPlaced', { orderId: string }>('Domain.Order.OrderPlaced');
62
+ * const event = OrderPlaced({ orderId: 'o-1' });
63
+ */
64
+ interface IntentCreator<Name extends IntentName, Payload = unknown> {
65
+ /**
66
+ * Creates a DomainEvent for this intent.
67
+ */
68
+ (payload: Payload): DomainEvent<Name, Payload>;
69
+ /**
70
+ * The fully-qualified semantic name of the intent (e.g. "Domain.Order.OrderPlaced").
71
+ */
72
+ readonly name: Name;
73
+ }
74
+ /** Kind of relationship between two intents. */
75
+ type IntentRelationshipKind = 'dependsOn' | 'produces';
76
+ /**
77
+ * Relationship declarations between intents.
78
+ * Used for dependency analysis and graph generation.
79
+ */
80
+ interface IntentRelationship {
81
+ from: string;
82
+ to: string;
83
+ kind: IntentRelationshipKind;
84
+ }
85
+
86
+ /**
87
+ * IntentRegistry
88
+ *
89
+ * Central registry for semantic intents.
90
+ * Supports registration, duplicate prevention, and declared dependency relationships.
91
+ *
92
+ * This is a core building block for governance, dependency graphs, and policy enforcement.
93
+ */
94
+
95
+ /**
96
+ * Options for declaring relationships when defining an intent.
97
+ */
98
+ interface DefineIntentOptions {
99
+ /** Other intents this one depends on (semantic names) */
100
+ dependsOn?: IntentName[];
101
+ /** Intents that this one produces / triggers */
102
+ produces?: IntentName[];
103
+ }
104
+ /**
105
+ * IntentRegistry manages all registered intents and their declared relationships.
106
+ */
107
+ declare class IntentRegistry {
108
+ private readonly intents;
109
+ private readonly dependencies;
110
+ private readonly productions;
111
+ /**
112
+ * Define/register a new intent.
113
+ *
114
+ * @param name - Semantic intent name following the convention (Domain.*, Application.*, etc.)
115
+ * @param options - Optional relationship declarations
116
+ * @throws Error if an intent with the same name is already registered
117
+ */
118
+ define<N extends IntentName, P = unknown>(name: N, options?: DefineIntentOptions): IntentCreator<N, P>;
119
+ /**
120
+ * Declare that one intent depends on / relates to another.
121
+ * This information is used by the DependencyGraph (future iterations) and for policy checks.
122
+ *
123
+ * @param from - The source intent (e.g. an Application operation)
124
+ * @param to - The target intent it depends on (e.g. a Domain event or concept)
125
+ */
126
+ declareDependency(from: string, to: string): void;
127
+ /**
128
+ * Declare that one intent produces / emits another (e.g. use case → domain event).
129
+ */
130
+ declareProduction(from: string, to: string): void;
131
+ /**
132
+ * Retrieve a previously defined intent creator by name.
133
+ */
134
+ get<N extends IntentName = IntentName, P = unknown>(name: string): IntentCreator<N, P> | undefined;
135
+ /**
136
+ * List all registered intent creators.
137
+ */
138
+ list(): IntentCreator<IntentName, unknown>[];
139
+ /**
140
+ * Get all declared dependencies for a given intent.
141
+ */
142
+ getDependencies(intentName: string): string[];
143
+ /**
144
+ * Get all intents produced / emitted by a given intent.
145
+ */
146
+ getProductions(intentName: string): string[];
147
+ /**
148
+ * Get all declared relationships (useful for graph generation).
149
+ */
150
+ getAllRelationships(): IntentRelationship[];
151
+ /**
152
+ * Check if an intent name has been registered.
153
+ */
154
+ has(name: string): boolean;
155
+ /**
156
+ * Clear the registry. Primarily useful for tests.
157
+ */
158
+ clear(): void;
159
+ }
160
+
161
+ /**
162
+ * defineIntent
163
+ *
164
+ * The primary ergonomic function for declaring semantic intents.
165
+ *
166
+ * Uses a default shared registry for convenience, while still allowing
167
+ * isolated registries via `createIntentRegistry()`.
168
+ *
169
+ * Intents are the core of Ark's governance model. They give every
170
+ * architectural concept (domain events, use cases, adapter operations, workflows)
171
+ * an explicit, namespaced, machine-readable identity.
172
+ */
173
+
174
+ /**
175
+ * Define a new semantic intent.
176
+ *
177
+ * This is the main entry point most users (and AI generators) will use.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * // Domain event
182
+ * const OrderPlaced = defineIntent<'Domain.Order.OrderPlaced', {
183
+ * orderId: string;
184
+ * amount: number;
185
+ * }>('Domain.Order.OrderPlaced');
186
+ *
187
+ * const event = OrderPlaced({ orderId: 'o-42', amount: 99.5 });
188
+ *
189
+ * // Application operation that declares a dependency at definition time
190
+ * const ConfirmOrder = defineIntent<'Application.ConfirmOrder', { orderId: string }>(
191
+ * 'Application.ConfirmOrder',
192
+ * { dependsOn: ['Domain.Order.OrderPlaced'] }
193
+ * );
194
+ * ```
195
+ *
196
+ * @param name - Unique semantic name. Recommended convention:
197
+ * - `Domain.*` for domain concepts and events
198
+ * - `Application.*` for use cases / orchestration
199
+ * - `Adapter.*` for external integrations
200
+ * - `Workflow.*` for sagas and long-running processes
201
+ * @param options - Optional initial relationship declarations (`dependsOn`, `produces`)
202
+ */
203
+ declare function defineIntent<N extends IntentName, P = unknown>(name: N, options?: DefineIntentOptions): IntentCreator<N, P>;
204
+ /**
205
+ * Create an isolated IntentRegistry.
206
+ * Useful for testing, multiple bounded contexts, or advanced governance setups.
207
+ */
208
+ declare function createIntentRegistry(): IntentRegistry;
209
+ /**
210
+ * The default registry backing the top-level `defineIntent` calls.
211
+ * You can inspect it or use it directly if needed.
212
+ */
213
+ declare const defaultIntentRegistry: IntentRegistry;
214
+
215
+ /**
216
+ * Runtime validation for semantic intent naming conventions.
217
+ */
218
+ interface IntentNameValidation {
219
+ valid: boolean;
220
+ reason?: string;
221
+ }
222
+ /**
223
+ * Validate that an intent name follows Ark naming conventions.
224
+ */
225
+ declare function validateIntentName(name: string): IntentNameValidation;
226
+
227
+ /**
228
+ * Policy types for the Ark kernel.
229
+ *
230
+ * Policies allow declaring architectural rules that can be checked at runtime.
231
+ * Supports both hard policies (must never be violated) and soft policies (warnings).
232
+ */
233
+ type PolicySeverity = 'hard' | 'soft';
234
+ type PolicyEnforcementMode = 'runtime' | 'static' | 'runtime-and-static' | 'advisory';
235
+ /**
236
+ * Represents a single violation of a policy.
237
+ */
238
+ interface PolicyViolation {
239
+ /** Name of the policy that was violated */
240
+ policyName: string;
241
+ /** Severity level of the policy */
242
+ severity: PolicySeverity;
243
+ /** Human-readable explanation of the violation */
244
+ message: string;
245
+ /** Optional additional structured details */
246
+ details?: unknown;
247
+ }
248
+ /**
249
+ * A Policy defines a rule that can be evaluated against a context.
250
+ *
251
+ * @template Context - The shape of data the policy evaluates (e.g. { registry, events })
252
+ */
253
+ interface Policy<Context = unknown> {
254
+ /** Unique name of the policy (used in violations and reporting) */
255
+ readonly name: string;
256
+ /** Whether this is a hard rule (enforced strictly) or soft (advisory) */
257
+ readonly severity: PolicySeverity;
258
+ /** Optional tags for policy classification (e.g. 'layer', 'naming') */
259
+ readonly tags?: readonly string[];
260
+ readonly owner?: string;
261
+ readonly version?: string;
262
+ readonly rationale?: string;
263
+ readonly enforcementMode?: PolicyEnforcementMode;
264
+ readonly deprecated?: boolean | string;
265
+ readonly replacedBy?: string;
266
+ /**
267
+ * Evaluates the policy against the given context.
268
+ * Return true / [] for pass, false / single violation / array for failure.
269
+ */
270
+ check(context: Context): boolean | PolicyViolation | PolicyViolation[];
271
+ }
272
+
273
+ /**
274
+ * PolicyEngine
275
+ *
276
+ * Evaluates collections of policies against a context.
277
+ * Supports hard and soft policies.
278
+ * - Hard policies: violations cause enforcement to throw.
279
+ * - Soft policies: violations are reported as warnings but do not throw.
280
+ */
281
+
282
+ interface PolicyEvaluationResult {
283
+ passed: boolean;
284
+ violations: PolicyViolation[];
285
+ hardViolations: PolicyViolation[];
286
+ softViolations: PolicyViolation[];
287
+ }
288
+ /**
289
+ * The PolicyEngine is responsible for registering policies and evaluating
290
+ * them against a given context.
291
+ */
292
+ declare class PolicyEngine<Context = unknown> {
293
+ private readonly policies;
294
+ constructor(initialPolicies?: Policy<Context>[]);
295
+ /**
296
+ * Adds a policy to the engine.
297
+ */
298
+ add(policy: Policy<Context>): void;
299
+ /**
300
+ * Returns all registered policies.
301
+ */
302
+ getPolicies(): Policy<Context>[];
303
+ /**
304
+ * Evaluates all policies against the provided context.
305
+ */
306
+ evaluate(context: Context): PolicyEvaluationResult;
307
+ /**
308
+ * Enforces all policies.
309
+ *
310
+ * - Soft violations are collected and can be observed (returned or logged).
311
+ * - Hard violations cause an error to be thrown (by default).
312
+ *
313
+ * @returns Evaluation result (including any soft violations)
314
+ * @throws Error if any hard policy is violated
315
+ */
316
+ enforce(context: Context): PolicyEvaluationResult;
317
+ /**
318
+ * Clears all registered policies.
319
+ */
320
+ clear(): void;
321
+ }
322
+
323
+ /**
324
+ * Typed error thrown when hard policies are violated.
325
+ */
326
+
327
+ declare class PolicyViolationError extends Error {
328
+ readonly violations: PolicyViolation[];
329
+ constructor(violations: PolicyViolation[]);
330
+ }
331
+
332
+ /**
333
+ * definePolicy
334
+ *
335
+ * Factory function to create architectural policies in a declarative way.
336
+ */
337
+
338
+ interface DefinePolicyOptions<Context = unknown> {
339
+ name: string;
340
+ severity?: PolicySeverity;
341
+ tags?: readonly string[];
342
+ owner?: string;
343
+ version?: string;
344
+ rationale?: string;
345
+ enforcementMode?: PolicyEnforcementMode;
346
+ deprecated?: boolean | string;
347
+ replacedBy?: string;
348
+ check: (context: Context) => boolean | PolicyViolation | PolicyViolation[];
349
+ }
350
+ /**
351
+ * Creates a Policy from a declarative configuration.
352
+ *
353
+ * The provided `check` function is called as-is. The PolicyEngine is responsible
354
+ * for normalizing results (booleans, single violations, arrays) into a consistent
355
+ * set of PolicyViolation objects.
356
+ *
357
+ * @example
358
+ * ```ts
359
+ * const noDomainToInfra = definePolicy({
360
+ * name: 'Domain must not depend on infrastructure',
361
+ * severity: 'hard',
362
+ * check: (ctx) => {
363
+ * const violations: PolicyViolation[] = [];
364
+ * // ... logic using ctx.registry.getAllRelationships()
365
+ * return violations.length > 0 ? violations : true;
366
+ * }
367
+ * });
368
+ * ```
369
+ */
370
+ declare function definePolicy<Context = unknown>(options: DefinePolicyOptions<Context>): Policy<Context>;
371
+
372
+ /**
373
+ * Architecture layer profiles.
374
+ *
375
+ * A profile turns semantic names such as `Domain.Order.Placed` into governed
376
+ * layer names and dependency rules.
377
+ */
378
+ interface ArchitectureLayer {
379
+ name: string;
380
+ prefixes: string[];
381
+ description?: string;
382
+ order?: number;
383
+ }
384
+ interface ArchitectureRule {
385
+ from: string;
386
+ to: string;
387
+ allowed: boolean;
388
+ message?: string;
389
+ }
390
+ interface ArchitectureProfile {
391
+ name: string;
392
+ layers: ArchitectureLayer[];
393
+ rules: ArchitectureRule[];
394
+ resolveLayer(name: string): string | undefined;
395
+ }
396
+ interface CreateArchitectureProfileOptions {
397
+ name: string;
398
+ layers: ArchitectureLayer[];
399
+ rules?: ArchitectureRule[];
400
+ }
401
+ interface ArchitectureLayerConfig {
402
+ name: string;
403
+ patterns: string[];
404
+ intentPrefixes: string[];
405
+ /** Optional layers do not warn when their patterns match no files. */
406
+ optional?: boolean;
407
+ }
408
+ interface ArkCheckConfig {
409
+ include: string[];
410
+ layers: ArchitectureLayerConfig[];
411
+ rules: ArchitectureRule[];
412
+ }
413
+ interface CreateElevenLayerArkConfigOptions {
414
+ /** Source root used in generated file patterns. Default: "src". */
415
+ rootDir?: string;
416
+ /** Include entries for ark-check. Default: [rootDir]. */
417
+ include?: string[];
418
+ /** Mark generated layers optional. Default: true. */
419
+ optionalLayers?: boolean;
420
+ }
421
+
422
+ declare function createArchitectureProfile(options: CreateArchitectureProfileOptions): ArchitectureProfile;
423
+ declare const elevenLayerProfile: ArchitectureProfile;
424
+ declare function createElevenLayerArkConfig(options?: CreateElevenLayerArkConfigOptions): ArkCheckConfig;
425
+
426
+ /**
427
+ * Dependency Graph types.
428
+ *
429
+ * Used to model declared + observed relationships between intents,
430
+ * and to generate visualizations (Mermaid) and detect violations.
431
+ */
432
+
433
+ interface GraphEdge {
434
+ from: string;
435
+ to: string;
436
+ kind?: 'declared' | 'observed' | 'produces';
437
+ }
438
+ interface GraphNode {
439
+ id: string;
440
+ kind?: string;
441
+ }
442
+ interface DependencyGraph {
443
+ /**
444
+ * Register a declared dependency between two semantic names.
445
+ */
446
+ registerDependency(from: string, to: string, kind?: GraphEdge['kind']): void;
447
+ /**
448
+ * Register an observed event flow (producer -> consumer).
449
+ */
450
+ registerEventFlow(producer: string, consumer: string): void;
451
+ /**
452
+ * Return all nodes.
453
+ */
454
+ getNodes(): GraphNode[];
455
+ /**
456
+ * Return all edges.
457
+ */
458
+ getEdges(): GraphEdge[];
459
+ /**
460
+ * Export as JSON.
461
+ */
462
+ toJSON(): {
463
+ nodes: GraphNode[];
464
+ edges: GraphEdge[];
465
+ };
466
+ /**
467
+ * Export as Mermaid flowchart.
468
+ */
469
+ toMermaid(): string;
470
+ /**
471
+ * Export as Mermaid flowchart grouped into profile layers.
472
+ */
473
+ toLayerMermaid(profile: ArchitectureProfile): string;
474
+ /**
475
+ * Detect violations by running provided policies or simple rules.
476
+ * For simplicity here we accept predicates that return violation messages.
477
+ */
478
+ detectViolations(rules?: Array<(edges: GraphEdge[]) => string[]>): string[];
479
+ }
480
+
481
+ /**
482
+ * DependencyGraph implementation.
483
+ *
484
+ * Collects declared and observed relationships.
485
+ * Generates Mermaid diagrams and JSON.
486
+ * Supports simple violation detection via rule functions.
487
+ */
488
+
489
+ declare function createDependencyGraph(): DependencyGraph;
490
+
491
+ /**
492
+ * Bridge IntentRegistry relationships into a DependencyGraph.
493
+ */
494
+
495
+ interface SyncRegistryOptions {
496
+ /** Skip edges whose target intent is not registered (default: false). */
497
+ requireRegisteredTargets?: boolean;
498
+ }
499
+ /**
500
+ * Sync declared intent relationships from a registry into a dependency graph.
501
+ *
502
+ * - `dependsOn` → `declared` edges
503
+ * - `produces` → `produces` edges
504
+ */
505
+ declare function syncRegistryToGraph(registry: IntentRegistry, graph: DependencyGraph, options?: SyncRegistryOptions): void;
506
+
507
+ /**
508
+ * Built-in architectural policy helpers.
509
+ */
510
+
511
+ interface LayerFlowRule {
512
+ from: string;
513
+ to: string;
514
+ allowed: boolean;
515
+ message?: string;
516
+ }
517
+ interface LayerPolicyOptions {
518
+ name?: string;
519
+ severity?: 'hard' | 'soft';
520
+ /** Prefix rules — e.g. { from: 'Domain', to: 'Adapter', allowed: false } */
521
+ rules: LayerFlowRule[];
522
+ resolveLayer?: (name: string) => string | undefined;
523
+ }
524
+ /**
525
+ * Create a policy that enforces layer-crossing rules on graph edges or intent relationships.
526
+ */
527
+ declare function defineLayerPolicy<Context extends {
528
+ edges?: GraphEdge[];
529
+ relationships?: IntentRelationship[];
530
+ }>(options: LayerPolicyOptions): Policy<Context>;
531
+ /** True when a policy requires graph/registry context to enforce layer rules. */
532
+ declare function isLayerPolicy(policy: Policy): boolean;
533
+ /** Preset architectural policy factories. */
534
+ declare const architecturalPolicies: {
535
+ /**
536
+ * @deprecated Use cleanArchitectureMatrix() for full layer rules.
537
+ * Blocks Domain → Adapter declared dependencies only.
538
+ */
539
+ layerIsolation(): Policy<{
540
+ edges?: GraphEdge[];
541
+ relationships?: IntentRelationship[];
542
+ }>;
543
+ /**
544
+ * Clean-architecture dependency matrix (declared dependsOn / declared edges only).
545
+ * Does not block observed event flows (Domain events consumed by Application).
546
+ */
547
+ cleanArchitectureMatrix(): Policy<{
548
+ edges?: GraphEdge[];
549
+ relationships?: IntentRelationship[];
550
+ }>;
551
+ };
552
+ declare function defineArchitectureProfilePolicy<Context extends {
553
+ edges?: GraphEdge[];
554
+ relationships?: IntentRelationship[];
555
+ }>(profile: ArchitectureProfile, options?: Omit<LayerPolicyOptions, 'rules' | 'resolveLayer'>): Policy<Context>;
556
+
557
+ type MaybePromise<T> = T | Promise<T>;
558
+ type AuditRecordType = 'event.published' | 'event.rawPublish' | 'event.intercepted' | 'interceptor.error' | 'policy.softViolation' | 'policy.hardViolation' | 'layer.observedViolation' | 'handler.error' | 'hook.error' | 'workflow.started' | 'workflow.step.completed' | 'workflow.step.failed' | 'workflow.compensation.completed' | 'workflow.completed' | 'workflow.failed' | 'projection.applied' | 'metadata.changed';
559
+ interface AuditRecord {
560
+ id: string;
561
+ type: AuditRecordType;
562
+ timestamp: string;
563
+ source?: string;
564
+ actor?: string;
565
+ intent?: string;
566
+ correlationId?: string;
567
+ causationId?: string;
568
+ subject?: string;
569
+ details?: unknown;
570
+ }
571
+ interface AuditRecordInput {
572
+ type: AuditRecordType;
573
+ timestamp?: string;
574
+ source?: string;
575
+ actor?: string;
576
+ intent?: string;
577
+ correlationId?: string;
578
+ causationId?: string;
579
+ subject?: string;
580
+ details?: unknown;
581
+ }
582
+ interface AuditQuery {
583
+ type?: AuditRecordType;
584
+ intent?: string;
585
+ correlationId?: string;
586
+ subject?: string;
587
+ since?: string;
588
+ until?: string;
589
+ limit?: number;
590
+ }
591
+ interface AuditStore {
592
+ append(record: AuditRecord): MaybePromise<void>;
593
+ query(query?: AuditQuery): MaybePromise<AuditRecord[]>;
594
+ clear(): MaybePromise<void>;
595
+ }
596
+ interface AuditTrail {
597
+ record(input: AuditRecordInput): Promise<AuditRecord>;
598
+ query(query?: AuditQuery): Promise<AuditRecord[]>;
599
+ clear(): Promise<void>;
600
+ }
601
+ interface CreateAuditTrailOptions {
602
+ store?: AuditStore;
603
+ maxRecords?: number;
604
+ }
605
+
606
+ declare class InMemoryAuditStore implements AuditStore {
607
+ private readonly maxRecords?;
608
+ private readonly records;
609
+ constructor(maxRecords?: number | undefined);
610
+ append(record: AuditRecord): void;
611
+ query(query?: AuditQuery): AuditRecord[];
612
+ clear(): void;
613
+ }
614
+ declare function createAuditTrail(options?: CreateAuditTrailOptions): AuditTrail;
615
+
616
+ type EventSchemaFieldType = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'unknown';
617
+ interface EventSchemaField {
618
+ type: EventSchemaFieldType;
619
+ required?: boolean;
620
+ description?: string;
621
+ /** Allowed literal values for this field. Compared with Object.is. */
622
+ enum?: unknown[];
623
+ /** Nested object fields when type is "object". */
624
+ fields?: EventPayloadSchema;
625
+ /** Array item schema when type is "array". */
626
+ items?: EventSchemaField;
627
+ }
628
+ type EventPayloadSchema = Record<string, EventSchemaField>;
629
+ interface EventContract {
630
+ intent: IntentName;
631
+ version: string;
632
+ schema?: EventPayloadSchema;
633
+ owner?: string;
634
+ rationale?: string;
635
+ deprecated?: boolean | string;
636
+ allowAdditionalFields?: boolean;
637
+ }
638
+ interface EventContractIssue {
639
+ intent: string;
640
+ version?: string;
641
+ field?: string;
642
+ message: string;
643
+ }
644
+ interface EventContractValidationResult {
645
+ ok: boolean;
646
+ contract?: EventContract;
647
+ issues: EventContractIssue[];
648
+ }
649
+ interface EventContractRegistry {
650
+ register(contract: EventContract): void;
651
+ get(intent: string, version?: string): EventContract | undefined;
652
+ list(intent?: string): EventContract[];
653
+ validate(event: DomainEvent): EventContractValidationResult;
654
+ clear(): void;
655
+ }
656
+
657
+ declare class EventContractRegistryImpl implements EventContractRegistry {
658
+ private readonly contracts;
659
+ register(contract: EventContract): void;
660
+ get(intent: string, version?: string): EventContract | undefined;
661
+ list(intent?: string): EventContract[];
662
+ validate(event: DomainEvent): EventContractValidationResult;
663
+ clear(): void;
664
+ private key;
665
+ }
666
+ declare function createEventContractRegistry(): EventContractRegistry;
667
+
668
+ type OutboxStatus = 'pending' | 'dispatched' | 'failed';
669
+ interface OutboxRecord {
670
+ id: string;
671
+ event: DomainEvent;
672
+ status: OutboxStatus;
673
+ attempts: number;
674
+ createdAt: string;
675
+ updatedAt: string;
676
+ error?: string;
677
+ }
678
+ interface OutboxStore {
679
+ enqueue(event: DomainEvent): Promise<OutboxRecord>;
680
+ markDispatched(id: string): Promise<void>;
681
+ markFailed(id: string, error: unknown): Promise<void>;
682
+ list(status?: OutboxStatus): Promise<OutboxRecord[]>;
683
+ clear(): Promise<void>;
684
+ }
685
+
686
+ declare class InMemoryOutboxStore implements OutboxStore {
687
+ private readonly records;
688
+ enqueue(event: DomainEvent): Promise<OutboxRecord>;
689
+ markDispatched(id: string): Promise<void>;
690
+ markFailed(id: string, error: unknown): Promise<void>;
691
+ list(status?: OutboxStatus): Promise<OutboxRecord[]>;
692
+ clear(): Promise<void>;
693
+ }
694
+
695
+ /**
696
+ * Event Bus types for the Ark kernel.
697
+ *
698
+ * The Event Bus is the central nervous system for Domain Events.
699
+ * It provides publish/subscribe, history for observability, and metadata handling.
700
+ */
701
+
702
+ /** Standard trace record for observability and agent consumption. */
703
+ type TraceRecordType = 'event.published' | 'event.rawPublish' | 'event.intercepted' | 'interceptor.error' | 'policy.hardViolation' | 'policy.softViolation' | 'layer.observedViolation' | 'handler.error' | 'hook.error';
704
+ /**
705
+ * Runtime enforcement mode for observed producer→event layer flows.
706
+ * - 'off': flows are recorded (for drift reports) but never enforced.
707
+ * - 'soft': a `layer.observedViolation` trace + audit record is emitted; publish proceeds.
708
+ * - 'hard': publish throws `ObservedLayerFlowViolationError` before the event reaches
709
+ * history, outbox, or subscribers.
710
+ */
711
+ type ObservedLayerFlowMode = 'off' | 'soft' | 'hard';
712
+ interface TraceRecord {
713
+ type: TraceRecordType;
714
+ timestamp: string;
715
+ intent: string;
716
+ correlationId?: string;
717
+ traceId?: string;
718
+ spanId?: string;
719
+ details?: unknown;
720
+ }
721
+ type TraceSink = (record: TraceRecord) => void;
722
+ /**
723
+ * Options when creating an EventBus.
724
+ */
725
+ interface EventBusOptions<Context = unknown> {
726
+ /** Optional hook called after every successful publish */
727
+ onPublish?: (event: DomainEvent) => void | Promise<void>;
728
+ /** Native audit trail used to persist publish, policy, and handler events. */
729
+ auditTrail?: AuditTrail;
730
+ /** Event contracts used to validate payload shape and event versions. */
731
+ eventContracts?: EventContractRegistry;
732
+ /** When true, events without a registered contract are rejected. */
733
+ strictEventContracts?: boolean;
734
+ /** When true, metadata.source must be explicit and not "unknown". */
735
+ requireKnownSource?: boolean;
736
+ /**
737
+ * Architecture profile used to enforce the OBSERVED producer→event layer flow at
738
+ * publish time. Required for `enforceObservedLayerFlow` to have effect.
739
+ */
740
+ architectureProfile?: ArchitectureProfile;
741
+ /**
742
+ * Enforce each published event's real producer→event flow (metadata.source → intent)
743
+ * against `architectureProfile` layer rules at runtime. Unlike the declared-model layer
744
+ * policy, this checks what the system actually did. Default: 'off'.
745
+ */
746
+ enforceObservedLayerFlow?: ObservedLayerFlowMode;
747
+ /** Optional outbox store for durable delivery handoff. */
748
+ outbox?: OutboxStore;
749
+ /** Stable id stamped into event metadata for this kernel/event bus instance. */
750
+ instanceId?: string;
751
+ /** Lightweight tracing hooks for OpenTelemetry or custom tracer bridges. */
752
+ traceSinks?: TraceSink[];
753
+ /** Called when soft policies produce violations (publish still proceeds). */
754
+ onSoftViolation?: (result: PolicyEvaluationResult, event: DomainEvent) => void | Promise<void>;
755
+ /** Called when a subscriber handler throws or rejects. */
756
+ onHandlerError?: (error: unknown, event: DomainEvent, intentName: string) => void | Promise<void>;
757
+ /** When true, rethrow handler errors after calling onHandlerError. Default: false. */
758
+ rethrowHandlerErrors?: boolean;
759
+ /**
760
+ * Policies to evaluate on every publish.
761
+ * If provided, they run before subscribers are notified.
762
+ * Hard violations will cause publish to throw.
763
+ */
764
+ policies?: Policy<Context>[];
765
+ /**
766
+ * Function to build the context object passed to policies for a given event.
767
+ * Default: { event }, or { event, relationships, edges } when registry/graph provided.
768
+ */
769
+ getPolicyContext?: (event: DomainEvent) => Context;
770
+ /**
771
+ * Intent registry whose relationships are injected into the default policy context.
772
+ * Enables layer policies (e.g. architecturalPolicies.layerIsolation) on publish.
773
+ */
774
+ intentRegistry?: IntentRegistry;
775
+ /**
776
+ * Dependency graph whose edges are injected into the default policy context.
777
+ */
778
+ dependencyGraph?: DependencyGraph;
779
+ /**
780
+ * Pre-configured PolicyEngine to use (alternative to policies array).
781
+ */
782
+ policyEngine?: PolicyEngine<Context>;
783
+ /**
784
+ * Maximum publish history entries to retain. Oldest evicted when exceeded.
785
+ * Default: unlimited.
786
+ */
787
+ maxHistorySize?: number;
788
+ /**
789
+ * When true (default: true if intentRegistry is provided), reject publish/subscribe
790
+ * for intents not registered in intentRegistry and optionally validate naming.
791
+ */
792
+ strictRegistry?: boolean;
793
+ /**
794
+ * When true (default: matches strictRegistry), validate intent names follow
795
+ * Domain.* / Application.* / Adapter.* / Workflow.* conventions at runtime.
796
+ */
797
+ validateIntentNaming?: boolean;
798
+ }
799
+ /**
800
+ * A subscriber is a function that receives events of a specific intent.
801
+ */
802
+ type EventHandler<N extends IntentName, P = unknown> = (event: DomainEvent<N, P>) => void | Promise<void>;
803
+ type EventPayloadPatch = Record<string, unknown> | unknown[];
804
+ interface EventInterceptorContext<N extends IntentName = IntentName, P = unknown> {
805
+ readonly event: Readonly<DomainEvent<N, P>>;
806
+ intercept(patch: EventPayloadPatch): void;
807
+ }
808
+ type EventInterceptor<N extends IntentName = IntentName, P = unknown> = (context: EventInterceptorContext<N, P>) => void | Promise<void>;
809
+ interface EventInterceptionInfo {
810
+ registrationId: string;
811
+ interceptorId: string;
812
+ intent: string;
813
+ createdAt: string;
814
+ lastInterceptedAt?: string;
815
+ }
816
+ /**
817
+ * Unsubscribe function returned by subscribe.
818
+ */
819
+ type Unsubscribe = () => void;
820
+ /**
821
+ * Record of a published event for observability.
822
+ */
823
+ interface PublishedEventRecord {
824
+ event: DomainEvent;
825
+ publishedAt: string;
826
+ subscribersNotified: number;
827
+ }
828
+ interface EventPublisher {
829
+ readonly source: string;
830
+ publish<N extends IntentName, P>(intent: IntentCreator<N, P>, payload: P, metadata?: Partial<EventMetadata>): Promise<void>;
831
+ }
832
+ /**
833
+ * The public EventBus interface.
834
+ */
835
+ interface EventBus {
836
+ /**
837
+ * Publish an event.
838
+ * Accepts either a pre-built DomainEvent or an IntentCreator + payload (plus optional metadata).
839
+ */
840
+ publish<N extends IntentName, P>(eventOrCreator: DomainEvent<N, P> | IntentCreator<N, P>, payloadOrMeta?: P | Partial<EventMetadata>, metadata?: Partial<EventMetadata>): Promise<void>;
841
+ /**
842
+ * Create a source-bound publisher capability. The returned publisher stamps
843
+ * metadata.source internally and rejects attempts to publish as another source.
844
+ */
845
+ createPublisher<N extends IntentName, P>(source: N | IntentCreator<N, P>): EventPublisher;
846
+ /**
847
+ * Subscribe to events for a specific intent (by name or creator).
848
+ * Returns an unsubscribe function.
849
+ */
850
+ subscribe<N extends IntentName, P>(intent: N | IntentCreator<N, P>, handler: EventHandler<N, P>): Unsubscribe;
851
+ /**
852
+ * Register an add-only interceptor for one intent.
853
+ * Interceptors may enrich payloads, but cannot overwrite existing payload fields.
854
+ */
855
+ registerInterceptor<N extends IntentName, P>(intent: N | IntentCreator<N, P>, interceptor: EventInterceptor<N, P>, interceptorId?: string): string;
856
+ /**
857
+ * Remove a registered interceptor by registration id.
858
+ */
859
+ unregisterInterceptor(registrationId: string): boolean;
860
+ /**
861
+ * List registered interceptors.
862
+ */
863
+ listInterceptors(intent?: string): EventInterceptionInfo[];
864
+ /**
865
+ * Returns the history of published events (for observability and testing).
866
+ */
867
+ getHistory(): PublishedEventRecord[];
868
+ /**
869
+ * Clears publish history (useful in tests).
870
+ */
871
+ clearHistory(): void;
872
+ /**
873
+ * Returns the observability trace (publish, soft violations, handler errors).
874
+ */
875
+ getTrace(): TraceRecord[];
876
+ /**
877
+ * Clears the observability trace.
878
+ */
879
+ clearTrace(): void;
880
+ }
881
+
882
+ /**
883
+ * EventBus implementation.
884
+ *
885
+ * Core publish/subscribe mechanics with:
886
+ * - Intent-aware typing via creators
887
+ * - Automatic metadata enrichment
888
+ * - Full publish history for observability
889
+ * - Strict registry validation (opt-in by default when registry provided)
890
+ */
891
+
892
+ declare function createEventBus<Context = unknown>(options?: EventBusOptions<Context>): EventBus;
893
+
894
+ /**
895
+ * Helpers for building policy evaluation context on event publish.
896
+ */
897
+
898
+ /**
899
+ * Standard context for policies evaluated during event publish.
900
+ * Includes the event plus optional registry relationships and graph edges
901
+ * so layer policies (e.g. architecturalPolicies.layerIsolation) can run.
902
+ */
903
+ interface PublishPolicyContext {
904
+ event: DomainEvent;
905
+ relationships?: IntentRelationship[];
906
+ edges?: GraphEdge[];
907
+ }
908
+ interface GraphPolicyContext {
909
+ relationships?: IntentRelationship[];
910
+ edges?: GraphEdge[];
911
+ }
912
+ interface BuildPublishPolicyContextOptions {
913
+ intentRegistry?: IntentRegistry;
914
+ dependencyGraph?: DependencyGraph;
915
+ }
916
+ /**
917
+ * Build a getPolicyContext function that feeds registry + graph data to policies.
918
+ *
919
+ * @example
920
+ * ```ts
921
+ * const bus = createEventBus({
922
+ * intentRegistry: registry,
923
+ * dependencyGraph: graph,
924
+ * policies: [architecturalPolicies.layerIsolation()],
925
+ * });
926
+ * ```
927
+ */
928
+ declare function buildPublishPolicyContext(options: BuildPublishPolicyContextOptions): (event: DomainEvent) => PublishPolicyContext;
929
+ declare function definePublishPolicy(options: DefinePolicyOptions<PublishPolicyContext>): Policy<PublishPolicyContext>;
930
+
931
+ /**
932
+ * Event bus governance errors.
933
+ */
934
+ declare class UnregisteredIntentError extends Error {
935
+ readonly intentName: string;
936
+ constructor(intentName: string);
937
+ }
938
+ declare class InvalidIntentNameError extends Error {
939
+ readonly intentName: string;
940
+ readonly reason: string;
941
+ constructor(intentName: string, reason: string);
942
+ }
943
+ declare class LayerPolicyContextError extends Error {
944
+ constructor();
945
+ }
946
+ declare class EventContractViolationError extends Error {
947
+ readonly intentName: string;
948
+ readonly issues: unknown[];
949
+ constructor(intentName: string, issues: unknown[]);
950
+ }
951
+ declare class UnknownEventSourceError extends Error {
952
+ readonly intentName: string;
953
+ readonly source?: string;
954
+ constructor(intentName: string, source?: string);
955
+ }
956
+ declare class SourceMetadataOverrideError extends Error {
957
+ readonly boundSource: string;
958
+ readonly attemptedSource: string;
959
+ constructor(boundSource: string, attemptedSource: string);
960
+ }
961
+ /**
962
+ * Thrown when the OBSERVED producer→event flow crosses a forbidden layer boundary
963
+ * under `enforceObservedLayerFlow: 'hard'`. Unlike declared-model policy errors, this
964
+ * reflects what the running system actually did at publish time.
965
+ */
966
+ declare class ObservedLayerFlowViolationError extends Error {
967
+ readonly source: string;
968
+ readonly intentName: string;
969
+ readonly fromLayer: string;
970
+ readonly toLayer: string;
971
+ constructor(source: string, intentName: string, fromLayer: string, toLayer: string, message?: string);
972
+ }
973
+
974
+ interface ObservabilityFlow {
975
+ from: string;
976
+ to: string;
977
+ }
978
+ interface ObservabilityDriftReport {
979
+ generatedAt: string;
980
+ declaredProductions: ObservabilityFlow[];
981
+ observedProductions: ObservabilityFlow[];
982
+ declaredButUnobserved: ObservabilityFlow[];
983
+ observedButUndeclared: ObservabilityFlow[];
984
+ unknownSources: ObservabilityFlow[];
985
+ unregisteredObservedSources: string[];
986
+ unregisteredObservedIntents: string[];
987
+ registeredButNeverObserved: string[];
988
+ }
989
+ interface ObservabilityReporter {
990
+ report(): ObservabilityDriftReport;
991
+ }
992
+ interface CreateObservabilityReporterOptions {
993
+ registry?: IntentRegistry;
994
+ eventBus?: EventBus;
995
+ graph?: DependencyGraph;
996
+ }
997
+
998
+ declare function createObservabilityReporter(options: CreateObservabilityReporterOptions): ObservabilityReporter;
999
+
1000
+ /**
1001
+ * Metadata System (basic) for extensibility.
1002
+ *
1003
+ * Allows declaring entities, fields and simple rules/behaviors as data.
1004
+ * This can be used by tools, codegen, or AI to understand the domain without hardcoding.
1005
+ */
1006
+ interface FieldMeta {
1007
+ type: string;
1008
+ identity?: boolean;
1009
+ required?: boolean;
1010
+ description?: string;
1011
+ relation?: {
1012
+ entity: string;
1013
+ kind?: 'one' | 'many';
1014
+ };
1015
+ readonly?: boolean;
1016
+ deprecated?: boolean | string;
1017
+ tags?: string[];
1018
+ [key: string]: unknown;
1019
+ }
1020
+ interface EntityRuleMeta {
1021
+ name: string;
1022
+ description?: string;
1023
+ severity?: 'hard' | 'soft';
1024
+ }
1025
+ interface EntityMeta {
1026
+ name: string;
1027
+ version?: string;
1028
+ owner?: string;
1029
+ layer?: string;
1030
+ tags?: string[];
1031
+ fields: Record<string, FieldMeta>;
1032
+ rules?: EntityRuleMeta[];
1033
+ /** Intent names this entity emits (domain events). */
1034
+ emits?: string[];
1035
+ /** Intent names this entity consumes / reacts to. */
1036
+ consumes?: string[];
1037
+ /** Read-model or projection names that derive from this entity. */
1038
+ projections?: string[];
1039
+ deprecated?: boolean | string;
1040
+ [key: string]: unknown;
1041
+ }
1042
+ interface MetadataRegistrationOptions {
1043
+ allowOverwrite?: boolean;
1044
+ }
1045
+ interface MetadataIssue {
1046
+ entity: string;
1047
+ field?: string;
1048
+ message: string;
1049
+ }
1050
+ interface MetadataValidationResult {
1051
+ ok: boolean;
1052
+ issues: MetadataIssue[];
1053
+ }
1054
+ interface MetadataRegistry {
1055
+ entity(name: string, meta: Omit<EntityMeta, 'name'>, options?: MetadataRegistrationOptions): EntityMeta;
1056
+ getEntity(name: string): EntityMeta | undefined;
1057
+ listEntities(): EntityMeta[];
1058
+ findEntitiesByIntent(intentName: string): EntityMeta[];
1059
+ validate(): MetadataValidationResult;
1060
+ toJSON(): EntityMeta[];
1061
+ }
1062
+
1063
+ /**
1064
+ * Basic MetadataRegistry implementation.
1065
+ */
1066
+
1067
+ declare function createMetadataRegistry(): MetadataRegistry;
1068
+
1069
+ interface ProjectionDefinition<State = unknown> {
1070
+ name: string;
1071
+ sourceIntents: IntentName[];
1072
+ initialState: State | (() => State);
1073
+ project(event: DomainEvent<IntentName, unknown>, state: State): MaybePromise<State>;
1074
+ }
1075
+ interface ProjectionCheckpoint {
1076
+ projection: string;
1077
+ appliedCount: number;
1078
+ lastIntent?: string;
1079
+ lastCorrelationId?: string;
1080
+ updatedAt?: string;
1081
+ }
1082
+ interface ReadModelStore {
1083
+ load<State = unknown>(name: string): MaybePromise<State | undefined>;
1084
+ save<State = unknown>(name: string, state: State): MaybePromise<void>;
1085
+ clear(name?: string): MaybePromise<void>;
1086
+ }
1087
+ interface ProjectionRegistry {
1088
+ register<State>(definition: ProjectionDefinition<State>): void;
1089
+ list(): ProjectionDefinition[];
1090
+ apply(event: DomainEvent<IntentName, unknown>): Promise<string[]>;
1091
+ getState<State = unknown>(name: string): Promise<State | undefined>;
1092
+ getCheckpoint(name: string): ProjectionCheckpoint | undefined;
1093
+ getCheckpoints(): ProjectionCheckpoint[];
1094
+ clear(): Promise<void>;
1095
+ }
1096
+ interface CreateProjectionRegistryOptions {
1097
+ store?: ReadModelStore;
1098
+ auditTrail?: AuditTrail;
1099
+ }
1100
+
1101
+ declare class InMemoryReadModelStore implements ReadModelStore {
1102
+ private readonly states;
1103
+ load<State = unknown>(name: string): State | undefined;
1104
+ save<State = unknown>(name: string, state: State): void;
1105
+ clear(name?: string): void;
1106
+ }
1107
+ declare function createProjectionRegistry(options?: CreateProjectionRegistryOptions): ProjectionRegistry;
1108
+
1109
+ /**
1110
+ * Machine-readable manifest types for agent and tooling consumption.
1111
+ */
1112
+
1113
+ interface ArkManifestIntent {
1114
+ name: string;
1115
+ dependencies: string[];
1116
+ productions: string[];
1117
+ }
1118
+ interface ArkManifestPolicy {
1119
+ /** Stable slug for agents (derived from policy name). */
1120
+ id: string;
1121
+ name: string;
1122
+ severity: 'hard' | 'soft';
1123
+ tags?: string[];
1124
+ description?: string;
1125
+ owner?: string;
1126
+ version?: string;
1127
+ rationale?: string;
1128
+ enforcementMode?: PolicyEnforcementMode;
1129
+ deprecated?: boolean | string;
1130
+ replacedBy?: string;
1131
+ }
1132
+ interface ArkManifestEntityLink {
1133
+ entity: string;
1134
+ emits?: string[];
1135
+ consumes?: string[];
1136
+ }
1137
+ interface ArkManifestGraph {
1138
+ nodes: GraphNode[];
1139
+ edges: GraphEdge[];
1140
+ }
1141
+ interface ArkManifestArchitecture {
1142
+ profile: string;
1143
+ layers: ArchitectureLayer[];
1144
+ rules: ArchitectureRule[];
1145
+ }
1146
+ interface ArkManifestProjection {
1147
+ name: string;
1148
+ sourceIntents: string[];
1149
+ checkpoint?: ProjectionCheckpoint;
1150
+ }
1151
+ interface ArkManifestData {
1152
+ /** Manifest schema version for agent/tooling compatibility. */
1153
+ schemaVersion: string;
1154
+ version: string;
1155
+ exportedAt: string;
1156
+ intents: ArkManifestIntent[];
1157
+ relationships: IntentRelationship[];
1158
+ policies: ArkManifestPolicy[];
1159
+ entities: EntityMeta[];
1160
+ graph: ArkManifestGraph;
1161
+ architecture?: ArkManifestArchitecture;
1162
+ projections: ArkManifestProjection[];
1163
+ eventContracts: EventContract[];
1164
+ observability?: ObservabilityDriftReport;
1165
+ /** Cross-registry links for agent contract discovery. */
1166
+ links: {
1167
+ entityIntents: ArkManifestEntityLink[];
1168
+ };
1169
+ }
1170
+ interface ArkManifest {
1171
+ toJSON(): ArkManifestData;
1172
+ }
1173
+
1174
+ /** Current Ark manifest JSON schema version. */
1175
+ declare const MANIFEST_SCHEMA_VERSION = "1.0";
1176
+
1177
+ /**
1178
+ * Aggregates kernel registries into a single machine-readable manifest.
1179
+ */
1180
+
1181
+ interface CreateArkManifestOptions {
1182
+ registry?: IntentRegistry;
1183
+ policyEngine?: PolicyEngine;
1184
+ metadata?: MetadataRegistry;
1185
+ graph?: DependencyGraph;
1186
+ profile?: ArchitectureProfile;
1187
+ projections?: ProjectionRegistry;
1188
+ eventContracts?: EventContractRegistry;
1189
+ observability?: ObservabilityReporter;
1190
+ }
1191
+ /**
1192
+ * Create a machine-readable snapshot of the current architectural contract.
1193
+ * Intended for AI agents, codegen tools, and documentation generators.
1194
+ */
1195
+ declare function createArkManifest(options?: CreateArkManifestOptions): ArkManifest;
1196
+
1197
+ /**
1198
+ * Workflow / Saga support.
1199
+ */
1200
+
1201
+ type SagaContext = Record<string, unknown>;
1202
+ type SagaStatus = 'idle' | 'running' | 'compensating' | 'completed' | 'failed';
1203
+ type WorkflowStatus = SagaStatus | 'waiting';
1204
+ interface RetryPolicy {
1205
+ attempts: number;
1206
+ delayMs?: number;
1207
+ }
1208
+ interface WorkflowStep<P extends SagaContext = SagaContext> {
1209
+ name: string;
1210
+ onEvent?: IntentName;
1211
+ retry?: RetryPolicy;
1212
+ timeoutMs?: number;
1213
+ execute: (payload: P, bus: EventBus) => MaybePromise<Partial<P> | void>;
1214
+ compensate?: (payload: P, bus: EventBus, error?: unknown) => MaybePromise<void>;
1215
+ }
1216
+ interface WorkflowStartTrigger<P extends SagaContext = SagaContext> {
1217
+ intent: IntentName;
1218
+ mapEventToPayload(event: DomainEvent<IntentName, unknown>): P;
1219
+ }
1220
+ interface WorkflowDefinition<P extends SagaContext = SagaContext> {
1221
+ name: string;
1222
+ steps: WorkflowStep<P>[];
1223
+ startOn?: WorkflowStartTrigger<P>;
1224
+ }
1225
+ interface WorkflowSnapshot<P extends SagaContext = SagaContext> {
1226
+ id: string;
1227
+ workflowName: string;
1228
+ status: WorkflowStatus;
1229
+ context: P;
1230
+ completedSteps: string[];
1231
+ currentStep?: string;
1232
+ failedStep?: string;
1233
+ attempts: Record<string, number>;
1234
+ startedAt: string;
1235
+ updatedAt: string;
1236
+ completedAt?: string;
1237
+ error?: string;
1238
+ }
1239
+ interface WorkflowStore {
1240
+ save<P extends SagaContext>(snapshot: WorkflowSnapshot<P>): MaybePromise<void>;
1241
+ get<P extends SagaContext = SagaContext>(id: string): MaybePromise<WorkflowSnapshot<P> | undefined>;
1242
+ list(workflowName?: string): MaybePromise<WorkflowSnapshot[]>;
1243
+ clear(): MaybePromise<void>;
1244
+ }
1245
+ interface WorkflowEngine {
1246
+ register<P extends SagaContext>(definition: WorkflowDefinition<P>): void;
1247
+ start<P extends SagaContext>(workflowName: string, initialPayload: P, options?: {
1248
+ id?: string;
1249
+ }): Promise<WorkflowSnapshot<P>>;
1250
+ get<P extends SagaContext = SagaContext>(id: string): Promise<WorkflowSnapshot<P> | undefined>;
1251
+ list(workflowName?: string): Promise<WorkflowSnapshot[]>;
1252
+ }
1253
+ interface CreateWorkflowEngineOptions {
1254
+ store?: WorkflowStore;
1255
+ auditTrail?: AuditTrail;
1256
+ defaultRetry?: RetryPolicy;
1257
+ }
1258
+ interface SagaStep<P extends SagaContext = SagaContext> extends WorkflowStep<P> {
1259
+ }
1260
+ interface SagaDefinition<P extends SagaContext = SagaContext> {
1261
+ name: string;
1262
+ steps: SagaStep<P>[];
1263
+ }
1264
+ interface SagaInstance<P extends SagaContext = SagaContext> {
1265
+ id: string;
1266
+ definition: SagaDefinition<P>;
1267
+ readonly status: SagaStatus;
1268
+ readonly completedSteps: string[];
1269
+ run(initialPayload: P): Promise<void>;
1270
+ }
1271
+
1272
+ /**
1273
+ * In-process workflow engine with durable-store seams.
1274
+ */
1275
+
1276
+ declare class InMemoryWorkflowStore implements WorkflowStore {
1277
+ private readonly snapshots;
1278
+ save<P extends SagaContext>(snapshot: WorkflowSnapshot<P>): void;
1279
+ get<P extends SagaContext = SagaContext>(id: string): WorkflowSnapshot<P> | undefined;
1280
+ list(workflowName?: string): WorkflowSnapshot[];
1281
+ clear(): void;
1282
+ }
1283
+ declare function createWorkflowEngine(bus: EventBus, options?: CreateWorkflowEngineOptions): WorkflowEngine;
1284
+ declare function createSaga<P extends SagaContext = SagaContext>(def: SagaDefinition<P>, bus: EventBus, options?: CreateWorkflowEngineOptions & {
1285
+ id?: string;
1286
+ }): SagaInstance<P>;
1287
+
1288
+ interface ArkKernel {
1289
+ instanceId: string;
1290
+ profile: ArchitectureProfile;
1291
+ registry: IntentRegistry;
1292
+ graph: DependencyGraph;
1293
+ metadata: MetadataRegistry;
1294
+ auditTrail: AuditTrail;
1295
+ eventContracts: EventContractRegistry;
1296
+ outbox: OutboxStore;
1297
+ projections: ProjectionRegistry;
1298
+ policyEngine: PolicyEngine;
1299
+ eventBus: EventBus;
1300
+ workflowEngine: WorkflowEngine;
1301
+ observability: ObservabilityReporter;
1302
+ publisher<N extends IntentName, P>(source: N | IntentCreator<N, P>): EventPublisher;
1303
+ syncGraph(): void;
1304
+ manifest(): ArkManifest;
1305
+ }
1306
+ interface CreateArkKernelOptions {
1307
+ /**
1308
+ * When true (default), createArkKernel uses the hardened runtime defaults:
1309
+ * strict event contracts and hard observed-layer enforcement.
1310
+ * Set to false only for explicit migration/legacy paths.
1311
+ */
1312
+ strict?: boolean;
1313
+ profile?: ArchitectureProfile;
1314
+ policies?: Policy[];
1315
+ auditTrail?: AuditTrail;
1316
+ eventContracts?: EventContractRegistry;
1317
+ outbox?: OutboxStore;
1318
+ metadata?: MetadataRegistry;
1319
+ projections?: ProjectionRegistry;
1320
+ maxHistorySize?: number;
1321
+ autoApplyProjections?: boolean;
1322
+ strictEventContracts?: boolean;
1323
+ requireKnownSource?: boolean;
1324
+ /**
1325
+ * Enforce observed producer→event layer flows against the profile at runtime.
1326
+ * Defaults to 'hard' when strict is true and 'off' when strict is false.
1327
+ */
1328
+ enforceObservedLayerFlow?: ObservedLayerFlowMode;
1329
+ instanceId?: string;
1330
+ }
1331
+
1332
+ declare function createArkKernel(options?: CreateArkKernelOptions): ArkKernel;
1333
+ declare function createStrictArkKernel(options?: CreateArkKernelOptions): ArkKernel;
1334
+ declare function createLenientArkKernel(options?: CreateArkKernelOptions): ArkKernel;
1335
+
1336
+ interface ArkTestSnapshot {
1337
+ events: DomainEvent[];
1338
+ traces: TraceRecord[];
1339
+ audit: AuditRecord[];
1340
+ outbox: OutboxRecord[];
1341
+ observability: ObservabilityDriftReport;
1342
+ }
1343
+ interface ArkTestHarness {
1344
+ events(intent?: string): DomainEvent[];
1345
+ traces(type?: TraceRecordType): TraceRecord[];
1346
+ audit(query?: AuditQuery): Promise<AuditRecord[]>;
1347
+ outbox(status?: OutboxStatus): Promise<OutboxRecord[]>;
1348
+ observability(): ObservabilityDriftReport;
1349
+ snapshot(): Promise<ArkTestSnapshot>;
1350
+ clear(): Promise<void>;
1351
+ }
1352
+
1353
+ declare function createArkTestHarness(kernel: ArkKernel): ArkTestHarness;
1354
+
1355
+ /**
1356
+ * Ports & Adapters basic contracts.
1357
+ */
1358
+ interface Port<T = unknown> {
1359
+ readonly name: string;
1360
+ readonly ownerLayer?: string;
1361
+ readonly intent?: IntentName;
1362
+ readonly allowedAdapters?: string[];
1363
+ readonly __port?: T;
1364
+ }
1365
+ interface Adapter<T = unknown> {
1366
+ readonly name?: string;
1367
+ readonly layer?: string;
1368
+ readonly intent?: IntentName;
1369
+ readonly port: Port<T>;
1370
+ readonly impl: T;
1371
+ }
1372
+ interface DefinePortOptions {
1373
+ ownerLayer?: string;
1374
+ intent?: IntentName;
1375
+ allowedAdapters?: string[];
1376
+ }
1377
+ interface CreateAdapterOptions {
1378
+ name?: string;
1379
+ layer?: string;
1380
+ intent?: IntentName;
1381
+ requiredKeys?: string[];
1382
+ }
1383
+ /**
1384
+ * Simple contract checker (duck typing + optional required keys).
1385
+ */
1386
+ type ContractCheckResult = {
1387
+ ok: true;
1388
+ } | {
1389
+ ok: false;
1390
+ missing: string[];
1391
+ };
1392
+ interface AdapterGovernanceIssue {
1393
+ ruleId: 'ADAPTER_NOT_ALLOWED_FOR_PORT';
1394
+ message: string;
1395
+ port: string;
1396
+ adapter?: string;
1397
+ }
1398
+ type AdapterGovernanceResult = {
1399
+ ok: true;
1400
+ issues: [];
1401
+ } | {
1402
+ ok: false;
1403
+ issues: AdapterGovernanceIssue[];
1404
+ };
1405
+
1406
+ /**
1407
+ * Ports and Adapters utilities.
1408
+ *
1409
+ * definePort + createAdapter with basic runtime contract validation.
1410
+ */
1411
+
1412
+ declare function definePort<T = unknown>(name: string, options?: DefinePortOptions): Port<T>;
1413
+ declare function createAdapter<T>(port: Port<T>, impl: T, requiredKeysOrOptions?: string[] | CreateAdapterOptions, adapterOptions?: CreateAdapterOptions): Adapter<T>;
1414
+ declare function checkContract(impl: unknown, requiredKeys?: string[]): ContractCheckResult;
1415
+ declare function checkAdapterGovernance(adapter: Adapter): AdapterGovernanceResult;
1416
+
1417
+ /**
1418
+ * AI Code Gate (basic).
1419
+ *
1420
+ * Allows validation of generated source code against the defined architecture.
1421
+ */
1422
+ interface AICodeGateViolation {
1423
+ /** Stable rule identifier for agents and CI pipelines. */
1424
+ ruleId: string;
1425
+ /** @deprecated Use ruleId — kept for backward compatibility. */
1426
+ code: string;
1427
+ message: string;
1428
+ line?: number;
1429
+ suggestion?: string;
1430
+ source?: string;
1431
+ filePath?: string;
1432
+ target?: string;
1433
+ fromLayer?: string;
1434
+ toLayer?: string;
1435
+ details?: unknown;
1436
+ }
1437
+ /** Extension point for external analyzers (AST, semantic, etc.). */
1438
+ interface AIGateExtension<Context = unknown> {
1439
+ readonly name: string;
1440
+ analyze(source: string, context?: Context): AICodeGateViolation[];
1441
+ }
1442
+ interface AICodeGateContext {
1443
+ filePath?: string;
1444
+ agentId?: string;
1445
+ layer?: string;
1446
+ [key: string]: unknown;
1447
+ }
1448
+ interface AICodeGateResult {
1449
+ valid: boolean;
1450
+ violations: AICodeGateViolation[];
1451
+ }
1452
+ interface AICodeGate<Context = AICodeGateContext> {
1453
+ validate(source: string, context?: Context): AICodeGateResult;
1454
+ }
1455
+
1456
+ /**
1457
+ * Basic AI Code Gate implementation.
1458
+ *
1459
+ * Uses simple string heuristics + registered intent names to detect obvious
1460
+ * architectural violations in generated code (e.g. direct infra imports from domain).
1461
+ * Not a full static analyzer — documented limitation.
1462
+ */
1463
+
1464
+ interface AICodeGatePolicyContext<Context = AICodeGateContext> {
1465
+ source: string;
1466
+ context?: Context;
1467
+ }
1468
+ interface AICodeGateOptions<Context = AICodeGateContext> {
1469
+ policies?: Policy<AICodeGatePolicyContext<Context>>[];
1470
+ intents?: Array<string | Pick<IntentCreator<IntentName, unknown>, 'name'>>;
1471
+ /**
1472
+ * Additional forbidden patterns (regex or strings).
1473
+ */
1474
+ forbiddenPatterns?: Array<string | RegExp>;
1475
+ /**
1476
+ * External analyzer extensions (type-only contract; plug in AST tools later).
1477
+ */
1478
+ extensions?: AIGateExtension<Context>[];
1479
+ /**
1480
+ * Optional architecture profile for layer-aware generated-code checks.
1481
+ * When context.layer is provided, intent references are checked against it.
1482
+ */
1483
+ architectureProfile?: ArchitectureProfile;
1484
+ /**
1485
+ * When true, flag string literals that look like intent names but are not registered.
1486
+ */
1487
+ enforceIntentAllowlist?: boolean;
1488
+ /**
1489
+ * Optional TypeScript module object. When provided, AICodeGate adds AST-backed checks
1490
+ * for publish misuse without taking a runtime dependency on TypeScript.
1491
+ */
1492
+ typescript?: unknown;
1493
+ }
1494
+ declare function createAICodeGate<Context = AICodeGateContext>(options?: AICodeGateOptions<Context>): AICodeGate<Context>;
1495
+
1496
+ export { type AICodeGate, type AICodeGateContext, type AICodeGateOptions, type AICodeGateResult, type AICodeGateViolation, type AIGateExtension, type Adapter, type AdapterGovernanceIssue, type AdapterGovernanceResult, type ArchitectureLayer, type ArchitectureLayerConfig, type ArchitectureProfile, type ArchitectureRule, type ArkCheckConfig, type ArkKernel, type ArkManifest, type ArkManifestArchitecture, type ArkManifestData, type ArkManifestEntityLink, type ArkManifestGraph, type ArkManifestIntent, type ArkManifestPolicy, type ArkManifestProjection, type ArkTestHarness, type ArkTestSnapshot, type AuditQuery, type AuditRecord, type AuditRecordInput, type AuditRecordType, type AuditStore, type AuditTrail, type BuildPublishPolicyContextOptions, type ContractCheckResult, type CorrelationId, type CreateAdapterOptions, type CreateArchitectureProfileOptions, type CreateArkKernelOptions, type CreateArkManifestOptions, type CreateAuditTrailOptions, type CreateElevenLayerArkConfigOptions, type CreateObservabilityReporterOptions, type CreateProjectionRegistryOptions, type CreateWorkflowEngineOptions, type DefineIntentOptions, type DefinePolicyOptions, type DefinePortOptions, type DependencyGraph, type DomainEvent, type EntityMeta, type EventBus, type EventBusOptions, type EventContract, type EventContractIssue, type EventContractRegistry, EventContractRegistryImpl, type EventContractValidationResult, EventContractViolationError, type EventHandler, type EventInterceptionInfo, type EventInterceptor, type EventInterceptorContext, type EventMetadata, type EventPayloadPatch, type EventPayloadSchema, type EventPublisher, type EventSchemaField, type EventSchemaFieldType, type FieldMeta, type GraphEdge, type GraphNode, type GraphPolicyContext, InMemoryAuditStore, InMemoryOutboxStore, InMemoryReadModelStore, InMemoryWorkflowStore, type IntentCreator, type IntentCreator as IntentDefinition, type IntentName, type IntentNameValidation, IntentRegistry, type IntentRelationship, type IntentRelationshipKind, InvalidIntentNameError, type LayerFlowRule, LayerPolicyContextError, type LayerPolicyOptions, MANIFEST_SCHEMA_VERSION, type MetadataRegistry, type ObservabilityDriftReport, type ObservabilityFlow, type ObservabilityReporter, type ObservedLayerFlowMode, ObservedLayerFlowViolationError, type OutboxRecord, type OutboxStatus, type OutboxStore, type Policy, type PolicyEnforcementMode, PolicyEngine, type PolicyEvaluationResult, type PolicySeverity, type PolicyViolation, PolicyViolationError, type Port, type ProjectionCheckpoint, type ProjectionDefinition, type ProjectionRegistry, type PublishPolicyContext, type PublishedEventRecord, type ReadModelStore, type RetryPolicy, type SagaDefinition, type SagaInstance, type SagaStatus, type SagaStep, SourceMetadataOverrideError, type SyncRegistryOptions, type TraceRecord, type TraceRecordType, type TraceSink, UnknownEventSourceError, UnregisteredIntentError, type Unsubscribe, type WorkflowDefinition, type WorkflowEngine, type WorkflowSnapshot, type WorkflowStatus, type WorkflowStep, type WorkflowStore, architecturalPolicies, buildPublishPolicyContext, checkAdapterGovernance, checkContract, createAICodeGate, createAdapter, createArchitectureProfile, createArkKernel, createArkManifest, createArkTestHarness, createAuditTrail, createDependencyGraph, createElevenLayerArkConfig, createEventBus, createEventContractRegistry, createIntentRegistry, createLenientArkKernel, createMetadataRegistry, createObservabilityReporter, createProjectionRegistry, createSaga, createStrictArkKernel, createWorkflowEngine, defaultIntentRegistry, defineArchitectureProfilePolicy, defineIntent, defineLayerPolicy, definePolicy, definePort, definePublishPolicy, elevenLayerProfile, isLayerPolicy, syncRegistryToGraph, validateIntentName, version };