@unblocklabs/unblock-memory 0.12.3 → 0.14.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 (138) hide show
  1. package/README.md +19 -18
  2. package/defaults.json +162 -0
  3. package/dist/src/analysis.js +1 -1
  4. package/dist/src/cluster-review.d.ts +2 -0
  5. package/dist/src/cluster-review.js +9 -8
  6. package/dist/src/config.d.ts +9 -6
  7. package/dist/src/config.js +59 -45
  8. package/dist/src/curation.d.ts +1 -1
  9. package/dist/src/decision-client.d.ts +45 -0
  10. package/dist/src/decision-client.js +87 -0
  11. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  12. package/dist/src/decision-ranking.js +155 -0
  13. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  14. package/dist/src/decision-review.js +193 -0
  15. package/dist/src/defaults.d.ts +8 -0
  16. package/dist/src/defaults.js +128 -0
  17. package/dist/src/diagnostics.d.ts +5 -5
  18. package/dist/src/emotion-baselines.d.ts +28 -3
  19. package/dist/src/emotion-baselines.js +312 -115
  20. package/dist/src/evidence-review.d.ts +22 -8
  21. package/dist/src/evidence-review.js +11 -8
  22. package/dist/src/extraction-chunk.d.ts +3 -0
  23. package/dist/src/extraction-chunk.js +25 -6
  24. package/dist/src/extraction-config.js +4 -2
  25. package/dist/src/extraction-model.d.ts +25 -17
  26. package/dist/src/extraction-model.js +232 -104
  27. package/dist/src/extraction-runtime.d.ts +3 -1
  28. package/dist/src/extraction-runtime.js +48 -20
  29. package/dist/src/extraction-source.d.ts +1 -1
  30. package/dist/src/extraction-source.js +21 -12
  31. package/dist/src/extraction-store.d.ts +29 -3
  32. package/dist/src/extraction-store.js +149 -25
  33. package/dist/src/extraction-worker.d.ts +3 -3
  34. package/dist/src/extraction-worker.js +250 -95
  35. package/dist/src/inside-out-runtime.js +43 -30
  36. package/dist/src/inside-out-sources.js +2 -1
  37. package/dist/src/inside-out-store.d.ts +2 -2
  38. package/dist/src/inside-out-store.js +111 -69
  39. package/dist/src/inside-out.d.ts +10 -9
  40. package/dist/src/inside-out.js +194 -106
  41. package/dist/src/manager.d.ts +22 -9
  42. package/dist/src/manager.js +279 -172
  43. package/dist/src/memory-database.js +3 -2
  44. package/dist/src/memory-passage.d.ts +2 -2
  45. package/dist/src/memory-passage.js +3 -2
  46. package/dist/src/memory-search.d.ts +4 -2
  47. package/dist/src/memory-search.js +5 -5
  48. package/dist/src/memory-whisperer.d.ts +1 -1
  49. package/dist/src/memory-whisperer.js +195 -129
  50. package/dist/src/my-turn.d.ts +1 -1
  51. package/dist/src/my-turn.js +90 -70
  52. package/dist/src/people-background.d.ts +5 -1
  53. package/dist/src/people-background.js +31 -7
  54. package/dist/src/people-dossier-review.d.ts +20 -8
  55. package/dist/src/people-dossier-review.js +15 -11
  56. package/dist/src/people-hooks.js +127 -22
  57. package/dist/src/people-learning-cron.d.ts +1 -1
  58. package/dist/src/people-learning-cron.js +107 -57
  59. package/dist/src/people-learning-inventory.d.ts +1 -0
  60. package/dist/src/people-learning-inventory.js +283 -172
  61. package/dist/src/people-learning-prompt.js +1 -1
  62. package/dist/src/people-learning-runtime.d.ts +1 -1
  63. package/dist/src/people-learning-runtime.js +360 -203
  64. package/dist/src/people-learning-store.d.ts +27 -4
  65. package/dist/src/people-learning-store.js +312 -96
  66. package/dist/src/people-primer-tool.js +13 -10
  67. package/dist/src/people-primer.d.ts +3 -1
  68. package/dist/src/people-primer.js +66 -48
  69. package/dist/src/people-store.d.ts +18 -21
  70. package/dist/src/people-store.js +188 -64
  71. package/dist/src/people-tools.js +138 -93
  72. package/dist/src/plugin.js +19 -18
  73. package/dist/src/quality-audit.d.ts +2 -0
  74. package/dist/src/quality-audit.js +11 -9
  75. package/dist/src/quality-triage.js +4 -3
  76. package/dist/src/query-generator.js +5 -2
  77. package/dist/src/response-audit.d.ts +1 -1
  78. package/dist/src/response-audit.js +78 -44
  79. package/dist/src/response-config.js +3 -1
  80. package/dist/src/response-episodes.d.ts +1 -1
  81. package/dist/src/response-episodes.js +15 -19
  82. package/dist/src/response-identity.js +2 -1
  83. package/dist/src/response-judge.d.ts +151 -145
  84. package/dist/src/response-judge.js +535 -204
  85. package/dist/src/response-memory.js +2 -1
  86. package/dist/src/response-outcome.js +9 -8
  87. package/dist/src/response-reviews.d.ts +29 -1
  88. package/dist/src/response-reviews.js +113 -15
  89. package/dist/src/response-runtime.js +10 -9
  90. package/dist/src/response-stages.d.ts +50 -53
  91. package/dist/src/response-stages.js +10 -4
  92. package/dist/src/response-store.d.ts +7 -6
  93. package/dist/src/response-store.js +335 -212
  94. package/dist/src/review-tools.d.ts +8 -2
  95. package/dist/src/review-tools.js +22 -21
  96. package/dist/src/runtime.d.ts +7 -4
  97. package/dist/src/runtime.js +625 -98
  98. package/dist/src/safety-config.js +3 -2
  99. package/dist/src/safety-whisperer.d.ts +2 -2
  100. package/dist/src/safety-whisperer.js +90 -73
  101. package/dist/src/session-sync.d.ts +3 -1
  102. package/dist/src/session-sync.js +202 -96
  103. package/dist/src/skill-whisperer.d.ts +2 -2
  104. package/dist/src/skill-whisperer.js +55 -32
  105. package/dist/src/slack-directory.js +3 -2
  106. package/dist/src/training-gate.d.ts +9 -22
  107. package/dist/src/training-gate.js +34 -36
  108. package/dist/src/training-input.js +4 -3
  109. package/dist/src/training-judge.d.ts +9 -16
  110. package/dist/src/training-judge.js +6 -5
  111. package/dist/src/training-models.d.ts +1 -1
  112. package/dist/src/training-models.js +9 -7
  113. package/dist/src/training-queries.d.ts +14 -9
  114. package/dist/src/training-queries.js +374 -231
  115. package/dist/src/training-retrieval.d.ts +17 -27
  116. package/dist/src/training-retrieval.js +186 -139
  117. package/dist/src/training-runtime.d.ts +3 -0
  118. package/dist/src/training-runtime.js +76 -18
  119. package/dist/src/training-store.d.ts +18 -3
  120. package/dist/src/training-store.js +141 -52
  121. package/dist/src/training.js +9 -11
  122. package/dist/src/whisperer-context.d.ts +13 -0
  123. package/dist/src/whisperer-context.js +22 -1
  124. package/docs/configuration.md +83 -64
  125. package/docs/extraction.md +26 -35
  126. package/docs/memory-training.md +7 -6
  127. package/docs/people-learning.md +2 -2
  128. package/docs/peoplesql.md +6 -6
  129. package/docs/response-audit.md +10 -8
  130. package/docs/retrieval.md +43 -47
  131. package/openclaw.plugin.json +76 -75
  132. package/package.json +5 -2
  133. package/skills/memory-curator/SKILL.md +1 -1
  134. package/skills/people-whisperer/SKILL.md +1 -1
  135. package/dist/src/typesafe-client.d.ts +0 -30
  136. package/dist/src/typesafe-client.js +0 -92
  137. package/dist/src/typesafe-review.js +0 -154
  138. package/dist/src/typesafe.js +0 -147
