@unblocklabs/unblock-memory 0.10.1 → 0.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -7
- package/dist/src/abortable.d.ts +2 -0
- package/dist/src/abortable.js +4 -0
- package/dist/src/agent-paths.d.ts +5 -0
- package/dist/src/agent-paths.js +10 -0
- package/dist/src/analysis.js +13 -18
- package/dist/src/cluster-review.js +9 -7
- package/dist/src/config.js +2 -2
- package/dist/src/curation.js +3 -10
- package/dist/src/diagnostics.d.ts +6 -1
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/emotion-baselines.d.ts +0 -2
- package/dist/src/emotion-baselines.js +18 -39
- package/dist/src/evidence-review.js +2 -1
- package/dist/src/extraction-chunk.js +3 -4
- package/dist/src/extraction-index.d.ts +2 -0
- package/dist/src/extraction-index.js +4 -2
- package/dist/src/extraction-runtime.js +3 -3
- package/dist/src/extraction-store.js +7 -19
- package/dist/src/extraction-worker.js +3 -2
- package/dist/src/guards.d.ts +6 -0
- package/dist/src/guards.js +12 -0
- package/dist/src/inside-out-runtime.js +4 -3
- package/dist/src/inside-out-store.js +4 -10
- package/dist/src/inside-out.js +5 -3
- package/dist/src/json-hash.d.ts +2 -0
- package/dist/src/json-hash.js +6 -0
- package/dist/src/manager.d.ts +6 -1
- package/dist/src/manager.js +62 -91
- package/dist/src/memory-database.d.ts +3 -0
- package/dist/src/memory-database.js +18 -1
- package/dist/src/memory-search.d.ts +8 -2
- package/dist/src/memory-search.js +18 -2
- package/dist/src/people-hooks.js +3 -6
- package/dist/src/people-primer-tool.js +0 -2
- package/dist/src/people-primer.js +3 -6
- package/dist/src/people-store.d.ts +2 -1
- package/dist/src/people-store.js +29 -82
- package/dist/src/people-tools.js +4 -5
- package/dist/src/plugin.js +36 -27
- package/dist/src/quality-audit.js +2 -2
- package/dist/src/query-generator.js +1 -1
- package/dist/src/response-audit.js +7 -8
- package/dist/src/response-episodes.js +5 -8
- package/dist/src/response-judge.js +2 -3
- package/dist/src/response-reviews.js +8 -18
- package/dist/src/response-runtime.js +4 -3
- package/dist/src/response-stages.js +4 -4
- package/dist/src/response-store.js +15 -44
- package/dist/src/response-text.d.ts +1 -0
- package/dist/src/response-text.js +6 -4
- package/dist/src/retrieval-telemetry.d.ts +7 -2
- package/dist/src/retrieval-telemetry.js +3 -2
- package/dist/src/runtime.js +9 -8
- package/dist/src/safety-whisperer.js +4 -12
- package/dist/src/session-projector.js +7 -14
- package/dist/src/session-sync.d.ts +1 -0
- package/dist/src/session-sync.js +13 -17
- package/dist/src/skill-whisperer.js +3 -9
- package/dist/src/slack-directory.js +1 -5
- package/dist/src/sources.js +17 -37
- package/dist/src/tool-context.d.ts +2 -0
- package/dist/src/tool-context.js +5 -1
- package/dist/src/training-input.d.ts +0 -1
- package/dist/src/training-input.js +3 -6
- package/dist/src/training-queries.d.ts +1 -1
- package/dist/src/training-queries.js +9 -8
- package/dist/src/training-retrieval.js +2 -2
- package/dist/src/training-runtime.js +3 -3
- package/dist/src/training-store.js +14 -25
- package/dist/src/typesafe-client.d.ts +8 -0
- package/dist/src/typesafe-client.js +7 -1
- package/dist/src/typesafe-review.d.ts +1 -1
- package/dist/src/typesafe-review.js +1 -3
- package/dist/src/typesafe.js +4 -7
- package/docs/configuration.md +1 -1
- package/docs/retrieval.md +34 -7
- package/openclaw.plugin.json +1 -1
- package/package.json +6 -2
|
@@ -59,9 +59,10 @@ export async function runExtraction(params) {
|
|
|
59
59
|
if (existing.length > 100 || JSON.stringify(existing.map(m => ({ id: m.id, text: m.text }))).length > 40_000) {
|
|
60
60
|
throw new Error("Existing memories exceed review budget");
|
|
61
61
|
}
|
|
62
|
+
const existingFacts = existing.map(m => ({ id: m.id, text: m.text, observedAt: m.observedAt }));
|
|
62
63
|
const page = await readExtractionChunk({ agentId: params.agentId, agentName: params.agentName, session,
|
|
63
64
|
cursor: checkpoint.cursor, context: extractionHistory(checkpoint.context, config.historyMessages),
|
|
64
|
-
existing:
|
|
65
|
+
existing: existingFacts, signal, readPage });
|
|
65
66
|
if (page.kind === "unavailable") {
|
|
66
67
|
store.error(session.sessionId, "source_unavailable");
|
|
67
68
|
failed++;
|
|
@@ -85,7 +86,7 @@ export async function runExtraction(params) {
|
|
|
85
86
|
const messages = page.messages;
|
|
86
87
|
const newIds = fresh.map(m => m.id);
|
|
87
88
|
stage = "propose";
|
|
88
|
-
const proposals = newIds.length ? await (params.extract ?? extractWithLuna)(params.runtime, params.agentId, messages, newIds,
|
|
89
|
+
const proposals = newIds.length ? await (params.extract ?? extractWithLuna)(params.runtime, params.agentId, messages, newIds, existingFacts, signal) : [];
|
|
89
90
|
const accepted = [];
|
|
90
91
|
stage = "validate";
|
|
91
92
|
for (let start = 0; start < proposals.length; start += 4) {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Narrowing for untrusted JSON-shaped input such as transcripts and API responses. */
|
|
2
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
3
|
+
/** A plain object, or undefined for null, arrays and primitives. */
|
|
4
|
+
export declare function record(value: unknown): Record<string, unknown> | undefined;
|
|
5
|
+
/** A trimmed non-empty string, or undefined. */
|
|
6
|
+
export declare function nonBlank(value: unknown): string | undefined;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Narrowing for untrusted JSON-shaped input such as transcripts and API responses. */
|
|
2
|
+
export function isRecord(value) {
|
|
3
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
/** A plain object, or undefined for null, arrays and primitives. */
|
|
6
|
+
export function record(value) {
|
|
7
|
+
return isRecord(value) ? value : undefined;
|
|
8
|
+
}
|
|
9
|
+
/** A trimmed non-empty string, or undefined. */
|
|
10
|
+
export function nonBlank(value) {
|
|
11
|
+
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
12
|
+
}
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { join, dirname } from "node:path";
|
|
2
|
-
import { resolveAgentDir
|
|
2
|
+
import { resolveAgentDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
|
|
3
3
|
import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
|
|
4
4
|
import { MEMORY_DATABASE } from "./memory-database.js";
|
|
5
5
|
import { dateOption } from "./date-option.js";
|
|
6
6
|
import { linkInsideOutPeople, purgeInsideOutPerson, repairInsideOutIdentities, reportInsideOut, runInsideOut, refreshInsideOutBaselinesAsync, reportInsideOutBaselines } from "./inside-out.js";
|
|
7
|
+
import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
|
|
7
8
|
export function registerInsideOut(api, config) {
|
|
8
9
|
const paths = (cfg, agentId) => {
|
|
9
10
|
if (!listAgentIds(cfg).includes(agentId))
|
|
10
11
|
throw new Error("Unknown Inside Out agent");
|
|
11
12
|
const agentDir = resolveAgentDir(cfg, agentId);
|
|
12
|
-
return { agentId, databasePath:
|
|
13
|
-
storePath: join(
|
|
13
|
+
return { agentId, databasePath: agentTranscriptDatabase(cfg, agentId), sessionsDir: join(dirname(agentDir), "sessions"),
|
|
14
|
+
storePath: join(agentStateDir(agentId), MEMORY_DATABASE) };
|
|
14
15
|
};
|
|
15
16
|
api.registerCli(({ program, config: cfg }) => {
|
|
16
17
|
const root = program.command("memory-emotions").description("Inside Out: review human replies and analyze emotion probabilities");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { Worker } from "node:worker_threads";
|
|
3
|
-
import { openMemoryDatabase } from "./memory-database.js";
|
|
4
|
-
import { PURGED_GRADE, baselineFingerprint, purgeEmotionProfile, refreshEmotionBaselines
|
|
3
|
+
import { immediateTransaction, openMemoryDatabase, tableExists } from "./memory-database.js";
|
|
4
|
+
import { PURGED_GRADE, baselineFingerprint, purgeEmotionProfile, refreshEmotionBaselines } from "./emotion-baselines.js";
|
|
5
5
|
// Imported by the baseline worker with plain Node resolution: host SDK aliases do not
|
|
6
6
|
// reach worker threads, so this module and its imports must stay free of `openclaw`.
|
|
7
7
|
const SCHEMA = `CREATE TABLE IF NOT EXISTS inside_out (
|
|
@@ -52,16 +52,10 @@ export function linkInsideOutPeople(path) {
|
|
|
52
52
|
WHERE e.person_id IS NOT ${person} AND e.error IS NOT ?`).all(PURGED_GRADE);
|
|
53
53
|
const link = db.prepare("UPDATE inside_out SET person_id=? WHERE rowid=? AND error IS NOT ?");
|
|
54
54
|
for (let start = 0; start < changes.length; start += 500) {
|
|
55
|
-
db
|
|
56
|
-
try {
|
|
55
|
+
immediateTransaction(db, () => {
|
|
57
56
|
for (const change of changes.slice(start, start + 500))
|
|
58
57
|
updated += Number(link.run(change.person_id, change.id, PURGED_GRADE).changes);
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
catch (error) {
|
|
62
|
-
db.exec("ROLLBACK");
|
|
63
|
-
throw error;
|
|
64
|
-
}
|
|
58
|
+
});
|
|
65
59
|
}
|
|
66
60
|
}
|
|
67
61
|
const counts = db.prepare(`SELECT count(person_id) linked,count(*)-count(person_id) unlinked FROM inside_out`).get();
|
package/dist/src/inside-out.js
CHANGED
|
@@ -5,8 +5,10 @@ import { messageText } from "./whisperer-context.js";
|
|
|
5
5
|
import { conversationUserText } from "./response-text.js";
|
|
6
6
|
import { estimateJevTokens, requestTypeSafe, resolveTypeSafeApiKey, TYPESAFE_MODEL } from "./typesafe-client.js";
|
|
7
7
|
import { readInsideOutSources } from "./inside-out-sources.js";
|
|
8
|
-
import { INSIDE_OUT_EMOTIONS, PURGED_GRADE, deviationReader, emotionBaselineHistory
|
|
8
|
+
import { INSIDE_OUT_EMOTIONS, PURGED_GRADE, deviationReader, emotionBaselineHistory } from "./emotion-baselines.js";
|
|
9
9
|
import { PERSON_MATCH, openInsideOutStore, refreshInsideOutBaselinesAsync } from "./inside-out-store.js";
|
|
10
|
+
import { jsonHash } from "./json-hash.js";
|
|
11
|
+
import { tableExists } from "./memory-database.js";
|
|
10
12
|
export { linkInsideOutPeople, purgeInsideOutPerson, refreshInsideOutBaselines, refreshInsideOutBaselinesAsync } from "./inside-out-store.js";
|
|
11
13
|
const RUBRIC = "emotion-presence-v2";
|
|
12
14
|
const CONTEXT_ERROR = "Target reply and preceding assistant exceed context budget";
|
|
@@ -99,10 +101,10 @@ function* interactions(source, budget, cached, after) {
|
|
|
99
101
|
if (!text)
|
|
100
102
|
continue;
|
|
101
103
|
const { channel, sender, human } = humanIdentity(source, m);
|
|
102
|
-
const message = { id: event.id ??
|
|
104
|
+
const message = { id: event.id ?? jsonHash(event), role: parsed.role, text,
|
|
103
105
|
...(parsed.role === "user" ? { human } : {}) };
|
|
104
106
|
const assistant = parsed.role === "user" && event.seq > after ? history.findLastIndex(item => item.role === "assistant") : -1;
|
|
105
|
-
const id = assistant >= 0 ?
|
|
107
|
+
const id = assistant >= 0 ? jsonHash([source.sessionId, message.id]) : "";
|
|
106
108
|
if (assistant >= 0 && !cached(id)) {
|
|
107
109
|
const selected = [{ message: history[assistant], position: assistant }];
|
|
108
110
|
let size = estimateJevTokens({ history: selected.map(s => s.message), target: message });
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
// Loaded by the Inside Out baseline worker (see inside-out-store.ts): keep this module free of `openclaw`.
|
|
3
|
+
/** Hex SHA-256 of a value's JSON: the shared identity for cache, checkpoint and dedup keys. */
|
|
4
|
+
export function jsonHash(value) {
|
|
5
|
+
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
6
|
+
}
|
package/dist/src/manager.d.ts
CHANGED
|
@@ -61,9 +61,10 @@ export declare class QmdMemoryManager implements MemorySearchManagerContract {
|
|
|
61
61
|
failed?: number | undefined;
|
|
62
62
|
empty?: number | undefined;
|
|
63
63
|
timed_out?: number | undefined;
|
|
64
|
+
degraded?: number | undefined;
|
|
64
65
|
};
|
|
65
66
|
slowestRecent: {
|
|
66
|
-
outcome: "cancelled" | "ok" | "partial" | "skipped" | "failed" | "empty" | "timed_out";
|
|
67
|
+
outcome: "cancelled" | "ok" | "partial" | "skipped" | "failed" | "empty" | "timed_out" | "degraded";
|
|
67
68
|
setupMs?: number | undefined;
|
|
68
69
|
queueWaitMs?: number | undefined;
|
|
69
70
|
metadataMs?: number | undefined;
|
|
@@ -92,6 +93,10 @@ export declare class QmdMemoryManager implements MemorySearchManagerContract {
|
|
|
92
93
|
eligible?: number | undefined;
|
|
93
94
|
results?: number | undefined;
|
|
94
95
|
contextChars?: number | undefined;
|
|
96
|
+
requestsSucceeded?: number | undefined;
|
|
97
|
+
requestsFailed?: number | undefined;
|
|
98
|
+
fallbackKeyUnavailable?: number | undefined;
|
|
99
|
+
fallbackAllJudgmentsFailed?: number | undefined;
|
|
95
100
|
}[];
|
|
96
101
|
measurements: {
|
|
97
102
|
[k: string]: {
|
package/dist/src/manager.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
1
|
import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
2
|
import { mkdir, stat } from "node:fs/promises";
|
|
4
3
|
import { basename, dirname, relative, resolve, sep } from "node:path";
|
|
5
|
-
import { EXTRACTED_COLLECTION, extractedRecords, extractedPath, extractedHit, syncExtractedIndex } from "./extraction-index.js";
|
|
4
|
+
import { EXTRACTED_COLLECTION, EXTRACTED_PREFIX, extractedRecords, extractedPath, extractedHit, extractedUri, syncExtractedIndex } from "./extraction-index.js";
|
|
6
5
|
import chokidar from "chokidar";
|
|
7
6
|
import picomatch from "picomatch";
|
|
8
7
|
import { ensureMemoryAnalysisSchema, latestAnalysisCollections, latestAnalysisRunId, markMemoryAnalysisStale, readAnalysisSummary, readCluster, readClusters, runAnalysisWorker, } from "./analysis.js";
|
|
9
8
|
import { CurationStore, chunkFingerprint, } from "./curation.js";
|
|
10
|
-
import { readSessionManifest, sessionMetadataByPath, syncSessionProjections, PROJECTOR_VERSION, } from "./session-sync.js";
|
|
9
|
+
import { projectionHash, readSessionManifest, sessionMetadataByPath, syncSessionProjections, PROJECTOR_VERSION, } from "./session-sync.js";
|
|
11
10
|
import { parseSessionMessageSpans, sessionContextSpans, sessionSnippetMessages } from "./session-projector.js";
|
|
12
11
|
import { parseSafeVirtualPath, sourceMatchesPath } from "./sources.js";
|
|
13
12
|
import { auditQualityPage } from "./quality-audit.js";
|
|
@@ -211,8 +210,13 @@ export class QmdMemoryManager {
|
|
|
211
210
|
#dbPath;
|
|
212
211
|
#workspaceDir;
|
|
213
212
|
#curationPath;
|
|
214
|
-
|
|
213
|
+
/** Present only when extracted memories are published into search. */
|
|
214
|
+
#publishedExtraction;
|
|
215
215
|
#sources;
|
|
216
|
+
/** Non-skill sources: the QMD-indexed, analyzable corpora. */
|
|
217
|
+
#indexSources;
|
|
218
|
+
#indexCollections;
|
|
219
|
+
#hasSkills;
|
|
216
220
|
#storeFactory;
|
|
217
221
|
#keepModelsWarm;
|
|
218
222
|
#analysisExecutable;
|
|
@@ -264,9 +268,12 @@ export class QmdMemoryManager {
|
|
|
264
268
|
constructor(params) {
|
|
265
269
|
this.#dbPath = params.dbPath;
|
|
266
270
|
this.#curationPath = params.curationPath ?? `${params.dbPath}.curation.sqlite`;
|
|
267
|
-
this.#
|
|
271
|
+
this.#publishedExtraction = params.extraction?.enabled && params.extraction.publish ? params.extraction : undefined;
|
|
268
272
|
this.#workspaceDir = params.workspaceDir;
|
|
269
273
|
this.#sources = new Map(params.sources.map((source) => [source.collection, source]));
|
|
274
|
+
this.#indexSources = [...this.#sources.values()].filter((source) => source.kind !== "skills");
|
|
275
|
+
this.#indexCollections = this.#indexSources.map((source) => source.collection);
|
|
276
|
+
this.#hasSkills = [...this.#sources.values()].some((source) => source.kind === "skills");
|
|
270
277
|
this.#storeFactory = params.storeFactory;
|
|
271
278
|
this.#keepModelsWarm = params.keepModelsWarm ?? true;
|
|
272
279
|
this.#analysisExecutable = params.analysisExecutable;
|
|
@@ -360,7 +367,7 @@ export class QmdMemoryManager {
|
|
|
360
367
|
const store = this.#store;
|
|
361
368
|
if (store.internal) {
|
|
362
369
|
ensureMemoryAnalysisSchema(store.internal.db);
|
|
363
|
-
markStaleForAnalysisCollectionChange(store.internal.db, this.#
|
|
370
|
+
markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
|
|
364
371
|
}
|
|
365
372
|
return this.#store;
|
|
366
373
|
}
|
|
@@ -369,36 +376,31 @@ export class QmdMemoryManager {
|
|
|
369
376
|
dbPath: this.#dbPath,
|
|
370
377
|
keepModelsWarm: this.#keepModelsWarm,
|
|
371
378
|
config: {
|
|
372
|
-
collections: Object.fromEntries([...this.#
|
|
379
|
+
collections: Object.fromEntries([...this.#indexSources.map((source) => [
|
|
373
380
|
source.collection,
|
|
374
381
|
{ path: source.root, pattern: source.pattern },
|
|
375
|
-
]), ...(this.#
|
|
382
|
+
]), ...(this.#publishedExtraction
|
|
376
383
|
? [[EXTRACTED_COLLECTION, { path: dirname(this.#dbPath), pattern: ".no-extracted-files", includeByDefault: false }]] : [])]),
|
|
377
384
|
},
|
|
378
385
|
});
|
|
379
386
|
try {
|
|
380
387
|
enableSecureDelete(store);
|
|
381
388
|
ensureMemoryAnalysisSchema(store.internal.db);
|
|
382
|
-
markStaleForAnalysisCollectionChange(store.internal.db, this.#
|
|
383
|
-
const configuredCollections = new Set(this.#
|
|
384
|
-
if (this.#extraction?.enabled && this.#extraction.publish)
|
|
385
|
-
configuredCollections.add(EXTRACTED_COLLECTION);
|
|
389
|
+
markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
|
|
390
|
+
const configuredCollections = new Set(this.#collectionNames());
|
|
386
391
|
const staleCollections = (await store.getStatus()).collections
|
|
387
392
|
.map((collection) => collection.name)
|
|
388
393
|
.filter((collection) => !configuredCollections.has(collection));
|
|
394
|
+
const latestRunId = latestAnalysisRunId(store.internal.db);
|
|
389
395
|
const appearsInAnalysis = store.internal.db.prepare(`
|
|
390
396
|
SELECT 1
|
|
391
397
|
FROM memory_analysis_memberships membership
|
|
392
398
|
JOIN documents document ON document.hash = membership.hash
|
|
393
|
-
WHERE membership.run_id =
|
|
394
|
-
SELECT id FROM memory_analysis_runs
|
|
395
|
-
WHERE completed_at IS NOT NULL
|
|
396
|
-
ORDER BY completed_at DESC, created_at DESC, id DESC
|
|
397
|
-
LIMIT 1
|
|
398
|
-
) AND document.collection = ?
|
|
399
|
+
WHERE membership.run_id = ? AND document.collection = ?
|
|
399
400
|
LIMIT 1
|
|
400
401
|
`);
|
|
401
|
-
const prunedAnalysisInput =
|
|
402
|
+
const prunedAnalysisInput = latestRunId !== undefined &&
|
|
403
|
+
staleCollections.some((collection) => appearsInAnalysis.get(latestRunId, collection));
|
|
402
404
|
const prunedDocuments = await pruneStaleCollections(store, configuredCollections);
|
|
403
405
|
if (prunedDocuments > 0 && prunedAnalysisInput)
|
|
404
406
|
markMemoryAnalysisStale(store.internal.db);
|
|
@@ -414,69 +416,64 @@ export class QmdMemoryManager {
|
|
|
414
416
|
this.#store = store;
|
|
415
417
|
return store;
|
|
416
418
|
}
|
|
417
|
-
#qmdSources() {
|
|
418
|
-
return [...this.#sources.values()].filter((source) => source.kind !== "skills");
|
|
419
|
-
}
|
|
420
|
-
#analysisCollectionNames() {
|
|
421
|
-
return [...this.#sources.values()]
|
|
422
|
-
.filter((source) => source.kind !== "skills")
|
|
423
|
-
.map((source) => source.collection);
|
|
424
|
-
}
|
|
425
|
-
#skillCollectionNames() {
|
|
426
|
-
return [...this.#sources.values()]
|
|
427
|
-
.filter((source) => source.kind === "skills")
|
|
428
|
-
.map((source) => source.collection);
|
|
429
|
-
}
|
|
430
419
|
#collectionNames(corpora) {
|
|
431
|
-
const
|
|
432
|
-
const extracted = this.#extraction?.enabled && this.#extraction.publish ? [EXTRACTED_COLLECTION] : [];
|
|
420
|
+
const extracted = this.#publishedExtraction ? [EXTRACTED_COLLECTION] : [];
|
|
433
421
|
if (corpora === undefined)
|
|
434
|
-
return [...
|
|
422
|
+
return [...this.#indexCollections, ...extracted];
|
|
435
423
|
if (corpora.length === 0)
|
|
436
424
|
throw new Error("memory_search corpora must not be empty");
|
|
437
425
|
const selected = new Set(corpora);
|
|
438
426
|
if (selected.has("all")) {
|
|
439
427
|
if (selected.size > 1)
|
|
440
428
|
throw new Error('memory_search corpus "all" must be used alone');
|
|
441
|
-
return [...
|
|
429
|
+
return [...this.#indexCollections, ...extracted];
|
|
442
430
|
}
|
|
443
|
-
const known = new Set(
|
|
431
|
+
const known = new Set(this.#indexSources.map((source) => source.corpus));
|
|
444
432
|
if (extracted.length)
|
|
445
433
|
known.add("extracted");
|
|
446
434
|
const unknown = [...selected].find((corpus) => !known.has(corpus));
|
|
447
435
|
if (unknown)
|
|
448
436
|
throw new Error(`memory_search unknown corpus: ${unknown}`);
|
|
449
|
-
return [...
|
|
437
|
+
return [...this.#indexSources
|
|
450
438
|
.filter((source) => selected.has(source.corpus))
|
|
451
439
|
.map((source) => source.collection), ...(selected.has("extracted") ? extracted : [])];
|
|
452
440
|
}
|
|
453
441
|
syncExtracted() {
|
|
454
442
|
return this.#enqueue(async () => {
|
|
455
|
-
if (!this.#
|
|
443
|
+
if (!this.#publishedExtraction)
|
|
456
444
|
return;
|
|
457
445
|
const store = await this.#getAnalysisStore();
|
|
458
|
-
|
|
459
|
-
await syncExtractedIndex(store, records);
|
|
446
|
+
await syncExtractedIndex(store, this.#currentExtracted());
|
|
460
447
|
await this.#refreshIndexStatus(store);
|
|
461
448
|
});
|
|
462
449
|
}
|
|
463
450
|
#currentExtracted(paths, filter) {
|
|
464
|
-
|
|
451
|
+
const extraction = this.#publishedExtraction;
|
|
452
|
+
if (!extraction)
|
|
465
453
|
return [];
|
|
466
|
-
const records = extractedRecords(this.#curationPath, paths?.filter(path => path.startsWith(
|
|
467
|
-
.map(path => path.slice(
|
|
468
|
-
.filter(r =>
|
|
454
|
+
const records = extractedRecords(this.#curationPath, paths?.filter(path => path.startsWith(EXTRACTED_PREFIX))
|
|
455
|
+
.map(path => path.slice(EXTRACTED_PREFIX.length)))
|
|
456
|
+
.filter(r => extraction.chatTypes.includes(r.metadata.chatType));
|
|
469
457
|
if (!filter)
|
|
470
458
|
return records;
|
|
471
459
|
const allowed = new Set(sessionAllowedPaths(new Map(records.map(r => [extractedPath(r), r.metadata])), EXTRACTED_COLLECTION, filter)[EXTRACTED_COLLECTION]);
|
|
472
460
|
return records.filter(r => allowed.has(extractedPath(r)));
|
|
473
461
|
}
|
|
462
|
+
/** Search scope: session-filtered transcripts plus currently published extracted memories. */
|
|
463
|
+
#allowedPaths(collections, filter) {
|
|
464
|
+
const sessions = this.#sessions;
|
|
465
|
+
const allowed = filter && sessions && collections.includes(sessions.collection)
|
|
466
|
+
? sessionAllowedPaths(this.#sessionMetadata, sessions.collection, filter) : undefined;
|
|
467
|
+
return collections.includes(EXTRACTED_COLLECTION)
|
|
468
|
+
? { ...allowed, [EXTRACTED_COLLECTION]: this.#currentExtracted(undefined, filter).map(extractedPath) }
|
|
469
|
+
: allowed;
|
|
470
|
+
}
|
|
474
471
|
async #updateAndEmbed(store, collections, force) {
|
|
475
472
|
// Extracted facts are DB projections, not files: never run filesystem sync on them.
|
|
476
473
|
const analysisStore = store;
|
|
477
474
|
let changedDocuments = 0;
|
|
478
475
|
try {
|
|
479
|
-
const update = await store.update({ collections:
|
|
476
|
+
const update = await store.update({ collections: [...(collections ?? this.#indexCollections)] });
|
|
480
477
|
changedDocuments = update.updated + update.removed;
|
|
481
478
|
if ((update.indexed + changedDocuments > 0 || update.needsEmbedding > 0 || force) && analysisStore.internal) {
|
|
482
479
|
markMemoryAnalysisStale(analysisStore.internal.db);
|
|
@@ -517,7 +514,7 @@ export class QmdMemoryManager {
|
|
|
517
514
|
const run = async () => {
|
|
518
515
|
const store = await this.#getStore();
|
|
519
516
|
this.#dirty = true;
|
|
520
|
-
const collections = affectedCollections ?? this.#
|
|
517
|
+
const collections = affectedCollections ?? this.#indexSources.filter((source) => source.kind !== "sessions").map(source => source.collection);
|
|
521
518
|
await this.#updateAndEmbed(store, collections.length ? collections : undefined, params?.force);
|
|
522
519
|
await this.#refreshIndexStatus(store);
|
|
523
520
|
};
|
|
@@ -565,7 +562,7 @@ export class QmdMemoryManager {
|
|
|
565
562
|
await this.#analysisRunner({
|
|
566
563
|
executable: this.#analysisExecutable,
|
|
567
564
|
dbPath: this.#dbPath,
|
|
568
|
-
collections: this.#
|
|
565
|
+
collections: this.#indexCollections,
|
|
569
566
|
options,
|
|
570
567
|
signal,
|
|
571
568
|
});
|
|
@@ -810,19 +807,9 @@ export class QmdMemoryManager {
|
|
|
810
807
|
if (sessions && collections.includes(sessions.collection)) {
|
|
811
808
|
await this.#refreshSessionMetadata();
|
|
812
809
|
}
|
|
813
|
-
let allowedPaths = opts?.sessionFilter && sessions && collections.includes(sessions.collection)
|
|
814
|
-
? sessionAllowedPaths(this.#sessionMetadata, sessions.collection, opts.sessionFilter)
|
|
815
|
-
: undefined;
|
|
816
810
|
const store = await this.#getStore();
|
|
817
811
|
opts?.signal?.throwIfAborted();
|
|
818
|
-
const
|
|
819
|
-
if (!collections.includes(EXTRACTED_COLLECTION))
|
|
820
|
-
return [];
|
|
821
|
-
return this.#currentExtracted(paths, opts?.sessionFilter);
|
|
822
|
-
};
|
|
823
|
-
if (collections.includes(EXTRACTED_COLLECTION)) {
|
|
824
|
-
allowedPaths = { ...allowedPaths, [EXTRACTED_COLLECTION]: currentRecords().map(extractedPath) };
|
|
825
|
-
}
|
|
812
|
+
const allowedPaths = this.#allowedPaths(collections, opts?.sessionFilter);
|
|
826
813
|
const hits = await store.vsearch(query, {
|
|
827
814
|
collection: collections,
|
|
828
815
|
limit: opts?.maxResults ?? 5,
|
|
@@ -850,13 +837,7 @@ export class QmdMemoryManager {
|
|
|
850
837
|
if (timings && !signal?.aborted)
|
|
851
838
|
timings.metadataReloads = Number(reloaded);
|
|
852
839
|
}
|
|
853
|
-
|
|
854
|
-
let allowed = opts.sessionFilter && sessions && collections.includes(sessions.collection)
|
|
855
|
-
? sessionAllowedPaths(this.#sessionMetadata, sessions.collection, opts.sessionFilter) : undefined;
|
|
856
|
-
if (collections.includes(EXTRACTED_COLLECTION)) {
|
|
857
|
-
allowed = { ...allowed, [EXTRACTED_COLLECTION]: this.#currentExtracted(undefined, opts.sessionFilter).map(extractedPath) };
|
|
858
|
-
}
|
|
859
|
-
return allowed;
|
|
840
|
+
return this.#allowedPaths(collections, opts.sessionFilter);
|
|
860
841
|
});
|
|
861
842
|
const store = await timeStage("storeSetupMs", timings, signal, () => this.#getAnalysisStore());
|
|
862
843
|
const hits = new Map();
|
|
@@ -890,7 +871,7 @@ export class QmdMemoryManager {
|
|
|
890
871
|
async #renderSearchHits(hits, store, opts, whisperer = false) {
|
|
891
872
|
const tokenizer = store.internal?.llm;
|
|
892
873
|
const results = [];
|
|
893
|
-
const current = new Map(this.#currentExtracted(hits.map(hit => hit.file), opts?.sessionFilter).map(r => [
|
|
874
|
+
const current = new Map(this.#currentExtracted(hits.map(hit => hit.file), opts?.sessionFilter).map(r => [extractedUri(r), r]));
|
|
894
875
|
for (const hit of hits) {
|
|
895
876
|
opts?.signal?.throwIfAborted();
|
|
896
877
|
// Proactive hints must retain the entire matched chunk, even when expanded
|
|
@@ -917,7 +898,7 @@ export class QmdMemoryManager {
|
|
|
917
898
|
// Never apply offsets from a newer projection to an older indexed snapshot.
|
|
918
899
|
const messages = corpus === "sessions"
|
|
919
900
|
? projection?.messages && projection.documentPath === relativePath &&
|
|
920
|
-
projection.projectionHash ===
|
|
901
|
+
projection.projectionHash === projectionHash(hit.body)
|
|
921
902
|
? projection.messages : parseSessionMessageSpans(hit.body)
|
|
922
903
|
: undefined;
|
|
923
904
|
const messageTimestamp = messages
|
|
@@ -945,12 +926,11 @@ export class QmdMemoryManager {
|
|
|
945
926
|
});
|
|
946
927
|
}
|
|
947
928
|
// Expansion above can yield; recheck only derived hits once more before returning.
|
|
948
|
-
const finalPaths = new Set(this.#currentExtracted(results.map(hit => hit.path), opts?.sessionFilter).map(
|
|
949
|
-
return results.filter(hit => !hit.path.startsWith(
|
|
929
|
+
const finalPaths = new Set(this.#currentExtracted(results.map(hit => hit.path), opts?.sessionFilter).map(extractedUri));
|
|
930
|
+
return results.filter(hit => !hit.path.startsWith(EXTRACTED_PREFIX) || finalPaths.has(hit.path));
|
|
950
931
|
}
|
|
951
932
|
async searchSkills(query, minScore, limit) {
|
|
952
|
-
|
|
953
|
-
if (collections.length === 0)
|
|
933
|
+
if (!this.#hasSkills)
|
|
954
934
|
return [];
|
|
955
935
|
await this.#operationChain;
|
|
956
936
|
const store = await this.#getStore();
|
|
@@ -961,29 +941,22 @@ export class QmdMemoryManager {
|
|
|
961
941
|
let skillIndex = this.#skillIndex;
|
|
962
942
|
if (!skillIndex) {
|
|
963
943
|
const pending = (async () => {
|
|
964
|
-
|
|
965
|
-
const
|
|
944
|
+
// Sources iterate in configuration order, so the first skill of a name wins.
|
|
945
|
+
const byName = new Map();
|
|
966
946
|
for (const source of this.#sources.values()) {
|
|
967
947
|
if (source.kind !== "skills")
|
|
968
948
|
continue;
|
|
969
949
|
for (const document of readSkillDocuments(source)) {
|
|
970
950
|
const name = frontmatterValue(document.body, "name") || basename(dirname(document.path));
|
|
971
|
-
const description = frontmatterValue(document.body, "description") ?? "";
|
|
972
951
|
const key = name.toLowerCase();
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
metadata.set(key, {
|
|
977
|
-
candidate: { name, description, path: document.path },
|
|
978
|
-
description,
|
|
979
|
-
sourceOrder: order,
|
|
980
|
-
});
|
|
981
|
-
}
|
|
952
|
+
if (byName.has(key))
|
|
953
|
+
continue;
|
|
954
|
+
byName.set(key, { name, description: frontmatterValue(document.body, "description") ?? "", path: document.path });
|
|
982
955
|
}
|
|
983
956
|
}
|
|
984
|
-
const skills = [...
|
|
985
|
-
const embeddings = await llm.embedBatch(skills.map((
|
|
986
|
-
return skills.flatMap((
|
|
957
|
+
const skills = [...byName.values()];
|
|
958
|
+
const embeddings = await llm.embedBatch(skills.map((candidate) => formatDocForEmbedding(candidate.description, candidate.name, llm.embedModelName)));
|
|
959
|
+
return skills.flatMap((candidate, index) => {
|
|
987
960
|
const embedding = embeddings[index]?.embedding;
|
|
988
961
|
return embedding ? [{ ...candidate, score: 0, embedding }] : [];
|
|
989
962
|
});
|
|
@@ -1009,10 +982,8 @@ export class QmdMemoryManager {
|
|
|
1009
982
|
.slice(0, limit);
|
|
1010
983
|
}
|
|
1011
984
|
async readFile(params) {
|
|
1012
|
-
if (params.relPath.startsWith(
|
|
1013
|
-
const record = this.#
|
|
1014
|
-
? extractedRecords(this.#curationPath, [params.relPath.slice(`qmd://${EXTRACTED_COLLECTION}/`.length)]).find(r => this.#extraction.chatTypes.includes(r.metadata.chatType) &&
|
|
1015
|
-
params.relPath === `qmd://${EXTRACTED_COLLECTION}/${extractedPath(r)}`) : undefined;
|
|
985
|
+
if (params.relPath.startsWith(EXTRACTED_PREFIX)) {
|
|
986
|
+
const record = this.#currentExtracted([params.relPath]).find(r => params.relPath === extractedUri(r));
|
|
1016
987
|
return record ? buildReadResult({ content: `${record.text}\nObserved: ${new Date(record.observedAt).toISOString()}\nSource: ${extractedHit(record, 1).citation}`,
|
|
1017
988
|
path: params.relPath, from: params.from, lines: params.lines }) : { status: "not_found", text: "", path: params.relPath };
|
|
1018
989
|
}
|
|
@@ -2,5 +2,8 @@ import { DatabaseSync } from "node:sqlite";
|
|
|
2
2
|
export declare const MEMORY_DATABASE = "unblock-memory.sqlite";
|
|
3
3
|
/** Separate domain stores share settings, not a monolithic data-access API. */
|
|
4
4
|
export declare function openMemoryDatabase(path: string): DatabaseSync;
|
|
5
|
+
/** Runs synchronous writes atomically; never pass an async callback. */
|
|
6
|
+
export declare function immediateTransaction<T>(db: DatabaseSync, fn: () => T): T;
|
|
7
|
+
export declare function tableExists(db: DatabaseSync, name: string): boolean;
|
|
5
8
|
/** File existence no longer tells us which feature has initialized its tables. */
|
|
6
9
|
export declare function hasMemoryTable(path: string, table: string): boolean;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { closeSync, constants, existsSync, fchmodSync, lstatSync, mkdirSync, openSync } from "node:fs";
|
|
2
2
|
import { basename, dirname, join } from "node:path";
|
|
3
3
|
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
// Loaded by the Inside Out baseline worker (see inside-out-store.ts): keep this module free of `openclaw`.
|
|
4
5
|
export const MEMORY_DATABASE = "unblock-memory.sqlite";
|
|
5
6
|
const legacyStores = [
|
|
6
7
|
{ file: "curation.sqlite", component: "curation", tables: [
|
|
@@ -66,6 +67,19 @@ export function openMemoryDatabase(path) {
|
|
|
66
67
|
throw error;
|
|
67
68
|
}
|
|
68
69
|
}
|
|
70
|
+
/** Runs synchronous writes atomically; never pass an async callback. */
|
|
71
|
+
export function immediateTransaction(db, fn) {
|
|
72
|
+
db.exec("BEGIN IMMEDIATE");
|
|
73
|
+
try {
|
|
74
|
+
const result = fn();
|
|
75
|
+
db.exec("COMMIT");
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
db.exec("ROLLBACK");
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
69
83
|
function consolidate(db, directory) {
|
|
70
84
|
const completed = () => {
|
|
71
85
|
const version = db.prepare("SELECT version FROM memory_schema WHERE component='storage'").get()?.version;
|
|
@@ -159,6 +173,9 @@ function consolidate(db, directory) {
|
|
|
159
173
|
db.exec(`DETACH DATABASE ${identifier(alias)}`);
|
|
160
174
|
}
|
|
161
175
|
}
|
|
176
|
+
export function tableExists(db, name) {
|
|
177
|
+
return Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?").get(name));
|
|
178
|
+
}
|
|
162
179
|
/** File existence no longer tells us which feature has initialized its tables. */
|
|
163
180
|
export function hasMemoryTable(path, table) {
|
|
164
181
|
if (!existsSync(path) && !(basename(path) === MEMORY_DATABASE &&
|
|
@@ -166,7 +183,7 @@ export function hasMemoryTable(path, table) {
|
|
|
166
183
|
return false;
|
|
167
184
|
const db = openMemoryDatabase(path);
|
|
168
185
|
try {
|
|
169
|
-
return
|
|
186
|
+
return tableExists(db, table);
|
|
170
187
|
}
|
|
171
188
|
finally {
|
|
172
189
|
db.close();
|
|
@@ -13,12 +13,18 @@ export type MemorySearchObservation = RetrievalTimings & {
|
|
|
13
13
|
requestsSucceeded: number;
|
|
14
14
|
requestsFailed: number;
|
|
15
15
|
};
|
|
16
|
+
export type MemoryRanking = {
|
|
17
|
+
rankingMode: "typesafe_usefulness" | "retrieval";
|
|
18
|
+
fallbackReason?: "key_unavailable" | "all_judgments_failed";
|
|
19
|
+
};
|
|
16
20
|
/** Both entry points use the same complete passages and independent usefulness judgments. */
|
|
17
21
|
export declare function searchMemory(manager: MemoryCandidateManager, queries: QueryPair, options: CorpusSearchOptions & {
|
|
18
|
-
apiKey
|
|
22
|
+
apiKey?: string;
|
|
19
23
|
timeoutMs: number;
|
|
20
24
|
conversation: QueryConversation;
|
|
21
25
|
asOf?: string;
|
|
26
|
+
/** Only explicit, agent-requested search opts in. Automatic injection stays strict. */
|
|
27
|
+
allowRetrievalFallback?: boolean;
|
|
22
28
|
minUsefulness?: number;
|
|
23
29
|
excludedPassages?: ReadonlyMap<string, number>;
|
|
24
30
|
onCandidates?: (observation: MemorySearchObservation) => void;
|
|
@@ -27,6 +33,6 @@ export declare function searchMemory(manager: MemoryCandidateManager, queries: Q
|
|
|
27
33
|
elapsedMs: number;
|
|
28
34
|
error?: unknown;
|
|
29
35
|
}) => void;
|
|
30
|
-
}): Promise<MemorySearchObservation & {
|
|
36
|
+
}): Promise<MemorySearchObservation & MemoryRanking & {
|
|
31
37
|
results: CorpusMemorySearchResult[];
|
|
32
38
|
}>;
|
|
@@ -46,6 +46,20 @@ export async function searchMemory(manager, queries, options) {
|
|
|
46
46
|
}
|
|
47
47
|
observation.eligible = candidates.length;
|
|
48
48
|
options.onCandidates?.(observation);
|
|
49
|
+
const fallback = (reason) => ({
|
|
50
|
+
...timings, ...observation, rankingMode: "retrieval", fallbackReason: reason,
|
|
51
|
+
// Discovery is a lexical-first union, not a ranking. Stable reciprocal-rank
|
|
52
|
+
// ordering lets strong vector-only hits compete before maxResults truncation.
|
|
53
|
+
// These original lane scores are not fused ranks or usefulness probabilities.
|
|
54
|
+
results: [...candidates].sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5),
|
|
55
|
+
});
|
|
56
|
+
if (!options.apiKey) {
|
|
57
|
+
signal?.throwIfAborted();
|
|
58
|
+
if (options.allowRetrievalFallback)
|
|
59
|
+
return fallback("key_unavailable");
|
|
60
|
+
return { ...timings, ...observation, rankingMode: "typesafe_usefulness", results: [] };
|
|
61
|
+
}
|
|
62
|
+
const apiKey = options.apiKey;
|
|
49
63
|
const endJudge = startTiming("judgeMs", timings, signal);
|
|
50
64
|
let judged;
|
|
51
65
|
try {
|
|
@@ -56,7 +70,7 @@ export async function searchMemory(manager, queries, options) {
|
|
|
56
70
|
excerpt: hit.snippet, corpus: hit.corpus, sourcePath: hit.path,
|
|
57
71
|
dates: [...new Set(hit.sessionMessages?.flatMap(message => message.timestamp ? [message.timestamp] : [])
|
|
58
72
|
?? (hit.messageTimestamp ? [hit.messageTimestamp] : []))],
|
|
59
|
-
}, asOf), options);
|
|
73
|
+
}, asOf), { ...options, apiKey });
|
|
60
74
|
signal?.throwIfAborted();
|
|
61
75
|
observation.requestsSucceeded++;
|
|
62
76
|
options.onJudgment?.({ candidateIndex, elapsedMs: performance.now() - requestStarted });
|
|
@@ -78,6 +92,8 @@ export async function searchMemory(manager, queries, options) {
|
|
|
78
92
|
}
|
|
79
93
|
signal?.throwIfAborted();
|
|
80
94
|
observation.judgeMs = timings.judgeMs ?? 0;
|
|
81
|
-
|
|
95
|
+
if (options.allowRetrievalFallback && candidates.length && !observation.requestsSucceeded)
|
|
96
|
+
return fallback("all_judgments_failed");
|
|
97
|
+
return { ...timings, ...observation, rankingMode: "typesafe_usefulness", results: judged.filter(hit => hit.score >= (options.minUsefulness ?? 0.7))
|
|
82
98
|
.sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5) };
|
|
83
99
|
}
|
package/dist/src/people-hooks.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { parseAgentSessionKey } from "openclaw/plugin-sdk/routing";
|
|
2
|
-
|
|
3
|
-
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
4
|
-
}
|
|
2
|
+
import { nonBlank } from "./guards.js";
|
|
5
3
|
function identifier(value) {
|
|
6
4
|
if (typeof value === "number" && Number.isFinite(value))
|
|
7
5
|
return String(value);
|
|
@@ -101,10 +99,9 @@ export function registerPeopleHooks(api, stores, config) {
|
|
|
101
99
|
const identityKey = promptIdentityKey(sessionKey, accountScope, externalId);
|
|
102
100
|
const mappedThreadKey = threadByRun.get(runId);
|
|
103
101
|
const pendingThreadKey = mappedThreadKey ? undefined : pendingThreadByIdentity.get(identityKey);
|
|
104
|
-
if (!mappedThreadKey
|
|
102
|
+
if (!mappedThreadKey)
|
|
105
103
|
pendingThreadByIdentity.delete(identityKey);
|
|
106
|
-
|
|
107
|
-
const threadKey = mappedThreadKey ?? pendingThreadKey ?? undefined;
|
|
104
|
+
const threadKey = mappedThreadKey ?? pendingThreadKey;
|
|
108
105
|
if (!threadKey)
|
|
109
106
|
return;
|
|
110
107
|
if (typeof pendingThreadKey === "string") {
|