@imliulian/dsh-zeromem 0.1.0 → 0.2.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/CHANGELOG.md +10 -0
- package/NOTICE +17 -0
- package/README.md +35 -10
- package/README.zh.md +35 -10
- package/assets/panel.js +110 -4
- package/bin/dsh-zeromem.mjs +187 -0
- package/lib/contracts.mjs +94 -2
- package/lib/expiry.mjs +105 -1
- package/lib/hooks.mjs +8 -2
- package/lib/index.mjs +3 -1
- package/lib/llm.mjs +6 -2
- package/lib/memory.mjs +177 -7
- package/lib/portability.mjs +819 -0
- package/lib/store.mjs +268 -28
- package/lib/tools.mjs +60 -3
- package/lib/web.mjs +86 -8
- package/package.json +8 -4
package/lib/contracts.mjs
CHANGED
|
@@ -54,6 +54,50 @@ export const FACT_ADMISSION_SYSTEM =
|
|
|
54
54
|
"as in the source; path identifies the source field, and adjacent segments may overlap. " +
|
|
55
55
|
"An absent role means no speaker role was supplied.";
|
|
56
56
|
|
|
57
|
+
export const FACT_ADMISSION_SUPERSEDE_ADDENDUM =
|
|
58
|
+
'supersedes_fact_id rule: input JSON also includes "prior_facts" (existing active facts in ' +
|
|
59
|
+
"the same namespace, NOT source evidence for the current document—still judge " +
|
|
60
|
+
'pass/revise/drop/hold strictly against "evidence"). For every candidate ID also return ' +
|
|
61
|
+
'"supersedes_fact_id": set it to the exact integer fact_id from prior_facts ONLY when this ' +
|
|
62
|
+
"pass/revise candidate directly replaces, migrates, updates, or contradicts that specific " +
|
|
63
|
+
"prior fact on the same subject/parameter/owner. If the candidate is additive, about a " +
|
|
64
|
+
"different module/aspect, dropped/held, or uncertain, set supersedes_fact_id to null. " +
|
|
65
|
+
"Never invent a fact_id not present in prior_facts.";
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Build an Ollama JSON Schema constraining verdicts and supersedes_fact_id to [null, ...offered IDs].
|
|
69
|
+
*/
|
|
70
|
+
export function buildAdmissionSupersedeSchema(numCandidates, priorFactIds) {
|
|
71
|
+
const validSet = new Set();
|
|
72
|
+
for (const fid of Array.isArray(priorFactIds) ? priorFactIds : []) {
|
|
73
|
+
if (typeof fid === "number" && Number.isInteger(fid) && fid > 0) {
|
|
74
|
+
validSet.add(fid);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const validIds = [...validSet].sort((a, b) => a - b);
|
|
78
|
+
const itemSchema = {
|
|
79
|
+
type: "object",
|
|
80
|
+
additionalProperties: false,
|
|
81
|
+
required: ["decision", "evidence", "replacement", "supersedes_fact_id"],
|
|
82
|
+
properties: {
|
|
83
|
+
decision: { type: "string", enum: ["pass", "revise", "drop", "hold"] },
|
|
84
|
+
evidence: { type: "array", items: { type: "string" } },
|
|
85
|
+
replacement: { type: "string" },
|
|
86
|
+
supersedes_fact_id: { enum: [null, ...validIds] },
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
const count = Math.max(0, Math.trunc(Number(numCandidates) || 0));
|
|
90
|
+
const keys = Array.from({ length: count }, (_, i) => String(i));
|
|
91
|
+
const properties = {};
|
|
92
|
+
for (const k of keys) properties[k] = itemSchema;
|
|
93
|
+
return {
|
|
94
|
+
type: "object",
|
|
95
|
+
additionalProperties: false,
|
|
96
|
+
required: keys,
|
|
97
|
+
properties,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
57
101
|
export const VALID_FACT_TYPES = new Set(["world", "experience", "observation"]);
|
|
58
102
|
export const VALID_DECISIONS = new Set(["pass", "revise", "drop", "hold"]);
|
|
59
103
|
|
|
@@ -89,6 +133,29 @@ const CREDENTIAL_RE_3 = /\b(api[_-]?key|access[_-]?token|secret[_-]?key|password
|
|
|
89
133
|
const HEX_TOKEN_RE = /\b[0-9a-fA-F]{16,64}\b/g;
|
|
90
134
|
const SENTENCE_SPLIT_RE = /(?<=[。!?!?;;\n])|(?<=\.\s)/;
|
|
91
135
|
const ISO_DATE_PREFIX_RE = /^\d{4}-\d{2}-\d{2}/;
|
|
136
|
+
const GROUNDED_ISO_DATE_RE = /(?<!until:)(?<![0-9])(\d{4})-(\d{2})-(\d{2})(?![0-9])/gi;
|
|
137
|
+
const GROUNDED_ZH_DATE_RE = /(?<![0-9])(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日/g;
|
|
138
|
+
|
|
139
|
+
function extractGroundedDates(str) {
|
|
140
|
+
const out = [];
|
|
141
|
+
const pushValid = (y, mo, da) => {
|
|
142
|
+
if (y < 1970 || y > 9999 || mo < 1 || mo > 12 || da < 1 || da > 31) return;
|
|
143
|
+
const dt = new Date(Date.UTC(y, mo - 1, da));
|
|
144
|
+
if (dt.getUTCFullYear() !== y || dt.getUTCMonth() !== mo - 1 || dt.getUTCDate() !== da) return;
|
|
145
|
+
const iso = `${String(y).padStart(4, "0")}-${String(mo).padStart(2, "0")}-${String(da).padStart(2, "0")}`;
|
|
146
|
+
if (!out.includes(iso)) out.push(iso);
|
|
147
|
+
};
|
|
148
|
+
let m;
|
|
149
|
+
GROUNDED_ISO_DATE_RE.lastIndex = 0;
|
|
150
|
+
while ((m = GROUNDED_ISO_DATE_RE.exec(str)) !== null) {
|
|
151
|
+
pushValid(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
152
|
+
}
|
|
153
|
+
GROUNDED_ZH_DATE_RE.lastIndex = 0;
|
|
154
|
+
while ((m = GROUNDED_ZH_DATE_RE.exec(str)) !== null) {
|
|
155
|
+
pushValid(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
92
159
|
|
|
93
160
|
export function redactCredentials(text) {
|
|
94
161
|
if (!text) return text;
|
|
@@ -325,6 +392,19 @@ function alignHexDigests(factText, evidenceBlob) {
|
|
|
325
392
|
return { text: repaired, ok: true };
|
|
326
393
|
}
|
|
327
394
|
|
|
395
|
+
export function inferGroundedOccurredStart(text, evidenceBlob, mentionedAt = null) {
|
|
396
|
+
let mDateStr = null;
|
|
397
|
+
if (mentionedAt) {
|
|
398
|
+
const mDate = ISO_DATE_PREFIX_RE.exec(String(mentionedAt));
|
|
399
|
+
if (mDate) mDateStr = mDate[0];
|
|
400
|
+
}
|
|
401
|
+
const evDates = new Set(extractGroundedDates(String(evidenceBlob || "")));
|
|
402
|
+
const groundedDates = extractGroundedDates(String(text || "")).filter(
|
|
403
|
+
(dStr) => dStr !== mDateStr && evDates.has(dStr)
|
|
404
|
+
);
|
|
405
|
+
return groundedDates.length === 1 ? groundedDates[0] : null;
|
|
406
|
+
}
|
|
407
|
+
|
|
328
408
|
/**
|
|
329
409
|
* Deterministic post-check on extracted/admitted fact.
|
|
330
410
|
*/
|
|
@@ -356,10 +436,15 @@ export function guardFact(fact, segMap, { mentionedAt = null } = {}) {
|
|
|
356
436
|
let occurredStart = fact.occurred_start ? String(fact.occurred_start).trim() : null;
|
|
357
437
|
let occurredEnd = fact.occurred_end ? String(fact.occurred_end).trim() : null;
|
|
358
438
|
|
|
359
|
-
|
|
439
|
+
let mDateStr = null;
|
|
440
|
+
if (mentionedAt) {
|
|
360
441
|
const mDate = ISO_DATE_PREFIX_RE.exec(String(mentionedAt));
|
|
442
|
+
if (mDate) mDateStr = mDate[0];
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
if (occurredStart && mDateStr) {
|
|
361
446
|
const oDate = ISO_DATE_PREFIX_RE.exec(occurredStart);
|
|
362
|
-
if (
|
|
447
|
+
if (oDate && mDateStr === oDate[0] && !evidenceBlob.includes(oDate[0])) {
|
|
363
448
|
occurredStart = null;
|
|
364
449
|
if (occurredEnd && occurredEnd.startsWith(oDate[0])) {
|
|
365
450
|
occurredEnd = null;
|
|
@@ -367,6 +452,13 @@ export function guardFact(fact, segMap, { mentionedAt = null } = {}) {
|
|
|
367
452
|
}
|
|
368
453
|
}
|
|
369
454
|
|
|
455
|
+
// Conservative deterministic backfill: if a single explicit grounded event date appears in fact text
|
|
456
|
+
// (grounded in evidence as ISO or YYYY年M月D日, not an `until:` tag, and distinct from record date)
|
|
457
|
+
// while occurred_start is null.
|
|
458
|
+
if (!occurredStart) {
|
|
459
|
+
occurredStart = inferGroundedOccurredStart(text, evidenceBlob, mentionedAt);
|
|
460
|
+
}
|
|
461
|
+
|
|
370
462
|
const whereLoc = fact.where ? redactCredentials(String(fact.where).trim()) : null;
|
|
371
463
|
const entities = [];
|
|
372
464
|
if (Array.isArray(fact.entities)) {
|
package/lib/expiry.mjs
CHANGED
|
@@ -17,6 +17,9 @@ export const ADAPTIVE_SCORE_RATIO = 0.35;
|
|
|
17
17
|
|
|
18
18
|
const UNTIL_TOKEN_RE = /^until:(\d{4})-?(\d{2})-?(\d{2})$/i;
|
|
19
19
|
const UNTIL_INLINE_RE = /(?<![A-Za-z0-9_])until:(\d{4})-?(\d{2})-?(\d{2})(?![0-9])/gi;
|
|
20
|
+
const OCCURRED_FULL_RE = /^(\d{4})-?(\d{2})-?(\d{2})(?:$|T|\s)/;
|
|
21
|
+
const OCCURRED_YM_RE = /^(\d{4})-(\d{2})$/;
|
|
22
|
+
const OCCURRED_Y_RE = /^(\d{4})$/;
|
|
20
23
|
const DISABLED_VALUES = new Set(["0", "off", "false", "no"]);
|
|
21
24
|
const ENABLED_VALUES = new Set(["1", "true", "yes", "on"]);
|
|
22
25
|
|
|
@@ -71,6 +74,107 @@ export function parseCalendarDate(year, month, day) {
|
|
|
71
74
|
return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
|
|
72
75
|
}
|
|
73
76
|
|
|
77
|
+
function daysInMonth(year, month) {
|
|
78
|
+
return new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Parse YYYY, YYYY-MM, YYYY-MM-DD, YYYYMMDD, or ISO-8601 prefix into a canonical YYYY-MM-DD bound.
|
|
83
|
+
*/
|
|
84
|
+
export function parseOccurredBound(value, { isEnd = false } = {}) {
|
|
85
|
+
if (value === null || value === undefined) return null;
|
|
86
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) {
|
|
87
|
+
return parseCalendarDate(value.getUTCFullYear(), value.getUTCMonth() + 1, value.getUTCDate());
|
|
88
|
+
}
|
|
89
|
+
if (typeof value !== "string") return null;
|
|
90
|
+
const s = value.trim();
|
|
91
|
+
if (!s) return null;
|
|
92
|
+
|
|
93
|
+
let m = OCCURRED_FULL_RE.exec(s);
|
|
94
|
+
if (m) {
|
|
95
|
+
return parseCalendarDate(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
96
|
+
}
|
|
97
|
+
m = OCCURRED_YM_RE.exec(s);
|
|
98
|
+
if (m) {
|
|
99
|
+
const year = Number(m[1]);
|
|
100
|
+
const month = Number(m[2]);
|
|
101
|
+
if (year < 1970 || year > 9999 || month < 1 || month > 12) return null;
|
|
102
|
+
const day = isEnd ? daysInMonth(year, month) : 1;
|
|
103
|
+
return parseCalendarDate(year, month, day);
|
|
104
|
+
}
|
|
105
|
+
m = OCCURRED_Y_RE.exec(s);
|
|
106
|
+
if (m) {
|
|
107
|
+
const year = Number(m[1]);
|
|
108
|
+
if (year < 1970 || year > 9999) return null;
|
|
109
|
+
return isEnd ? parseCalendarDate(year, 12, 31) : parseCalendarDate(year, 1, 1);
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Validate optional occurred_from / occurred_to filter bounds (fail-closed on bad dates or inverted range).
|
|
116
|
+
*/
|
|
117
|
+
export function normalizeOccurredRange(occurredFrom = null, occurredTo = null) {
|
|
118
|
+
let fromDate = null;
|
|
119
|
+
let toDate = null;
|
|
120
|
+
|
|
121
|
+
if (occurredFrom !== null && occurredFrom !== undefined && (typeof occurredFrom !== "string" || occurredFrom.trim())) {
|
|
122
|
+
fromDate = parseOccurredBound(occurredFrom, { isEnd: false });
|
|
123
|
+
if (!fromDate) {
|
|
124
|
+
throw new Error(`invalid-occurred-from: ${JSON.stringify(occurredFrom)} (expected YYYY, YYYY-MM, or YYYY-MM-DD)`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (occurredTo !== null && occurredTo !== undefined && (typeof occurredTo !== "string" || occurredTo.trim())) {
|
|
128
|
+
toDate = parseOccurredBound(occurredTo, { isEnd: true });
|
|
129
|
+
if (!toDate) {
|
|
130
|
+
throw new Error(`invalid-occurred-to: ${JSON.stringify(occurredTo)} (expected YYYY, YYYY-MM, or YYYY-MM-DD)`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (fromDate && toDate && fromDate > toDate) {
|
|
134
|
+
throw new Error(`invalid-occurred-range: occurred_from (${fromDate}) > occurred_to (${toDate})`);
|
|
135
|
+
}
|
|
136
|
+
return { fromDate, toDate };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Return true iff a fact's occurred interval overlaps [fromDate, toDate].
|
|
141
|
+
*/
|
|
142
|
+
export function factMatchesOccurredRange(occurredStart, occurredEnd = null, { fromDate = null, toDate = null } = {}) {
|
|
143
|
+
if (!fromDate && !toDate) return true;
|
|
144
|
+
const fStart = parseOccurredBound(occurredStart, { isEnd: false });
|
|
145
|
+
if (!fStart) return false;
|
|
146
|
+
let fEnd = occurredEnd ? parseOccurredBound(occurredEnd, { isEnd: true }) : null;
|
|
147
|
+
if (!fEnd) {
|
|
148
|
+
fEnd = parseOccurredBound(occurredStart, { isEnd: true }) || fStart;
|
|
149
|
+
}
|
|
150
|
+
if (fEnd < fStart) fEnd = fStart;
|
|
151
|
+
if (fromDate && fEnd < fromDate) return false;
|
|
152
|
+
if (toDate && fStart > toDate) return false;
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Stable-partition non-superseded records ahead of superseded historical facts without dropping any item.
|
|
158
|
+
*/
|
|
159
|
+
export function partitionSuperseded(records) {
|
|
160
|
+
if (!Array.isArray(records) || !records.length) {
|
|
161
|
+
return { items: [], supersededCount: 0 };
|
|
162
|
+
}
|
|
163
|
+
const current = [];
|
|
164
|
+
const superseded = [];
|
|
165
|
+
for (const row of records) {
|
|
166
|
+
if (Array.isArray(row?.superseded_by) && row.superseded_by.length > 0) {
|
|
167
|
+
superseded.push({ ...row });
|
|
168
|
+
} else {
|
|
169
|
+
current.push({ ...row });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (!superseded.length) {
|
|
173
|
+
return { items: current, supersededCount: 0 };
|
|
174
|
+
}
|
|
175
|
+
return { items: [...current, ...superseded], supersededCount: superseded.length };
|
|
176
|
+
}
|
|
177
|
+
|
|
74
178
|
export function resolveAsOfDate(today = null) {
|
|
75
179
|
if (today instanceof Date && Number.isFinite(today.getTime())) {
|
|
76
180
|
return parseCalendarDate(today.getUTCFullYear(), today.getUTCMonth() + 1, today.getUTCDate());
|
|
@@ -225,7 +329,7 @@ export function selectAdaptiveHits(
|
|
|
225
329
|
|
|
226
330
|
let leading = 0;
|
|
227
331
|
for (const row of records) {
|
|
228
|
-
if (!row.until_expiry) {
|
|
332
|
+
if (!row.until_expiry && !(Array.isArray(row.superseded_by) && row.superseded_by.length > 0)) {
|
|
229
333
|
const sc = Number(row.score || 0);
|
|
230
334
|
if (sc > leading) leading = sc;
|
|
231
335
|
}
|
package/lib/hooks.mjs
CHANGED
|
@@ -93,12 +93,18 @@ export function readDshTranscriptTurns(events) {
|
|
|
93
93
|
export function formatRecallInjection(hits, namespace) {
|
|
94
94
|
if (!Array.isArray(hits) || !hits.length) return "";
|
|
95
95
|
const lines = hits.map((h, i) => {
|
|
96
|
-
const
|
|
96
|
+
const tags = [h.namespace];
|
|
97
|
+
if (h.occurred_start) tags.push(String(h.occurred_start));
|
|
98
|
+
if (h.supersedes_fact_id) tags.push(`替代 #${h.supersedes_fact_id}`);
|
|
99
|
+
if (Array.isArray(h.superseded_by) && h.superseded_by.length) {
|
|
100
|
+
tags.push(`已被 ${h.superseded_by.map((x) => `#${x}`).join(",")} 替代`);
|
|
101
|
+
}
|
|
102
|
+
if (h.until_expiry?.label) tags.push(h.until_expiry.label);
|
|
97
103
|
const ev =
|
|
98
104
|
Array.isArray(h.evidence) && h.evidence.length
|
|
99
105
|
? ` (证据: ${h.evidence[0].text.slice(0, 120)})`
|
|
100
106
|
: "";
|
|
101
|
-
return `${i + 1}. [${
|
|
107
|
+
return `${i + 1}. [${tags.join(" · ")}] ${h.text}${ev}`;
|
|
102
108
|
});
|
|
103
109
|
return [
|
|
104
110
|
INJECT_START,
|
package/lib/index.mjs
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
import { attachZeroMemHooks } from "./hooks.mjs";
|
|
13
13
|
import { ZeroMemEngine } from "./memory.mjs";
|
|
14
|
+
import { backupDatabase, exportMarkdown } from "./portability.mjs";
|
|
15
|
+
import { SQLiteMemoryStore } from "./store.mjs";
|
|
14
16
|
import { registerZeroMemTools } from "./tools.mjs";
|
|
15
17
|
import { mountWebServer, registerDesktopIndexInject } from "./web.mjs";
|
|
16
18
|
|
|
@@ -115,4 +117,4 @@ export function apply(root, config = {}) {
|
|
|
115
117
|
}
|
|
116
118
|
|
|
117
119
|
export default { name, apply };
|
|
118
|
-
export { ZeroMemEngine };
|
|
120
|
+
export { ZeroMemEngine, SQLiteMemoryStore, exportMarkdown, backupDatabase };
|
package/lib/llm.mjs
CHANGED
|
@@ -454,7 +454,7 @@ export class OllamaAdapter {
|
|
|
454
454
|
);
|
|
455
455
|
}
|
|
456
456
|
|
|
457
|
-
async chatJson(systemPrompt, userPayload, { numPredict = 1024, retries = 1 } = {}) {
|
|
457
|
+
async chatJson(systemPrompt, userPayload, { numPredict = 1024, retries = 1, responseFormat = null } = {}) {
|
|
458
458
|
const model = await this.resolveModel();
|
|
459
459
|
const payload = {
|
|
460
460
|
model,
|
|
@@ -474,6 +474,9 @@ export class OllamaAdapter {
|
|
|
474
474
|
repeat_penalty: 1.08,
|
|
475
475
|
},
|
|
476
476
|
};
|
|
477
|
+
if (responseFormat && (typeof responseFormat === "object" || typeof responseFormat === "string")) {
|
|
478
|
+
payload.format = responseFormat;
|
|
479
|
+
}
|
|
477
480
|
|
|
478
481
|
let lastErr = null;
|
|
479
482
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
@@ -644,7 +647,8 @@ export class OpenAICompatibleAdapter {
|
|
|
644
647
|
return `${this.baseUrl}/models`;
|
|
645
648
|
}
|
|
646
649
|
|
|
647
|
-
async chatJson(systemPrompt, userPayload, { numPredict = 1024, retries = 1 } = {}) {
|
|
650
|
+
async chatJson(systemPrompt, userPayload, { numPredict = 1024, retries = 1, responseFormat = null } = {}) {
|
|
651
|
+
void responseFormat;
|
|
648
652
|
const url = this._completionsUrl();
|
|
649
653
|
const isLocal = isLoopbackHost(new URL(url).hostname);
|
|
650
654
|
if (!this.apiKey && !isLocal) {
|
package/lib/memory.mjs
CHANGED
|
@@ -9,11 +9,14 @@
|
|
|
9
9
|
|
|
10
10
|
import { createHash } from "node:crypto";
|
|
11
11
|
import {
|
|
12
|
+
FACT_ADMISSION_SUPERSEDE_ADDENDUM,
|
|
12
13
|
FACT_ADMISSION_SYSTEM,
|
|
13
14
|
FACT_EXTRACTION_SYSTEM,
|
|
14
15
|
VALID_DECISIONS,
|
|
16
|
+
buildAdmissionSupersedeSchema,
|
|
15
17
|
buildSegments,
|
|
16
18
|
guardFact,
|
|
19
|
+
inferGroundedOccurredStart,
|
|
17
20
|
parseJsonObject,
|
|
18
21
|
segmentToPayload,
|
|
19
22
|
windowSegments,
|
|
@@ -27,6 +30,7 @@ import {
|
|
|
27
30
|
pullOllamaModel,
|
|
28
31
|
startLocalOllamaService,
|
|
29
32
|
} from "./llm.mjs";
|
|
33
|
+
import { backupDatabase, exportMarkdown } from "./portability.mjs";
|
|
30
34
|
import { SQLiteMemoryStore } from "./store.mjs";
|
|
31
35
|
|
|
32
36
|
function utcNowIso() {
|
|
@@ -364,7 +368,7 @@ export class ZeroMemEngine {
|
|
|
364
368
|
}
|
|
365
369
|
|
|
366
370
|
/**
|
|
367
|
-
* Ingest text or chat turns: redact -> short-window chunk -> extract -> 1-round admit -> guard -> SQLite.
|
|
371
|
+
* Ingest text or chat turns: redact -> short-window chunk -> extract -> prior FTS5 lookup -> 1-round admit -> guard -> SQLite.
|
|
368
372
|
*/
|
|
369
373
|
async remember(
|
|
370
374
|
content,
|
|
@@ -373,6 +377,7 @@ export class ZeroMemEngine {
|
|
|
373
377
|
sourceId = null,
|
|
374
378
|
mentionedAt = null,
|
|
375
379
|
verify = null,
|
|
380
|
+
linkSupersessions = true,
|
|
376
381
|
maxWindowChars = 1400,
|
|
377
382
|
} = {}
|
|
378
383
|
) {
|
|
@@ -392,6 +397,7 @@ export class ZeroMemEngine {
|
|
|
392
397
|
extracted: 0,
|
|
393
398
|
saved: 0,
|
|
394
399
|
revised: 0,
|
|
400
|
+
superseded: 0,
|
|
395
401
|
dropped: 0,
|
|
396
402
|
held: 0,
|
|
397
403
|
guard_rejected: 0,
|
|
@@ -415,6 +421,7 @@ export class ZeroMemEngine {
|
|
|
415
421
|
extracted: 0,
|
|
416
422
|
saved: 0,
|
|
417
423
|
revised: 0,
|
|
424
|
+
superseded: 0,
|
|
418
425
|
dropped: 0,
|
|
419
426
|
held: 0,
|
|
420
427
|
guard_rejected: 0,
|
|
@@ -438,6 +445,7 @@ export class ZeroMemEngine {
|
|
|
438
445
|
extracted: 0,
|
|
439
446
|
saved: 0,
|
|
440
447
|
revised: 0,
|
|
448
|
+
superseded: 0,
|
|
441
449
|
dropped: 0,
|
|
442
450
|
held: 0,
|
|
443
451
|
guard_rejected: 0,
|
|
@@ -469,12 +477,16 @@ export class ZeroMemEngine {
|
|
|
469
477
|
let reviewed;
|
|
470
478
|
if (shouldVerify) {
|
|
471
479
|
task.update("verify", "审校中");
|
|
480
|
+
const priorFacts = linkSupersessions
|
|
481
|
+
? this._findPriorFacts(store, { namespace, candidates, maxItems: 6 })
|
|
482
|
+
: [];
|
|
472
483
|
reviewed = await this._admitWindow(llm, {
|
|
473
484
|
window: win,
|
|
474
485
|
candidates,
|
|
475
486
|
mentionedAt: ts,
|
|
476
487
|
namespace,
|
|
477
488
|
result,
|
|
489
|
+
priorFacts,
|
|
478
490
|
});
|
|
479
491
|
} else {
|
|
480
492
|
reviewed = candidates.map((c) => ({ ...c, action: "bypass" }));
|
|
@@ -482,6 +494,7 @@ export class ZeroMemEngine {
|
|
|
482
494
|
|
|
483
495
|
for (const cand of reviewed) {
|
|
484
496
|
const action = String(cand.action || "pass");
|
|
497
|
+
const supersedesFid = cand.supersedes_fact_id;
|
|
485
498
|
const { guarded } = guardFact(cand, segMap, { mentionedAt: ts });
|
|
486
499
|
if (!guarded) {
|
|
487
500
|
result.guard_rejected += 1;
|
|
@@ -490,7 +503,11 @@ export class ZeroMemEngine {
|
|
|
490
503
|
const dedupKey = guarded.text.toLowerCase();
|
|
491
504
|
if (seenFactKeys.has(dedupKey)) continue;
|
|
492
505
|
seenFactKeys.add(dedupKey);
|
|
493
|
-
|
|
506
|
+
const entry = { ...guarded, action };
|
|
507
|
+
if (typeof supersedesFid === "number" && Number.isInteger(supersedesFid) && supersedesFid > 0) {
|
|
508
|
+
entry.supersedes_fact_id = supersedesFid;
|
|
509
|
+
}
|
|
510
|
+
acceptedFacts.push(entry);
|
|
494
511
|
}
|
|
495
512
|
}
|
|
496
513
|
|
|
@@ -507,6 +524,7 @@ export class ZeroMemEngine {
|
|
|
507
524
|
});
|
|
508
525
|
|
|
509
526
|
result.saved = savedIds.length;
|
|
527
|
+
result.superseded = acceptedFacts.filter((f) => f.supersedes_fact_id !== undefined).length;
|
|
510
528
|
result.fact_ids = savedIds;
|
|
511
529
|
result.facts = acceptedFacts;
|
|
512
530
|
this.runtimeMetrics.lastRememberAt = createdAt;
|
|
@@ -532,14 +550,93 @@ export class ZeroMemEngine {
|
|
|
532
550
|
return { candidates, model: String(meta?.model || "") };
|
|
533
551
|
}
|
|
534
552
|
|
|
535
|
-
|
|
553
|
+
_findPriorFacts(store, { namespace, candidates, maxItems = 6 }) {
|
|
554
|
+
if (!Array.isArray(candidates) || !candidates.length || maxItems <= 0) return [];
|
|
555
|
+
const collected = new Map();
|
|
556
|
+
for (const cand of candidates) {
|
|
557
|
+
const entities = Array.isArray(cand.entities) ? cand.entities : [];
|
|
558
|
+
const parts = entities
|
|
559
|
+
.slice(0, 4)
|
|
560
|
+
.map((e) => String(e || "").trim())
|
|
561
|
+
.filter(Boolean);
|
|
562
|
+
const text = String(cand.text || "").trim();
|
|
563
|
+
if (text) parts.push(text.slice(0, 120));
|
|
564
|
+
const query = parts.join(" ").trim();
|
|
565
|
+
if (!query) continue;
|
|
566
|
+
let rows = [];
|
|
567
|
+
try {
|
|
568
|
+
rows = store.search(query, {
|
|
569
|
+
namespace,
|
|
570
|
+
limit: 3,
|
|
571
|
+
adaptive: false,
|
|
572
|
+
includeSuperseded: false,
|
|
573
|
+
});
|
|
574
|
+
} catch {
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
for (const r of rows) {
|
|
578
|
+
const fid = Number(r.fact_id);
|
|
579
|
+
const score = Number(r.score || 0);
|
|
580
|
+
const prev = collected.get(fid);
|
|
581
|
+
if (!prev || score > prev.score) {
|
|
582
|
+
collected.set(fid, {
|
|
583
|
+
score,
|
|
584
|
+
item: {
|
|
585
|
+
fact_id: fid,
|
|
586
|
+
text: String(r.text),
|
|
587
|
+
occurred_start: r.occurred_start ?? null,
|
|
588
|
+
mentioned_at: String(r.mentioned_at || ""),
|
|
589
|
+
entities: Array.isArray(r.entities) ? r.entities.slice(0, 6) : [],
|
|
590
|
+
},
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return [...collected.values()]
|
|
596
|
+
.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.item.fact_id - b.item.fact_id))
|
|
597
|
+
.slice(0, maxItems)
|
|
598
|
+
.map((entry) => entry.item);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
_parseSupersedesId(verdict, offeredPriorIds) {
|
|
602
|
+
if (!offeredPriorIds || !offeredPriorIds.size) return null;
|
|
603
|
+
const rawCandidates = [];
|
|
604
|
+
if (Array.isArray(verdict?.supersedes_fact_id)) {
|
|
605
|
+
rawCandidates.push(...verdict.supersedes_fact_id);
|
|
606
|
+
} else if (verdict?.supersedes_fact_id !== undefined && verdict?.supersedes_fact_id !== null) {
|
|
607
|
+
rawCandidates.push(verdict.supersedes_fact_id);
|
|
608
|
+
} else if (Array.isArray(verdict?.supersedes_fact_ids)) {
|
|
609
|
+
rawCandidates.push(...verdict.supersedes_fact_ids);
|
|
610
|
+
}
|
|
611
|
+
for (const val of rawCandidates) {
|
|
612
|
+
if (typeof val === "boolean") continue;
|
|
613
|
+
let parsed = null;
|
|
614
|
+
if (typeof val === "number" && Number.isInteger(val)) {
|
|
615
|
+
parsed = val;
|
|
616
|
+
} else if (typeof val === "string" && /^\d+$/.test(val.trim())) {
|
|
617
|
+
parsed = Number(val.trim());
|
|
618
|
+
}
|
|
619
|
+
if (parsed !== null && offeredPriorIds.has(parsed)) {
|
|
620
|
+
return parsed;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async _admitWindow(llm, { window, candidates, mentionedAt, namespace, result, priorFacts = [] }) {
|
|
627
|
+
const winSegText = new Map(window.map((s) => [s.id, s.text]));
|
|
536
628
|
const factsMap = {};
|
|
537
629
|
for (let idx = 0; idx < candidates.length; idx++) {
|
|
538
630
|
const cand = candidates[idx];
|
|
631
|
+
let occStart = cand.occurred_start ?? null;
|
|
632
|
+
if (!occStart && Array.isArray(cand.evidence) && cand.evidence.length) {
|
|
633
|
+
const evBlob = cand.evidence.map((eid) => winSegText.get(String(eid)) || "").join("\n");
|
|
634
|
+
occStart = inferGroundedOccurredStart(cand.text, evBlob, mentionedAt);
|
|
635
|
+
}
|
|
539
636
|
factsMap[String(idx)] = {
|
|
540
637
|
text: String(cand.text || ""),
|
|
541
638
|
type: String(cand.type || "world"),
|
|
542
|
-
occurred_start:
|
|
639
|
+
occurred_start: occStart,
|
|
543
640
|
occurred_end: cand.occurred_end ?? null,
|
|
544
641
|
where: cand.where ?? null,
|
|
545
642
|
entities: Array.isArray(cand.entities) ? cand.entities : [],
|
|
@@ -553,7 +650,26 @@ export class ZeroMemEngine {
|
|
|
553
650
|
evidence: window.map(segmentToPayload),
|
|
554
651
|
facts: factsMap,
|
|
555
652
|
};
|
|
556
|
-
const
|
|
653
|
+
const offeredPriorIds = new Set();
|
|
654
|
+
let systemPrompt = FACT_ADMISSION_SYSTEM;
|
|
655
|
+
let admitSchema = null;
|
|
656
|
+
|
|
657
|
+
if (Array.isArray(priorFacts) && priorFacts.length) {
|
|
658
|
+
payload.prior_facts = priorFacts;
|
|
659
|
+
for (const pf of priorFacts) {
|
|
660
|
+
if (typeof pf?.fact_id === "number" && Number.isInteger(pf.fact_id) && pf.fact_id > 0) {
|
|
661
|
+
offeredPriorIds.add(pf.fact_id);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
systemPrompt = `${FACT_ADMISSION_SYSTEM} ${FACT_ADMISSION_SUPERSEDE_ADDENDUM}`;
|
|
665
|
+
if (offeredPriorIds.size) {
|
|
666
|
+
admitSchema = buildAdmissionSupersedeSchema(candidates.length, [...offeredPriorIds]);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
const chatOpts = { numPredict: 768 };
|
|
671
|
+
if (admitSchema) chatOpts.responseFormat = admitSchema;
|
|
672
|
+
const { content } = await llm.chatJson(systemPrompt, payload, chatOpts);
|
|
557
673
|
const verdicts = parseJsonObject(content);
|
|
558
674
|
if (!verdicts) {
|
|
559
675
|
return candidates.map((c) => ({ ...c, action: "pass_fallback" }));
|
|
@@ -574,14 +690,19 @@ export class ZeroMemEngine {
|
|
|
574
690
|
}
|
|
575
691
|
const ev =
|
|
576
692
|
Array.isArray(verdict.evidence) && verdict.evidence.length ? verdict.evidence : cand.evidence;
|
|
693
|
+
const supersedesId = this._parseSupersedesId(verdict, offeredPriorIds);
|
|
577
694
|
|
|
578
695
|
if (decision === "pass") {
|
|
579
|
-
|
|
696
|
+
const entry = { ...cand, evidence: ev, action: "pass" };
|
|
697
|
+
if (supersedesId !== null) entry.supersedes_fact_id = supersedesId;
|
|
698
|
+
approved.push(entry);
|
|
580
699
|
} else if (decision === "revise") {
|
|
581
700
|
const replacement = String(verdict.replacement || "").trim();
|
|
582
701
|
if (replacement) {
|
|
583
702
|
result.revised += 1;
|
|
584
|
-
|
|
703
|
+
const entry = { ...cand, text: replacement, evidence: ev, action: "revise" };
|
|
704
|
+
if (supersedesId !== null) entry.supersedes_fact_id = supersedesId;
|
|
705
|
+
approved.push(entry);
|
|
585
706
|
} else {
|
|
586
707
|
result.held += 1;
|
|
587
708
|
}
|
|
@@ -604,6 +725,9 @@ export class ZeroMemEngine {
|
|
|
604
725
|
scoreRatio = ADAPTIVE_SCORE_RATIO,
|
|
605
726
|
asOf = null,
|
|
606
727
|
untilEnabled = null,
|
|
728
|
+
occurredFrom = null,
|
|
729
|
+
occurredTo = null,
|
|
730
|
+
includeSuperseded = true,
|
|
607
731
|
} = {}
|
|
608
732
|
) {
|
|
609
733
|
const cfg = this.getConfig();
|
|
@@ -617,6 +741,9 @@ export class ZeroMemEngine {
|
|
|
617
741
|
scoreRatio,
|
|
618
742
|
asOf,
|
|
619
743
|
untilEnabled: useUntil,
|
|
744
|
+
occurredFrom,
|
|
745
|
+
occurredTo,
|
|
746
|
+
includeSuperseded,
|
|
620
747
|
});
|
|
621
748
|
}
|
|
622
749
|
|
|
@@ -651,4 +778,47 @@ export class ZeroMemEngine {
|
|
|
651
778
|
deleteDocument(docId) {
|
|
652
779
|
return this.getStore().deleteDocument(docId);
|
|
653
780
|
}
|
|
781
|
+
|
|
782
|
+
exportMarkdown({
|
|
783
|
+
outputPath = null,
|
|
784
|
+
outputDir = null,
|
|
785
|
+
ns = null,
|
|
786
|
+
occurredFrom = null,
|
|
787
|
+
occurredTo = null,
|
|
788
|
+
asOf = null,
|
|
789
|
+
includeSuperseded = true,
|
|
790
|
+
includeEvicted = false,
|
|
791
|
+
frontmatter = true,
|
|
792
|
+
} = {}) {
|
|
793
|
+
const store = this.getStore();
|
|
794
|
+
return exportMarkdown({
|
|
795
|
+
dbPath: store.dbPath,
|
|
796
|
+
outputPath,
|
|
797
|
+
outputDir,
|
|
798
|
+
namespace: ns || null,
|
|
799
|
+
occurredFrom,
|
|
800
|
+
occurredTo,
|
|
801
|
+
asOf,
|
|
802
|
+
includeSuperseded,
|
|
803
|
+
includeEvicted,
|
|
804
|
+
frontmatter,
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
async backup(outputPath = null, { overwrite = false, verify = true, writeSha256 = false, pages = 256 } = {}) {
|
|
809
|
+
const store = this.getStore();
|
|
810
|
+
const task = this.beginActivity("backup", "备份中");
|
|
811
|
+
try {
|
|
812
|
+
return await backupDatabase({
|
|
813
|
+
dbPath: store.dbPath,
|
|
814
|
+
outputPath,
|
|
815
|
+
overwrite,
|
|
816
|
+
verify,
|
|
817
|
+
writeSha256,
|
|
818
|
+
pages,
|
|
819
|
+
});
|
|
820
|
+
} finally {
|
|
821
|
+
task.end();
|
|
822
|
+
}
|
|
823
|
+
}
|
|
654
824
|
}
|