agentflow-core 0.6.3 → 0.8.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.
package/dist/index.d.cts CHANGED
@@ -229,6 +229,302 @@ interface DistributedTrace {
229
229
  readonly endTime: number | null;
230
230
  readonly status: GraphStatus;
231
231
  }
232
+ /** A transition between two steps in a discovered process model. */
233
+ interface ProcessTransition {
234
+ /** Source step identifier (`type:name`). */
235
+ readonly from: string;
236
+ /** Target step identifier (`type:name`). */
237
+ readonly to: string;
238
+ /** Absolute frequency: how many times this transition was observed. */
239
+ readonly count: number;
240
+ /** Relative frequency from the source step (0.0–1.0). */
241
+ readonly probability: number;
242
+ }
243
+ /** A process model discovered from multiple execution graphs. */
244
+ interface ProcessModel {
245
+ /** All observed step identifiers (`type:name`). */
246
+ readonly steps: readonly string[];
247
+ /** All observed transitions with frequencies. */
248
+ readonly transitions: readonly ProcessTransition[];
249
+ /** Number of graphs used to build this model. */
250
+ readonly totalGraphs: number;
251
+ /** Agent ID from the input graphs. */
252
+ readonly agentId: string;
253
+ }
254
+ /** A group of execution graphs that share the same structural path. */
255
+ interface Variant {
256
+ /** Canonical path signature for this variant. */
257
+ readonly pathSignature: string;
258
+ /** Number of graphs in this variant. */
259
+ readonly count: number;
260
+ /** Percentage of total graphs (0–100). */
261
+ readonly percentage: number;
262
+ /** IDs of graphs belonging to this variant. */
263
+ readonly graphIds: readonly string[];
264
+ /** First graph in the group (representative example). */
265
+ readonly exampleGraph: ExecutionGraph;
266
+ }
267
+ /** Duration statistics for a node across multiple execution graphs. */
268
+ interface Bottleneck {
269
+ /** Node name (e.g. `"fetch-data"`). */
270
+ readonly nodeName: string;
271
+ /** Node type (e.g. `"tool"`). */
272
+ readonly nodeType: NodeType;
273
+ /** How many graphs contain this node. */
274
+ readonly occurrences: number;
275
+ /** Duration statistics in milliseconds. */
276
+ readonly durations: {
277
+ readonly median: number;
278
+ readonly p95: number;
279
+ readonly p99: number;
280
+ readonly min: number;
281
+ readonly max: number;
282
+ };
283
+ /** Fraction of input graphs that include this node (0–100). */
284
+ readonly percentOfGraphs: number;
285
+ }
286
+ /** Category of deviation detected during conformance checking. */
287
+ type DeviationType = 'unexpected-transition' | 'missing-transition' | 'low-frequency-path';
288
+ /** A specific deviation between a graph and a process model. */
289
+ interface Deviation {
290
+ /** Category of deviation. */
291
+ readonly type: DeviationType;
292
+ /** Source step identifier. */
293
+ readonly from: string;
294
+ /** Target step identifier. */
295
+ readonly to: string;
296
+ /** Human-readable description of the deviation. */
297
+ readonly message: string;
298
+ /** Model probability of this transition (if applicable). */
299
+ readonly modelProbability?: number;
300
+ }
301
+ /** Result of comparing a single graph against a process model. */
302
+ interface ConformanceReport {
303
+ /** Ratio of conforming transitions to total transitions (0.0–1.0). */
304
+ readonly conformanceScore: number;
305
+ /** True when conformanceScore is 1.0 (no deviations). */
306
+ readonly isConforming: boolean;
307
+ /** List of specific deviations found. */
308
+ readonly deviations: readonly Deviation[];
309
+ }
310
+ /**
311
+ * A detected guard violation.
312
+ */
313
+ interface GuardViolation {
314
+ readonly type: 'timeout' | 'reasoning-loop' | 'spawn-explosion' | 'high-failure-rate' | 'conformance-drift' | 'known-bottleneck';
315
+ readonly nodeId: string;
316
+ readonly message: string;
317
+ readonly timestamp: number;
318
+ }
319
+ /** Event type discriminator for AgentFlow events. */
320
+ type AgentFlowEventType = 'execution.completed' | 'execution.failed' | 'pattern.discovered' | 'pattern.updated';
321
+ /** Optional semantic context attached to an execution event by adapters. */
322
+ interface SemanticContext {
323
+ readonly intent?: string;
324
+ readonly trigger?: string;
325
+ readonly inputSummary?: string;
326
+ readonly outputSummary?: string;
327
+ readonly tokenCost?: number;
328
+ readonly modelId?: string;
329
+ }
330
+ /** Process mining context for an execution event. */
331
+ interface ProcessContext {
332
+ readonly variant: string;
333
+ readonly conformanceScore: number;
334
+ readonly isAnomaly: boolean;
335
+ }
336
+ /** The point at which an execution failed. */
337
+ interface FailurePoint {
338
+ readonly nodeId: string;
339
+ readonly nodeName: string;
340
+ readonly nodeType: NodeType;
341
+ readonly error?: string;
342
+ }
343
+ /** A structured event emitted after an agent execution completes or fails. */
344
+ interface ExecutionEvent {
345
+ readonly eventType: 'execution.completed' | 'execution.failed';
346
+ readonly graphId: string;
347
+ readonly agentId: string;
348
+ readonly timestamp: number;
349
+ readonly schemaVersion: number;
350
+ readonly status: GraphStatus;
351
+ readonly duration: number;
352
+ readonly nodeCount: number;
353
+ readonly pathSignature: string;
354
+ readonly failurePoint?: FailurePoint;
355
+ readonly processContext?: ProcessContext;
356
+ readonly semantic?: SemanticContext;
357
+ readonly violations: readonly GuardViolation[];
358
+ }
359
+ /** A structured event emitted when process mining discovers a pattern. */
360
+ interface PatternEvent {
361
+ readonly eventType: 'pattern.discovered' | 'pattern.updated';
362
+ readonly agentId: string;
363
+ readonly timestamp: number;
364
+ readonly schemaVersion: number;
365
+ readonly pattern: {
366
+ readonly totalGraphs: number;
367
+ readonly variantCount: number;
368
+ readonly topVariants: readonly {
369
+ readonly pathSignature: string;
370
+ readonly count: number;
371
+ readonly percentage: number;
372
+ }[];
373
+ readonly topBottlenecks: readonly {
374
+ readonly nodeName: string;
375
+ readonly nodeType: NodeType;
376
+ readonly p95: number;
377
+ }[];
378
+ readonly processModel: ProcessModel;
379
+ };
380
+ }
381
+ /** Options for creating an ExecutionEvent from a graph. */
382
+ interface ExecutionEventOptions {
383
+ readonly processContext?: ProcessContext;
384
+ readonly semantic?: SemanticContext;
385
+ readonly violations?: readonly GuardViolation[];
386
+ }
387
+ /** Configuration for the event emitter. */
388
+ interface EventEmitterConfig {
389
+ readonly writers?: readonly EventWriter[];
390
+ readonly onError?: (error: unknown) => void;
391
+ /** Optional knowledge store for automatic event persistence. */
392
+ readonly knowledgeStore?: KnowledgeStore;
393
+ }
394
+ /**
395
+ * Extended Writer interface that can handle structured events.
396
+ * Backward-compatible — existing Writers are unaffected.
397
+ */
398
+ interface EventWriter extends Writer {
399
+ /** Write a structured event to the output target. */
400
+ writeEvent(event: ExecutionEvent | PatternEvent): Promise<void>;
401
+ }
402
+ /** Event emitter for routing AgentFlow events to writers and subscribers. */
403
+ interface EventEmitter {
404
+ /** Emit an event to all writers and subscribers. */
405
+ emit(event: ExecutionEvent | PatternEvent): Promise<void>;
406
+ /** Subscribe to events. Returns an unsubscribe function. */
407
+ subscribe(listener: (event: ExecutionEvent | PatternEvent) => void): () => void;
408
+ }
409
+ /** Derived per-agent profile accumulated from execution and pattern events. */
410
+ interface AgentProfile {
411
+ readonly agentId: string;
412
+ readonly totalRuns: number;
413
+ readonly successCount: number;
414
+ readonly failureCount: number;
415
+ readonly failureRate: number;
416
+ readonly recentDurations: readonly number[];
417
+ readonly lastConformanceScore: number | null;
418
+ readonly knownBottlenecks: readonly string[];
419
+ readonly lastPatternTimestamp: number | null;
420
+ readonly updatedAt: string;
421
+ }
422
+ /** Configuration for the knowledge store. */
423
+ interface KnowledgeStoreConfig {
424
+ /** Base directory for knowledge storage. Defaults to `.agentflow/knowledge`. */
425
+ readonly baseDir?: string;
426
+ }
427
+ /**
428
+ * Filesystem-based knowledge store that accumulates execution and pattern events.
429
+ * Implements EventWriter so it can be used directly with createEventEmitter.
430
+ */
431
+ interface KnowledgeStore extends EventWriter {
432
+ /** Base directory of the knowledge store. */
433
+ readonly baseDir: string;
434
+ /** Persist an event and update the agent profile. */
435
+ append(event: ExecutionEvent | PatternEvent): void;
436
+ /** Query recent execution events for an agent. */
437
+ getRecentEvents(agentId: string, options?: {
438
+ limit?: number;
439
+ since?: number;
440
+ }): ExecutionEvent[];
441
+ /** Get the derived profile for an agent, or null if no history. */
442
+ getAgentProfile(agentId: string): AgentProfile | null;
443
+ /** Query pattern event history for an agent. */
444
+ getPatternHistory(agentId: string, options?: {
445
+ limit?: number;
446
+ }): PatternEvent[];
447
+ /** Remove event files older than the given timestamp. Profiles are preserved. */
448
+ compact(options: {
449
+ olderThan: number;
450
+ }): {
451
+ removed: number;
452
+ };
453
+ /** Persist an insight event generated by the insight engine. */
454
+ appendInsight(event: InsightEvent): void;
455
+ /** Query recent insight events for an agent. */
456
+ getRecentInsights(agentId: string, options?: {
457
+ type?: string;
458
+ limit?: number;
459
+ }): InsightEvent[];
460
+ }
461
+ /**
462
+ * Read-only interface for querying accumulated knowledge.
463
+ * Used by guards to make adaptive decisions based on execution history.
464
+ */
465
+ interface PolicySource {
466
+ /** Recent failure rate for an agent (0.0–1.0). Returns 0 if no history. */
467
+ recentFailureRate(agentId: string): number;
468
+ /** Whether a node name appears as a known bottleneck across any agent. */
469
+ isKnownBottleneck(nodeName: string): boolean;
470
+ /** Most recent conformance score for an agent, or null if none recorded. */
471
+ lastConformanceScore(agentId: string): number | null;
472
+ /** Full derived profile for an agent, or null if no history. */
473
+ getAgentProfile(agentId: string): AgentProfile | null;
474
+ }
475
+ /**
476
+ * User-provided LLM function. AgentFlow constructs prompts and delegates
477
+ * the actual LLM call to this function. Any provider can be wrapped as an AnalysisFn.
478
+ */
479
+ type AnalysisFn = (prompt: string) => Promise<string>;
480
+ /** A structured event emitted when the insight engine generates an LLM-powered analysis. */
481
+ interface InsightEvent {
482
+ readonly eventType: 'insight.generated';
483
+ readonly agentId: string;
484
+ readonly timestamp: number;
485
+ readonly schemaVersion: number;
486
+ readonly insightType: 'failure-analysis' | 'anomaly-explanation' | 'agent-summary' | 'fix-suggestion';
487
+ /** The prompt that was sent to the AnalysisFn (for auditing). */
488
+ readonly prompt: string;
489
+ /** The LLM response. */
490
+ readonly response: string;
491
+ /** Hash of input data — used for cache identity. */
492
+ readonly dataHash: string;
493
+ }
494
+ /** Result returned by InsightEngine methods. */
495
+ interface InsightResult {
496
+ readonly agentId: string;
497
+ readonly insightType: InsightEvent['insightType'];
498
+ /** The LLM response or pre-computed message. */
499
+ readonly content: string;
500
+ /** Whether this result came from cache. */
501
+ readonly cached: boolean;
502
+ /** When the insight was generated (epoch ms). */
503
+ readonly timestamp: number;
504
+ }
505
+ /** Configuration for the insight engine. */
506
+ interface InsightEngineConfig {
507
+ /** How long cached insights remain valid (ms). Default: 3600000 (1 hour). */
508
+ readonly cacheTtlMs?: number;
509
+ }
510
+ /** LLM-powered semantic analysis engine for agent execution data. */
511
+ interface InsightEngine {
512
+ /** Explain recent failures for an agent in natural language. */
513
+ explainFailures(agentId: string): Promise<InsightResult>;
514
+ /** Explain why a specific execution was anomalous. */
515
+ explainAnomaly(agentId: string, event: ExecutionEvent): Promise<InsightResult>;
516
+ /** Generate a natural language health summary for an agent. */
517
+ summarizeAgent(agentId: string): Promise<InsightResult>;
518
+ /** Suggest actionable fixes based on failure patterns and bottlenecks. */
519
+ suggestFixes(agentId: string): Promise<InsightResult>;
520
+ }
521
+ /** Thresholds for policy-derived guard violations. */
522
+ interface PolicyThresholds {
523
+ /** Maximum acceptable failure rate before triggering a violation (default 0.5). */
524
+ readonly maxFailureRate?: number;
525
+ /** Minimum acceptable conformance score before triggering a violation (default 0.7). */
526
+ readonly minConformance?: number;
527
+ }
232
528
  /** @internal Mutable version of ExecutionNode used during graph construction. */
