@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.
- package/README.md +19 -18
- package/defaults.json +162 -0
- package/dist/src/analysis.js +1 -1
- package/dist/src/cluster-review.d.ts +2 -0
- package/dist/src/cluster-review.js +9 -8
- package/dist/src/config.d.ts +9 -6
- package/dist/src/config.js +59 -45
- package/dist/src/curation.d.ts +1 -1
- package/dist/src/decision-client.d.ts +45 -0
- package/dist/src/decision-client.js +87 -0
- package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
- package/dist/src/decision-ranking.js +155 -0
- package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
- package/dist/src/decision-review.js +193 -0
- package/dist/src/defaults.d.ts +8 -0
- package/dist/src/defaults.js +128 -0
- package/dist/src/diagnostics.d.ts +5 -5
- package/dist/src/emotion-baselines.d.ts +28 -3
- package/dist/src/emotion-baselines.js +312 -115
- package/dist/src/evidence-review.d.ts +22 -8
- package/dist/src/evidence-review.js +11 -8
- package/dist/src/extraction-chunk.d.ts +3 -0
- package/dist/src/extraction-chunk.js +25 -6
- package/dist/src/extraction-config.js +4 -2
- package/dist/src/extraction-model.d.ts +25 -17
- package/dist/src/extraction-model.js +232 -104
- package/dist/src/extraction-runtime.d.ts +3 -1
- package/dist/src/extraction-runtime.js +48 -20
- package/dist/src/extraction-source.d.ts +1 -1
- package/dist/src/extraction-source.js +21 -12
- package/dist/src/extraction-store.d.ts +29 -3
- package/dist/src/extraction-store.js +149 -25
- package/dist/src/extraction-worker.d.ts +3 -3
- package/dist/src/extraction-worker.js +250 -95
- package/dist/src/inside-out-runtime.js +43 -30
- package/dist/src/inside-out-sources.js +2 -1
- package/dist/src/inside-out-store.d.ts +2 -2
- package/dist/src/inside-out-store.js +111 -69
- package/dist/src/inside-out.d.ts +10 -9
- package/dist/src/inside-out.js +194 -106
- package/dist/src/manager.d.ts +22 -9
- package/dist/src/manager.js +279 -172
- package/dist/src/memory-database.js +3 -2
- package/dist/src/memory-passage.d.ts +2 -2
- package/dist/src/memory-passage.js +3 -2
- 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 +195 -129
- package/dist/src/my-turn.d.ts +1 -1
- package/dist/src/my-turn.js +90 -70
- package/dist/src/people-background.d.ts +5 -1
- package/dist/src/people-background.js +31 -7
- package/dist/src/people-dossier-review.d.ts +20 -8
- package/dist/src/people-dossier-review.js +15 -11
- 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 +107 -57
- package/dist/src/people-learning-inventory.d.ts +1 -0
- package/dist/src/people-learning-inventory.js +283 -172
- 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 +13 -10
- package/dist/src/people-primer.d.ts +3 -1
- package/dist/src/people-primer.js +66 -48
- package/dist/src/people-store.d.ts +18 -21
- package/dist/src/people-store.js +188 -64
- package/dist/src/people-tools.js +138 -93
- package/dist/src/plugin.js +19 -18
- package/dist/src/quality-audit.d.ts +2 -0
- package/dist/src/quality-audit.js +11 -9
- package/dist/src/quality-triage.js +4 -3
- package/dist/src/query-generator.js +5 -2
- package/dist/src/response-audit.d.ts +1 -1
- package/dist/src/response-audit.js +78 -44
- package/dist/src/response-config.js +3 -1
- package/dist/src/response-episodes.d.ts +1 -1
- package/dist/src/response-episodes.js +15 -19
- package/dist/src/response-identity.js +2 -1
- package/dist/src/response-judge.d.ts +151 -145
- package/dist/src/response-judge.js +535 -204
- package/dist/src/response-memory.js +2 -1
- package/dist/src/response-outcome.js +9 -8
- package/dist/src/response-reviews.d.ts +29 -1
- package/dist/src/response-reviews.js +113 -15
- package/dist/src/response-runtime.js +10 -9
- 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 +335 -212
- package/dist/src/review-tools.d.ts +8 -2
- package/dist/src/review-tools.js +22 -21
- package/dist/src/runtime.d.ts +7 -4
- package/dist/src/runtime.js +625 -98
- package/dist/src/safety-config.js +3 -2
- package/dist/src/safety-whisperer.d.ts +2 -2
- package/dist/src/safety-whisperer.js +90 -73
- package/dist/src/session-sync.d.ts +3 -1
- package/dist/src/session-sync.js +202 -96
- package/dist/src/skill-whisperer.d.ts +2 -2
- package/dist/src/skill-whisperer.js +55 -32
- package/dist/src/slack-directory.js +3 -2
- package/dist/src/training-gate.d.ts +9 -22
- package/dist/src/training-gate.js +34 -36
- package/dist/src/training-input.js +4 -3
- package/dist/src/training-judge.d.ts +9 -16
- package/dist/src/training-judge.js +6 -5
- package/dist/src/training-models.d.ts +1 -1
- package/dist/src/training-models.js +9 -7
- package/dist/src/training-queries.d.ts +14 -9
- package/dist/src/training-queries.js +374 -231
- package/dist/src/training-retrieval.d.ts +17 -27
- package/dist/src/training-retrieval.js +186 -139
- 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 +141 -52
- package/dist/src/training.js +9 -11
- package/dist/src/whisperer-context.d.ts +13 -0
- package/dist/src/whisperer-context.js +22 -1
- package/docs/configuration.md +83 -64
- package/docs/extraction.md +26 -35
- 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 +43 -47
- package/openclaw.plugin.json +76 -75
- package/package.json +5 -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
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
1
2
|
import { join } from "node:path";
|
|
2
3
|
import { Type } from "typebox";
|
|
3
4
|
import { Value } from "typebox/value";
|
|
@@ -8,29 +9,41 @@ import { ExtractionStore } from "./extraction-store.js";
|
|
|
8
9
|
import { extractionSessions } from "./extraction-source.js";
|
|
9
10
|
import { dateOption } from "./date-option.js";
|
|
10
11
|
import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
|
|
11
|
-
export function registerExtraction(api, config, runtime) {
|
|
12
|
+
export function registerExtraction(api, config, runtime, deps) {
|
|
12
13
|
let lifetime = new AbortController();
|
|
14
|
+
let stopped = false;
|
|
13
15
|
let timer, running;
|
|
16
|
+
const activeRuns = new Set();
|
|
17
|
+
const track = (pending) => {
|
|
18
|
+
const settled = pending.then(() => undefined, () => undefined);
|
|
19
|
+
activeRuns.add(settled);
|
|
20
|
+
void settled.finally(() => { activeRuns.delete(settled); });
|
|
21
|
+
return pending;
|
|
22
|
+
};
|
|
14
23
|
const options = (cfg, agentId) => {
|
|
15
24
|
if (!listAgentIds(cfg).includes(agentId))
|
|
16
25
|
throw new Error("Unknown extraction agent");
|
|
17
26
|
return { agentId, agentName: resolveAgentIdentity(cfg, agentId)?.name?.trim() || agentId,
|
|
18
|
-
config,
|
|
27
|
+
config, storePath: join(agentStateDir(agentId), MEMORY_DATABASE),
|
|
19
28
|
sessions: () => extractionSessions(agentTranscriptDatabase(cfg, agentId), agentId, config.extraction.chatTypes) };
|
|
20
29
|
};
|
|
21
|
-
const run =
|
|
30
|
+
const run = (cfg, agentId, signal, since, sessionId, scheduled = false) => track((async () => {
|
|
31
|
+
signal.throwIfAborted();
|
|
22
32
|
const opts = options(cfg, agentId);
|
|
23
33
|
// Keep the extraction tokenizer/model modules out of normal plugin startup.
|
|
24
|
-
const
|
|
25
|
-
|
|
34
|
+
const execute = deps?.runExtraction ?? (await import("./extraction-worker.js")).runExtraction;
|
|
35
|
+
signal.throwIfAborted();
|
|
36
|
+
const result = await execute({ ...opts, signal, since, scheduled, sessionId });
|
|
26
37
|
if (result.status === "completed" && config.extraction.publish && runtime) {
|
|
38
|
+
signal.throwIfAborted();
|
|
27
39
|
const { manager, error } = await runtime.getMemorySearchManager({ cfg, agentId });
|
|
28
40
|
if (!manager)
|
|
29
41
|
throw new Error(error ?? "Extraction index unavailable");
|
|
42
|
+
signal.throwIfAborted();
|
|
30
43
|
await manager.syncExtracted();
|
|
31
44
|
}
|
|
32
45
|
return result;
|
|
33
|
-
};
|
|
46
|
+
})());
|
|
34
47
|
api.registerCli(({ program, config: cfg }) => {
|
|
35
48
|
const root = program.command("memory-extract").description("Optional session fact extraction; no daily Markdown writes");
|
|
36
49
|
root.command("run").option("--agent <id>", "Agent id", "main")
|
|
@@ -39,8 +52,8 @@ export function registerExtraction(api, config, runtime) {
|
|
|
39
52
|
.action(async (opts) => {
|
|
40
53
|
const since = opts.since === undefined ? undefined : dateOption(opts.since, 0);
|
|
41
54
|
try {
|
|
42
|
-
//
|
|
43
|
-
const result = await callGatewayFromCli("unblock-memory.extract", { timeout:
|
|
55
|
+
// Transcript reads and scheduling belong to the running Gateway.
|
|
56
|
+
const result = await callGatewayFromCli("unblock-memory.extract", { timeout: String(DEFAULTS.extraction.runTimeoutMs) }, { agentId: opts.agent, ...(since === undefined ? {} : { since }), ...(opts.session ? { sessionId: opts.session } : {}) });
|
|
44
57
|
console.log(JSON.stringify(result, null, 2));
|
|
45
58
|
if (result.status === "unavailable" || (result.status === "completed" && result.failed))
|
|
46
59
|
process.exitCode = 1;
|
|
@@ -74,6 +87,10 @@ export function registerExtraction(api, config, runtime) {
|
|
|
74
87
|
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "Invalid extraction parameters"));
|
|
75
88
|
return;
|
|
76
89
|
}
|
|
90
|
+
if (stopped || lifetime.signal.aborted) {
|
|
91
|
+
respond(false, undefined, errorShape(ErrorCodes.UNAVAILABLE, "Extraction failed; check host prerequisites and operator report"));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
77
94
|
try {
|
|
78
95
|
respond(true, await run(api.config, params.agentId, lifetime.signal, params.since, params.sessionId));
|
|
79
96
|
}
|
|
@@ -81,35 +98,46 @@ export function registerExtraction(api, config, runtime) {
|
|
|
81
98
|
respond(false, undefined, errorShape(ErrorCodes.UNAVAILABLE, "Extraction failed; check host prerequisites and operator report"));
|
|
82
99
|
}
|
|
83
100
|
}, { scope: "operator.admin" });
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
101
|
+
api.on("gateway_stop", async () => {
|
|
102
|
+
stopped = true;
|
|
103
|
+
lifetime.abort();
|
|
104
|
+
if (timer)
|
|
105
|
+
clearInterval(timer);
|
|
106
|
+
timer = undefined;
|
|
107
|
+
while (activeRuns.size || running) {
|
|
108
|
+
await Promise.allSettled([...activeRuns, ...(running ? [running] : [])]);
|
|
109
|
+
}
|
|
110
|
+
});
|
|
90
111
|
const tick = () => {
|
|
91
|
-
if (running || lifetime.signal.aborted)
|
|
112
|
+
if (stopped || running || lifetime.signal.aborted)
|
|
92
113
|
return;
|
|
114
|
+
const signal = lifetime.signal;
|
|
93
115
|
running = (async () => {
|
|
94
116
|
for (const agentId of listAgentIds(api.config)) {
|
|
95
|
-
if (
|
|
117
|
+
if (stopped || signal.aborted)
|
|
96
118
|
break;
|
|
97
119
|
try {
|
|
98
|
-
const result = await run(api.config, agentId,
|
|
120
|
+
const result = await run(api.config, agentId, signal, undefined, undefined, true);
|
|
99
121
|
if (result.status === "unavailable" || (result.status === "completed" && result.failed))
|
|
100
122
|
api.logger.warn("unblock-memory extraction unavailable; inspect memory-extract report");
|
|
101
123
|
}
|
|
102
124
|
catch {
|
|
103
|
-
|
|
125
|
+
if (!signal.aborted)
|
|
126
|
+
api.logger.warn("unblock-memory extraction unavailable");
|
|
104
127
|
}
|
|
105
128
|
}
|
|
106
129
|
})().finally(() => { running = undefined; });
|
|
107
130
|
};
|
|
108
131
|
api.on("gateway_start", () => {
|
|
132
|
+
stopped = false;
|
|
109
133
|
if (timer)
|
|
110
134
|
clearInterval(timer);
|
|
111
|
-
|
|
112
|
-
|
|
135
|
+
timer = undefined;
|
|
136
|
+
if (lifetime.signal.aborted)
|
|
137
|
+
lifetime = new AbortController();
|
|
138
|
+
if (!config.extraction.enabled || !config.extraction.intervalMinutes || !config.decisionModel.enabled)
|
|
139
|
+
return;
|
|
140
|
+
timer = setInterval(tick, DEFAULTS.extraction.pollIntervalMs);
|
|
113
141
|
timer.unref();
|
|
114
142
|
tick();
|
|
115
143
|
});
|
|
@@ -23,4 +23,4 @@ export declare function readExtractionPage(agentId: string, agentName: string, s
|
|
|
23
23
|
cursor?: string;
|
|
24
24
|
maxMessages: number;
|
|
25
25
|
maxBytes: number;
|
|
26
|
-
}) => Promise<unknown
|
|
26
|
+
}) => Promise<unknown>, signal?: AbortSignal): Promise<ExtractionPage>;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
1
2
|
import { DatabaseSync } from "node:sqlite";
|
|
2
3
|
import { Type } from "typebox";
|
|
3
4
|
import { Value } from "typebox/value";
|
|
5
|
+
import { abortable } from "./abortable.js";
|
|
4
6
|
import { projectMessage } from "./session-projector.js";
|
|
5
7
|
export function extractionSessions(databasePath, agentId, chatTypes) {
|
|
6
8
|
const db = new DatabaseSync(databasePath, { readOnly: true });
|
|
7
9
|
try {
|
|
8
|
-
db.exec(
|
|
10
|
+
db.exec(`PRAGMA query_only=ON; PRAGMA busy_timeout=${DEFAULTS.sqlite.mainBusyTimeoutMs}`);
|
|
9
11
|
if (db.prepare("SELECT agent_id FROM schema_meta WHERE meta_key='primary'").get()?.agent_id !== agentId) {
|
|
10
12
|
throw new Error("Wrong extraction source agent");
|
|
11
13
|
}
|
|
@@ -30,7 +32,10 @@ export function extractionSessions(databasePath, agentId, chatTypes) {
|
|
|
30
32
|
const pageSchema = Type.Object({ kind: Type.Literal("page"), cursor: Type.String(), hasMore: Type.Boolean(),
|
|
31
33
|
requiredBytes: Type.Optional(Type.Number()), entries: Type.Array(Type.Object({ entryId: Type.String(),
|
|
32
34
|
message: Type.Unknown(), createdAt: Type.Optional(Type.String()) })) });
|
|
33
|
-
|
|
35
|
+
const resetSchema = Type.Object({ kind: Type.Literal("reset"), cursor: Type.String() });
|
|
36
|
+
const missingSchema = Type.Object({ kind: Type.Union([Type.Literal("missing"), Type.Literal("unavailable")]) });
|
|
37
|
+
export async function readExtractionPage(agentId, agentName, session, cursor, read, signal) {
|
|
38
|
+
signal?.throwIfAborted();
|
|
34
39
|
// Runtime-only import: the supported host export ships JS without a declaration file.
|
|
35
40
|
const sdkPath = "openclaw/plugin-sdk/session-transcript-runtime";
|
|
36
41
|
const sdk = read ? undefined : await import(sdkPath);
|
|
@@ -40,17 +45,23 @@ export async function readExtractionPage(agentId, agentName, session, cursor, re
|
|
|
40
45
|
let maxBytes = 1_000_000;
|
|
41
46
|
let result;
|
|
42
47
|
for (;;) {
|
|
43
|
-
|
|
48
|
+
signal?.throwIfAborted();
|
|
49
|
+
const pending = readDelta({ agentId, sessionId: session.sessionId,
|
|
44
50
|
sessionKey: session.sessionKey, ...(cursor ? { cursor } : {}), maxMessages: 40, maxBytes });
|
|
45
|
-
if (
|
|
51
|
+
if (signal)
|
|
52
|
+
void pending.catch(() => { });
|
|
53
|
+
result = await abortable(pending, signal);
|
|
54
|
+
signal?.throwIfAborted();
|
|
55
|
+
if (!Value.Check(pageSchema, result))
|
|
46
56
|
break;
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
57
|
+
if (!result.entries.length && result.requiredBytes) {
|
|
58
|
+
// The host caps reads at 64 MiB. This is an allocation bound, not a model budget.
|
|
59
|
+
if (!Number.isSafeInteger(result.requiredBytes) || result.requiredBytes <= maxBytes || result.requiredBytes > 64 * 1024 * 1024) {
|
|
60
|
+
throw new Error("Transcript entry exceeds host read capacity");
|
|
61
|
+
}
|
|
62
|
+
maxBytes = result.requiredBytes;
|
|
63
|
+
continue;
|
|
50
64
|
}
|
|
51
|
-
maxBytes = result.requiredBytes;
|
|
52
|
-
}
|
|
53
|
-
if (Value.Check(pageSchema, result)) {
|
|
54
65
|
const messages = result.entries.flatMap(entry => {
|
|
55
66
|
const createdAt = Date.parse(entry.createdAt ?? "");
|
|
56
67
|
if (!Number.isFinite(createdAt))
|
|
@@ -60,10 +71,8 @@ export async function readExtractionPage(agentId, agentName, session, cursor, re
|
|
|
60
71
|
});
|
|
61
72
|
return { kind: "page", cursor: result.cursor, hasMore: result.hasMore, messages, entryCount: result.entries.length };
|
|
62
73
|
}
|
|
63
|
-
const resetSchema = Type.Object({ kind: Type.Literal("reset"), cursor: Type.String() });
|
|
64
74
|
if (Value.Check(resetSchema, result))
|
|
65
75
|
return { kind: "reset", cursor: result.cursor };
|
|
66
|
-
const missingSchema = Type.Object({ kind: Type.Union([Type.Literal("missing"), Type.Literal("unavailable")]) });
|
|
67
76
|
if (Value.Check(missingSchema, result))
|
|
68
77
|
return { kind: result.kind };
|
|
69
78
|
throw new Error("Invalid host transcript page");
|
|
@@ -10,6 +10,7 @@ type Checkpoint = {
|
|
|
10
10
|
context: ExtractionMessage[];
|
|
11
11
|
since: number;
|
|
12
12
|
completeRevision: string | null;
|
|
13
|
+
policyFingerprint: string | null;
|
|
13
14
|
};
|
|
14
15
|
export type ExtractedRecord = {
|
|
15
16
|
id: string;
|
|
@@ -21,6 +22,19 @@ export type ExtractedRecord = {
|
|
|
21
22
|
metadata: ExtractionSession;
|
|
22
23
|
judgment: unknown;
|
|
23
24
|
};
|
|
25
|
+
export declare class ExtractionLeaseLostError extends Error {
|
|
26
|
+
constructor();
|
|
27
|
+
}
|
|
28
|
+
export declare function extractionPolicyFingerprint(params: {
|
|
29
|
+
version: string;
|
|
30
|
+
historyMessages: number;
|
|
31
|
+
minSupport: number;
|
|
32
|
+
minRetention: number;
|
|
33
|
+
minReplacement: number;
|
|
34
|
+
extractorModel?: string;
|
|
35
|
+
validatorModel?: string;
|
|
36
|
+
}): string;
|
|
37
|
+
export declare function buildCompleteRevision(sourceRevision: string, policyFingerprint: string): string;
|
|
24
38
|
export declare class ExtractionStore {
|
|
25
39
|
readonly db: import("node:sqlite").DatabaseSync;
|
|
26
40
|
constructor(path: string);
|
|
@@ -29,9 +43,20 @@ export declare class ExtractionStore {
|
|
|
29
43
|
claim(scheduled: boolean, intervalMs: number): string | undefined;
|
|
30
44
|
renew(owner: string): void;
|
|
31
45
|
release(owner: string): void;
|
|
32
|
-
|
|
46
|
+
readCheckpoint(sessionId: string): (Checkpoint & {
|
|
47
|
+
error: string | null;
|
|
48
|
+
}) | undefined;
|
|
49
|
+
checkpoint(session: ExtractionSession, owner: string, since?: number, policyFingerprint?: string): Checkpoint;
|
|
33
50
|
records(sessionId?: string, paths?: readonly string[]): ExtractedRecord[];
|
|
34
|
-
reset(sessionId: string, cursor: string | null, owner: string): void;
|
|
51
|
+
reset(sessionId: string, cursor: string | null, owner: string, policyFingerprint?: string): void;
|
|
52
|
+
private assertCheckpointFenced;
|
|
53
|
+
completeEmpty(params: {
|
|
54
|
+
sessionId: string;
|
|
55
|
+
expected: string | null;
|
|
56
|
+
owner: string;
|
|
57
|
+
completeRevision?: string;
|
|
58
|
+
policyFingerprint?: string;
|
|
59
|
+
}): void;
|
|
35
60
|
commit(params: {
|
|
36
61
|
session: ExtractionSession;
|
|
37
62
|
expected: string | null;
|
|
@@ -45,8 +70,9 @@ export declare class ExtractionStore {
|
|
|
45
70
|
owner: string;
|
|
46
71
|
version: string;
|
|
47
72
|
completeRevision?: string;
|
|
73
|
+
policyFingerprint?: string;
|
|
48
74
|
}): number;
|
|
49
|
-
error(sessionId: string, code: string): void;
|
|
75
|
+
error(sessionId: string, code: string, owner: string): void;
|
|
50
76
|
report(): {
|
|
51
77
|
memories: ExtractedRecord[];
|
|
52
78
|
sessions: Record<string, import("node:sqlite").SQLOutputValue>[];
|
|
@@ -1,5 +1,44 @@
|
|
|
1
|
+
import { DEFAULTS } from "./defaults.js";
|
|
1
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
3
|
import { immediateTransaction, openMemoryDatabase } from "./memory-database.js";
|
|
4
|
+
import { jsonHash } from "./json-hash.js";
|
|
5
|
+
export class ExtractionLeaseLostError extends Error {
|
|
6
|
+
constructor() {
|
|
7
|
+
super("Extraction lease lost");
|
|
8
|
+
this.name = "ExtractionLeaseLostError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function extractionPolicyFingerprint(params) {
|
|
12
|
+
return jsonHash({
|
|
13
|
+
version: params.version,
|
|
14
|
+
historyMessages: params.historyMessages,
|
|
15
|
+
minSupport: params.minSupport,
|
|
16
|
+
minRetention: params.minRetention,
|
|
17
|
+
minReplacement: params.minReplacement,
|
|
18
|
+
extractorModel: params.extractorModel ?? null,
|
|
19
|
+
validatorModel: params.validatorModel ?? null,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export function buildCompleteRevision(sourceRevision, policyFingerprint) {
|
|
23
|
+
return JSON.stringify({ sourceRevision, policy: policyFingerprint });
|
|
24
|
+
}
|
|
25
|
+
function parseCompleteRevision(value) {
|
|
26
|
+
if (value === null)
|
|
27
|
+
return null;
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(value);
|
|
30
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed) &&
|
|
31
|
+
typeof parsed.sourceRevision === "string" &&
|
|
32
|
+
typeof parsed.policy === "string") {
|
|
33
|
+
return {
|
|
34
|
+
sourceRevision: parsed.sourceRevision,
|
|
35
|
+
policy: parsed.policy,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
catch { /* Legacy plain-string complete_revision without policy binding. */ }
|
|
40
|
+
return { sourceRevision: value, policy: null };
|
|
41
|
+
}
|
|
3
42
|
function memoryDigest(text) {
|
|
4
43
|
return createHash("sha256").update(text.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.!]+$/, "")).digest("hex");
|
|
5
44
|
}
|
|
@@ -20,7 +59,7 @@ export class ExtractionStore {
|
|
|
20
59
|
session_id TEXT PRIMARY KEY, metadata TEXT NOT NULL CHECK(json_valid(metadata)), cursor TEXT,
|
|
21
60
|
extract_since INTEGER NOT NULL,
|
|
22
61
|
context TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(context)), updated_at INTEGER NOT NULL,
|
|
23
|
-
error TEXT, complete_revision TEXT
|
|
62
|
+
error TEXT, complete_revision TEXT, policy_fingerprint TEXT
|
|
24
63
|
) STRICT;
|
|
25
64
|
CREATE TABLE IF NOT EXISTS extracted_memories (
|
|
26
65
|
id TEXT NOT NULL, revision INTEGER NOT NULL, session_id TEXT NOT NULL REFERENCES extraction_sessions(session_id),
|
|
@@ -36,6 +75,9 @@ export class ExtractionStore {
|
|
|
36
75
|
if (!this.db.prepare("SELECT 1 FROM pragma_table_info('extraction_sessions') WHERE name='complete_revision'").get()) {
|
|
37
76
|
this.db.exec("ALTER TABLE extraction_sessions ADD COLUMN complete_revision TEXT");
|
|
38
77
|
}
|
|
78
|
+
if (!this.db.prepare("SELECT 1 FROM pragma_table_info('extraction_sessions') WHERE name='policy_fingerprint'").get()) {
|
|
79
|
+
this.db.exec("ALTER TABLE extraction_sessions ADD COLUMN policy_fingerprint TEXT");
|
|
80
|
+
}
|
|
39
81
|
this.db.prepare("INSERT OR IGNORE INTO extraction_worker(id,live_since) VALUES(1,?)").run(Date.now());
|
|
40
82
|
}
|
|
41
83
|
catch (error) {
|
|
@@ -48,28 +90,76 @@ export class ExtractionStore {
|
|
|
48
90
|
claim(scheduled, intervalMs) {
|
|
49
91
|
const owner = randomUUID(), now = Date.now();
|
|
50
92
|
const result = this.db.prepare(`UPDATE extraction_worker SET owner=?,lease_until=?,next_run=?
|
|
51
|
-
WHERE id=1 AND lease_until<? AND (?=0 OR next_run<=?)`).run(owner, now +
|
|
93
|
+
WHERE id=1 AND lease_until<? AND (?=0 OR next_run<=?)`).run(owner, now + DEFAULTS.extraction.leaseMs, now + intervalMs, now, Number(scheduled), now);
|
|
52
94
|
return result.changes ? owner : undefined;
|
|
53
95
|
}
|
|
54
96
|
renew(owner) {
|
|
55
97
|
const now = Date.now();
|
|
56
98
|
if (!this.db.prepare("UPDATE extraction_worker SET lease_until=? WHERE id=1 AND owner=? AND lease_until>=?")
|
|
57
|
-
.run(now +
|
|
58
|
-
throw new
|
|
99
|
+
.run(now + DEFAULTS.extraction.leaseMs, owner, now).changes)
|
|
100
|
+
throw new ExtractionLeaseLostError();
|
|
59
101
|
}
|
|
60
102
|
release(owner) { this.db.prepare("UPDATE extraction_worker SET owner=NULL,lease_until=0 WHERE id=1 AND owner=?").run(owner); }
|
|
61
|
-
|
|
62
|
-
this.db.prepare(
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
103
|
+
readCheckpoint(sessionId) {
|
|
104
|
+
const row = this.db.prepare("SELECT cursor,context,extract_since,complete_revision,policy_fingerprint,error FROM extraction_sessions WHERE session_id=?").get(sessionId);
|
|
105
|
+
if (!row)
|
|
106
|
+
return undefined;
|
|
107
|
+
return {
|
|
108
|
+
cursor: row.cursor,
|
|
109
|
+
context: JSON.parse(String(row.context)),
|
|
110
|
+
since: Number(row.extract_since),
|
|
111
|
+
completeRevision: row.complete_revision,
|
|
112
|
+
policyFingerprint: row.policy_fingerprint,
|
|
113
|
+
error: row.error,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
checkpoint(session, owner, since, policyFingerprint) {
|
|
117
|
+
return immediateTransaction(this.db, () => {
|
|
118
|
+
this.renew(owner);
|
|
119
|
+
this.db.prepare(`INSERT INTO extraction_sessions(session_id,metadata,updated_at,extract_since,policy_fingerprint) VALUES(?,?,?,?,?)
|
|
120
|
+
ON CONFLICT(session_id) DO UPDATE SET metadata=excluded.metadata WHERE metadata IS NOT excluded.metadata`)
|
|
121
|
+
.run(session.sessionId, JSON.stringify(session), Date.now(), since ?? this.liveSince(), policyFingerprint ?? null);
|
|
122
|
+
const row = this.db.prepare("SELECT cursor,context,extract_since,complete_revision,policy_fingerprint FROM extraction_sessions WHERE session_id=?").get(session.sessionId);
|
|
123
|
+
const storedCursor = row.cursor;
|
|
124
|
+
const storedCompleteRevision = row.complete_revision;
|
|
125
|
+
const storedPolicy = row.policy_fingerprint;
|
|
126
|
+
if (since !== undefined && since < Number(row.extract_since)) {
|
|
127
|
+
// A broader explicitly approved backfill replays this session. Existing facts are
|
|
128
|
+
// supplied to Luna and exact duplicates are ignored; history is never deleted.
|
|
129
|
+
const nextPolicy = policyFingerprint ?? storedPolicy;
|
|
130
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=NULL,context='[]',complete_revision=NULL,extract_since=?,policy_fingerprint=? WHERE session_id=?")
|
|
131
|
+
.run(since, nextPolicy, session.sessionId);
|
|
132
|
+
return { cursor: null, context: [], since, completeRevision: null, policyFingerprint: nextPolicy };
|
|
133
|
+
}
|
|
134
|
+
if (policyFingerprint !== undefined) {
|
|
135
|
+
const completeRevisionPolicyMismatch = storedCompleteRevision !== null && parseCompleteRevision(storedCompleteRevision)?.policy !== policyFingerprint;
|
|
136
|
+
if ((storedCursor !== null || storedCompleteRevision !== null) && (storedPolicy !== policyFingerprint || completeRevisionPolicyMismatch)) {
|
|
137
|
+
// A prompt or retention-policy change (or unversioned legacy cursor) replays the
|
|
138
|
+
// session from the start with existing facts retained so completion covers the full scan.
|
|
139
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=NULL,context='[]',complete_revision=NULL,policy_fingerprint=? WHERE session_id=?")
|
|
140
|
+
.run(policyFingerprint, session.sessionId);
|
|
141
|
+
return { cursor: null, context: [], since: Number(row.extract_since), completeRevision: null, policyFingerprint };
|
|
142
|
+
}
|
|
143
|
+
if (storedPolicy !== policyFingerprint) {
|
|
144
|
+
this.db.prepare("UPDATE extraction_sessions SET policy_fingerprint=? WHERE session_id=?")
|
|
145
|
+
.run(policyFingerprint, session.sessionId);
|
|
146
|
+
return {
|
|
147
|
+
cursor: storedCursor,
|
|
148
|
+
context: JSON.parse(String(row.context)),
|
|
149
|
+
since: Number(row.extract_since),
|
|
150
|
+
completeRevision: storedCompleteRevision,
|
|
151
|
+
policyFingerprint,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
cursor: storedCursor,
|
|
157
|
+
context: JSON.parse(String(row.context)),
|
|
158
|
+
since: Number(row.extract_since),
|
|
159
|
+
completeRevision: storedCompleteRevision,
|
|
160
|
+
policyFingerprint: storedPolicy,
|
|
161
|
+
};
|
|
162
|
+
});
|
|
73
163
|
}
|
|
74
164
|
records(sessionId, paths) {
|
|
75
165
|
const keys = paths?.filter(path => /^[a-f0-9-]+\/[1-9]\d*$/.test(path)).map(path => path.split("/"));
|
|
@@ -82,20 +172,48 @@ export class ExtractionStore {
|
|
|
82
172
|
.map(r => ({ id: String(r.id), revision: Number(r.revision), text: String(r.text), sessionId: String(r.session_id),
|
|
83
173
|
observedAt: Number(r.observed_at), evidence: JSON.parse(String(r.evidence)), metadata: JSON.parse(String(r.metadata)), judgment: JSON.parse(String(r.judgment)) }));
|
|
84
174
|
}
|
|
85
|
-
reset(sessionId, cursor, owner) {
|
|
175
|
+
reset(sessionId, cursor, owner, policyFingerprint) {
|
|
86
176
|
immediateTransaction(this.db, () => {
|
|
87
177
|
this.renew(owner);
|
|
88
178
|
this.db.prepare("UPDATE extracted_memories SET status='withdrawn' WHERE session_id=? AND status='active'").run(sessionId);
|
|
89
|
-
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context='[]',complete_revision=NULL,error=NULL WHERE session_id=?")
|
|
179
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context='[]',complete_revision=NULL,policy_fingerprint=?,error=NULL,updated_at=? WHERE session_id=?")
|
|
180
|
+
.run(cursor, policyFingerprint ?? null, Date.now(), sessionId);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
assertCheckpointFenced(current, expected, policyFingerprint, completeRevision) {
|
|
184
|
+
if (!current || current.cursor !== expected)
|
|
185
|
+
throw new Error("Extraction checkpoint changed");
|
|
186
|
+
const storedPolicy = current.policy_fingerprint;
|
|
187
|
+
if (policyFingerprint !== undefined) {
|
|
188
|
+
if (expected !== null ? storedPolicy !== policyFingerprint : storedPolicy !== null && storedPolicy !== policyFingerprint) {
|
|
189
|
+
throw new Error("Extraction checkpoint changed");
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const nextPolicy = policyFingerprint ?? storedPolicy;
|
|
193
|
+
if (completeRevision !== undefined) {
|
|
194
|
+
const parsed = parseCompleteRevision(completeRevision);
|
|
195
|
+
if (parsed && parsed.policy !== null && nextPolicy !== parsed.policy) {
|
|
196
|
+
throw new Error("Extraction checkpoint changed");
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return nextPolicy;
|
|
200
|
+
}
|
|
201
|
+
completeEmpty(params) {
|
|
202
|
+
immediateTransaction(this.db, () => {
|
|
203
|
+
this.renew(params.owner);
|
|
204
|
+
const current = this.db.prepare("SELECT cursor,policy_fingerprint FROM extraction_sessions WHERE session_id=?").get(params.sessionId);
|
|
205
|
+
const nextPolicy = this.assertCheckpointFenced(current, params.expected, params.policyFingerprint, params.completeRevision);
|
|
206
|
+
this.db.prepare("UPDATE extraction_sessions SET updated_at=?,complete_revision=?,policy_fingerprint=?,error=NULL WHERE session_id=?")
|
|
207
|
+
.run(Date.now(), params.completeRevision ?? null, nextPolicy, params.sessionId);
|
|
90
208
|
});
|
|
91
209
|
}
|
|
92
210
|
commit(params) {
|
|
93
211
|
return immediateTransaction(this.db, () => {
|
|
94
212
|
let written = 0;
|
|
213
|
+
const replaced = new Set();
|
|
95
214
|
this.renew(params.owner);
|
|
96
|
-
const current = this.db.prepare("SELECT cursor FROM extraction_sessions WHERE session_id=?").get(params.session.sessionId);
|
|
97
|
-
|
|
98
|
-
throw new Error("Extraction checkpoint changed");
|
|
215
|
+
const current = this.db.prepare("SELECT cursor,policy_fingerprint FROM extraction_sessions WHERE session_id=?").get(params.session.sessionId);
|
|
216
|
+
const nextPolicy = this.assertCheckpointFenced(current, params.expected, params.policyFingerprint, params.completeRevision);
|
|
99
217
|
for (const { proposal, observedAt, judgment } of params.accepted) {
|
|
100
218
|
const digest = memoryDigest(proposal.text);
|
|
101
219
|
const duplicate = this.db.prepare("SELECT id FROM extracted_memories WHERE session_id=? AND digest=? AND status='active'")
|
|
@@ -104,10 +222,13 @@ export class ExtractionStore {
|
|
|
104
222
|
continue;
|
|
105
223
|
let id = randomUUID(), revision = 1;
|
|
106
224
|
if (proposal.replaces) {
|
|
225
|
+
if (replaced.has(proposal.replaces))
|
|
226
|
+
throw new Error("Conflicting memory replacement in batch");
|
|
107
227
|
const previous = this.db.prepare("SELECT revision,observed_at FROM extracted_memories WHERE id=? AND session_id=? AND status='active'")
|
|
108
228
|
.get(proposal.replaces, params.session.sessionId);
|
|
109
229
|
if (!previous || Number(previous.observed_at) > observedAt)
|
|
110
230
|
throw new Error("Invalid or stale memory replacement");
|
|
231
|
+
replaced.add(proposal.replaces);
|
|
111
232
|
id = proposal.replaces;
|
|
112
233
|
revision = Number(previous.revision) + 1;
|
|
113
234
|
this.db.prepare("UPDATE extracted_memories SET status='superseded' WHERE id=? AND status='active'").run(id);
|
|
@@ -116,13 +237,16 @@ export class ExtractionStore {
|
|
|
116
237
|
.run(id, revision, params.session.sessionId, proposal.text.trim(), digest, JSON.stringify(proposal.evidence), observedAt, JSON.stringify(judgment), params.version, Date.now());
|
|
117
238
|
written++;
|
|
118
239
|
}
|
|
119
|
-
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context=?,updated_at=?,complete_revision=?,error=NULL WHERE session_id=?")
|
|
120
|
-
.run(params.cursor, JSON.stringify(params.context), Date.now(), params.completeRevision ?? null, params.session.sessionId);
|
|
240
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context=?,updated_at=?,complete_revision=?,policy_fingerprint=?,error=NULL WHERE session_id=?")
|
|
241
|
+
.run(params.cursor, JSON.stringify(params.context), Date.now(), params.completeRevision ?? null, nextPolicy, params.session.sessionId);
|
|
121
242
|
return written;
|
|
122
243
|
});
|
|
123
244
|
}
|
|
124
|
-
error(sessionId, code) {
|
|
125
|
-
this.db
|
|
245
|
+
error(sessionId, code, owner) {
|
|
246
|
+
immediateTransaction(this.db, () => {
|
|
247
|
+
this.renew(owner);
|
|
248
|
+
this.db.prepare("UPDATE extraction_sessions SET error=?,updated_at=? WHERE session_id=?").run(code, Date.now(), sessionId);
|
|
249
|
+
});
|
|
126
250
|
}
|
|
127
251
|
report() {
|
|
128
252
|
return { memories: this.records(), sessions: this.db.prepare("SELECT session_id,updated_at,error,cursor IS NOT NULL AS checkpointed FROM extraction_sessions").all() };
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import type { UnblockMemoryConfig } from "./config.js";
|
|
2
|
-
import {
|
|
2
|
+
import { extractWithDecisionModel, validateExtractedMemory } from "./extraction-model.js";
|
|
3
3
|
import { type ExtractionSession } from "./extraction-store.js";
|
|
4
4
|
import { readExtractionPage } from "./extraction-source.js";
|
|
5
5
|
export declare function runExtraction(params: {
|
|
6
6
|
config: UnblockMemoryConfig;
|
|
7
7
|
storePath: string;
|
|
8
8
|
agentId: string;
|
|
9
|
-
runtime: unknown;
|
|
10
9
|
agentName: string;
|
|
11
10
|
sessions: () => ExtractionSession[];
|
|
12
11
|
signal: AbortSignal;
|
|
13
12
|
since?: number;
|
|
14
13
|
sessionId?: string;
|
|
15
14
|
scheduled?: boolean;
|
|
15
|
+
version?: string;
|
|
16
16
|
readPage?: typeof readExtractionPage;
|
|
17
|
-
extract?: typeof
|
|
17
|
+
extract?: typeof extractWithDecisionModel;
|
|
18
18
|
validate?: typeof validateExtractedMemory;
|
|
19
19
|
}): Promise<{
|
|
20
20
|
status: "disabled";
|