claude-flow 3.67.0 → 3.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.claude/skills/agentdb-advanced/SKILL.md +1 -1
  2. package/.claude/skills/agentdb-learning/SKILL.md +1 -1
  3. package/.claude/skills/agentdb-memory-patterns/SKILL.md +1 -1
  4. package/.claude/skills/agentdb-optimization/SKILL.md +1 -1
  5. package/.claude/skills/agentdb-vector-search/SKILL.md +1 -1
  6. package/.claude/skills/hooks-automation/SKILL.md +1 -1
  7. package/.claude/skills/pair-programming/SKILL.md +1 -1
  8. package/.claude/skills/reasoningbank-agentdb/SKILL.md +1 -1
  9. package/.claude/skills/reasoningbank-intelligence/SKILL.md +1 -1
  10. package/.claude/skills/skill-builder/SKILL.md +1 -1
  11. package/.claude/skills/swarm-orchestration/SKILL.md +1 -1
  12. package/.claude/skills/v3-cli-modernization/SKILL.md +1 -1
  13. package/.claude/skills/v3-core-implementation/SKILL.md +1 -1
  14. package/.claude/skills/v3-ddd-architecture/SKILL.md +1 -1
  15. package/.claude/skills/v3-integration-deep/SKILL.md +1 -1
  16. package/.claude/skills/v3-mcp-optimization/SKILL.md +1 -1
  17. package/.claude/skills/v3-memory-unification/SKILL.md +1 -1
  18. package/.claude/skills/v3-performance-optimization/SKILL.md +1 -1
  19. package/.claude/skills/v3-security-overhaul/SKILL.md +1 -1
  20. package/.claude/skills/v3-swarm-coordination/SKILL.md +1 -1
  21. package/.claude/skills/verification-quality/SKILL.md +1 -1
  22. package/.claude-plugin/marketplace.json +22 -0
  23. package/README.md +2 -0
  24. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/policy-engine.d.ts +1 -0
  25. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/policy-engine.d.ts.map +1 -1
  26. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/policy-engine.js +8 -0
  27. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/policy-engine.js.map +1 -1
  28. package/node_modules/@claude-flow/plugin-agent-federation/dist/domain/entities/trust-level.d.ts.map +1 -1
  29. package/node_modules/@claude-flow/plugin-agent-federation/dist/domain/entities/trust-level.js +9 -2
  30. package/node_modules/@claude-flow/plugin-agent-federation/dist/domain/entities/trust-level.js.map +1 -1
  31. package/node_modules/@claude-flow/security/dist/input-validator.d.ts +6 -6
  32. package/package.json +3 -3
  33. package/v3/@claude-flow/cli/README.md +2 -0
  34. package/v3/@claude-flow/cli/catalog-manifest.json +3 -3
  35. package/v3/@claude-flow/cli/dist/src/commands/hooks.js +18 -4
  36. package/v3/@claude-flow/cli/dist/src/commands/workflow.js +3 -1
  37. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +31 -14
  38. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-episode-tools.d.ts +16 -0
  39. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-episode-tools.js +214 -0
  40. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.d.ts +1 -0
  41. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.js +59 -1
  42. package/v3/@claude-flow/cli/dist/src/mcp-tools/claims-tools.js +7 -3
  43. package/v3/@claude-flow/cli/dist/src/mcp-tools/config-tools.js +48 -22
  44. package/v3/@claude-flow/cli/dist/src/mcp-tools/coordination-tools.js +5 -2
  45. package/v3/@claude-flow/cli/dist/src/mcp-tools/daa-tools.js +12 -5
  46. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +46 -7
  47. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.d.ts +10 -0
  48. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +15 -2
  49. package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.js +9 -4
  50. package/v3/@claude-flow/cli/dist/src/memory/episode-crud.d.ts +70 -0
  51. package/v3/@claude-flow/cli/dist/src/memory/episode-crud.js +114 -0
  52. package/v3/@claude-flow/cli/dist/src/memory/ewc-consolidation.d.ts +7 -0
  53. package/v3/@claude-flow/cli/dist/src/memory/ewc-consolidation.js +19 -1
  54. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +49 -0
  55. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +181 -43
  56. package/v3/@claude-flow/cli/dist/src/mods/command-registry/schema.d.ts +6 -6
  57. package/v3/@claude-flow/cli/package.json +5 -5
  58. package/.claude/.proven-config-version +0 -1
  59. package/.claude/proven-config.json +0 -42
@@ -19,5 +19,15 @@ export interface MemoryCaptureReport {
19
19
  };
20
20
  error?: string;
21
21
  }