233
529
  interface MutableExecutionNode {
234
530
  id: string;
@@ -243,6 +539,80 @@ interface MutableExecutionNode {
243
539
  state: Record<string, unknown>;
244
540
  }
245
541
 
542
+ /**
543
+ * Event emission layer for AgentFlow execution intelligence.
544
+ *
545
+ * Transforms completed execution graphs and process mining results into
546
+ * structured, self-describing events consumable by external systems
547
+ * (Soma, dashboards, sentinel agents, custom knowledge engines).
548
+ *
549
+ * @module
550
+ */
551
+
552
+ /**
553
+ * Create a structured ExecutionEvent from a completed execution graph.
554
+ *
555
+ * Pure function — no side effects. The returned event is self-describing:
556
+ * it contains all context needed to understand the execution without
557
+ * reading the original graph.
558
+ *
559
+ * @param graph - The completed execution graph.
560
+ * @param options - Optional process mining context, semantic context, and violations.
561
+ * @returns A structured ExecutionEvent.
562
+ *
563
+ * @example
564
+ * ```ts
565
+ * const event = createExecutionEvent(graph, {
566
+ * processContext: { variant: 'A→B→C', conformanceScore: 0.9, isAnomaly: false },
567
+ * semantic: { intent: 'daily-rebalance', trigger: 'cron' },
568
+ * });
569
+ * ```
570
+ */
571
+ declare function createExecutionEvent(graph: ExecutionGraph, options?: ExecutionEventOptions): ExecutionEvent;
572
+ /**
573
+ * Create a structured PatternEvent from process mining results.
574
+ *
575
+ * Pure function — no side effects. Summarizes the mining results into
576
+ * a compact event with top variants (up to 5) and top bottlenecks (up to 5).
577
+ *
578
+ * @param agentId - The agent these patterns belong to.
579
+ * @param model - The discovered process model.
580
+ * @param variants - Variant analysis results.
581
+ * @param bottlenecks - Bottleneck detection results.
582
+ * @returns A structured PatternEvent.
583
+ *
584
+ * @example
585
+ * ```ts
586
+ * const model = discoverProcess(graphs);
587
+ * const variants = findVariants(graphs);
588
+ * const bottlenecks = getBottlenecks(graphs);
589
+ * const event = createPatternEvent('my-agent', model, variants, bottlenecks);
590
+ * ```
591
+ */
592
+ declare function createPatternEvent(agentId: string, model: ProcessModel, variants: Variant[], bottlenecks: Bottleneck[]): PatternEvent;
593
+ /**
594
+ * Create an event emitter for routing AgentFlow events to writers and subscribers.
595
+ *
596
+ * The emitter is a simple pub/sub — no queuing, no retry, no backpressure.
597
+ * Writer errors are reported via the `onError` callback and do not block emission.
598
+ *
599
+ * @param config - Optional configuration with writers and error handler.
600
+ * @returns An EventEmitter with emit and subscribe methods.
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * const emitter = createEventEmitter({
605
+ * writers: [jsonWriter],
606
+ * onError: (err) => console.error('Event write failed:', err),
607
+ * });
608
+ *
609
+ * emitter.subscribe((event) => console.log('Event:', event.eventType));
610
+ *
611
+ * await emitter.emit(createExecutionEvent(graph));
612
+ * ```
613
+ */
614
+ declare function createEventEmitter(config?: EventEmitterConfig): EventEmitter;
615
+
246
616
  /**
247
617
  * Closure-based factory for constructing execution graphs.
248
618
  *
@@ -276,6 +646,35 @@ interface MutableExecutionNode {
276
646
  */
277
647
  declare function createGraphBuilder(config?: AgentFlowConfig): GraphBuilder;
278
648
 
649
+ /**
650
+ * LLM-powered semantic analysis engine for agent execution data.
651
+ *
652
+ * The insight engine reads from the knowledge store, constructs prompts via
653
+ * pure prompt builder functions, delegates to a user-provided AnalysisFn,
654
+ * and caches results as InsightEvents in the store.
655
+ *
656
+ * @module
657
+ */
658
+
659
+ /**
660
+ * Create an LLM-powered semantic analysis engine.
661
+ *
662
+ * @param store - The knowledge store to read data from and cache insights to.
663
+ * @param analysisFn - User-provided LLM function (prompt → response).
664
+ * @param config - Optional configuration (cache TTL).
665
+ * @returns An InsightEngine for semantic analysis of agent execution data.
666
+ *
667
+ * @example
668
+ * ```ts
669
+ * const engine = createInsightEngine(store, async (prompt) => {
670
+ * return await myLlm.complete(prompt);
671
+ * });
672
+ * const result = await engine.explainFailures('my-agent');
673
+ * console.log(result.content);
674
+ * ```
675
+ */
676
+ declare function createInsightEngine(store: KnowledgeStore, analysisFn: AnalysisFn, config?: InsightEngineConfig): InsightEngine;
677
+
279
678
  /**
280
679
  * Pure query functions for interrogating a built `ExecutionGraph`.
281
680
  * Every function takes a frozen graph and returns derived data without mutation.
@@ -423,16 +822,12 @@ interface GuardConfig {
423
822
  readonly onViolation?: 'warn' | 'error' | 'abort';
424
823
  /** Custom logger for warnings (defaults to console.warn). */
425
824
  readonly logger?: (message: string) => void;
825
+ /** Optional policy source for adaptive guard behavior based on accumulated knowledge. */
826
+ readonly policySource?: PolicySource;
827
+ /** Thresholds for policy-derived violations (only used when policySource is set). */
828
+ readonly policyThresholds?: PolicyThresholds;
426
829
  }
