dsh-tdai-memory 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +9 -1
  3. package/README.zh.md +8 -1
  4. package/THIRD-PARTY-NOTICES.md +20 -20
  5. package/client.js +4 -3
  6. package/cordis.patch.yml +8 -8
  7. package/index.js +436 -436
  8. package/package.json +16 -4
  9. package/recall-inject.js +86 -86
  10. package/vendor/tdai/adapters/index.js +15 -15
  11. package/vendor/tdai/adapters/openclaw/host-adapter.js +83 -83
  12. package/vendor/tdai/adapters/openclaw/index.js +5 -5
  13. package/vendor/tdai/adapters/openclaw/llm-runner.js +69 -69
  14. package/vendor/tdai/adapters/standalone/host-adapter.js +58 -58
  15. package/vendor/tdai/adapters/standalone/index.js +5 -5
  16. package/vendor/tdai/adapters/standalone/llm-runner.js +274 -274
  17. package/vendor/tdai/config.js +366 -366
  18. package/vendor/tdai/core/conversation/l0-recorder.js +420 -420
  19. package/vendor/tdai/core/hooks/auto-capture.js +236 -236
  20. package/vendor/tdai/core/hooks/auto-recall.js +653 -653
  21. package/vendor/tdai/core/index.js +8 -8
  22. package/vendor/tdai/core/persona/persona-generator.js +184 -184
  23. package/vendor/tdai/core/persona/persona-trigger.js +94 -94
  24. package/vendor/tdai/core/profile/profile-sync.js +200 -200
  25. package/vendor/tdai/core/prompts/l1-dedup.js +136 -136
  26. package/vendor/tdai/core/prompts/l1-extraction.js +132 -132
  27. package/vendor/tdai/core/prompts/persona-generation.js +160 -160
  28. package/vendor/tdai/core/prompts/scene-extraction.js +269 -269
  29. package/vendor/tdai/core/record/l1-dedup.js +318 -318
  30. package/vendor/tdai/core/record/l1-extractor.js +379 -379
  31. package/vendor/tdai/core/record/l1-reader.js +178 -178
  32. package/vendor/tdai/core/record/l1-writer.js +141 -141
  33. package/vendor/tdai/core/report/reporter.js +86 -86
  34. package/vendor/tdai/core/scene/filename-normalizer.js +161 -161
  35. package/vendor/tdai/core/scene/scene-extractor.js +410 -410
  36. package/vendor/tdai/core/scene/scene-format.js +53 -53
  37. package/vendor/tdai/core/scene/scene-index.js +82 -82
  38. package/vendor/tdai/core/scene/scene-navigation.js +60 -60
  39. package/vendor/tdai/core/seed/input.js +404 -404
  40. package/vendor/tdai/core/seed/seed-runtime.js +318 -318
  41. package/vendor/tdai/core/seed/types.js +9 -9
  42. package/vendor/tdai/core/store/bm25-client.js +117 -117
  43. package/vendor/tdai/core/store/bm25-local.js +68 -68
  44. package/vendor/tdai/core/store/embedding.js +632 -632
  45. package/vendor/tdai/core/store/factory.js +95 -95
  46. package/vendor/tdai/core/store/search-utils.js +54 -54
  47. package/vendor/tdai/core/store/sqlite.js +1822 -1822
  48. package/vendor/tdai/core/store/tcvdb-client.js +221 -221
  49. package/vendor/tdai/core/store/tcvdb.js +1047 -1047
  50. package/vendor/tdai/core/store/types.js +17 -17
  51. package/vendor/tdai/core/tdai-core.js +450 -450
  52. package/vendor/tdai/core/tools/conversation-search.js +199 -199
  53. package/vendor/tdai/core/tools/memory-search.js +207 -207
  54. package/vendor/tdai/core/types.js +12 -12
  55. package/vendor/tdai/utils/backup.js +189 -189
  56. package/vendor/tdai/utils/checkpoint.js +360 -360
  57. package/vendor/tdai/utils/clean-context-runner.js +472 -472
  58. package/vendor/tdai/utils/ensure-hook-policy.js +213 -213
  59. package/vendor/tdai/utils/env.js +13 -13
  60. package/vendor/tdai/utils/managed-timer.js +127 -127
  61. package/vendor/tdai/utils/manifest.js +91 -91
  62. package/vendor/tdai/utils/memory-cleaner.js +300 -300
  63. package/vendor/tdai/utils/no-think-fetch.js +109 -109
  64. package/vendor/tdai/utils/openclaw-state-dir.js +26 -26
  65. package/vendor/tdai/utils/pipeline-factory.js +517 -517
  66. package/vendor/tdai/utils/pipeline-manager.js +892 -892
  67. package/vendor/tdai/utils/sanitize.js +360 -360
  68. package/vendor/tdai/utils/serial-queue.js +103 -103
  69. package/vendor/tdai/utils/session-filter.js +88 -88
  70. package/vendor/tdai/utils/session-header-fetch.js +88 -88
  71. package/vendor/tdai/utils/text-utils.js +29 -29
  72. package/vendor/tdai/utils/time.js +252 -252
