dsh-tdai-memory 0.2.9 → 0.2.11

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