427
- /**
428
- * A detected guard violation.
429
- */
430
- interface GuardViolation {
431
- readonly type: 'timeout' | 'reasoning-loop' | 'spawn-explosion';
432
- readonly nodeId: string;
433
- readonly message: string;
434
- readonly timestamp: number;
435
- }
830
+
436
831
  /**
437
832
  * Check an execution graph for guard violations.
438
833
  *
@@ -475,6 +870,139 @@ declare function checkGuards(graph: ExecutionGraph, config?: GuardConfig): reado
475
870
  */
476
871
  declare function withGuards(builder: GraphBuilder, config?: GuardConfig): GraphBuilder;
477
872
 
873
+ /**
874
+ * JSON file-based event writer for AgentFlow.
875
+ *
876
+ * Writes each event as an individual JSON file to a configurable directory.
877
+ * Designed for filesystem-as-IPC: Soma's Curator (or any file-watching consumer)
878
+ * picks up events from the output directory.
879
+ *
880
+ * @module
881
+ */
882
+
883
+ /**
884
+ * Configuration for the JSON event writer.
885
+ */
886
+ interface JsonEventWriterConfig {
887
+ /** Directory to write event files to. Created if it does not exist. */
888
+ readonly outputDir: string;
889
+ }
890
+ /**
891
+ * Create a JSON event writer that persists events as individual files.
892
+ *
893
+ * Each event is written to `{eventType}-{agentId}-{timestamp}.json` where
894
+ * dots in the eventType are replaced with dashes. Files are formatted with
895
+ * 2-space indentation for human readability.
896
+ *
897
+ * The `write(graph)` method is a no-op — this writer only handles structured events.
898
+ *
899
+ * @param config - Writer configuration with output directory.
900
+ * @returns An EventWriter that writes JSON files.
901
+ *
902
+ * @example
903
+ * ```ts
904
+ * const writer = createJsonEventWriter({ outputDir: './events' });
905
+ * await writer.writeEvent(executionEvent);
906
+ * // Creates: events/execution-completed-my-agent-1710800000000.json
907
+ * ```
908
+ */
909
+ declare function createJsonEventWriter(config: JsonEventWriterConfig): EventWriter;
910
+
911
+ /**
912
+ * Filesystem-based knowledge store for accumulating execution intelligence.
913
+ *
914
+ * Stores execution and pattern events as individual JSON files, organized by
915
+ * agentId and date. Maintains derived agent profiles that summarize execution
916
+ * history for fast querying by guards and dashboards.
917
+ *
918
+ * Storage layout:
919
+ * ```
920
+ * {baseDir}/
921
+ * ├── events/{agentId}/{YYYY-MM-DD}/{eventType}-{timestamp}.json
922
+ * ├── patterns/{agentId}/{timestamp}.json
923
+ * └── profiles/{agentId}.json
924
+ * ```
925
+ *
926
+ * @module
927
+ */
928
+
929
+ /**
930
+ * Create a filesystem-based knowledge store for accumulating execution intelligence.
931
+ *
932
+ * @param config - Optional configuration with base directory path.
933
+ * @returns A KnowledgeStore that persists events and maintains agent profiles.
934
+ *
935
+ * @example
936
+ * ```ts
937
+ * const store = createKnowledgeStore({ baseDir: '.agentflow/knowledge' });
938
+ * store.append(createExecutionEvent(graph));
939
+ * const profile = store.getAgentProfile('my-agent');
940
+ * ```
941
+ */
942
+ declare function createKnowledgeStore(config?: KnowledgeStoreConfig): KnowledgeStore;
943
+
944
+ /**
945
+ * PolicySource: read-only interface over the knowledge store for adaptive guards.
946
+ *
947
+ * Bridges accumulated execution knowledge to guard decisions without
948
+ * coupling guards to storage internals.
949
+ *
950
+ * @module
951
+ */
952
+
953
+ /**
954
+ * Create a PolicySource backed by a knowledge store.
955
+ *
956
+ * All methods delegate to the store's profile data. The PolicySource is a
957
+ * pure read interface — it never writes to the store.
958
+ *
959
+ * @param store - The knowledge store to query.
960
+ * @returns A PolicySource for use with adaptive guards.
961
+ *
962
+ * @example
963
+ * ```ts
964
+ * const store = createKnowledgeStore({ baseDir: '.agentflow/knowledge' });
965
+ * const policy = createPolicySource(store);
966
+ * const rate = policy.recentFailureRate('my-agent'); // 0.0–1.0
967
+ * ```
968
+ */
969
+ declare function createPolicySource(store: KnowledgeStore): PolicySource;
970
+
971
+ /**
972
+ * Soma-compatible event writer for AgentFlow.
973
+ *
974
+ * Converts AgentFlow events (ExecutionEvent, PatternEvent) into Markdown files
975
+ * with YAML frontmatter that Soma's Curator can ingest from its inbox directory.
976
+ *
977
+ * @module
978
+ */
979
+
980
+ /**
981
+ * Configuration for the Soma event writer.
982
+ */
983
+ interface SomaEventWriterConfig {
984
+ /** Directory to write event files to (Soma's inbox). Created if it does not exist. */
985
+ readonly inboxDir: string;
986
+ }
987
+ /**
988
+ * Create a Soma event writer that persists events as Curator-compatible Markdown files.
989
+ *
990
+ * Each event is written to `{type}-{agentId}-{compact-ISO-timestamp}.md` in the
991
+ * configured inbox directory. The Curator picks up these files on its 60-second cycle.
992
+ *
993
+ * @param config - Writer configuration with inbox directory path.
994
+ * @returns An EventWriter that writes Markdown files to the Soma inbox.
995
+ *
996
+ * @example
997
+ * ```ts
998
+ * const writer = createSomaEventWriter({ inboxDir: '~/.openclaw/workspace/inbox' });
999
+ * const emitter = createEventEmitter({ writers: [writer] });
1000
+ * await emitter.emit(createExecutionEvent(graph));
1001
+ * // Creates: ~/.openclaw/workspace/inbox/execution-alfred-20260314T083502.md
1002
+ * ```
1003
+ */
1004
+ declare function createSomaEventWriter(config: SomaEventWriterConfig): EventWriter;
1005
+
478
1006
  /**
479
1007
  * AgentFlow Live Monitor — real-time terminal dashboard for any agent system.
480
1008
  *
@@ -494,6 +1022,58 @@ declare function withGuards(builder: GraphBuilder, config?: GuardConfig): GraphB
494
1022
 
495
1023
  declare function startLive(argv: string[]): void;
496
1024
 
1025
+ /**
1026
+ * Load and deserialize execution graphs from JSON.
1027
+ *
1028
+ * Handles all serialization formats produced by the runner, graph-builder,
1029
+ * and third-party tools:
1030
+ * - `nodes` as a plain object `{ "node_001": { ... } }` (runner.ts output)
1031
+ * - `nodes` as an array of `[id, node]` pairs (Map JSON serialization)
1032
+ * - `nodes` already a Map (in-memory passthrough)
1033
+ *
1034
+ * @module
1035
+ */
1036
+
1037
+ /**
1038
+ * Deserialize a JSON object (or JSON string) into a valid `ExecutionGraph`.
1039
+ *
1040
+ * Use this whenever you read a trace file from disk or receive one over the
1041
+ * network. It normalizes `nodes` into a proper `Map` regardless of the
1042
+ * serialization format.
1043
+ *
1044
+ * @param input - A parsed JSON object, or a JSON string to be parsed.
1045
+ * @returns A valid `ExecutionGraph` ready for use with query functions.
1046
+ * @throws {Error} If the input cannot be parsed or is missing required fields.
1047
+ *
1048
+ * @example
1049
+ * ```ts
1050
+ * import { readFileSync } from 'fs';
1051
+ * import { loadGraph, getStats } from 'agentflow-core';
1052
+ *
1053
+ * const graph = loadGraph(readFileSync('trace.json', 'utf8'));
1054
+ * console.log(getStats(graph));
1055
+ * ```
1056
+ */
1057
+ declare function loadGraph(input: string | Record<string, unknown>): ExecutionGraph;
1058
+ /**
1059
+ * Serialize an `ExecutionGraph` to a plain JSON-safe object.
1060
+ *
1061
+ * The inverse of `loadGraph`. `nodes` is written as a plain object keyed by
1062
+ * node ID, which is the most readable format for trace files on disk.
1063
+ *
1064
+ * @param graph - The execution graph to serialize.
1065
+ * @returns A plain object safe to pass to `JSON.stringify`.
1066
+ *
1067
+ * @example
1068
+ * ```ts
1069
+ * import { writeFileSync } from 'fs';
1070
+ * import { graphToJson } from 'agentflow-core';
1071
+ *
1072
+ * writeFileSync('trace.json', JSON.stringify(graphToJson(graph), null, 2));
1073
+ * ```
1074
+ */
1075
+ declare function graphToJson(graph: ExecutionGraph): Record<string, unknown>;
1076
+
497
1077
  /**
498
1078
  * AgentFlow Process Audit — OS-level process health checks for agent systems.
499
1079
  *
@@ -609,56 +1189,149 @@ declare function auditProcesses(config: ProcessAuditConfig): ProcessAuditResult;
609
1189
  declare function formatAuditReport(result: ProcessAuditResult): string;
610
1190
 
611
1191
  /**
612
- * Load and deserialize execution graphs from JSON.
1192
+ * Pure prompt construction functions for LLM-powered semantic analysis.
613
1193
  *
614
- * Handles all serialization formats produced by the runner, graph-builder,
615
- * and third-party tools:
616
- * - `nodes` as a plain object `{ "node_001": { ... } }` (runner.ts output)
617
- * - `nodes` as an array of `[id, node]` pairs (Map JSON serialization)
618
- * - `nodes` already a Map (in-memory passthrough)
1194
+ * Each function takes knowledge store data and returns a structured prompt string.
1195
+ * No side effects, no filesystem access, no external calls.
619
1196
  *
620
1197
  * @module
621
1198
  */