@@ -1,318 +1,318 @@
1
- /**
2
- * Seed runtime: L0→L1→L2→L3 orchestration for the `seed` command.
3
- *
4
- * Uses the shared pipeline-factory for VectorStore/EmbeddingService init,
5
- * L1 runner, L2 runner, L3 runner, and persister wiring — keeping this
6
- * module focused on seed-specific concerns:
7
- * - Synchronous per-round L0 capture with progress reporting
8
- * - waitForL1Idle polling (L1 only — see FIXME below)
9
- * - Ctrl+C graceful shutdown
10
- *
11
- * FIXME: Currently we only wait for L1 to become idle before destroying the
12
- * pipeline. L2 (scene extraction) and L3 (persona generation) may still be
13
- * in-flight when `pipeline.destroy()` is called. This is intentional for now
14
- * to avoid excessively long seed runs, but means seed output may not include
15
- * the latest L2/L3 artifacts. Re-evaluate adding a full L1+L2+L3 idle wait
16
- * once pipeline-manager exposes reliable L2/L3 idle signals.
17
- */
18
- import path from "node:path";
19
- import { parseConfig } from "../../config.js";
20
- import { performAutoCapture } from "../hooks/auto-capture.js";
21
- import { createPipeline, createL2Runner, createL3Runner } from "../../utils/pipeline-factory.js";
22
- import { readManifest, writeManifest } from "../../utils/manifest.js";
23
- import { StandaloneLLMRunnerFactory } from "../../adapters/standalone/llm-runner.js";
24
- const TAG = "[memory-tdai] [seed]";
25
- // ============================
26
- // Seed pipeline creation
27
- // ============================
28
- /**
29
- * Create a seed pipeline using the shared factory, with L2/L3 runners
30
- * wired via shared factory functions (same logic as index.ts live runtime).
31
- */
32
- async function createSeedPipeline(opts) {
33
- const { outputDir, openclawConfig, pluginConfig, logger } = opts;
34
- // Parse config — all values come from pluginConfig (or parseConfig defaults)
35
- const cfg = parseConfig(pluginConfig);
36
- logger.info(`${TAG} Creating seed pipeline: outputDir=${outputDir}, ` +
37
- `everyN=${cfg.pipeline.everyNConversations}, l1Idle=${cfg.pipeline.l1IdleTimeoutSeconds}s, ` +
38
- `l2Delay=${cfg.pipeline.l2DelayAfterL1Seconds}s, l2Min=${cfg.pipeline.l2MinIntervalSeconds}s, l2Max=${cfg.pipeline.l2MaxIntervalSeconds}s`);
39
- // Create standalone LLM runners if cfg.llm is configured.
40
- // Seed always runs outside OpenClaw, so it needs standalone runners
41
- // unless an explicit openclawConfig is provided (rare).
42
- let l1LlmRunner;
43
- let l2l3LlmRunner;
44
- if (cfg.llm.enabled && cfg.llm.apiKey) {
45
- const runnerFactory = new StandaloneLLMRunnerFactory({
46
- config: {
47
- baseUrl: cfg.llm.baseUrl,
48
- apiKey: cfg.llm.apiKey,
49
- model: cfg.llm.model,
50
- maxTokens: cfg.llm.maxTokens,
51
- timeoutMs: cfg.llm.timeoutMs,
52
- disableThinking: cfg.llm.disableThinking,
53
- sendSessionHeader: cfg.llm.sendSessionHeader,
54
- sessionHeaderName: cfg.llm.sessionHeaderName,
55
- sessionId: cfg.llm.sessionId,
56
- dataDir: outputDir,
57
- },
58
- logger,
59
- });
60
- l1LlmRunner = runnerFactory.createRunner({ enableTools: false });
61
- l2l3LlmRunner = runnerFactory.createRunner({ enableTools: true });
62
- logger.info(`${TAG} Seed using standalone LLM: model=${cfg.llm.model}`);
63
- }
64
- // Use shared factory for everything: store init, L1 runner, persister, destroy
65
- const pipeline = await createPipeline({
66
- pluginDataDir: outputDir,
67
- cfg,
68
- openclawConfig,
69
- logger,
70
- l1LlmRunner,
71
- });
72
- // Wire L2 runner via shared factory (same logic as index.ts live runtime)
73
- pipeline.scheduler.setL2Runner(createL2Runner({
74
- pluginDataDir: outputDir,
75
- cfg,
76
- openclawConfig,
77
- vectorStore: pipeline.vectorStore,
78
- logger,
79
- llmRunner: l2l3LlmRunner,
80
- }));
81
- // Wire L3 runner via shared factory (same logic as index.ts live runtime)
82
- pipeline.scheduler.setL3Runner(createL3Runner({
83
- pluginDataDir: outputDir,
84
- cfg,
85
- openclawConfig,
86
- vectorStore: pipeline.vectorStore,
87
- logger,
88
- llmRunner: l2l3LlmRunner,
89
- }));
90
- return { pipeline, cfg };
91
- }
92
- // ============================
93
- // waitForL1Idle
94
- // ============================
95
- /**
96
- * Poll pipeline queue status until L1 is idle for a given session.
97
- * Modeled after benchmark-ingest.ts waitForPipelineIdle() but focused on L1 only.
98
- */
99
- async function waitForL1Idle(scheduler, sessionKeys, logger, opts = {}) {
100
- const pollInterval = opts.pollIntervalMs ?? 1_000;
101
- const stableRounds = opts.stableRounds ?? 3;
102
- const maxWait = opts.maxWaitMs ?? 300_000; // 5 min default
103
- const startTime = Date.now();
104
- let consecutiveIdle = 0;
105
- while (true) {
106
- const elapsed = Date.now() - startTime;
107
- if (elapsed > maxWait) {
108
- logger.warn(`${TAG} [waitL1] Max wait time reached (${(maxWait / 1000).toFixed(0)}s), proceeding`);
109
- break;
110
- }
111
- const queues = scheduler.getQueueSizes();
112
- // Check per-session: buffered messages + conversation count
113
- let totalBuffered = 0;
114
- let totalConversationCount = 0;
115
- for (const key of sessionKeys) {
116
- totalBuffered += scheduler.getBufferedMessageCount(key);
117
- const state = scheduler.getSessionState(key);
118
- if (state) {
119
- totalConversationCount += state.conversation_count;
120
- }
121
- }
122
- const isIdle = queues.l1Idle &&
123
- totalBuffered === 0 &&
124
- totalConversationCount === 0;
125
- if (isIdle) {
126
- consecutiveIdle++;
127
- if (consecutiveIdle >= stableRounds) {
128
- logger.debug?.(`${TAG} [waitL1] L1 stable for ${stableRounds} consecutive polls`);
129
- return;
130
- }
131
- }
132
- else {
133
- consecutiveIdle = 0;
134
- logger.debug?.(`${TAG} [waitL1] Waiting: l1Queue=${queues.l1}, l1Pending=${queues.l1Pending}, l1Idle=${queues.l1Idle}, ` +
135
- `buffered=${totalBuffered}, convCount=${totalConversationCount}`);
136
- }
137
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
138
- }
139
- }
140
- // ============================
141
- // Main execution function
142
- // ============================
143
- /**
144
- * Execute the seed pipeline: feed normalized input through L0 → L1.
145
- *
146
- * L2/L3 runners are wired but their completion is **not** awaited — see the
147
- * module-level FIXME. The pipeline is destroyed after L1 idle, so L2/L3 may
148
- * be interrupted mid-run.
149
- *
150
- * This is the core runtime called by `src/cli/commands/seed.ts` after
151
- * all input validation and user confirmation are complete.
152
- */
153
- export async function executeSeed(input, opts) {
154
- const { logger, onProgress } = opts;
155
- const startTime = Date.now();
156
- // Track interrupt signal
157
- let interrupted = false;
158
- const onSigint = () => {
159
- if (interrupted) {
160
- // Second Ctrl+C — force exit
161
- logger.warn(`${TAG} Force exit (second Ctrl+C)`);
162
- process.exit(1);
163
- }
164
- interrupted = true;
165
- logger.warn(`${TAG} Interrupt received, finishing current round and shutting down...`);
166
- };
167
- process.on("SIGINT", onSigint);
168
- let pipeline;
169
- let totalL0Recorded = 0;
170
- let roundsProcessed = 0;
171
- try {
172
- // Create and start pipeline (returns both the pipeline instance and the
173
- // seed-optimized config so we don't need to parse config again)
174
- const seed = await createSeedPipeline(opts);
175
- pipeline = seed.pipeline;
176
- const seedCfg = seed.cfg;
177
- pipeline.scheduler.start({});
178
- logger.info(`${TAG} Pipeline started, processing ${input.sessions.length} session(s), ${input.totalRounds} round(s)`);
179
- // Seed-specific: use 0 so the cold-start guard in captureAtomically()
180
- // does NOT filter out historical messages. In live mode Date.now()
181
- // prevents the first agent_end from dumping full session history,
182
- // but seed intentionally feeds all historical data.
183
- const captureStartTimestamp = 0;
184
- // Process each session → each round
185
- // Key invariant: after every everyNConversations rounds we must wait for L1
186
- // to finish before feeding more rounds. Without this pause the for-loop
187
- // would dump all rounds into L0 back-to-back and L1 would only run once
188
- // with the full batch (defeating the "every N" batching semantics).
189
- const everyN = seedCfg.pipeline.everyNConversations;
190
- for (const session of input.sessions) {
191
- if (interrupted)
192
- break;
193
- logger.info(`${TAG} Session: key="${session.sessionKey}" id="${session.sessionId}" rounds=${session.rounds.length}`);
194
- for (let ri = 0; ri < session.rounds.length; ri++) {
195
- if (interrupted)
196
- break;
197
- const round = session.rounds[ri];
198
- roundsProcessed++;
199
- // Build messages in the format expected by performAutoCapture.
200
- // Field must be named "timestamp" (not "ts") because l0-recorder's
201
- // extractUserAssistantMessages reads m.timestamp for incremental filtering.
202
- const messages = round.messages.map((m) => ({
203
- role: m.role,
204
- content: m.content,
205
- timestamp: m.timestamp,
206
- }));
207
- try {
208
- const result = await performAutoCapture({
209
- messages,
210
- sessionKey: session.sessionKey,
211
- sessionId: session.sessionId,
212
- cfg: seedCfg,
213
- pluginDataDir: opts.outputDir,
214
- logger,
215
- scheduler: pipeline.scheduler,
216
- pluginStartTimestamp: captureStartTimestamp,
217
- vectorStore: pipeline.vectorStore,
218
- embeddingService: pipeline.embeddingService,
219
- });
220
- totalL0Recorded += result.l0RecordedCount;
221
- }
222
- catch (err) {
223
- logger.error(`${TAG} L0 capture failed for session="${session.sessionKey}" round=${ri}: ` +
224
- `${err instanceof Error ? err.message : String(err)}`);
225
- }
226
- // Report progress
227
- onProgress?.({
228
- currentRound: roundsProcessed,
229
- totalRounds: input.totalRounds,
230
- sessionKey: session.sessionKey,
231
- stage: "l0_captured",
232
- });
233
- // After every N rounds, wait for the triggered L1 to finish before
234
- // feeding the next batch. This keeps L1 batches aligned with the
235
- // everyNConversations boundary instead of letting all rounds pile up.
236
- const roundInSession = ri + 1; // 1-based
237
- if (roundInSession % everyN === 0 && !interrupted) {
238
- onProgress?.({
239
- currentRound: roundsProcessed,
240
- totalRounds: input.totalRounds,
241
- sessionKey: session.sessionKey,
242
- stage: "l1_waiting",
243
- });
244
- logger.info(`${TAG} Pausing after round ${roundInSession}/${session.rounds.length} ` +
245
- `for session="${session.sessionKey}" — waiting for L1 to drain`);
246
- await waitForL1Idle(pipeline.scheduler, [session.sessionKey], logger, { pollIntervalMs: 500, stableRounds: 2, maxWaitMs: 120_000 });
247
- }
248
- }
249
- // After all rounds for this session, wait for any residual L1 work
250
- // (handles the tail when total rounds is not a multiple of everyN)
251
- if (!interrupted) {
252
- onProgress?.({
253
- currentRound: roundsProcessed,
254
- totalRounds: input.totalRounds,
255
- sessionKey: session.sessionKey,
256
- stage: "l1_waiting",
257
- });
258
- await waitForL1Idle(pipeline.scheduler, [session.sessionKey], logger, { pollIntervalMs: 1_000, stableRounds: 3, maxWaitMs: 300_000 });
259
- logger.info(`${TAG} L1 idle for session="${session.sessionKey}"`);
260
- }
261
- }
262
- // Final wait for all sessions
263
- if (!interrupted) {
264
- const allKeys = input.sessions.map((s) => s.sessionKey);
265
- logger.info(`${TAG} Final L1 idle wait for all sessions...`);
266
- await waitForL1Idle(pipeline.scheduler, allKeys, logger, { pollIntervalMs: 1_000, stableRounds: 3, maxWaitMs: 300_000 });
267
- }
268
- }
269
- finally {
270
- process.removeListener("SIGINT", onSigint);
271
- // Graceful shutdown
272
- if (pipeline) {
273
- try {
274
- await pipeline.destroy();
275
- }
276
- catch (err) {
277
- logger.error(`${TAG} Pipeline destroy error: ${err instanceof Error ? err.message : String(err)}`);
278
- }
279
- }
280
- }
281
- const durationMs = Date.now() - startTime;
282
- const summary = {
283
- sessionsProcessed: input.sessions.length,
284
- roundsProcessed,
285
- messagesProcessed: input.totalMessages,
286
- l0RecordedCount: totalL0Recorded,
287
- durationMs,
288
- outputDir: opts.outputDir,
289
- };
290
- if (interrupted) {
291
- logger.warn(`${TAG} Seed interrupted after ${roundsProcessed}/${input.totalRounds} rounds`);
292
- }
293
- else {
294
- logger.info(`${TAG} Seed complete: sessions=${summary.sessionsProcessed}, ` +
295
- `rounds=${summary.roundsProcessed}, messages=${summary.messagesProcessed}, ` +
296
- `l0Recorded=${summary.l0RecordedCount}, duration=${(durationMs / 1000).toFixed(1)}s`);
297
- }
298
- // Append seed info to manifest (non-fatal if it fails)
299
- try {
300
- const manifest = readManifest(opts.outputDir);
301
- if (manifest) {
302
- manifest.seed = {
303
- inputFile: opts.inputFile ? path.basename(opts.inputFile) : undefined,
304
- sessions: summary.sessionsProcessed,
305
- rounds: summary.roundsProcessed,
306
- messages: summary.messagesProcessed,
307
- startedAt: new Date(startTime).toISOString(),
308
- completedAt: new Date().toISOString(),
309
- };
310
- writeManifest(opts.outputDir, manifest);
311
- logger.info(`${TAG} Manifest updated with seed info`);
312
- }
313
- }
314
- catch (err) {
315
- logger.warn(`${TAG} Failed to update manifest with seed info (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
316
- }
317
- return summary;
318
- }
1
+ /**
2
+ * Seed runtime: L0→L1→L2→L3 orchestration for the `seed` command.
3
+ *
4
+ * Uses the shared pipeline-factory for VectorStore/EmbeddingService init,
5
+ * L1 runner, L2 runner, L3 runner, and persister wiring — keeping this
6
+ * module focused on seed-specific concerns:
7
+ * - Synchronous per-round L0 capture with progress reporting
8
+ * - waitForL1Idle polling (L1 only — see FIXME below)
9
+ * - Ctrl+C graceful shutdown
10
+ *
11
+ * FIXME: Currently we only wait for L1 to become idle before destroying the
12
+ * pipeline. L2 (scene extraction) and L3 (persona generation) may still be
13
+ * in-flight when `pipeline.destroy()` is called. This is intentional for now
14
+ * to avoid excessively long seed runs, but means seed output may not include
15
+ * the latest L2/L3 artifacts. Re-evaluate adding a full L1+L2+L3 idle wait
16
+ * once pipeline-manager exposes reliable L2/L3 idle signals.
17
+ */
18
+ import path from "node:path";
19
+ import { parseConfig } from "../../config.js";
20
+ import { performAutoCapture } from "../hooks/auto-capture.js";
21
+ import { createPipeline, createL2Runner, createL3Runner } from "../../utils/pipeline-factory.js";
22
+ import { readManifest, writeManifest } from "../../utils/manifest.js";
23
+ import { StandaloneLLMRunnerFactory } from "../../adapters/standalone/llm-runner.js";
24
+ const TAG = "[memory-tdai] [seed]";
25
+ // ============================
26
+ // Seed pipeline creation
27
+ // ============================
28
+ /**
29
+ * Create a seed pipeline using the shared factory, with L2/L3 runners
30
+ * wired via shared factory functions (same logic as index.ts live runtime).
31
+ */
32
+ async function createSeedPipeline(opts) {
33
+ const { outputDir, openclawConfig, pluginConfig, logger } = opts;
34
+ // Parse config — all values come from pluginConfig (or parseConfig defaults)
35
+ const cfg = parseConfig(pluginConfig);
36
+ logger.info(`${TAG} Creating seed pipeline: outputDir=${outputDir}, ` +
37
+ `everyN=${cfg.pipeline.everyNConversations}, l1Idle=${cfg.pipeline.l1IdleTimeoutSeconds}s, ` +
38
+ `l2Delay=${cfg.pipeline.l2DelayAfterL1Seconds}s, l2Min=${cfg.pipeline.l2MinIntervalSeconds}s, l2Max=${cfg.pipeline.l2MaxIntervalSeconds}s`);
39
+ // Create standalone LLM runners if cfg.llm is configured.
40
+ // Seed always runs outside OpenClaw, so it needs standalone runners
41
+ // unless an explicit openclawConfig is provided (rare).
42
+ let l1LlmRunner;
43
+ let l2l3LlmRunner;
44
+ if (cfg.llm.enabled && cfg.llm.apiKey) {
45
+ const runnerFactory = new StandaloneLLMRunnerFactory({
46
+ config: {
47
+ baseUrl: cfg.llm.baseUrl,
48
+ apiKey: cfg.llm.apiKey,
49
+ model: cfg.llm.model,
50
+ maxTokens: cfg.llm.maxTokens,
51
+ timeoutMs: cfg.llm.timeoutMs,
52
+ disableThinking: cfg.llm.disableThinking,
53
+ sendSessionHeader: cfg.llm.sendSessionHeader,
54
+ sessionHeaderName: cfg.llm.sessionHeaderName,
55
+ sessionId: cfg.llm.sessionId,
56
+ dataDir: outputDir,
57
+ },
58
+ logger,
59
+ });
60
+ l1LlmRunner = runnerFactory.createRunner({ enableTools: false });
61
+ l2l3LlmRunner = runnerFactory.createRunner({ enableTools: true });
62
+ logger.info(`${TAG} Seed using standalone LLM: model=${cfg.llm.model}`);
63
+ }
64
+ // Use shared factory for everything: store init, L1 runner, persister, destroy
65
+ const pipeline = await createPipeline({
66
+ pluginDataDir: outputDir,
67
+ cfg,
68
+ openclawConfig,
69
+ logger,
70
+ l1LlmRunner,
71
+ });
72
+ // Wire L2 runner via shared factory (same logic as index.ts live runtime)
73
+ pipeline.scheduler.setL2Runner(createL2Runner({
74
+ pluginDataDir: outputDir,
75
+ cfg,
76
+ openclawConfig,
77
+ vectorStore: pipeline.vectorStore,
78
+ logger,
79
+ llmRunner: l2l3LlmRunner,
80
+ }));
81
+ // Wire L3 runner via shared factory (same logic as index.ts live runtime)
82
+ pipeline.scheduler.setL3Runner(createL3Runner({
83
+ pluginDataDir: outputDir,
84
+ cfg,
85
+ openclawConfig,
86
+ vectorStore: pipeline.vectorStore,
87
+ logger,
88
+ llmRunner: l2l3LlmRunner,
89
+ }));
90
+ return { pipeline, cfg };
91
+ }
92
+ // ============================
93
+ // waitForL1Idle
94
+ // ============================
95
+ /**
96
+ * Poll pipeline queue status until L1 is idle for a given session.
97
+ * Modeled after benchmark-ingest.ts waitForPipelineIdle() but focused on L1 only.
98
+ */
99
+ async function waitForL1Idle(scheduler, sessionKeys, logger, opts = {}) {
100
+ const pollInterval = opts.pollIntervalMs ?? 1_000;
101
+ const stableRounds = opts.stableRounds ?? 3;
102
+ const maxWait = opts.maxWaitMs ?? 300_000; // 5 min default
103
+ const startTime = Date.now();
104
+ let consecutiveIdle = 0;
105
+ while (true) {
106
+ const elapsed = Date.now() - startTime;
107
+ if (elapsed > maxWait) {
108
+ logger.warn(`${TAG} [waitL1] Max wait time reached (${(maxWait / 1000).toFixed(0)}s), proceeding`);
109
+ break;
110
+ }
111
+ const queues = scheduler.getQueueSizes();
112
+ // Check per-session: buffered messages + conversation count
113
+ let totalBuffered = 0;
114
+ let totalConversationCount = 0;
115
+ for (const key of sessionKeys) {
116
+ totalBuffered += scheduler.getBufferedMessageCount(key);
117
+ const state = scheduler.getSessionState(key);
118
+ if (state) {
119
+ totalConversationCount += state.conversation_count;
120
+ }
121
+ }
122
+ const isIdle = queues.l1Idle &&
123
+ totalBuffered === 0 &&
124
+ totalConversationCount === 0;
125
+ if (isIdle) {
126
+ consecutiveIdle++;
127
+ if (consecutiveIdle >= stableRounds) {
128
+ logger.debug?.(`${TAG} [waitL1] L1 stable for ${stableRounds} consecutive polls`);
129
+ return;
130
+ }
131
+ }
132
+ else {
133
+ consecutiveIdle = 0;
134
+ logger.debug?.(`${TAG} [waitL1] Waiting: l1Queue=${queues.l1}, l1Pending=${queues.l1Pending}, l1Idle=${queues.l1Idle}, ` +
135
+ `buffered=${totalBuffered}, convCount=${totalConversationCount}`);
136
+ }
137
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
138
+ }
139
+ }
140
+ // ============================
141
+ // Main execution function
142
+ // ============================
143
+ /**
144
+ * Execute the seed pipeline: feed normalized input through L0 → L1.
145
+ *
146
+ * L2/L3 runners are wired but their completion is **not** awaited — see the
147
+ * module-level FIXME. The pipeline is destroyed after L1 idle, so L2/L3 may
148
+ * be interrupted mid-run.
149
+ *
150
+ * This is the core runtime called by `src/cli/commands/seed.ts` after
151
+ * all input validation and user confirmation are complete.
152
+ */
153
+ export async function executeSeed(input, opts) {
154
+ const { logger, onProgress } = opts;
155
+ const startTime = Date.now();
156
+ // Track interrupt signal
157
+ let interrupted = false;
158
+ const onSigint = () => {
159
+ if (interrupted) {
160
+ // Second Ctrl+C — force exit
161
+ logger.warn(`${TAG} Force exit (second Ctrl+C)`);
162
+ process.exit(1);
163
+ }
164
+ interrupted = true;
165
+ logger.warn(`${TAG} Interrupt received, finishing current round and shutting down...`);
166
+ };
167
+ process.on("SIGINT", onSigint);
168
+ let pipeline;
169
+ let totalL0Recorded = 0;
170
+ let roundsProcessed = 0;
171
+ try {
172
+ // Create and start pipeline (returns both the pipeline instance and the
173
+ // seed-optimized config so we don't need to parse config again)
174
+ const seed = await createSeedPipeline(opts);
175
+ pipeline = seed.pipeline;
176
+ const seedCfg = seed.cfg;
177
+ pipeline.scheduler.start({});
178
+ logger.info(`${TAG} Pipeline started, processing ${input.sessions.length} session(s), ${input.totalRounds} round(s)`);
179
+ // Seed-specific: use 0 so the cold-start guard in captureAtomically()
180
+ // does NOT filter out historical messages. In live mode Date.now()
181
+ // prevents the first agent_end from dumping full session history,
182
+ // but seed intentionally feeds all historical data.
183
+ const captureStartTimestamp = 0;
184
+ // Process each session → each round
185
+ // Key invariant: after every everyNConversations rounds we must wait for L1
186
+ // to finish before feeding more rounds. Without this pause the for-loop
187
+ // would dump all rounds into L0 back-to-back and L1 would only run once
188
+ // with the full batch (defeating the "every N" batching semantics).
189
+ const everyN = seedCfg.pipeline.everyNConversations;
190
+ for (const session of input.sessions) {
191
+ if (interrupted)
192
+ break;
193
+ logger.info(`${TAG} Session: key="${session.sessionKey}" id="${session.sessionId}" rounds=${session.rounds.length}`);
194
+ for (let ri = 0; ri < session.rounds.length; ri++) {
195
+ if (interrupted)
196
+ break;
197
+ const round = session.rounds[ri];
198
+ roundsProcessed++;
199
+ // Build messages in the format expected by performAutoCapture.
200
+ // Field must be named "timestamp" (not "ts") because l0-recorder's
201
+ // extractUserAssistantMessages reads m.timestamp for incremental filtering.
202
+ const messages = round.messages.map((m) => ({
203
+ role: m.role,
204
+ content: m.content,
205
+ timestamp: m.timestamp,
206
+ }));
207
+ try {
208
+ const result = await performAutoCapture({
209
+ messages,
210
+ sessionKey: session.sessionKey,
211
+ sessionId: session.sessionId,
212
+ cfg: seedCfg,
213
+ pluginDataDir: opts.outputDir,
214
+ logger,
215
+ scheduler: pipeline.scheduler,
216
+ pluginStartTimestamp: captureStartTimestamp,
217
+ vectorStore: pipeline.vectorStore,
218
+ embeddingService: pipeline.embeddingService,
219
+ });
220
+ totalL0Recorded += result.l0RecordedCount;
221
+ }
222
+ catch (err) {
223
+ logger.error(`${TAG} L0 capture failed for session="${session.sessionKey}" round=${ri}: ` +
224
+ `${err instanceof Error ? err.message : String(err)}`);
225
+ }
226
+ // Report progress
227
+ onProgress?.({
228
+ currentRound: roundsProcessed,
229
+ totalRounds: input.totalRounds,
230
+ sessionKey: session.sessionKey,
231
+ stage: "l0_captured",
232
+ });
233
+ // After every N rounds, wait for the triggered L1 to finish before
234
+ // feeding the next batch. This keeps L1 batches aligned with the
235
+ // everyNConversations boundary instead of letting all rounds pile up.
236
+ const roundInSession = ri + 1; // 1-based
237
+ if (roundInSession % everyN === 0 && !interrupted) {
238
+ onProgress?.({
239
+ currentRound: roundsProcessed,
240
+ totalRounds: input.totalRounds,
241
+ sessionKey: session.sessionKey,
242
+ stage: "l1_waiting",
243
+ });
244
+ logger.info(`${TAG} Pausing after round ${roundInSession}/${session.rounds.length} ` +
245
+ `for session="${session.sessionKey}" — waiting for L1 to drain`);
246
+ await waitForL1Idle(pipeline.scheduler, [session.sessionKey], logger, { pollIntervalMs: 500, stableRounds: 2, maxWaitMs: 120_000 });
247
+ }
248
+ }
249
+ // After all rounds for this session, wait for any residual L1 work
250
+ // (handles the tail when total rounds is not a multiple of everyN)
251
+ if (!interrupted) {
252
+ onProgress?.({
253
+ currentRound: roundsProcessed,
254
+ totalRounds: input.totalRounds,
255
+ sessionKey: session.sessionKey,
256
+ stage: "l1_waiting",
257
+ });
258
+ await waitForL1Idle(pipeline.scheduler, [session.sessionKey], logger, { pollIntervalMs: 1_000, stableRounds: 3, maxWaitMs: 300_000 });
259
+ logger.info(`${TAG} L1 idle for session="${session.sessionKey}"`);
260
+ }
261
+ }
262
+ // Final wait for all sessions
263
+ if (!interrupted) {
264
+ const allKeys = input.sessions.map((s) => s.sessionKey);
265
+ logger.info(`${TAG} Final L1 idle wait for all sessions...`);
266
+ await waitForL1Idle(pipeline.scheduler, allKeys, logger, { pollIntervalMs: 1_000, stableRounds: 3, maxWaitMs: 300_000 });
267
+ }
268
+ }
269
+ finally {
270
+ process.removeListener("SIGINT", onSigint);
271
+ // Graceful shutdown
272
+ if (pipeline) {
273
+ try {
274
+ await pipeline.destroy();
275
+ }
276
+ catch (err) {
277
+ logger.error(`${TAG} Pipeline destroy error: ${err instanceof Error ? err.message : String(err)}`);
278
+ }
279
+ }
280
+ }
281
+ const durationMs = Date.now() - startTime;
282
+ const summary = {
283
+ sessionsProcessed: input.sessions.length,
284
+ roundsProcessed,
285
+ messagesProcessed: input.totalMessages,
286
+ l0RecordedCount: totalL0Recorded,
287
+ durationMs,
288
+ outputDir: opts.outputDir,
289
+ };
290
+ if (interrupted) {
291
+ logger.warn(`${TAG} Seed interrupted after ${roundsProcessed}/${input.totalRounds} rounds`);
292
+ }
293
+ else {
294
+ logger.info(`${TAG} Seed complete: sessions=${summary.sessionsProcessed}, ` +
295
+ `rounds=${summary.roundsProcessed}, messages=${summary.messagesProcessed}, ` +
296
+ `l0Recorded=${summary.l0RecordedCount}, duration=${(durationMs / 1000).toFixed(1)}s`);
297
+ }
298
+ // Append seed info to manifest (non-fatal if it fails)
299
+ try {
300
+ const manifest = readManifest(opts.outputDir);
301
+ if (manifest) {
302
+ manifest.seed = {
303
+ inputFile: opts.inputFile ? path.basename(opts.inputFile) : undefined,
304
+ sessions: summary.sessionsProcessed,
305
+ rounds: summary.roundsProcessed,
306
+ messages: summary.messagesProcessed,
307
+ startedAt: new Date(startTime).toISOString(),
308
+ completedAt: new Date().toISOString(),
309
+ };
310
+ writeManifest(opts.outputDir, manifest);
311
+ logger.info(`${TAG} Manifest updated with seed info`);
312
+ }
313
+ }
314
+ catch (err) {
315
+ logger.warn(`${TAG} Failed to update manifest with seed info (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
316
+ }
317
+ return summary;
318
+ }
@@ -1,9 +1,9 @@
1
- /**
2
- * Shared type definitions for the `seed` command.
3
- *
4
- * Covers:
5
- * - Raw input shapes (Format A / B / JSONL)
6
- * - Normalized internal structures
7
- * - Validation error descriptors
8
- */
9
- export {};
1
+ /**
2
+ * Shared type definitions for the `seed` command.
3
+ *
4
+ * Covers:
5
+ * - Raw input shapes (Format A / B / JSONL)
6
+ * - Normalized internal structures
7
+ * - Validation error descriptors
8
+ */
9
+ export {};