@@ -1,10 +1,10 @@
1
1
  import type { ChatType } from "./config.js";
2
2
  import type { SessionMessageSpan } from "./session-projector.js";
3
3
  import type { QueryLane } from "./query-contract.js";
4
- export declare const TRAINING_RETRIEVAL_VERSION = "qmd-2.10.2-historical-lanes-depth10-v3:complete-excerpt-1200-v1";
4
+ export declare const TRAINING_RETRIEVAL_VERSION: string;
5
5
  export declare const TRAINING_SEARCH_OPTIONS: {
6
- readonly vector: 10;
7
- readonly bm25: 10;
6
+ readonly vector: number;
7
+ readonly bm25: number;
8
8
  readonly mergedLimit: null;
9
9
  readonly rerank: false;
10
10
  };
@@ -19,16 +19,7 @@ export type TrainingHit = {
19
19
  score: number;
20
20
  methods: string[];
21
21
  };
22
- /** Missing historical evidence is reviewable; unexpected SQLite/I/O failures remain fatal. */
23
- export declare class HistoricalCorpusUnavailableError extends Error {
24
- }
25
- /** Never infer dates by parsing message bodies: headings can be quoted or forged. */
26
- export declare function historicalPrefix(body: string, spans: readonly SessionMessageSpan[] | undefined, cutoff: number): {
27
- body: string;
28
- spans: SessionMessageSpan[];
29
- } | undefined;
30
- /** Capture source bytes once per run; each cutoff still owns its index and native model context. */
31
- export declare function historicalTrainingSource(stateDir: string, chatTypes: readonly ChatType[]): Promise<(cutoff: number, openStore?: typeof import("@unblocklabs/qmd")["createStore"]) => Promise<{
22
+ export type HistoricalTrainingSnapshot = {
32
23
  corpusHash: string;
33
24
  report: {
34
25
  sessions: number;
@@ -38,20 +29,19 @@ export declare function historicalTrainingSource(stateDir: string, chatTypes: re
38
29
  excludedChunks: number;
39
30
  };
40
31
  maxDate: string;
32
+ proven?: boolean;
41
33
  search: (query: string, lane: QueryLane) => Promise<TrainingHit[]>;
42
34
  close: () => Promise<void>;
43
- }>>;
35
+ };
36
+ /** Missing historical evidence is reviewable; unexpected SQLite/I/O failures remain fatal. */
37
+ export declare class HistoricalCorpusUnavailableError extends Error {
38
+ }
39
+ /** Never infer dates by parsing message bodies: headings can be quoted or forged. */
40
+ export declare function historicalPrefix(body: string, spans: readonly SessionMessageSpan[] | undefined, cutoff: number): {
41
+ body: string;
42
+ spans: SessionMessageSpan[];
43
+ } | undefined;
44
+ /** Capture source bytes once per run; each cutoff still owns its index and native model context. */
45
+ export declare function historicalTrainingSource(stateDir: string, chatTypes: readonly ChatType[]): Promise<(cutoff: number, openStore?: typeof import("@unblocklabs/qmd")["createStore"]) => Promise<HistoricalTrainingSnapshot>>;
44
46
  /** Standalone calls get a fresh source capture; evaluation runs reuse their own capture. */
45
- export declare function historicalTrainingSearch(stateDir: string, chatTypes: readonly ChatType[], cutoff: number, openStore?: typeof import("@unblocklabs/qmd")["createStore"]): Promise<{
46
- corpusHash: string;
47
- report: {
48
- sessions: number;
49
- chunks: number;
50
- excluded: number;
51
- truncated: number;
52
- excludedChunks: number;
53
- };
54
- maxDate: string;
55
- search: (query: string, lane: QueryLane) => Promise<TrainingHit[]>;
56
- close: () => Promise<void>;
57
- }>;
47
+ export declare function historicalTrainingSearch(stateDir: string, chatTypes: readonly ChatType[], cutoff: number, openStore?: typeof import("@unblocklabs/qmd")["createStore"]): Promise<HistoricalTrainingSnapshot>;
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { statSync } from "node:fs";
3
4
  import { join } from "node:path";
@@ -7,25 +8,44 @@ import { projectionHash, readSessionManifest } from "./session-sync.js";
7
8
  import { resolveSessionSource } from "./sources.js";
8
9
  import { trainingCandidates } from "./training-candidates.js";
9
10
  import { MEMORY_PASSAGE_VERSION, renderMemoryPassage, duplicateMemoryPassage } from "./memory-passage.js";
10
- export const TRAINING_RETRIEVAL_VERSION = `qmd-2.10.2-historical-lanes-depth10-v3:${MEMORY_PASSAGE_VERSION}`;
11
- export const TRAINING_SEARCH_OPTIONS = { vector: 10, bm25: 10, mergedLimit: null, rerank: false };
11
+ export const TRAINING_RETRIEVAL_VERSION = `qmd-2.10.2-historical-lanes-depth${DEFAULTS.training.retrievalDepth}-v3:${MEMORY_PASSAGE_VERSION}`;
12
+ export const TRAINING_SEARCH_OPTIONS = { vector: DEFAULTS.training.retrievalDepth, bm25: DEFAULTS.training.retrievalDepth, mergedLimit: null, rerank: false };
12
13
  /** Missing historical evidence is reviewable; unexpected SQLite/I/O failures remain fatal. */
13
14
  export class HistoricalCorpusUnavailableError extends Error {
14
15
  }
15
- /** Never infer dates by parsing message bodies: headings can be quoted or forged. */
16
- export function historicalPrefix(body, spans, cutoff) {
16
+ function createYielder(budgetMs = 25) {
17
+ let yieldAt = performance.now() + budgetMs;
18
+ return async () => {
19
+ if (performance.now() >= yieldAt) {
20
+ await yieldToEventLoop();
21
+ yieldAt = performance.now() + budgetMs;
22
+ }
23
+ };
24
+ }
25
+ function assertFileExists(path, unavailableMessage) {
26
+ try {
27
+ statSync(path);
28
+ }
29
+ catch (error) {
30
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
31
+ throw new HistoricalCorpusUnavailableError(unavailableMessage);
32
+ }
33
+ throw error;
34
+ }
35
+ }
36
+ function inspectHistoricalPrefix(body, spans, cutoff) {
17
37
  if (!spans?.length || !body.startsWith("# Transcript\n\n") || !Number.isFinite(cutoff))
18
- return;
38
+ return { status: "unproven" };
19
39
  let previousEnd = 14;
20
40
  const parsed = [];
21
41
  for (const span of spans) {
22
42
  if (![span.start, span.bodyStart, span.end].every(Number.isSafeInteger) || span.start < previousEnd ||
23
43
  span.bodyStart <= span.start || span.end < span.bodyStart || span.end > body.length ||
24
44
  body.slice(previousEnd, span.start).trim())
25
- return;
45
+ return { status: "unproven" };
26
46
  const heading = `## ${span.type === "user" ? "User" : "Assistant"} — ${span.name} — ${span.timestamp}\n\n`;
27
47
  if (body.slice(span.start, span.bodyStart) !== heading)
28
- return;
48
+ return { status: "unproven" };
29
49
  // Explicit zones only: no process-local timezone interpretation. Unknown zones fail closed.
30
50
  const time = typeof span.timestamp === "string" && / (?:UTC|GMT(?:[+-]\d{1,2}(?::\d{2})?)?|[ECMP][SD]T)$/u.test(span.timestamp)
31
51
  ? Date.parse(span.timestamp) : NaN;
@@ -33,39 +53,50 @@ export function historicalPrefix(body, spans, cutoff) {
33
53
  previousEnd = span.end;
34
54
  }
35
55
  if (body.slice(previousEnd).trim())
36
- return;
56
+ return { status: "unproven" };
37
57
  // Projection dates have second precision. Exclude the entire cutoff second,
38
58
  // including the current question, equal-time replies and crossing chunks.
39
59
  const before = Math.floor(cutoff / 1000) * 1000;
40
60
  const safe = [];
61
+ let unprovenTimestamp = false;
41
62
  for (const item of parsed) {
42
- if (!Number.isFinite(item.time) || item.time >= before)
63
+ if (!Number.isFinite(item.time)) {
64
+ unprovenTimestamp = true;
65
+ break;
66
+ }
67
+ if (item.time >= before)
43
68
  break;
44
69
  safe.push(item);
45
70
  }
46
71
  if (!safe.length)
47
- return;
48
- return { body: body.slice(0, parsed[safe.length]?.span.start ?? body.length), spans: safe.map(s => s.span) };
72
+ return { status: unprovenTimestamp ? "unproven" : "empty" };
73
+ return { status: "prefix", body: body.slice(0, parsed[safe.length]?.span.start ?? body.length), spans: safe.map(s => s.span) };
49
74
  }
50
- /** Capture source bytes once per run; each cutoff still owns its index and native model context. */
51
- export async function historicalTrainingSource(stateDir, chatTypes) {
75
+ /** Never infer dates by parsing message bodies: headings can be quoted or forged. */
76
+ export function historicalPrefix(body, spans, cutoff) {
77
+ const inspected = inspectHistoricalPrefix(body, spans, cutoff);
78
+ return inspected.status === "prefix" ? { body: inspected.body, spans: inspected.spans } : undefined;
79
+ }
80
+ async function captureSourceSessions(stateDir, chatTypes) {
52
81
  const indexPath = join(stateDir, "index.sqlite");
53
- try {
54
- statSync(indexPath);
82
+ const manifestPath = join(stateDir, "sessions-manifest.json");
83
+ assertFileExists(indexPath, "No QMD index; sync sessions before evaluating training queries");
84
+ assertFileExists(manifestPath, "No session manifest; sync sessions before evaluating training queries");
85
+ const manifest = await readSessionManifest(manifestPath);
86
+ if (manifest.failedSessions && Object.keys(manifest.failedSessions).length > 0) {
87
+ throw new HistoricalCorpusUnavailableError("Session manifest has unavailable/failed sessions; sync sessions before evaluating training queries");
55
88
  }
56
- catch (error) {
57
- if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
58
- throw new HistoricalCorpusUnavailableError("No QMD index; sync sessions before evaluating training queries");
59
- }
60
- throw error;
89
+ if (typeof manifest.lastSuccessfulSyncAt !== "number" || !Number.isFinite(manifest.lastSuccessfulSyncAt) ||
90
+ typeof manifest.indexSignature !== "string" || !manifest.indexSignature.trim()) {
91
+ throw new HistoricalCorpusUnavailableError("Session manifest is uncertified; sync sessions before evaluating training queries");
61
92
  }
62
- const manifest = await readSessionManifest(join(stateDir, "sessions-manifest.json"));
63
93
  const source = resolveSessionSource(join(stateDir, "sessions"), chatTypes);
64
94
  // Use QMD's exact binding, never mix node:sqlite with sqlite-vec.
65
95
  const requireQmd = createRequire(import.meta.resolve("@unblocklabs/qmd"));
66
96
  const Database = requireQmd("better-sqlite3");
67
97
  const sourceDb = new Database(indexPath, { readonly: true, fileMustExist: true });
68
98
  const sessions = [];
99
+ const unbackedSessions = [];
69
100
  let excluded = 0;
70
101
  let settings;
71
102
  try {
@@ -77,20 +108,27 @@ export async function historicalTrainingSource(stateDir, chatTypes) {
77
108
  if (typeof extensionPath !== "string")
78
109
  throw new Error("QMD sqlite-vec path unavailable");
79
110
  sourceDb.loadExtension(extensionPath);
80
- sourceDb.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=5000; BEGIN");
111
+ sourceDb.exec(`PRAGMA query_only=ON; PRAGMA busy_timeout=${DEFAULTS.sqlite.mainBusyTimeoutMs}; BEGIN`);
81
112
  settings = sourceDb.prepare("SELECT key,value FROM store_config WHERE key='embedding_chunk_strategy'").all();
113
+ const manifestSessions = Object.values(manifest.sessions).sort((a, b) => a.documentPath.localeCompare(b.documentPath));
114
+ if (!manifestSessions.length) {
115
+ const hasIndexedDocs = sourceDb.prepare("SELECT 1 FROM documents WHERE active=1 AND collection=? LIMIT 1").get(source.collection);
116
+ if (hasIndexedDocs) {
117
+ throw new HistoricalCorpusUnavailableError("Session manifest is unbacked by QMD index; sync sessions before evaluating training queries");
118
+ }
119
+ }
82
120
  const document = sourceDb.prepare(`SELECT d.hash,c.doc FROM documents d JOIN content c ON c.hash=d.hash
83
121
  WHERE d.active=1 AND d.collection=? AND d.path=?`);
84
- const chunks = sourceDb.prepare(`SELECT cv.seq,cv.pos,cv.chunk_len,cv.model,cv.embed_fingerprint,v.embedding
85
- FROM content_vectors cv JOIN vectors_vec v ON v.hash_seq=cv.hash||'_'||cv.seq
86
- WHERE cv.hash=? ORDER BY cv.seq`);
122
+ const hasVectorsTable = Boolean(sourceDb.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get());
123
+ const chunks = hasVectorsTable
124
+ ? sourceDb.prepare(`SELECT cv.seq,cv.pos,cv.chunk_len,cv.model,cv.embed_fingerprint,v.embedding
125
+ FROM content_vectors cv JOIN vectors_vec v ON v.hash_seq=cv.hash||'_'||cv.seq
126
+ WHERE cv.hash=? ORDER BY cv.seq`)
127
+ : undefined;
87
128
  const vectors = new Map();
88
- let yieldAt = performance.now() + 25;
89
- for (const session of Object.values(manifest.sessions).sort((a, b) => a.documentPath.localeCompare(b.documentPath))) {
90
- if (performance.now() >= yieldAt) {
91
- await yieldToEventLoop();
92
- yieldAt = performance.now() + 25;
93
- }
129
+ const maybeYield = createYielder(25);
130
+ for (const session of manifestSessions) {
131
+ await maybeYield();
94
132
  // Loggie projections can retroactively annotate old text using later revisions.
95
133
  // Workspace files and meetings lack immutable historical content proof here.
96
134
  if (!chatTypes.includes(session.chatType) || session.provider === "loggie") {
@@ -100,17 +138,17 @@ export async function historicalTrainingSource(stateDir, chatTypes) {
100
138
  const row = document.get(source.collection, session.documentPath);
101
139
  if (!row || projectionHash(row.doc) !== session.projectionHash) {
102
140
  excluded++;
141
+ unbackedSessions.push(session);
103
142
  continue;
104
143
  }
105
144
  let captured = vectors.get(row.hash);
106
145
  if (!captured) {
107
146
  captured = [];
108
- for (const chunk of chunks.iterate(row.hash)) {
109
- if (performance.now() >= yieldAt) {
110
- await yieldToEventLoop();
111
- yieldAt = performance.now() + 25;
147
+ if (chunks) {
148
+ for (const chunk of chunks.iterate(row.hash)) {
149
+ await maybeYield();
150
+ captured.push({ ...chunk, embedding: Buffer.from(chunk.embedding) });
112
151
  }
113
- captured.push({ ...chunk, embedding: Buffer.from(chunk.embedding) });
114
152
  }
115
153
  vectors.set(row.hash, captured);
116
154
  }
@@ -120,118 +158,127 @@ export async function historicalTrainingSource(stateDir, chatTypes) {
120
158
  finally {
121
159
  sourceDb.close();
122
160
  }
123
- return async (cutoff, openStore) => {
124
- const createStore = openStore ?? (await import("@unblocklabs/qmd")).createStore;
125
- const maxDate = new Date(cutoff).toISOString();
126
- const report = { sessions: 0, chunks: 0, excluded, truncated: 0, excludedChunks: 0 };
127
- const metadata = new Map();
128
- const fingerprint = createHash("sha256").update(JSON.stringify([TRAINING_RETRIEVAL_VERSION, chatTypes.toSorted(), maxDate]));
129
- fingerprint.update(JSON.stringify(settings));
130
- const documents = [];
131
- let dimensions, closed = false;
132
- let indexed;
133
- let yieldAt = performance.now() + 25;
134
- for (const { session, body, chunks } of sessions) {
135
- if (performance.now() >= yieldAt) {
136
- await yieldToEventLoop();
137
- yieldAt = performance.now() + 25;
138
- }
139
- if (session.startedAt >= cutoff) {
140
- report.excluded++;
141
- continue;
142
- }
143
- const prefix = historicalPrefix(body, session.messages, cutoff);
144
- if (!prefix) {
145
- report.excluded++;
161
+ return { source, sessions, unbackedSessions, excluded, settings };
162
+ }
163
+ async function selectCutoffDocuments(captured, chatTypes, cutoff) {
164
+ const maxDate = new Date(cutoff).toISOString();
165
+ const report = { sessions: 0, chunks: 0, excluded: captured.excluded, truncated: 0, excludedChunks: 0 };
166
+ const metadata = new Map();
167
+ const fingerprint = createHash("sha256").update(JSON.stringify([TRAINING_RETRIEVAL_VERSION, chatTypes.toSorted(), maxDate]));
168
+ fingerprint.update(JSON.stringify(captured.settings));
169
+ const documents = [];
170
+ let dimensions;
171
+ let unprovenBeforeCutoff = captured.unbackedSessions.some(session => !Number.isFinite(session.startedAt) || session.startedAt < cutoff);
172
+ const maybeYield = createYielder(25);
173
+ for (const { session, body, chunks } of captured.sessions) {
174
+ await maybeYield();
175
+ if (session.startedAt >= cutoff) {
176
+ report.excluded++;
177
+ continue;
178
+ }
179
+ const prefix = inspectHistoricalPrefix(body, session.messages, cutoff);
180
+ if (prefix.status !== "prefix") {
181
+ report.excluded++;
182
+ if (prefix.status === "unproven")
183
+ unprovenBeforeCutoff = true;
184
+ continue;
185
+ }
186
+ const hash = createHash("sha256").update(prefix.body).digest("hex");
187
+ const safeChunks = [];
188
+ documents.push({ path: session.documentPath, hash, body: prefix.body, chunks: safeChunks });
189
+ metadata.set(`qmd://${captured.source.collection}/${session.documentPath}`, prefix.spans);
190
+ fingerprint.update(JSON.stringify([session.documentPath, hash]));
191
+ report.sessions++;
192
+ if (prefix.spans.length < (session.messages?.length ?? 0))
193
+ report.truncated++;
194
+ for (const chunk of chunks) {
195
+ await maybeYield();
196
+ if (!historicalChunk(chunk, prefix.body.length)) {
197
+ report.excludedChunks++;
146
198
  continue;
147
199
  }
148
- const hash = createHash("sha256").update(prefix.body).digest("hex");
149
- const safeChunks = [];
150
- documents.push({ path: session.documentPath, hash, body: prefix.body, chunks: safeChunks });
151
- metadata.set(`qmd://${source.collection}/${session.documentPath}`, prefix.spans);
152
- fingerprint.update(JSON.stringify([session.documentPath, hash]));
153
- report.sessions++;
154
- if (prefix.spans.length < (session.messages?.length ?? 0))
155
- report.truncated++;
156
- for (const chunk of chunks) {
157
- if (performance.now() >= yieldAt) {
158
- await yieldToEventLoop();
159
- yieldAt = performance.now() + 25;
160
- }
161
- if (!historicalChunk(chunk, prefix.body.length)) {
162
- report.excludedChunks++;
163
- continue;
164
- }
165
- const bytes = chunk.embedding;
166
- if (bytes.length % 4 || !bytes.length)
167
- throw new Error("Invalid historical embedding");
168
- const size = bytes.length / 4;
169
- dimensions ??= size;
170
- if (dimensions !== size)
171
- throw new Error("Mixed historical embedding dimensions");
172
- safeChunks.push(chunk);
173
- fingerprint.update(JSON.stringify([chunk.seq, chunk.pos, chunk.chunk_len, chunk.model, chunk.embed_fingerprint])).update(bytes);
174
- report.chunks++;
175
- }
200
+ const bytes = chunk.embedding;
201
+ if (bytes.length % 4 || !bytes.length)
202
+ throw new Error("Invalid historical embedding");
203
+ const size = bytes.length / 4;
204
+ dimensions ??= size;
205
+ if (dimensions !== size)
206
+ throw new Error("Mixed historical embedding dimensions");
207
+ safeChunks.push(chunk);
208
+ fingerprint.update(JSON.stringify([chunk.seq, chunk.pos, chunk.chunk_len, chunk.model, chunk.embed_fingerprint])).update(bytes);
209
+ report.chunks++;
176
210
  }
177
- const corpusHash = fingerprint.digest("hex");
178
- const materialize = async () => {
179
- let qmd;
180
- try {
181
- qmd = await createStore({ dbPath: ":memory:", keepModelsWarm: true,
182
- config: { collections: { [source.collection]: { path: source.root, pattern: "**/*.md" } } } });
183
- // One native embedding context per snapshot; serialize only vector search.
184
- const searchVec = qmd.internal.searchVec;
185
- let vectorTail = Promise.resolve();
186
- qmd.internal.searchVec = (...args) => {
187
- const result = vectorTail.then(() => searchVec(...args));
188
- vectorTail = result.then(() => { }, () => { });
189
- return result;
190
- };
191
- const db = qmd.internal.db;
192
- db.exec("BEGIN");
193
- for (const { key, value } of settings)
194
- db.prepare("INSERT OR REPLACE INTO store_config VALUES (?,?)").run(key, value);
195
- if (dimensions !== undefined)
196
- qmd.internal.ensureVecTable(dimensions);
197
- yieldAt = performance.now() + 25;
198
- for (const document of documents) {
199
- if (performance.now() >= yieldAt) {
200
- await yieldToEventLoop();
201
- yieldAt = performance.now() + 25;
202
- }
203
- qmd.internal.insertContent(document.hash, document.body, maxDate);
204
- qmd.internal.insertDocument(source.collection, document.path, "Transcript", document.hash, maxDate, maxDate);
205
- for (const chunk of document.chunks) {
206
- if (performance.now() >= yieldAt) {
207
- await yieldToEventLoop();
208
- yieldAt = performance.now() + 25;
209
- }
210
- const bytes = Buffer.from(chunk.embedding.buffer, chunk.embedding.byteOffset, chunk.embedding.byteLength);
211
- const vector = new Float32Array(bytes.length / 4);
212
- for (let i = 0; i < vector.length; i++)
213
- vector[i] = bytes.readFloatLE(i * 4);
214
- qmd.internal.insertEmbedding(document.hash, chunk.seq, chunk.pos, vector, chunk.model, maxDate, 1, chunk.embed_fingerprint, chunk.chunk_len);
215
- }
216
- }
217
- db.exec("COMMIT");
218
- return qmd;
219
- }
220
- catch (error) {
221
- await qmd?.close();
222
- throw error;
223
- }
211
+ }
212
+ return { corpusHash: fingerprint.digest("hex"), maxDate, report, metadata, documents, dimensions, unprovenBeforeCutoff };
213
+ }
214
+ async function materializeQmdStore(createStore, source, settings, documents, dimensions, maxDate) {
215
+ let qmd;
216
+ try {
217
+ qmd = await createStore({ dbPath: ":memory:", keepModelsWarm: true,
218
+ config: { collections: { [source.collection]: { path: source.root, pattern: "**/*.md" } } } });
219
+ // One native embedding context per snapshot; serialize only vector search.
220
+ const searchVec = qmd.internal.searchVec;
221
+ let vectorTail = Promise.resolve();
222
+ qmd.internal.searchVec = (...args) => {
223
+ const result = vectorTail.then(() => searchVec(...args));
224
+ vectorTail = result.then(() => { }, () => { });
225
+ return result;
224
226
  };
225
- return { corpusHash, report, maxDate,
227
+ const db = qmd.internal.db;
228
+ db.exec("BEGIN");
229
+ for (const { key, value } of settings)
230
+ db.prepare("INSERT OR REPLACE INTO store_config VALUES (?,?)").run(key, value);
231
+ if (dimensions !== undefined)
232
+ qmd.internal.ensureVecTable(dimensions);
233
+ const maybeYield = createYielder(25);
234
+ for (const document of documents) {
235
+ await maybeYield();
236
+ qmd.internal.insertContent(document.hash, document.body, maxDate);
237
+ qmd.internal.insertDocument(source.collection, document.path, "Transcript", document.hash, maxDate, maxDate);
238
+ for (const chunk of document.chunks) {
239
+ await maybeYield();
240
+ const bytes = Buffer.from(chunk.embedding.buffer, chunk.embedding.byteOffset, chunk.embedding.byteLength);
241
+ const vector = new Float32Array(bytes.length / 4);
242
+ for (let i = 0; i < vector.length; i++)
243
+ vector[i] = bytes.readFloatLE(i * 4);
244
+ qmd.internal.insertEmbedding(document.hash, chunk.seq, chunk.pos, vector, chunk.model, maxDate, 1, chunk.embed_fingerprint, chunk.chunk_len);
245
+ }
246
+ }
247
+ db.exec("COMMIT");
248
+ return qmd;
249
+ }
250
+ catch (error) {
251
+ await qmd?.close();
252
+ throw error;
253
+ }
254
+ }
255
+ /** Capture source bytes once per run; each cutoff still owns its index and native model context. */
256
+ export async function historicalTrainingSource(stateDir, chatTypes) {
257
+ const captured = await captureSourceSessions(stateDir, chatTypes);
258
+ return async (cutoff, openStore) => {
259
+ const createStore = openStore ?? (await import("@unblocklabs/qmd")).createStore;
260
+ const { corpusHash, maxDate, report, metadata, documents, dimensions, unprovenBeforeCutoff } = await selectCutoffDocuments(captured, chatTypes, cutoff);
261
+ if (report.sessions && unprovenBeforeCutoff) {
262
+ throw new HistoricalCorpusUnavailableError("Historical snapshot cannot prove a complete cutoff; sync sessions before evaluating training queries");
263
+ }
264
+ const proven = report.sessions > 0 ? report.chunks > 0 : !unprovenBeforeCutoff;
265
+ let closed = false;
266
+ let indexed;
267
+ return { corpusHash, report, maxDate, proven,
226
268
  search: async (query, lane) => {
227
269
  if (closed)
228
270
  throw new Error("Historical snapshot is closed");
229
- if (!report.sessions)
271
+ if (!report.sessions) {
272
+ if (unprovenBeforeCutoff) {
273
+ throw new HistoricalCorpusUnavailableError("Historical snapshot cannot prove an empty cutoff; sync sessions before evaluating training queries");
274
+ }
230
275
  return [];
231
- if (lane === "vec" && !report.chunks)
276
+ }
277
+ if (lane === "vec" && !report.chunks) {
232
278
  throw new HistoricalCorpusUnavailableError("Historical snapshot has no vectors; refusing an unresolved vector evaluation");
233
- const qmd = await (indexed ??= materialize());
234
- const hits = await trainingCandidates(qmd, query, source.collection, lane);
279
+ }
280
+ const qmd = await (indexed ??= materializeQmdStore(createStore, captured.source, captured.settings, documents, dimensions, maxDate));
281
+ const hits = await trainingCandidates(qmd, query, captured.source.collection, lane);
235
282
  const rendered = await Promise.all(hits.map(hit => trainingHit(hit, metadata, cutoff)));
236
283
  const distinct = [];
237
284
  for (const hit of rendered)
@@ -1,4 +1,7 @@
1
+ import { linkSync } from "node:fs";
1
2
  import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
2
3
  import type { UnblockMemoryConfig } from "./config.js";
4
+ /** Write JSONL to a private same-filesystem temp file and publish atomically without overwriting. */
5
+ export declare function writeTrainingExportJsonl(output: string, data: Iterable<unknown>, link?: typeof linkSync): number;
3
6
  /** CLI only: no scheduler, tools, hooks, or live memory-index changes. */
4
7
  export declare function registerMemoryTraining(api: OpenClawPluginApi, config: UnblockMemoryConfig): void;
@@ -1,13 +1,74 @@
1
- import { existsSync, openSync, writeSync, closeSync } from "node:fs";
2
- import { join, resolve } from "node:path";
1
+ import { randomUUID } from "node:crypto";
2
+ import { closeSync, existsSync, fchmodSync, fsyncSync, linkSync, lstatSync, openSync, unlinkSync, writeSync } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
3
4
  import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
4
5
  import { normalizeAgentIdStrict } from "openclaw/plugin-sdk/routing";
5
6
  import { TrainingStore } from "./training-store.js";
6
7
  import { TRAINING_GATE_THRESHOLD } from "./training-gate.js";
7
8
  import { collectTraining, runTraining } from "./training.js";
8
- import { generateTrainingQueries, evaluateTrainingQueries, exportQueryTraining, TRAINING_EVALUATION_CONCURRENCY } from "./training-queries.js";
9
+ import { currentTrainingCorpusHashes, generateTrainingQueries, evaluateTrainingQueries, exportQueryTraining, TRAINING_EVALUATION_CONCURRENCY } from "./training-queries.js";
10
+ import { memoryJudgeVersion } from "./decision-ranking.js";
11
+ import { decisionModelScope } from "./decision-client.js";
9
12
  import { dateOption } from "./date-option.js";
10
13
  import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
14
+ function pathExists(path) {
15
+ try {
16
+ lstatSync(path);
17
+ return true;
18
+ }
19
+ catch (error) {
20
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
21
+ return false;
22
+ throw error;
23
+ }
24
+ }
25
+ function existsError(path) {
26
+ const error = new Error(`EEXIST: file already exists, open '${path}'`);
27
+ error.code = "EEXIST";
28
+ return error;
29
+ }
30
+ /** Write JSONL to a private same-filesystem temp file and publish atomically without overwriting. */
31
+ export function writeTrainingExportJsonl(output, data, link = linkSync) {
32
+ if (pathExists(output))
33
+ throw existsError(output);
34
+ const tempPath = join(dirname(output), `.${basename(output)}.${process.pid}.${randomUUID()}.tmp`);
35
+ const fd = openSync(tempPath, "wx", 0o600);
36
+ let rows = 0;
37
+ let closed = false;
38
+ try {
39
+ fchmodSync(fd, 0o600);
40
+ for (const row of data) {
41
+ writeSync(fd, JSON.stringify(row) + "\n");
42
+ rows++;
43
+ }
44
+ fsyncSync(fd);
45
+ closeSync(fd);
46
+ closed = true;
47
+ try {
48
+ link(tempPath, output);
49
+ }
50
+ catch (error) {
51
+ const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
52
+ if (code === "EEXIST")
53
+ throw existsError(output);
54
+ if (code === "EPERM" || code === "ENOTSUP" || code === "ENOSYS" || code === "EXDEV") {
55
+ const unsupported = new Error(`Atomic no-overwrite export requires filesystem hardlink support (${code}): '${output}'`, { cause: error });
56
+ unsupported.code = code;
57
+ throw unsupported;
58
+ }
59
+ throw error;
60
+ }
61
+ return rows;
62
+ }
63
+ finally {
64
+ if (!closed)
65
+ closeSync(fd);
66
+ try {
67
+ unlinkSync(tempPath);
68
+ }
69
+ catch { /* already removed */ }
70
+ }
71
+ }
11
72
  function thresholdOption(value) {
12
73
  const result = Number(value);
13
74
  if (!value.trim() || !Number.isFinite(result) || result < 0 || result > 1)
@@ -31,7 +92,7 @@ export function registerMemoryTraining(api, config) {
31
92
  const source = paths(cfg, agent);
32
93
  if (!options.create && !existsSync(source.storePath))
33
94
  throw new Error("No training database; run memory-training collect first");
34
- const store = new TrainingStore(source.storePath, source.agentId);
95
+ const store = new TrainingStore(source.storePath, source.agentId, decisionModelScope(config.decisionModel.model, config.decisionModel.endpoint));
35
96
  try {
36
97
  return await (options.readOnly ? fn(store, source) : store.locked(() => fn(store, source)));
37
98
  }
@@ -54,7 +115,7 @@ export function registerMemoryTraining(api, config) {
54
115
  root.command("run").description("Judge whether historical recall would help each collected input").option("--agent <id>", "Agent id", "main")
55
116
  .option("--max-examples <n>", "Optional maximum new API calls; no example-count limit by default")
56
117
  .option("--max-input-bytes <n>", "Maximum total serialized state + question bytes, not tokens", "3000000")
57
- .option("--concurrency <n>", "Concurrent TypeSafe recall requests", "256")
118
+ .option("--concurrency <n>", "Concurrent decision-model recall requests", "32")
58
119
  .option("--dry-run", "Refresh local checkpoints and preview pending work without API calls")
59
120
  .action(async (opts) => {
60
121
  const result = await withStore(opts.agent, {}, (store, source) => runTraining(source, store, config, {
@@ -111,21 +172,18 @@ export function registerMemoryTraining(api, config) {
111
172
  if (!["recall-gate", "query-training"].includes(opts.stage))
112
173
  throw new Error("Unknown training export stage");
113
174
  const output = resolve(opts.output);
175
+ if (pathExists(output))
176
+ throw existsError(output);
114
177
  const threshold = thresholdOption(opts.threshold);
115
- const result = await withStore(opts.agent, {}, (store, source) => {
178
+ const result = await withStore(opts.agent, {}, async (store, source) => {
116
179
  collectTraining(source, store, { existingOnly: true });
117
- const fd = openSync(output, "wx", 0o600);
118
- let rows = 0;
119
- const data = opts.stage === "query-training" ? exportQueryTraining(store, threshold) : store.exportRows(threshold);
120
- try {
121
- for (const row of data) {
122
- writeSync(fd, JSON.stringify(row) + "\n");
123
- rows++;
124
- }
125
- }
126
- finally {
127
- closeSync(fd);
128
- }
180
+ const judgeVersion = memoryJudgeVersion(config.decisionModel.model, config.decisionModel.endpoint);
181
+ const data = opts.stage === "query-training"
182
+ ? exportQueryTraining(store, threshold, judgeVersion, {
183
+ corpusHashes: await currentTrainingCorpusHashes(source, store, config, threshold),
184
+ })
185
+ : store.exportRows(threshold);
186
+ const rows = writeTrainingExportJsonl(output, data);
129
187
  return { output, rows, stage: opts.stage };
130
188
  });
131
189
  console.log(JSON.stringify(result, null, 2));