622
1199
 
623
1200
  /**
624
- * Deserialize a JSON object (or JSON string) into a valid `ExecutionGraph`.
1201
+ * Build a structured prompt for LLM analysis of agent failures.
625
1202
  *
626
- * Use this whenever you read a trace file from disk or receive one over the
627
- * network. It normalizes `nodes` into a proper `Map` regardless of the
628
- * serialization format.
1203
+ * @param events - Recent failed execution events for the agent.
1204
+ * @param profile - The agent's derived profile.
1205
+ * @returns A structured prompt string.
1206
+ */
1207
+ declare function buildFailureAnalysisPrompt(events: ExecutionEvent[], profile: AgentProfile): string;
1208
+ /**
1209
+ * Build a structured prompt for explaining why an execution was anomalous.
629
1210
  *
630
- * @param input - A parsed JSON object, or a JSON string to be parsed.
631
- * @returns A valid `ExecutionGraph` ready for use with query functions.
632
- * @throws {Error} If the input cannot be parsed or is missing required fields.
1211
+ * @param event - The specific execution event flagged as anomalous.
1212
+ * @param profile - The agent's derived profile for baseline context.
1213
+ * @returns A structured prompt string.
1214
+ */
1215
+ declare function buildAnomalyExplanationPrompt(event: ExecutionEvent, profile: AgentProfile): string;
1216
+ /**
1217
+ * Build a structured prompt for generating an agent health summary.
1218
+ *
1219
+ * @param profile - The agent's derived profile.
1220
+ * @param recentEvents - Recent execution events.
1221
+ * @param patterns - Recent pattern discovery events.
1222
+ * @returns A structured prompt string.
1223
+ */
1224
+ declare function buildAgentSummaryPrompt(profile: AgentProfile, recentEvents: ExecutionEvent[], patterns: PatternEvent[]): string;
1225
+ /**
1226
+ * Build a structured prompt for generating actionable fix recommendations.
1227
+ *
1228
+ * @param events - Recent failed execution events.
1229
+ * @param profile - The agent's derived profile.
1230
+ * @param patterns - Recent pattern discovery events.
1231
+ * @returns A structured prompt string.
1232
+ */
1233
+ declare function buildFixSuggestionPrompt(events: ExecutionEvent[], profile: AgentProfile, patterns: PatternEvent[]): string;
1234
+
1235
+ /**
1236
+ * Process mining primitives for cross-run analysis of execution graphs.
1237
+ *
1238
+ * All functions are pure: they take frozen graphs and return derived data
1239
+ * without mutation or side effects. Designed to operate on `ExecutionGraph[]`
1240
+ * collections to discover patterns across multiple agent runs.
1241
+ *
1242
+ * @module
1243
+ */
1244
+
1245
+ /**
1246
+ * Produce a canonical string representation of a graph's execution path.
1247
+ *
1248
+ * Performs a depth-first traversal, emitting `type:name` for each node.
1249
+ * Children are sorted alphabetically by `type:name` to ensure deterministic output.
1250
+ *
1251
+ * @param graph - The execution graph.
1252
+ * @returns A `→`-separated path signature, or `""` if the root is unresolvable.
633
1253
  *
634
1254
  * @example
635
1255
  * ```ts
636
- * import { readFileSync } from 'fs';
637
- * import { loadGraph, getStats } from 'agentflow-core';
1256
+ * const sig = getPathSignature(graph);
1257
+ * // "agent:main→tool:fetch→tool:analyze"
1258
+ * ```
1259
+ */
1260
+ declare function getPathSignature(graph: ExecutionGraph): string;
1261
+ /**
1262
+ * Discover a process model from multiple execution graphs.
638
1263
  *
639
- * const graph = loadGraph(readFileSync('trace.json', 'utf8'));
640
- * console.log(getStats(graph));
1264
+ * Walks every graph's node tree and counts parent→child transitions.
1265
+ * The returned model is a directly-follows graph (DFG) annotated with
1266
+ * absolute and relative frequencies.
1267
+ *
1268
+ * @param graphs - Array of execution graphs (must not be empty).
1269
+ * @returns A process model with steps, transitions, and frequencies.
1270
+ * @throws If `graphs` is empty.
1271
+ *
1272
+ * @example
1273
+ * ```ts
1274
+ * const model = discoverProcess(graphs);
1275
+ * for (const t of model.transitions) {
1276
+ * console.log(`${t.from} → ${t.to} (${(t.probability * 100).toFixed(0)}%)`);
1277
+ * }
641
1278
  * ```
642
1279
  */
