@unblocklabs/unblock-memory 0.12.3 → 0.13.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.
- package/README.md +19 -18
- package/dist/src/analysis.js +1 -1
- package/dist/src/cluster-review.d.ts +2 -0
- package/dist/src/cluster-review.js +3 -3
- package/dist/src/config.d.ts +9 -6
- package/dist/src/config.js +31 -20
- package/dist/src/curation.d.ts +1 -1
- package/dist/src/decision-client.d.ts +39 -0
- package/dist/src/decision-client.js +74 -0
- package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
- package/dist/src/decision-ranking.js +154 -0
- package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
- package/dist/src/decision-review.js +192 -0
- package/dist/src/diagnostics.d.ts +5 -5
- package/dist/src/emotion-baselines.d.ts +28 -3
- package/dist/src/emotion-baselines.js +309 -113
- package/dist/src/evidence-review.d.ts +22 -8
- package/dist/src/evidence-review.js +4 -4
- package/dist/src/extraction-chunk.d.ts +3 -0
- package/dist/src/extraction-chunk.js +23 -5
- package/dist/src/extraction-model.d.ts +2 -0
- package/dist/src/extraction-model.js +73 -48
- package/dist/src/extraction-runtime.d.ts +3 -1
- package/dist/src/extraction-runtime.js +43 -16
- package/dist/src/extraction-source.d.ts +1 -1
- package/dist/src/extraction-source.js +19 -11
- package/dist/src/extraction-store.d.ts +28 -3
- package/dist/src/extraction-store.js +145 -23
- package/dist/src/extraction-worker.d.ts +1 -0
- package/dist/src/extraction-worker.js +246 -93
- package/dist/src/inside-out-runtime.js +41 -29
- package/dist/src/inside-out-store.d.ts +2 -2
- package/dist/src/inside-out-store.js +110 -69
- package/dist/src/inside-out.d.ts +10 -9
- package/dist/src/inside-out.js +190 -105
- package/dist/src/manager.d.ts +22 -9
- package/dist/src/manager.js +275 -169
- package/dist/src/memory-search.d.ts +4 -2
- package/dist/src/memory-search.js +5 -5
- package/dist/src/memory-whisperer.d.ts +1 -1
- package/dist/src/memory-whisperer.js +183 -125
- package/dist/src/my-turn.d.ts +1 -1
- package/dist/src/my-turn.js +87 -68
- package/dist/src/people-background.d.ts +4 -0
- package/dist/src/people-background.js +29 -6
- package/dist/src/people-dossier-review.d.ts +20 -8
- package/dist/src/people-dossier-review.js +11 -8
- package/dist/src/people-hooks.js +127 -22
- package/dist/src/people-learning-cron.d.ts +1 -1
- package/dist/src/people-learning-cron.js +106 -57
- package/dist/src/people-learning-inventory.d.ts +1 -0
- package/dist/src/people-learning-inventory.js +281 -171
- package/dist/src/people-learning-prompt.js +1 -1
- package/dist/src/people-learning-runtime.d.ts +1 -1
- package/dist/src/people-learning-runtime.js +360 -203
- package/dist/src/people-learning-store.d.ts +27 -4
- package/dist/src/people-learning-store.js +312 -96
- package/dist/src/people-primer-tool.js +8 -6
- package/dist/src/people-primer.d.ts +3 -1
- package/dist/src/people-primer.js +61 -44
- package/dist/src/people-store.d.ts +18 -21
- package/dist/src/people-store.js +186 -63
- package/dist/src/people-tools.js +136 -92
- package/dist/src/plugin.js +16 -16
- package/dist/src/quality-audit.d.ts +2 -0
- package/dist/src/quality-audit.js +8 -7
- package/dist/src/response-audit.d.ts +1 -1
- package/dist/src/response-audit.js +76 -43
- package/dist/src/response-episodes.d.ts +1 -1
- package/dist/src/response-episodes.js +12 -17
- package/dist/src/response-judge.d.ts +151 -145
- package/dist/src/response-judge.js +535 -204
- package/dist/src/response-reviews.d.ts +29 -1
- package/dist/src/response-reviews.js +110 -13
- package/dist/src/response-runtime.js +8 -8
- package/dist/src/response-stages.d.ts +50 -53
- package/dist/src/response-stages.js +10 -4
- package/dist/src/response-store.d.ts +7 -6
- package/dist/src/response-store.js +332 -210
- package/dist/src/review-tools.d.ts +8 -2
- package/dist/src/review-tools.js +18 -18
- package/dist/src/runtime.d.ts +7 -4
- package/dist/src/runtime.js +624 -98
- package/dist/src/safety-whisperer.d.ts +2 -2
- package/dist/src/safety-whisperer.js +88 -71
- package/dist/src/session-sync.d.ts +3 -1
- package/dist/src/session-sync.js +200 -95
- package/dist/src/skill-whisperer.d.ts +1 -1
- package/dist/src/skill-whisperer.js +52 -30
- package/dist/src/training-gate.d.ts +8 -21
- package/dist/src/training-gate.js +32 -35
- package/dist/src/training-judge.d.ts +9 -16
- package/dist/src/training-judge.js +5 -5
- package/dist/src/training-queries.d.ts +13 -8
- package/dist/src/training-queries.js +370 -228
- package/dist/src/training-retrieval.d.ts +14 -24
- package/dist/src/training-retrieval.js +182 -136
- package/dist/src/training-runtime.d.ts +3 -0
- package/dist/src/training-runtime.js +76 -18
- package/dist/src/training-store.d.ts +18 -3
- package/dist/src/training-store.js +138 -50
- package/dist/src/training.js +8 -11
- package/dist/src/whisperer-context.d.ts +14 -0
- package/dist/src/whisperer-context.js +22 -1
- package/docs/configuration.md +76 -63
- package/docs/extraction.md +9 -7
- package/docs/memory-training.md +7 -6
- package/docs/people-learning.md +2 -2
- package/docs/peoplesql.md +6 -6
- package/docs/response-audit.md +10 -8
- package/docs/retrieval.md +40 -37
- package/openclaw.plugin.json +40 -26
- package/package.json +3 -2
- package/skills/memory-curator/SKILL.md +1 -1
- package/skills/people-whisperer/SKILL.md +1 -1
- package/dist/src/typesafe-client.d.ts +0 -30
- package/dist/src/typesafe-client.js +0 -92
- package/dist/src/typesafe-review.js +0 -154
- package/dist/src/typesafe.js +0 -147
|
@@ -19,16 +19,7 @@ export type TrainingHit = {
|
|
|
19
19
|
score: number;
|
|
20
20
|
methods: string[];
|
|
21
21
|
};
|
|
22
|
-
|
|
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>;
|
|
@@ -12,20 +12,39 @@ export const TRAINING_SEARCH_OPTIONS = { vector: 10, bm25: 10, mergedLimit: null
|
|
|
12
12
|
/** Missing historical evidence is reviewable; unexpected SQLite/I/O failures remain fatal. */
|
|
13
13
|
export class HistoricalCorpusUnavailableError extends Error {
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
function createYielder(budgetMs = 25) {
|
|
16
|
+
let yieldAt = performance.now() + budgetMs;
|
|
17
|
+
return async () => {
|
|
18
|
+
if (performance.now() >= yieldAt) {
|
|
19
|
+
await yieldToEventLoop();
|
|
20
|
+
yieldAt = performance.now() + budgetMs;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function assertFileExists(path, unavailableMessage) {
|
|
25
|
+
try {
|
|
26
|
+
statSync(path);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
30
|
+
throw new HistoricalCorpusUnavailableError(unavailableMessage);
|
|
31
|
+
}
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function inspectHistoricalPrefix(body, spans, cutoff) {
|
|
17
36
|
if (!spans?.length || !body.startsWith("# Transcript\n\n") || !Number.isFinite(cutoff))
|
|
18
|
-
return;
|
|
37
|
+
return { status: "unproven" };
|
|
19
38
|
let previousEnd = 14;
|
|
20
39
|
const parsed = [];
|
|
21
40
|
for (const span of spans) {
|
|
22
41
|
if (![span.start, span.bodyStart, span.end].every(Number.isSafeInteger) || span.start < previousEnd ||
|
|
23
42
|
span.bodyStart <= span.start || span.end < span.bodyStart || span.end > body.length ||
|
|
24
43
|
body.slice(previousEnd, span.start).trim())
|
|
25
|
-
return;
|
|
44
|
+
return { status: "unproven" };
|
|
26
45
|
const heading = `## ${span.type === "user" ? "User" : "Assistant"} — ${span.name} — ${span.timestamp}\n\n`;
|
|
27
46
|
if (body.slice(span.start, span.bodyStart) !== heading)
|
|
28
|
-
return;
|
|
47
|
+
return { status: "unproven" };
|
|
29
48
|
// Explicit zones only: no process-local timezone interpretation. Unknown zones fail closed.
|
|
30
49
|
const time = typeof span.timestamp === "string" && / (?:UTC|GMT(?:[+-]\d{1,2}(?::\d{2})?)?|[ECMP][SD]T)$/u.test(span.timestamp)
|
|
31
50
|
? Date.parse(span.timestamp) : NaN;
|
|
@@ -33,39 +52,50 @@ export function historicalPrefix(body, spans, cutoff) {
|
|
|
33
52
|
previousEnd = span.end;
|
|
34
53
|
}
|
|
35
54
|
if (body.slice(previousEnd).trim())
|
|
36
|
-
return;
|
|
55
|
+
return { status: "unproven" };
|
|
37
56
|
// Projection dates have second precision. Exclude the entire cutoff second,
|
|
38
57
|
// including the current question, equal-time replies and crossing chunks.
|
|
39
58
|
const before = Math.floor(cutoff / 1000) * 1000;
|
|
40
59
|
const safe = [];
|
|
60
|
+
let unprovenTimestamp = false;
|
|
41
61
|
for (const item of parsed) {
|
|
42
|
-
if (!Number.isFinite(item.time)
|
|
62
|
+
if (!Number.isFinite(item.time)) {
|
|
63
|
+
unprovenTimestamp = true;
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
if (item.time >= before)
|
|
43
67
|
break;
|
|
44
68
|
safe.push(item);
|
|
45
69
|
}
|
|
46
70
|
if (!safe.length)
|
|
47
|
-
return;
|
|
48
|
-
return { body: body.slice(0, parsed[safe.length]?.span.start ?? body.length), spans: safe.map(s => s.span) };
|
|
71
|
+
return { status: unprovenTimestamp ? "unproven" : "empty" };
|
|
72
|
+
return { status: "prefix", body: body.slice(0, parsed[safe.length]?.span.start ?? body.length), spans: safe.map(s => s.span) };
|
|
49
73
|
}
|
|
50
|
-
/**
|
|
51
|
-
export
|
|
74
|
+
/** Never infer dates by parsing message bodies: headings can be quoted or forged. */
|
|
75
|
+
export function historicalPrefix(body, spans, cutoff) {
|
|
76
|
+
const inspected = inspectHistoricalPrefix(body, spans, cutoff);
|
|
77
|
+
return inspected.status === "prefix" ? { body: inspected.body, spans: inspected.spans } : undefined;
|
|
78
|
+
}
|
|
79
|
+
async function captureSourceSessions(stateDir, chatTypes) {
|
|
52
80
|
const indexPath = join(stateDir, "index.sqlite");
|
|
53
|
-
|
|
54
|
-
|
|
81
|
+
const manifestPath = join(stateDir, "sessions-manifest.json");
|
|
82
|
+
assertFileExists(indexPath, "No QMD index; sync sessions before evaluating training queries");
|
|
83
|
+
assertFileExists(manifestPath, "No session manifest; sync sessions before evaluating training queries");
|
|
84
|
+
const manifest = await readSessionManifest(manifestPath);
|
|
85
|
+
if (manifest.failedSessions && Object.keys(manifest.failedSessions).length > 0) {
|
|
86
|
+
throw new HistoricalCorpusUnavailableError("Session manifest has unavailable/failed sessions; sync sessions before evaluating training queries");
|
|
55
87
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
throw error;
|
|
88
|
+
if (typeof manifest.lastSuccessfulSyncAt !== "number" || !Number.isFinite(manifest.lastSuccessfulSyncAt) ||
|
|
89
|
+
typeof manifest.indexSignature !== "string" || !manifest.indexSignature.trim()) {
|
|
90
|
+
throw new HistoricalCorpusUnavailableError("Session manifest is uncertified; sync sessions before evaluating training queries");
|
|
61
91
|
}
|
|
62
|
-
const manifest = await readSessionManifest(join(stateDir, "sessions-manifest.json"));
|
|
63
92
|
const source = resolveSessionSource(join(stateDir, "sessions"), chatTypes);
|
|
64
93
|
// Use QMD's exact binding, never mix node:sqlite with sqlite-vec.
|
|
65
94
|
const requireQmd = createRequire(import.meta.resolve("@unblocklabs/qmd"));
|
|
66
95
|
const Database = requireQmd("better-sqlite3");
|
|
67
96
|
const sourceDb = new Database(indexPath, { readonly: true, fileMustExist: true });
|
|
68
97
|
const sessions = [];
|
|
98
|
+
const unbackedSessions = [];
|
|
69
99
|
let excluded = 0;
|
|
70
100
|
let settings;
|
|
71
101
|
try {
|
|
@@ -79,18 +109,25 @@ export async function historicalTrainingSource(stateDir, chatTypes) {
|
|
|
79
109
|
sourceDb.loadExtension(extensionPath);
|
|
80
110
|
sourceDb.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=5000; BEGIN");
|
|
81
111
|
settings = sourceDb.prepare("SELECT key,value FROM store_config WHERE key='embedding_chunk_strategy'").all();
|
|
112
|
+
const manifestSessions = Object.values(manifest.sessions).sort((a, b) => a.documentPath.localeCompare(b.documentPath));
|
|
113
|
+
if (!manifestSessions.length) {
|
|
114
|
+
const hasIndexedDocs = sourceDb.prepare("SELECT 1 FROM documents WHERE active=1 AND collection=? LIMIT 1").get(source.collection);
|
|
115
|
+
if (hasIndexedDocs) {
|
|
116
|
+
throw new HistoricalCorpusUnavailableError("Session manifest is unbacked by QMD index; sync sessions before evaluating training queries");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
82
119
|
const document = sourceDb.prepare(`SELECT d.hash,c.doc FROM documents d JOIN content c ON c.hash=d.hash
|
|
83
120
|
WHERE d.active=1 AND d.collection=? AND d.path=?`);
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
121
|
+
const hasVectorsTable = Boolean(sourceDb.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get());
|
|
122
|
+
const chunks = hasVectorsTable
|
|
123
|
+
? sourceDb.prepare(`SELECT cv.seq,cv.pos,cv.chunk_len,cv.model,cv.embed_fingerprint,v.embedding
|
|
124
|
+
FROM content_vectors cv JOIN vectors_vec v ON v.hash_seq=cv.hash||'_'||cv.seq
|
|
125
|
+
WHERE cv.hash=? ORDER BY cv.seq`)
|
|
126
|
+
: undefined;
|
|
87
127
|
const vectors = new Map();
|
|
88
|
-
|
|
89
|
-
for (const session of
|
|
90
|
-
|
|
91
|
-
await yieldToEventLoop();
|
|
92
|
-
yieldAt = performance.now() + 25;
|
|
93
|
-
}
|
|
128
|
+
const maybeYield = createYielder(25);
|
|
129
|
+
for (const session of manifestSessions) {
|
|
130
|
+
await maybeYield();
|
|
94
131
|
// Loggie projections can retroactively annotate old text using later revisions.
|
|
95
132
|
// Workspace files and meetings lack immutable historical content proof here.
|
|
96
133
|
if (!chatTypes.includes(session.chatType) || session.provider === "loggie") {
|
|
@@ -100,17 +137,17 @@ export async function historicalTrainingSource(stateDir, chatTypes) {
|
|
|
100
137
|
const row = document.get(source.collection, session.documentPath);
|
|
101
138
|
if (!row || projectionHash(row.doc) !== session.projectionHash) {
|
|
102
139
|
excluded++;
|
|
140
|
+
unbackedSessions.push(session);
|
|
103
141
|
continue;
|
|
104
142
|
}
|
|
105
143
|
let captured = vectors.get(row.hash);
|
|
106
144
|
if (!captured) {
|
|
107
145
|
captured = [];
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
await
|
|
111
|
-
|
|
146
|
+
if (chunks) {
|
|
147
|
+
for (const chunk of chunks.iterate(row.hash)) {
|
|
148
|
+
await maybeYield();
|
|
149
|
+
captured.push({ ...chunk, embedding: Buffer.from(chunk.embedding) });
|
|
112
150
|
}
|
|
113
|
-
captured.push({ ...chunk, embedding: Buffer.from(chunk.embedding) });
|
|
114
151
|
}
|
|
115
152
|
vectors.set(row.hash, captured);
|
|
116
153
|
}
|
|
@@ -120,118 +157,127 @@ export async function historicalTrainingSource(stateDir, chatTypes) {
|
|
|
120
157
|
finally {
|
|
121
158
|
sourceDb.close();
|
|
122
159
|
}
|
|
123
|
-
return
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
if (
|
|
145
|
-
|
|
160
|
+
return { source, sessions, unbackedSessions, excluded, settings };
|
|
161
|
+
}
|
|
162
|
+
async function selectCutoffDocuments(captured, chatTypes, cutoff) {
|
|
163
|
+
const maxDate = new Date(cutoff).toISOString();
|
|
164
|
+
const report = { sessions: 0, chunks: 0, excluded: captured.excluded, truncated: 0, excludedChunks: 0 };
|
|
165
|
+
const metadata = new Map();
|
|
166
|
+
const fingerprint = createHash("sha256").update(JSON.stringify([TRAINING_RETRIEVAL_VERSION, chatTypes.toSorted(), maxDate]));
|
|
167
|
+
fingerprint.update(JSON.stringify(captured.settings));
|
|
168
|
+
const documents = [];
|
|
169
|
+
let dimensions;
|
|
170
|
+
let unprovenBeforeCutoff = captured.unbackedSessions.some(session => !Number.isFinite(session.startedAt) || session.startedAt < cutoff);
|
|
171
|
+
const maybeYield = createYielder(25);
|
|
172
|
+
for (const { session, body, chunks } of captured.sessions) {
|
|
173
|
+
await maybeYield();
|
|
174
|
+
if (session.startedAt >= cutoff) {
|
|
175
|
+
report.excluded++;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const prefix = inspectHistoricalPrefix(body, session.messages, cutoff);
|
|
179
|
+
if (prefix.status !== "prefix") {
|
|
180
|
+
report.excluded++;
|
|
181
|
+
if (prefix.status === "unproven")
|
|
182
|
+
unprovenBeforeCutoff = true;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const hash = createHash("sha256").update(prefix.body).digest("hex");
|
|
186
|
+
const safeChunks = [];
|
|
187
|
+
documents.push({ path: session.documentPath, hash, body: prefix.body, chunks: safeChunks });
|
|
188
|
+
metadata.set(`qmd://${captured.source.collection}/${session.documentPath}`, prefix.spans);
|
|
189
|
+
fingerprint.update(JSON.stringify([session.documentPath, hash]));
|
|
190
|
+
report.sessions++;
|
|
191
|
+
if (prefix.spans.length < (session.messages?.length ?? 0))
|
|
192
|
+
report.truncated++;
|
|
193
|
+
for (const chunk of chunks) {
|
|
194
|
+
await maybeYield();
|
|
195
|
+
if (!historicalChunk(chunk, prefix.body.length)) {
|
|
196
|
+
report.excludedChunks++;
|
|
146
197
|
continue;
|
|
147
198
|
}
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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
|
-
}
|
|
199
|
+
const bytes = chunk.embedding;
|
|
200
|
+
if (bytes.length % 4 || !bytes.length)
|
|
201
|
+
throw new Error("Invalid historical embedding");
|
|
202
|
+
const size = bytes.length / 4;
|
|
203
|
+
dimensions ??= size;
|
|
204
|
+
if (dimensions !== size)
|
|
205
|
+
throw new Error("Mixed historical embedding dimensions");
|
|
206
|
+
safeChunks.push(chunk);
|
|
207
|
+
fingerprint.update(JSON.stringify([chunk.seq, chunk.pos, chunk.chunk_len, chunk.model, chunk.embed_fingerprint])).update(bytes);
|
|
208
|
+
report.chunks++;
|
|
176
209
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
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
|
-
}
|
|
210
|
+
}
|
|
211
|
+
return { corpusHash: fingerprint.digest("hex"), maxDate, report, metadata, documents, dimensions, unprovenBeforeCutoff };
|
|
212
|
+
}
|
|
213
|
+
async function materializeQmdStore(createStore, source, settings, documents, dimensions, maxDate) {
|
|
214
|
+
let qmd;
|
|
215
|
+
try {
|
|
216
|
+
qmd = await createStore({ dbPath: ":memory:", keepModelsWarm: true,
|
|
217
|
+
config: { collections: { [source.collection]: { path: source.root, pattern: "**/*.md" } } } });
|
|
218
|
+
// One native embedding context per snapshot; serialize only vector search.
|
|
219
|
+
const searchVec = qmd.internal.searchVec;
|
|
220
|
+
let vectorTail = Promise.resolve();
|
|
221
|
+
qmd.internal.searchVec = (...args) => {
|
|
222
|
+
const result = vectorTail.then(() => searchVec(...args));
|
|
223
|
+
vectorTail = result.then(() => { }, () => { });
|
|
224
|
+
return result;
|
|
224
225
|
};
|
|
225
|
-
|
|
226
|
+
const db = qmd.internal.db;
|
|
227
|
+
db.exec("BEGIN");
|
|
228
|
+
for (const { key, value } of settings)
|
|
229
|
+
db.prepare("INSERT OR REPLACE INTO store_config VALUES (?,?)").run(key, value);
|
|
230
|
+
if (dimensions !== undefined)
|
|
231
|
+
qmd.internal.ensureVecTable(dimensions);
|
|
232
|
+
const maybeYield = createYielder(25);
|
|
233
|
+
for (const document of documents) {
|
|
234
|
+
await maybeYield();
|
|
235
|
+
qmd.internal.insertContent(document.hash, document.body, maxDate);
|
|
236
|
+
qmd.internal.insertDocument(source.collection, document.path, "Transcript", document.hash, maxDate, maxDate);
|
|
237
|
+
for (const chunk of document.chunks) {
|
|
238
|
+
await maybeYield();
|
|
239
|
+
const bytes = Buffer.from(chunk.embedding.buffer, chunk.embedding.byteOffset, chunk.embedding.byteLength);
|
|
240
|
+
const vector = new Float32Array(bytes.length / 4);
|
|
241
|
+
for (let i = 0; i < vector.length; i++)
|
|
242
|
+
vector[i] = bytes.readFloatLE(i * 4);
|
|
243
|
+
qmd.internal.insertEmbedding(document.hash, chunk.seq, chunk.pos, vector, chunk.model, maxDate, 1, chunk.embed_fingerprint, chunk.chunk_len);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
db.exec("COMMIT");
|
|
247
|
+
return qmd;
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
await qmd?.close();
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/** Capture source bytes once per run; each cutoff still owns its index and native model context. */
|
|
255
|
+
export async function historicalTrainingSource(stateDir, chatTypes) {
|
|
256
|
+
const captured = await captureSourceSessions(stateDir, chatTypes);
|
|
257
|
+
return async (cutoff, openStore) => {
|
|
258
|
+
const createStore = openStore ?? (await import("@unblocklabs/qmd")).createStore;
|
|
259
|
+
const { corpusHash, maxDate, report, metadata, documents, dimensions, unprovenBeforeCutoff } = await selectCutoffDocuments(captured, chatTypes, cutoff);
|
|
260
|
+
if (report.sessions && unprovenBeforeCutoff) {
|
|
261
|
+
throw new HistoricalCorpusUnavailableError("Historical snapshot cannot prove a complete cutoff; sync sessions before evaluating training queries");
|
|
262
|
+
}
|
|
263
|
+
const proven = report.sessions > 0 ? report.chunks > 0 : !unprovenBeforeCutoff;
|
|
264
|
+
let closed = false;
|
|
265
|
+
let indexed;
|
|
266
|
+
return { corpusHash, report, maxDate, proven,
|
|
226
267
|
search: async (query, lane) => {
|
|
227
268
|
if (closed)
|
|
228
269
|
throw new Error("Historical snapshot is closed");
|
|
229
|
-
if (!report.sessions)
|
|
270
|
+
if (!report.sessions) {
|
|
271
|
+
if (unprovenBeforeCutoff) {
|
|
272
|
+
throw new HistoricalCorpusUnavailableError("Historical snapshot cannot prove an empty cutoff; sync sessions before evaluating training queries");
|
|
273
|
+
}
|
|
230
274
|
return [];
|
|
231
|
-
|
|
275
|
+
}
|
|
276
|
+
if (lane === "vec" && !report.chunks) {
|
|
232
277
|
throw new HistoricalCorpusUnavailableError("Historical snapshot has no vectors; refusing an unresolved vector evaluation");
|
|
233
|
-
|
|
234
|
-
const
|
|
278
|
+
}
|
|
279
|
+
const qmd = await (indexed ??= materializeQmdStore(createStore, captured.source, captured.settings, documents, dimensions, maxDate));
|
|
280
|
+
const hits = await trainingCandidates(qmd, query, captured.source.collection, lane);
|
|
235
281
|
const rendered = await Promise.all(hits.map(hit => trainingHit(hit, metadata, cutoff)));
|
|
236
282
|
const distinct = [];
|
|
237
283
|
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 {
|
|
2
|
-
import {
|
|
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
|
|
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
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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));
|