dsh-tdai-memory 0.3.1 → 0.3.2

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.
@@ -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
+ }