643
- declare function loadGraph(input: string | Record<string, unknown>): ExecutionGraph;
1280
+ declare function discoverProcess(graphs: ExecutionGraph[]): ProcessModel;
644
1281
  /**
645
- * Serialize an `ExecutionGraph` to a plain JSON-safe object.
1282
+ * Group execution graphs by their structural path and return variant clusters.
646
1283
  *
647
- * The inverse of `loadGraph`. `nodes` is written as a plain object keyed by
648
- * node ID, which is the most readable format for trace files on disk.
1284
+ * Variants are sorted by frequency (most common first). Ties are broken
1285
+ * alphabetically by path signature.
649
1286
  *
650
- * @param graph - The execution graph to serialize.
651
- * @returns A plain object safe to pass to `JSON.stringify`.
1287
+ * @param graphs - Array of execution graphs.
1288
+ * @returns Variant clusters sorted by frequency descending.
652
1289
  *
653
1290
  * @example
654
1291
  * ```ts
655
- * import { writeFileSync } from 'fs';
656
- * import { graphToJson } from 'agentflow-core';
1292
+ * const variants = findVariants(graphs);
1293
+ * console.log(`${variants[0].percentage}% of runs follow the happy path`);
1294
+ * ```
1295
+ */
1296
+ declare function findVariants(graphs: ExecutionGraph[]): Variant[];
1297
+ /**
1298
+ * Identify performance bottlenecks by aggregating node durations across graphs.
657
1299
  *
658
- * writeFileSync('trace.json', JSON.stringify(graphToJson(graph), null, 2));
1300
+ * Collects duration samples per node `name` (grouped by `type:name`),
1301
+ * computes percentile statistics, and returns results sorted by p95 descending.
1302
+ *
1303
+ * @param graphs - Array of execution graphs.
1304
+ * @returns Bottleneck entries sorted by p95 duration descending.
1305
+ *
1306
+ * @example
1307
+ * ```ts
1308
+ * const bottlenecks = getBottlenecks(graphs);
1309
+ * console.log(`Slowest: ${bottlenecks[0].nodeName} (p95: ${bottlenecks[0].durations.p95}ms)`);
659
1310
  * ```
660
1311
  */