22
+ /**
23
+ * #4404: snapshot map ID for a live (namespace, key) row. A bare
24
+ * `namespace::key` join collides when either part contains `::`
25
+ * (`team::alice`/`profile` vs `team`/`alice::profile`), so one row was
26
+ * dropped on save and a distinct sibling row was skipped as a mirror. `%` and
27
+ * `:` are percent-escaped in each part, which keeps ordinary IDs unchanged.
28
+ * Restore reads the explicit namespace/key fields, never this ID, so older
29
+ * snapshots restore as before.
30
+ */
31
+ export declare function memorySnapshotId(namespace: string, key: string): string;
22
32
  export declare const sessionTools: MCPTool[];
23
33
  //# sourceMappingURL=session-tools.d.ts.map
@@ -115,6 +115,19 @@ function listSessions() {
115
115
  /** Snapshot format written by session_save since #3573. */
116
116
  const MEMORY_SNAPSHOT_FORMAT = 'ruflo-session-memory/2';
117
117
  const MEMORY_PAGE_SIZE = 500;
118
+ /**
119
+ * #4404: snapshot map ID for a live (namespace, key) row. A bare
120
+ * `namespace::key` join collides when either part contains `::`
121
+ * (`team::alice`/`profile` vs `team`/`alice::profile`), so one row was
122
+ * dropped on save and a distinct sibling row was skipped as a mirror. `%` and
123
+ * `:` are percent-escaped in each part, which keeps ordinary IDs unchanged.
124
+ * Restore reads the explicit namespace/key fields, never this ID, so older
125
+ * snapshots restore as before.
126
+ */
127
+ export function memorySnapshotId(namespace, key) {
128
+ const escape = (part) => part.replace(/%/g, '%25').replace(/:/g, '%3A');
129
+ return `${escape(namespace)}::${escape(key)}`;
130
+ }
118
131
  async function readLiveEntries(listEntries, dbPath, encryptWrites) {
119
132
  const rows = [];
120
133
  // Bounded: stop on a short page, once `total` rows are in hand, or after a
@@ -170,7 +183,7 @@ async function captureMemorySnapshot() {
170
183
  if (existsSync(primary)) {
171
184
  sawStore = true;
172
185
  for (const row of await readLiveEntries(listEntries, primary)) {
173
- const id = `${row.namespace}::${row.key}`;
186
+ const id = memorySnapshotId(row.namespace, row.key);
174
187
  seen.add(id);
175
188
  entries[id] = {
176
189
  key: row.key, value: row.content ?? '', namespace: row.namespace,
@@ -189,7 +202,7 @@ async function captureMemorySnapshot() {
189
202
  sawStore = true;
190
203
  // The AgentDB store is read by native SQLite and must stay plaintext.
191
204
  for (const row of await readLiveEntries(listEntries, sibling, false)) {
192
- const id = `${row.namespace}::${row.key}`;
205
+ const id = memorySnapshotId(row.namespace, row.key);
193
206
  if (seen.has(id))
194
207
  continue;
195
208
  seen.add(id);
@@ -173,11 +173,13 @@ export const workflowTools = [
173
173
  name: task || `${templateName} workflow`,
174
174
  description: task,
175
175
  steps,
176
- status: 'running',
176
+ // #4609: nothing is dispatched here, so this is not a run yet. Saving it
177
+ // as 'running' made workflow_execute and workflow_delete refuse it.
178
+ // 'ready' matches workflow_create; workflow_execute starts it.
179
+ status: 'ready',
177
180
  currentStep: 0,
178
181
  variables: { template: templateName, ...options },
179
182
  createdAt: new Date().toISOString(),
180
- startedAt: new Date().toISOString(),
181
183
  };
182
184
  store.workflows[workflowId] = workflow;
183
185
  saveWorkflowStore(store);
@@ -185,14 +187,17 @@ export const workflowTools = [
185
187
  return {
186
188
  workflowId,
187
189
  template: templateName,
188
- status: dryRun ? 'validated' : 'running',
190
+ status: dryRun ? 'validated' : 'ready',
189
191
  stages,
190
192
  metrics: {
191
193
  totalStages: stages.length,
192
194
  completedStages: 0,
193
195
  agentsSpawned: 0,
194
- estimatedDuration: `${stages.length * 30}s`,
196
+ estimatedDuration: 'unknown',
195
197
  },
198
+ ...(dryRun ? {} : {
199
+ nextStep: 'Start it with workflow_execute; task steps need config.agentId or options.defaultAgentId.',
200
+ }),
196
201
  };
197
202
  },
198
203
  },
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Episode get / list / update / delete over agentdb 3.3's ReflexionMemory (ADR-520).
3
+ *
4
+ * Episodes are what session ends and `memory distill` record, and what
5
+ * `agentdb_episode-recall` searches. agentdb 3.3 keeps the id on update and moves the row,
6
+ * embedding, vector entry and keyword index together; this module only validates, bounds
7
+ * what goes back over MCP, and feature-detects older agentdb builds.
8
+ *
9
+ * @module v3/cli/memory/episode-crud
10
+ */
11
+ export declare const EPISODE_CRUD_UNAVAILABLE = "Episode get/list/update/delete needs agentdb >= 3.3.0 with ReflexionMemory available.";
12
+ export interface EpisodeView {
13
+ id: number;
14
+ sessionId: string;
15
+ task: string;
16
+ input?: string;
17
+ output?: string;
18
+ critique?: string;
19
+ reward: number;
20
+ success: boolean;
21
+ latencyMs?: number;
22
+ tokensUsed?: number;
23
+ tags?: string[];
24
+ metadata?: Record<string, unknown>;
25
+ ts?: number;
26
+ }
27
+ export interface EpisodePatch {
28
+ task?: string;
29
+ input?: string | null;
30
+ output?: string | null;
31
+ critique?: string | null;
32
+ reward?: number;
33
+ success?: boolean;
34
+ tags?: string[] | null;
35
+ metadata?: Record<string, unknown> | null;
36
+ }
37
+ export type CrudResult<T> = {
38
+ success: true;
39
+ } & T | {
40
+ success: false;
41
+ error: string;
42
+ };
43
+ /** Strict positive integer id. "12-notes" must never reach a delete as 12. */
44
+ export declare function parseEpisodeId(value: unknown): number | null;
45
+ export declare function bridgeGetEpisode(id: number, dbPath?: string): Promise<CrudResult<{
46
+ episode: EpisodeView | null;
47
+ }> | null>;
48
+ export declare function bridgeListEpisodes(options: {
49
+ sessionId?: string;
50
+ success?: boolean;
51
+ limit?: number;
52
+ offset?: number;
53
+ order?: 'newest' | 'oldest';
54
+ }, dbPath?: string): Promise<CrudResult<{
55
+ episodes: EpisodeView[];
56
+ total: number;
57
+ limit: number;
58
+ offset: number;
59
+ }> | null>;
60
+ export declare function bridgeUpdateEpisode(id: number, patch: EpisodePatch, options?: {
61
+ replaceMetadata?: boolean;
62
+ }, dbPath?: string): Promise<CrudResult<{
63
+ episode: EpisodeView | null;
64
+ reembedded: boolean;
65
+ changedFields: string[];
66
+ }> | null>;
67
+ export declare function bridgeDeleteEpisode(id: number, dbPath?: string): Promise<CrudResult<{
68
+ deleted: boolean;
69
+ }> | null>;
70
+ //# sourceMappingURL=episode-crud.d.ts.map
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Episode get / list / update / delete over agentdb 3.3's ReflexionMemory (ADR-520).
3
+ *
4
+ * Episodes are what session ends and `memory distill` record, and what
5
+ * `agentdb_episode-recall` searches. agentdb 3.3 keeps the id on update and moves the row,
6
+ * embedding, vector entry and keyword index together; this module only validates, bounds
7
+ * what goes back over MCP, and feature-detects older agentdb builds.
8
+ *
9
+ * @module v3/cli/memory/episode-crud
10
+ */
11
+ import { withReflexionController } from './memory-bridge.js';
12
+ const TEXT_OUT_MAX = 4_000;
13
+ const LIST_MAX = 100;
14
+ export const EPISODE_CRUD_UNAVAILABLE = 'Episode get/list/update/delete needs agentdb >= 3.3.0 with ReflexionMemory available.';
15
+ /** Strict positive integer id. "12-notes" must never reach a delete as 12. */
16
+ export function parseEpisodeId(value) {
17
+ const n = typeof value === 'number' ? value
18
+ : typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value.trim())
19
+ : NaN;
20
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
21
+ }
22
+ const clip = (v) => typeof v === 'string' && v.length > 0 ? v.slice(0, TEXT_OUT_MAX) : undefined;
23
+ /** Bound what goes back over MCP and drop the embedding. */
24
+ function view(e) {
25
+ return {
26
+ id: Number(e.id),
27
+ sessionId: String(e.sessionId ?? ''),
28
+ task: String(e.task ?? '').slice(0, TEXT_OUT_MAX),
29
+ ...(clip(e.input) !== undefined ? { input: clip(e.input) } : {}),
30
+ ...(clip(e.output) !== undefined ? { output: clip(e.output) } : {}),
31
+ ...(clip(e.critique) !== undefined ? { critique: clip(e.critique) } : {}),
32
+ reward: Number(e.reward ?? 0),
33
+ success: !!e.success,
34
+ ...(typeof e.latencyMs === 'number' ? { latencyMs: e.latencyMs } : {}),
35
+ ...(typeof e.tokensUsed === 'number' ? { tokensUsed: e.tokensUsed } : {}),
36
+ ...(Array.isArray(e.tags) ? { tags: e.tags.slice(0, 64) } : {}),
37
+ ...(e.metadata && typeof e.metadata === 'object' ? { metadata: e.metadata } : {}),
38
+ ...(typeof e.ts === 'number' ? { ts: e.ts } : {}),
39
+ };
40
+ }
41
+ const supports = (r, method) => typeof r?.[method] === 'function';
42
+ /** agentdb throws ValidationError subclasses for bad input; pass their message through, bounded. */
43
+ function failure(error) {
44
+ const msg = error instanceof Error ? error.message : String(error);
45
+ return { success: false, error: msg.replace(/\/[^\s:]+\//g, '<path>/').slice(0, 500) };
46
+ }
47
+ export async function bridgeGetEpisode(id, dbPath) {
48
+ return withReflexionController(dbPath, async (r) => {
49
+ if (!supports(r, 'getEpisode'))
50
+ return { success: false, error: EPISODE_CRUD_UNAVAILABLE };
51
+ try {
52
+ const e = r.getEpisode(id);
53
+ return { success: true, episode: e ? view(e) : null };
54
+ }
55
+ catch (err) {
56
+ return failure(err);
57
+ }
58
+ });
59
+ }
60
+ export async function bridgeListEpisodes(options, dbPath) {
61
+ return withReflexionController(dbPath, async (r) => {
62
+ if (!supports(r, 'listEpisodes'))
63
+ return { success: false, error: EPISODE_CRUD_UNAVAILABLE };
64
+ try {
65
+ const page = r.listEpisodes({ ...options, limit: Math.min(options.limit ?? 20, LIST_MAX) });
66
+ return {
67
+ success: true,
68
+ episodes: page.items.map(view),
69
+ total: Number(page.total),
70
+ limit: Number(page.limit),
71
+ offset: Number(page.offset),
72
+ };
73
+ }
74
+ catch (err) {
75
+ return failure(err);
76
+ }
77
+ });
78
+ }
79
+ export async function bridgeUpdateEpisode(id, patch, options = {}, dbPath) {
80
+ return withReflexionController(dbPath, async (r) => {
81
+ if (!supports(r, 'updateEpisode'))
82
+ return { success: false, error: EPISODE_CRUD_UNAVAILABLE };
83
+ try {
84
+ const res = await r.updateEpisode(id, patch, { replaceMetadata: options.replaceMetadata === true });
85
+ if (!res)
86
+ return { success: true, episode: null, reembedded: false, changedFields: [] };
87
+ return {
88
+ success: true,
89
+ episode: view(res.episode),
90
+ reembedded: !!res.reembedded,
91
+ changedFields: Array.isArray(res.changedFields) ? res.changedFields : [],
92
+ };
93
+ }
94
+ catch (err) {
95
+ return failure(err);
96
+ }
97
+ });
98
+ }
99
+ export async function bridgeDeleteEpisode(id, dbPath) {
100
+ return withReflexionController(dbPath, async (r) => {
101
+ // deleteEpisode predates 3.3, but before 3.3 it parsed ids with parseInt and never removed
102
+ // the vector entry; gate on getEpisode so only the fixed implementation is used.
103
+ if (!supports(r, 'getEpisode') || !supports(r, 'deleteEpisode')) {
104
+ return { success: false, error: EPISODE_CRUD_UNAVAILABLE };
105
+ }
106
+ try {
107
+ return { success: true, deleted: (await r.deleteEpisode(id)) === true };
108
+ }
109
+ catch (err) {
110
+ return failure(err);
111
+ }
112
+ });
113
+ }
114
+ //# sourceMappingURL=episode-crud.js.map
@@ -125,6 +125,13 @@ export interface EWCStats {
125
125
  /** Storage size in bytes */
126
126
  storageSizeBytes: number;
127
127
  }
128
+ /**
129
+ * #3475: `CLAUDE_FLOW_FISHER_DECAY` overrides the default Fisher EMA decay
130
+ * rate. Only a finite number in (0, 1] is honoured; anything else is ignored
131
+ * and the default stands. An explicit `fisherDecayRate` passed to the
132
+ * constructor still wins.
133
+ */
134
+ export declare function fisherDecayRateFromEnv(env?: NodeJS.ProcessEnv): number | undefined;
128
135
  /**
129
136
  * EWC++ Consolidator
130
137
  * Implements Elastic Weight Consolidation with online updates
@@ -44,6 +44,19 @@ const DEFAULT_EWC_CONFIG = {
44
44
  onlineMode: true,
45
45
  dimensions: 384
46
46
  };
47
+ /**
48
+ * #3475: `CLAUDE_FLOW_FISHER_DECAY` overrides the default Fisher EMA decay
49
+ * rate. Only a finite number in (0, 1] is honoured; anything else is ignored
50
+ * and the default stands. An explicit `fisherDecayRate` passed to the
51
+ * constructor still wins.
52
+ */
53
+ export function fisherDecayRateFromEnv(env = process.env) {
54
+ const raw = env.CLAUDE_FLOW_FISHER_DECAY;
55
+ if (raw === undefined || raw.trim() === '')
56
+ return undefined;
57
+ const value = Number(raw);
58
+ return Number.isFinite(value) && value > 0 && value <= 1 ? value : undefined;
59
+ }
47
60
  // ============================================================================
48
61
  // EWC Consolidator Class
49
62
  // ============================================================================
@@ -60,7 +73,12 @@ export class EWCConsolidator {
60
73
  consolidationHistory = [];
61
74
  initialized = false;
62
75
  constructor(config) {
63
- this.config = { ...DEFAULT_EWC_CONFIG, ...config };
76
+ const envDecay = fisherDecayRateFromEnv();
77
+ this.config = {
78
+ ...DEFAULT_EWC_CONFIG,
79
+ ...(envDecay !== undefined ? { fisherDecayRate: envDecay } : {}),
80
+ ...config,
81
+ };
64
82
  this.globalFisher = new Array(this.config.dimensions).fill(0);
65
83
  }
66
84
  /**
@@ -507,6 +507,48 @@ export declare function bridgeDeleteCausalNode(options: {
507
507
  guarded?: boolean;
508
508
  error?: string;
509
509
  } | null>;
510
+ export interface RecalledEpisode {
511
+ id?: number;
512
+ sessionId: string;
513
+ task: string;
514
+ critique?: string;
515
+ reward: number;
516
+ success: boolean;
517
+ similarity?: number;
518
+ tags?: string[];
519
+ ts?: number;
520
+ }
521
+ export interface EpisodeRecallOptions {
522
+ task: string;
523
+ k?: number;
524
+ /** Keyword + vector fusion. Default true (agentdb's own default). */
525
+ hybrid?: boolean;
526
+ /** Cross-encoder rerank. Default false: ~200 ms on CPU, 23 MB model on first use. */
527
+ rerank?: boolean;
528
+ onlySuccesses?: boolean;
529
+ onlyFailures?: boolean;
530
+ minReward?: number;
531
+ timeWindowDays?: number;
532
+ }
533
+ /**
534
+ * Recall past episodes relevant to a task. Episodes come from session ends
535
+ * and from `memory distill`. Ranking is agentdb's keyword + vector fusion,
536
+ * optionally reranked by a local cross-encoder.
537
+ */
538
+ export declare function bridgeRecallEpisodes(options: EpisodeRecallOptions & {
539
+ dbPath?: string;
540
+ }): Promise<{
541
+ success: boolean;
542
+ controller: string;
543
+ episodes: RecalledEpisode[];
544
+ hybrid: boolean;
545
+ rerank: boolean;
546
+ } | null>;
547
+ /**
548
+ * Run `fn` against the ReflexionMemory controller inside one bridge operation, so a shutdown waits
549
+ * for it (ADR-520). Null when the bridge or the controller is unavailable.
550
+ */
551
+ export declare function withReflexionController<T>(dbPath: string | undefined, fn: (reflexion: any) => Promise<T>): Promise<T | null>;
510
552
  /**
511
553
  * Start a session with ReflexionMemory episodic replay.
512
554
  * Loads relevant past session patterns for the new session.
@@ -515,11 +557,17 @@ export declare function bridgeSessionStart(options: {
515
557
  sessionId: string;
516
558
  context?: string;
517
559
  dbPath?: string;
560
+ /** Recall past session episodes relevant to `context`. Default false. */
561
+ recall?: boolean;
562
+ k?: number;
563
+ hybrid?: boolean;
564
+ rerank?: boolean;
518
565
  }): Promise<{
519
566
  success: boolean;
520
567
  controller: string;
521
568
  restoredPatterns: number;
522
569
  sessionId: string;
570
+ episodes?: RecalledEpisode[];
523
571
  } | null>;
524
572
  /**
525
573
  * End a session and persist episodic summary to ReflexionMemory.
@@ -534,6 +582,7 @@ export declare function bridgeSessionEnd(options: {
534
582
  success: boolean;
535
583
  controller: string;
536
584
  persisted: boolean;
585
+ episodeId?: number;
537
586
  } | null>;
538
587
  /**
539
588
  * Route a task via AgentDB's SemanticRouter.
@@ -2952,6 +2952,77 @@ export async function bridgeDeleteCausalNode(options) {
2952
2952
  return null;
2953
2953
  }
2954
2954
  }
2955
+ // ===== Episode recall (agentdb 3.2 hybrid retrieval, ADR-519) =====
2956
+ const EPISODE_TASK_MAX = 4_000;
2957
+ const EPISODE_TEXT_MAX = 2_000;
2958
+ const EPISODE_RECALL_MAX = 50;
2959
+ /** #3908: upper bound on the session-end NightlyLearner sweep. */
2960
+ const SESSION_END_CONSOLIDATE_TIMEOUT_MS = 10_000;
2961
+ /** Null when the registry has no ReflexionMemory with retrieveRelevant. */
2962
+ async function recallEpisodesFrom(registry, options) {
2963
+ const reflexion = registry.get('reflexion');
2964
+ if (!reflexion || typeof reflexion.retrieveRelevant !== 'function')
2965
+ return null;
2966
+ const k = Math.min(Math.max(Math.trunc(options.k ?? 5), 1), EPISODE_RECALL_MAX);
2967
+ const rows = await reflexion.retrieveRelevant({
2968
+ task: options.task,
2969
+ k,
2970
+ hybrid: options.hybrid !== false,
2971
+ rerank: options.rerank === true,
2972
+ ...(options.onlySuccesses ? { onlySuccesses: true } : {}),
2973
+ ...(options.onlyFailures ? { onlyFailures: true } : {}),
2974
+ ...(typeof options.minReward === 'number' ? { minReward: options.minReward } : {}),
2975
+ ...(typeof options.timeWindowDays === 'number' ? { timeWindowDays: options.timeWindowDays } : {}),
2976
+ });
2977
+ if (!Array.isArray(rows))
2978
+ return [];
2979
+ // Drop the embedding (1.5 KB of floats per row) and bound the text fields:
2980
+ // this goes back over MCP.
2981
+ return rows.slice(0, k).map(r => ({
2982
+ ...(typeof r.id === 'number' ? { id: r.id } : {}),
2983
+ sessionId: String(r.sessionId ?? ''),
2984
+ task: String(r.task ?? '').slice(0, EPISODE_TEXT_MAX),
2985
+ ...(r.critique ? { critique: String(r.critique).slice(0, EPISODE_TEXT_MAX) } : {}),
2986
+ reward: Number(r.reward ?? 0),
2987
+ success: !!r.success,
2988
+ ...(typeof r.similarity === 'number' ? { similarity: Math.round(r.similarity * 1e4) / 1e4 } : {}),
2989
+ ...(Array.isArray(r.tags) ? { tags: r.tags.slice(0, 20) } : {}),
2990
+ ...(typeof r.ts === 'number' ? { ts: r.ts } : {}),
2991
+ }));
2992
+ }
2993
+ /**
2994
+ * Recall past episodes relevant to a task. Episodes come from session ends
2995
+ * and from `memory distill`. Ranking is agentdb's keyword + vector fusion,
2996
+ * optionally reranked by a local cross-encoder.
2997
+ */
2998
+ export async function bridgeRecallEpisodes(options) {
2999
+ if (!operationContext.getStore()?.active)
3000
+ return withBridgeOperation(() => bridgeRecallEpisodes(options));
3001
+ const registry = await getRegistry(options.dbPath);
3002
+ if (!registry)
3003
+ return null;
3004
+ const episodes = await recallEpisodesFrom(registry, options);
3005
+ if (!episodes)
3006
+ return null;
3007
+ return {
3008
+ success: true,
3009
+ controller: 'reflexion',
3010
+ episodes,
3011
+ hybrid: options.hybrid !== false,
3012
+ rerank: options.rerank === true,
3013
+ };
3014
+ }
3015
+ /**
3016
+ * Run `fn` against the ReflexionMemory controller inside one bridge operation, so a shutdown waits
3017
+ * for it (ADR-520). Null when the bridge or the controller is unavailable.
3018
+ */
3019
+ export async function withReflexionController(dbPath, fn) {
3020
+ if (!operationContext.getStore()?.active)
3021
+ return withBridgeOperation(() => withReflexionController(dbPath, fn));
3022
+ const registry = await getRegistry(dbPath);
3023
+ const reflexion = registry?.get?.('reflexion');
3024
+ return reflexion ? fn(reflexion) : null;
3025
+ }
2955
3026
  // ===== Phase 5: ReflexionMemory session lifecycle =====
2956
3027
  /**
2957
3028
  * Start a session with ReflexionMemory episodic replay.
@@ -2966,20 +3037,36 @@ export async function bridgeSessionStart(options) {
2966
3037
  try {
2967
3038
  let restoredPatterns = 0;
2968
3039
  let controller = 'none';
2969
- // Try ReflexionMemory for episodic session replay
2970
- const reflexion = registry.get('reflexion');
2971
- if (reflexion && typeof reflexion.startEpisode === 'function') {
2972
- await reflexion.startEpisode(options.sessionId, { context: options.context });
2973
- controller = 'reflexion';
2974
- }
2975
- // Load recent patterns from past sessions
2976
- const searchResult = await bridgeSearchEntries({
2977
- query: options.context || 'session patterns',
2978
- namespace: 'session',
2979
- limit: 10,
2980
- threshold: 0.2,
2981
- dbPath: options.dbPath,
2982
- });
3040
+ // Episodic replay: past session episodes relevant to this session's
3041
+ // context, ranked by agentdb's keyword + vector search (agentdb ADR-016).
3042
+ // Opt-in, because a recall costs an embedding call and a generic context
3043
+ // ("new session") matches nothing in particular.
3044
+ let episodes;
3045
+ if (options.recall && options.context) {
3046
+ const recalled = await recallEpisodesFrom(registry, {
3047
+ task: options.context, k: options.k, hybrid: options.hybrid, rerank: options.rerank,
3048
+ });
3049
+ if (recalled) {
3050
+ episodes = recalled;
3051
+ controller = 'reflexion';
3052
+ }
3053
+ }
3054
+ // Load recent patterns from past sessions. A failure here must not
3055
+ // discard episodes already recalled above.
3056
+ let searchResult = null;
3057
+ try {
3058
+ searchResult = await bridgeSearchEntries({
3059
+ query: options.context || 'session patterns',
3060
+ namespace: 'session',
3061
+ limit: 10,
3062
+ threshold: 0.2,
3063
+ dbPath: options.dbPath,
3064
+ });
3065
+ }
3066
+ catch (err) {
3067
+ if (!episodes)
3068
+ throw err;
3069
+ }
2983
3070
  if (searchResult?.results) {
2984
3071
  restoredPatterns = searchResult.results.length;
2985
3072
  }
@@ -2988,6 +3075,7 @@ export async function bridgeSessionStart(options) {
2988
3075
  controller: controller === 'none' ? 'bridge-search' : controller,
2989
3076
  restoredPatterns,
2990
3077
  sessionId: options.sessionId,
3078
+ ...(episodes ? { episodes } : {}),
2991
3079
  };
2992
3080
  }
2993
3081
  catch {
@@ -3006,45 +3094,95 @@ export async function bridgeSessionEnd(options) {
3006
3094
  try {
3007
3095
  let controller = 'none';
3008
3096
  let persisted = false;
3009
- // End episode in ReflexionMemory
3097
+ // Store the session summary as a ReflexionMemory episode so a later
3098
+ // session can recall it. Only a real summary is worth recalling. The
3099
+ // outcome is unverified, so it is stored neutral (reward 0, not a success)
3100
+ // and can never count as evidence that an approach worked (ADR-171).
3101
+ let episodeId;
3010
3102
  const reflexion = registry.get('reflexion');
3011
- if (reflexion && typeof reflexion.endEpisode === 'function') {
3012
- await reflexion.endEpisode(options.sessionId, {
3013
- summary: options.summary,
3014
- tasksCompleted: options.tasksCompleted,
3015
- patternsLearned: options.patternsLearned,
3103
+ if (options.summary && reflexion && typeof reflexion.storeEpisode === 'function') {
3104
+ try {
3105
+ const id = await reflexion.storeEpisode({
3106
+ sessionId: options.sessionId,
3107
+ task: options.summary.slice(0, EPISODE_TASK_MAX),
3108
+ reward: 0,
3109
+ success: false,
3110
+ tags: ['session-end'],
3111
+ metadata: {
3112
+ source: 'session-end',
3113
+ provenance: 'session-summary',
3114
+ tasksCompleted: options.tasksCompleted ?? 0,
3115
+ patternsLearned: options.patternsLearned ?? 0,
3116
+ },
3117
+ });
3118
+ if (typeof id === 'number' && Number.isFinite(id)) {
3119
+ episodeId = id;
3120
+ controller = 'reflexion';
3121
+ persisted = true;
3122
+ }
3123
+ }
3124
+ catch { /* non-fatal: the memory entry below still records the session */ }
3125
+ }
3126
+ // Persist session summary as memory entry. A failure here must not hide
3127
+ // an episode that was already stored above.
3128
+ let entryStored = false;
3129
+ try {
3130
+ await bridgeStoreEntry({
3131
+ key: `session-${options.sessionId}`,
3132
+ value: JSON.stringify({
3133
+ sessionId: options.sessionId,
3134
+ summary: options.summary || 'Session ended',
3135
+ tasksCompleted: options.tasksCompleted ?? 0,
3136
+ patternsLearned: options.patternsLearned ?? 0,
3137
+ endedAt: new Date().toISOString(),
3138
+ }),
3139
+ namespace: 'session',
3140
+ tags: ['session-end'],
3141
+ upsert: true,
3142
+ dbPath: options.dbPath,
3016
3143
  });
3017
- controller = 'reflexion';
3144
+ entryStored = true;
3145
+ }
3146
+ catch (err) {
3147
+ if (episodeId === undefined)
3148
+ throw err;
3149
+ }
3150
+ if (entryStored) {
3151
+ controller = controller === 'none' ? 'bridge-store' : controller + '+bridge-store';
3018
3152
  persisted = true;
3019
3153
  }
3020
- // Persist session summary as memory entry
3021
- await bridgeStoreEntry({
3022
- key: `session-${options.sessionId}`,
3023
- value: JSON.stringify({
3024
- sessionId: options.sessionId,
3025
- summary: options.summary || 'Session ended',
3026
- tasksCompleted: options.tasksCompleted ?? 0,
3027
- patternsLearned: options.patternsLearned ?? 0,
3028
- endedAt: new Date().toISOString(),
3029
- }),
3030
- namespace: 'session',
3031
- tags: ['session-end'],
3032
- upsert: true,
3033
- dbPath: options.dbPath,
3034
- });
3035
- if (controller === 'none')
3036
- controller = 'bridge-store';
3037
- persisted = true;
3038
- // Phase 3: Trigger NightlyLearner consolidation if available
3154
+ // Phase 3: Trigger NightlyLearner consolidation if available.
3155
+ // #3908: neither the MemoryConsolidator wrapper nor AgentDB's NightlyLearner
3156
+ // has `consolidate` — they expose `run`/`runAll` — so probing only for
3157
+ // `consolidate` meant session-end never consolidated. Bounded so a slow
3158
+ // sweep cannot hold session-end open.
3039
3159
  const nightlyLearner = registry.get('nightlyLearner');
3040
- if (nightlyLearner && typeof nightlyLearner.consolidate === 'function') {
3160
+ const consolidate = nightlyLearner && (typeof nightlyLearner.consolidate === 'function'
3161
+ ? () => nightlyLearner.consolidate({ sessionId: options.sessionId })
3162
+ : typeof nightlyLearner.run === 'function'
3163
+ ? () => nightlyLearner.run()
3164
+ : typeof nightlyLearner.runAll === 'function'
3165
+ ? () => nightlyLearner.runAll()
3166
+ : null);
3167
+ if (consolidate) {
3168
+ let timer;
3041
3169
  try {
3042
- await nightlyLearner.consolidate({ sessionId: options.sessionId });
3170
+ await Promise.race([
3171
+ Promise.resolve().then(consolidate),
3172
+ new Promise((_, reject) => {
3173
+ timer = setTimeout(() => reject(new Error('nightlyLearner timeout')), SESSION_END_CONSOLIDATE_TIMEOUT_MS);
3174
+ timer.unref?.();
3175
+ }),
3176
+ ]);
3043
3177
  controller += '+nightlyLearner';
3044
3178
  }
3045
3179
  catch { /* non-fatal */ }
3180
+ finally {
3181
+ if (timer)
3182
+ clearTimeout(timer);
3183
+ }
3046
3184
  }
3047
- return { success: true, controller, persisted };
3185
+ return { success: true, controller, persisted, ...(episodeId !== undefined ? { episodeId } : {}) };
3048
3186
  }
3049
3187
  catch {
3050
3188
  return null;