661
- declare function graphToJson(graph: ExecutionGraph): Record<string, unknown>;
1312
+ declare function getBottlenecks(graphs: ExecutionGraph[]): Bottleneck[];
1313
+ /**
1314
+ * Compare a single execution graph against a discovered process model.
1315
+ *
1316
+ * Classifies deviations into three categories:
1317
+ * - `unexpected-transition`: exists in the graph but not in the model
1318
+ * - `missing-transition`: exists in the model with probability > 0.5 but not in the graph
1319
+ * - `low-frequency-path`: exists in both but model probability < 0.1
1320
+ *
1321
+ * @param graph - The execution graph to check.
1322
+ * @param model - The process model to check against.
1323
+ * @returns A conformance report with score, deviations, and conformance flag.
1324
+ *
1325
+ * @example
1326
+ * ```ts
1327
+ * const report = checkConformance(newRun, model);
1328
+ * if (!report.isConforming) {
1329
+ * console.log(`Conformance: ${(report.conformanceScore * 100).toFixed(0)}%`);
1330
+ * for (const d of report.deviations) console.log(d.message);
1331
+ * }
1332
+ * ```
1333
+ */
1334
+ declare function checkConformance(graph: ExecutionGraph, model: ProcessModel): ConformanceReport;
662
1335
 
663
1336
  /**
664
1337
  * CLI runner that wraps any command with automatic AgentFlow tracing.
@@ -857,4 +1530,4 @@ interface AlertPayload {
857
1530
  readonly dirs: readonly string[];
858
1531
  }
859
1532
 
860
- export { type Adapter, type AgentFlowConfig, type AlertCondition, type AlertPayload, type DistributedTrace, type EdgeType, type ExecutionEdge, type ExecutionGraph, type ExecutionNode, type GraphBuilder, type GraphStats, type GraphStatus, type GuardConfig, type GuardViolation, type MutableExecutionNode, type NodeStatus, type NodeType, type NotifyChannel, type OsProcess, type PidFileResult, type ProcessAuditConfig, type ProcessAuditResult, type RunConfig, type RunResult, type StartNodeOptions, type SystemdUnitResult, type TraceEvent, type TraceEventType, type TraceStore, type WatchConfig, type WorkerEntry, type WorkersResult, type Writer, auditProcesses, checkGuards, createGraphBuilder, createTraceStore, discoverProcessConfig, findWaitingOn, formatAuditReport, getChildren, getCriticalPath, getDepth, getDuration, getFailures, getHungNodes, getNode, getParent, getStats, getSubtree, getTraceTree, graphToJson, groupByTraceId, loadGraph, runTraced, startLive, startWatch, stitchTrace, toAsciiTree, toTimeline, withGuards };
1533
+ export { type Adapter, type AgentFlowConfig, type AgentFlowEventType, type AgentProfile, type AlertCondition, type AlertPayload, type AnalysisFn, type Bottleneck, type ConformanceReport, type Deviation, type DeviationType, type DistributedTrace, type EdgeType, type EventEmitter, type EventEmitterConfig, type EventWriter, type ExecutionEdge, type ExecutionEvent, type ExecutionEventOptions, type ExecutionGraph, type ExecutionNode, type FailurePoint, type GraphBuilder, type GraphStats, type GraphStatus, type GuardConfig, type GuardViolation, type InsightEngine, type InsightEngineConfig, type InsightEvent, type InsightResult, type JsonEventWriterConfig, type KnowledgeStore, type KnowledgeStoreConfig, type MutableExecutionNode, type NodeStatus, type NodeType, type NotifyChannel, type OsProcess, type PatternEvent, type PidFileResult, type PolicySource, type PolicyThresholds, type ProcessAuditConfig, type ProcessAuditResult, type ProcessContext, type ProcessModel, type ProcessTransition, type RunConfig, type RunResult, type SemanticContext, type SomaEventWriterConfig, type StartNodeOptions, type SystemdUnitResult, type TraceEvent, type TraceEventType, type TraceStore, type Variant, type WatchConfig, type WorkerEntry, type WorkersResult, type Writer, auditProcesses, buildAgentSummaryPrompt, buildAnomalyExplanationPrompt, buildFailureAnalysisPrompt, buildFixSuggestionPrompt, checkConformance, checkGuards, createEventEmitter, createExecutionEvent, createGraphBuilder, createInsightEngine, createJsonEventWriter, createKnowledgeStore, createPatternEvent, createPolicySource, createSomaEventWriter, createTraceStore, discoverProcess, discoverProcessConfig, findVariants, findWaitingOn, formatAuditReport, getBottlenecks, getChildren, getCriticalPath, getDepth, getDuration, getFailures, getHungNodes, getNode, getParent, getPathSignature, getStats, getSubtree, getTraceTree, graphToJson, groupByTraceId, loadGraph, runTraced, startLive, startWatch, stitchTrace, toAsciiTree, toTimeline, withGuards };