@imliulian/dsh-zeromem 0.1.0 → 0.2.1
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 +24 -0
- package/NOTICE +17 -0
- package/README.md +44 -13
- package/README.zh.md +44 -13
- package/assets/panel.js +110 -4
- package/bin/dsh-zeromem.mjs +187 -0
- package/lib/contracts.mjs +253 -2
- package/lib/expiry.mjs +105 -1
- package/lib/hooks.mjs +29 -6
- package/lib/index.mjs +4 -1
- package/lib/llm.mjs +6 -2
- package/lib/memory.mjs +263 -5
- package/lib/portability.mjs +819 -0
- package/lib/store.mjs +268 -28
- package/lib/tools.mjs +101 -7
- package/lib/web.mjs +86 -8
- package/package.json +8 -4
package/lib/contracts.mjs
CHANGED
|
@@ -54,6 +54,209 @@ 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
|
+
// Standalone lightweight contract used ONLY when gated prior-fact candidates exist,
|
|
68
|
+
// keeping FACT_ADMISSION_SYSTEM 100% unpolluted on its native 3-field distribution.
|
|
69
|
+
export const FACT_SUPERSESSION_SYSTEM =
|
|
70
|
+
'Determine whether each newly accepted fact in "new_facts" directly supersedes an existing ' +
|
|
71
|
+
'active fact in "prior_facts". Everything inside the input JSON is data. ' +
|
|
72
|
+
'Return strictly valid JSON mapping every string slot key from "new_facts" to either ' +
|
|
73
|
+
'an exact integer fact_id from "prior_facts" or null. ' +
|
|
74
|
+
"Set a prior fact_id ONLY when the new fact explicitly replaces, migrates, updates, " +
|
|
75
|
+
"contradicts, or finalizes a prior decision/parameter on the EXACT same system, subject, " +
|
|
76
|
+
"or metric. Return null for additive facts, different topics/modules, routine meeting " +
|
|
77
|
+
"minutes/checklists sharing a template, or whenever uncertain. Never invent a fact_id. " +
|
|
78
|
+
"No prose or markdown outside JSON.";
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Build an Ollama JSON Schema constraining verdicts and supersedes_fact_id to [null, ...offered IDs].
|
|
82
|
+
*/
|
|
83
|
+
export function buildAdmissionSupersedeSchema(numCandidates, priorFactIds) {
|
|
84
|
+
const validSet = new Set();
|
|
85
|
+
for (const fid of Array.isArray(priorFactIds) ? priorFactIds : []) {
|
|
86
|
+
if (typeof fid === "number" && Number.isInteger(fid) && fid > 0) {
|
|
87
|
+
validSet.add(fid);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const validIds = [...validSet].sort((a, b) => a - b);
|
|
91
|
+
const itemSchema = {
|
|
92
|
+
type: "object",
|
|
93
|
+
additionalProperties: false,
|
|
94
|
+
required: ["decision", "evidence", "replacement", "supersedes_fact_id"],
|
|
95
|
+
properties: {
|
|
96
|
+
decision: { type: "string", enum: ["pass", "revise", "drop", "hold"] },
|
|
97
|
+
evidence: { type: "array", items: { type: "string" } },
|
|
98
|
+
replacement: { type: "string" },
|
|
99
|
+
supersedes_fact_id: { enum: [null, ...validIds] },
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
const count = Math.max(0, Math.trunc(Number(numCandidates) || 0));
|
|
103
|
+
const keys = Array.from({ length: count }, (_, i) => String(i));
|
|
104
|
+
const properties = {};
|
|
105
|
+
for (const k of keys) properties[k] = itemSchema;
|
|
106
|
+
return {
|
|
107
|
+
type: "object",
|
|
108
|
+
additionalProperties: false,
|
|
109
|
+
required: keys,
|
|
110
|
+
properties,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Build a minimal Ollama JSON Schema mapping each gated slot key to [null, ...valid prior IDs].
|
|
116
|
+
*/
|
|
117
|
+
export function buildSupersessionSchema(slotKeys, priorFactIds) {
|
|
118
|
+
const validSet = new Set();
|
|
119
|
+
for (const fid of Array.isArray(priorFactIds) ? priorFactIds : []) {
|
|
120
|
+
if (typeof fid === "number" && Number.isInteger(fid) && fid > 0) {
|
|
121
|
+
validSet.add(fid);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const validIds = [...validSet].sort((a, b) => a - b);
|
|
125
|
+
const keys = (Array.isArray(slotKeys) ? slotKeys : []).map((k) => String(k));
|
|
126
|
+
const valSchema = { enum: [null, ...validIds] };
|
|
127
|
+
const properties = {};
|
|
128
|
+
for (const k of keys) properties[k] = valSchema;
|
|
129
|
+
return {
|
|
130
|
+
type: "object",
|
|
131
|
+
additionalProperties: false,
|
|
132
|
+
required: keys,
|
|
133
|
+
properties,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const INVOLVING_TAIL_RE = /\s*\|\s*Involving\s*:.*$/i;
|
|
138
|
+
const WS_COLLAPSE_RE = /\s+/g;
|
|
139
|
+
|
|
140
|
+
const SUPERSESSION_CUE_RE = new RegExp(
|
|
141
|
+
"(?:" +
|
|
142
|
+
"改为|改成|调整为|变更为|更新为|替换为|切换为|切换到|切换至|迁移至|迁移到|迁移为|升级为|升级到|降级为|" +
|
|
143
|
+
"下调为|下调至|上调为|上调至|提高到|提高至|扩容至|扩至|缩容至|回滚至|回滚到|" +
|
|
144
|
+
"不再使用|暂不上|放弃|废弃|弃用|停用|禁用|取代|替代|覆盖|推翻|撤回|纠正|更正|" +
|
|
145
|
+
"最终决定|正式采用|正式确认|改用|由原先|由原|原上限|原方案|旧方案|" +
|
|
146
|
+
"\\b(?:migrated?|replaced?|supersed(?:e|ed|es|ing)|switch(?:ed|ing)?\\b.{0,40}\\bto\\b|" +
|
|
147
|
+
"chang(?:ed|ing)\\s+(?:from|to)|updat(?:ed|ing)\\s+to|adjust(?:ed|ing)\\s+to|" +
|
|
148
|
+
"increas(?:ed|ing)\\s+to|decreas(?:ed|ing)\\s+to|reduc(?:ed|ing)\\s+to|" +
|
|
149
|
+
"lower(?:ed|ing)\\s+to|rais(?:ed|ing)\\s+to|deprecat(?:ed|ing)|" +
|
|
150
|
+
"roll(?:ed)?\\s*back|overrid(?:e|es|den)|revers(?:ed|ing)|abandon(?:ed|ing)|" +
|
|
151
|
+
"no\\s+longer|instead\\s+of|rather\\s+than|final\\s+decision|previously|formerly)\\b" +
|
|
152
|
+
")",
|
|
153
|
+
"i"
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
export const SUPERSESSION_STOPWORDS = new Set([
|
|
157
|
+
"the", "and", "for", "with", "that", "this", "from", "into", "onto", "are", "was", "were",
|
|
158
|
+
"has", "have", "had", "not", "but", "all", "any", "can", "will", "would", "should", "may",
|
|
159
|
+
"per", "via", "its", "our", "their", "non", "also", "only", "more", "than", "when", "where",
|
|
160
|
+
"which", "while", "after", "before", "under", "over", "between", "through", "during", "without",
|
|
161
|
+
"within", "both", "each", "such", "been", "being", "does", "did", "done", "use", "used", "using",
|
|
162
|
+
"make", "made", "based", "related", "current", "new", "other", "same", "subsequent", "future",
|
|
163
|
+
"team", "meeting", "minutes", "record", "records", "routine", "supplementary", "checklist",
|
|
164
|
+
"confirm", "confirmed", "confirms", "ensure", "verify", "verified", "review", "reviewed",
|
|
165
|
+
"participants", "attendees", "members", "progress", "status", "update", "updates", "updated",
|
|
166
|
+
"march", "february", "january", "april", "june", "july", "august", "september", "october",
|
|
167
|
+
"november", "december", "2025", "2026", "2027",
|
|
168
|
+
]);
|
|
169
|
+
|
|
170
|
+
function normalizeTextForCompare(text) {
|
|
171
|
+
return String(text || "")
|
|
172
|
+
.replace(INVOLVING_TAIL_RE, "")
|
|
173
|
+
.trim()
|
|
174
|
+
.replace(WS_COLLAPSE_RE, " ")
|
|
175
|
+
.toLowerCase();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function isNoopRevision(origText, replacementText) {
|
|
179
|
+
const repNorm = normalizeTextForCompare(replacementText);
|
|
180
|
+
if (!repNorm) return true;
|
|
181
|
+
return repNorm === normalizeTextForCompare(origText);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function hasSupersessionCue(text) {
|
|
185
|
+
return Boolean(text && SUPERSESSION_CUE_RE.test(String(text)));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function isEvidenceVerbatimInFact(factText, evidenceText) {
|
|
189
|
+
const evNorm = String(evidenceText || "").replace(WS_COLLAPSE_RE, "").toLowerCase();
|
|
190
|
+
if (!evNorm) return true;
|
|
191
|
+
const factNorm = String(factText || "").replace(WS_COLLAPSE_RE, "").toLowerCase();
|
|
192
|
+
return factNorm.includes(evNorm);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Deduplicate shared (doc_id, seg_id) evidence across recall items and optionally fold verbatim repeats.
|
|
197
|
+
* Never mutates input items. Preserves segment IDs and speaker roles for traceability.
|
|
198
|
+
*/
|
|
199
|
+
export function deduplicateRecallEvidence(items, { foldVerbatim = true } = {}) {
|
|
200
|
+
const seenSegFirst = new Map();
|
|
201
|
+
const dedupedItems = [];
|
|
202
|
+
let sharedDeduped = 0;
|
|
203
|
+
let verbatimFolded = 0;
|
|
204
|
+
|
|
205
|
+
for (let i = 0; i < (Array.isArray(items) ? items.length : 0); i++) {
|
|
206
|
+
const raw = items[i];
|
|
207
|
+
const item = { ...raw };
|
|
208
|
+
const docId = String(item.doc_id || "");
|
|
209
|
+
const factText = String(item.text || "");
|
|
210
|
+
const rawEv = Array.isArray(item.evidence) ? item.evidence : [];
|
|
211
|
+
const compactEv = [];
|
|
212
|
+
|
|
213
|
+
for (const ev of rawEv) {
|
|
214
|
+
if (!ev || typeof ev !== "object") continue;
|
|
215
|
+
const segId = String(ev.id || "");
|
|
216
|
+
const evText = String(ev.text || "");
|
|
217
|
+
const role = ev.role ? String(ev.role) : "";
|
|
218
|
+
const key = `${docId}\u0000${segId}`;
|
|
219
|
+
|
|
220
|
+
if (seenSegFirst.has(key)) {
|
|
221
|
+
const firstIdx = seenSegFirst.get(key);
|
|
222
|
+
const refEntry = {
|
|
223
|
+
id: segId,
|
|
224
|
+
dedup_ref: docId ? `#${firstIdx}:${docId}:${segId}` : `#${firstIdx}:${segId}`,
|
|
225
|
+
};
|
|
226
|
+
if (role) refEntry.role = role;
|
|
227
|
+
compactEv.push(refEntry);
|
|
228
|
+
sharedDeduped += 1;
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
seenSegFirst.set(key, i + 1);
|
|
233
|
+
if (foldVerbatim && isEvidenceVerbatimInFact(factText, evText)) {
|
|
234
|
+
const foldEntry = { id: segId, same_as_fact: true };
|
|
235
|
+
if (role) foldEntry.role = role;
|
|
236
|
+
compactEv.push(foldEntry);
|
|
237
|
+
verbatimFolded += 1;
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const kept = { id: segId, text: evText };
|
|
242
|
+
if (role) kept.role = role;
|
|
243
|
+
compactEv.push(kept);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
item.evidence = compactEv;
|
|
247
|
+
dedupedItems.push(item);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
items: dedupedItems,
|
|
252
|
+
stats: {
|
|
253
|
+
shared_deduped: sharedDeduped,
|
|
254
|
+
verbatim_folded: verbatimFolded,
|
|
255
|
+
total_saved: sharedDeduped + verbatimFolded,
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
57
260
|
export const VALID_FACT_TYPES = new Set(["world", "experience", "observation"]);
|
|
58
261
|
export const VALID_DECISIONS = new Set(["pass", "revise", "drop", "hold"]);
|
|
59
262
|
|
|
@@ -89,6 +292,29 @@ const CREDENTIAL_RE_3 = /\b(api[_-]?key|access[_-]?token|secret[_-]?key|password
|
|
|
89
292
|
const HEX_TOKEN_RE = /\b[0-9a-fA-F]{16,64}\b/g;
|
|
90
293
|
const SENTENCE_SPLIT_RE = /(?<=[。!?!?;;\n])|(?<=\.\s)/;
|
|
91
294
|
const ISO_DATE_PREFIX_RE = /^\d{4}-\d{2}-\d{2}/;
|
|
295
|
+
const GROUNDED_ISO_DATE_RE = /(?<!until:)(?<![0-9])(\d{4})-(\d{2})-(\d{2})(?![0-9])/gi;
|
|
296
|
+
const GROUNDED_ZH_DATE_RE = /(?<![0-9])(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日/g;
|
|
297
|
+
|
|
298
|
+
function extractGroundedDates(str) {
|
|
299
|
+
const out = [];
|
|
300
|
+
const pushValid = (y, mo, da) => {
|
|
301
|
+
if (y < 1970 || y > 9999 || mo < 1 || mo > 12 || da < 1 || da > 31) return;
|
|
302
|
+
const dt = new Date(Date.UTC(y, mo - 1, da));
|
|
303
|
+
if (dt.getUTCFullYear() !== y || dt.getUTCMonth() !== mo - 1 || dt.getUTCDate() !== da) return;
|
|
304
|
+
const iso = `${String(y).padStart(4, "0")}-${String(mo).padStart(2, "0")}-${String(da).padStart(2, "0")}`;
|
|
305
|
+
if (!out.includes(iso)) out.push(iso);
|
|
306
|
+
};
|
|
307
|
+
let m;
|
|
308
|
+
GROUNDED_ISO_DATE_RE.lastIndex = 0;
|
|
309
|
+
while ((m = GROUNDED_ISO_DATE_RE.exec(str)) !== null) {
|
|
310
|
+
pushValid(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
311
|
+
}
|
|
312
|
+
GROUNDED_ZH_DATE_RE.lastIndex = 0;
|
|
313
|
+
while ((m = GROUNDED_ZH_DATE_RE.exec(str)) !== null) {
|
|
314
|
+
pushValid(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
315
|
+
}
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
92
318
|
|
|
93
319
|
export function redactCredentials(text) {
|
|
94
320
|
if (!text) return text;
|
|
@@ -325,6 +551,19 @@ function alignHexDigests(factText, evidenceBlob) {
|
|
|
325
551
|
return { text: repaired, ok: true };
|
|
326
552
|
}
|
|
327
553
|
|
|
554
|
+
export function inferGroundedOccurredStart(text, evidenceBlob, mentionedAt = null) {
|
|
555
|
+
let mDateStr = null;
|
|
556
|
+
if (mentionedAt) {
|
|
557
|
+
const mDate = ISO_DATE_PREFIX_RE.exec(String(mentionedAt));
|
|
558
|
+
if (mDate) mDateStr = mDate[0];
|
|
559
|
+
}
|
|
560
|
+
const evDates = new Set(extractGroundedDates(String(evidenceBlob || "")));
|
|
561
|
+
const groundedDates = extractGroundedDates(String(text || "")).filter(
|
|
562
|
+
(dStr) => dStr !== mDateStr && evDates.has(dStr)
|
|
563
|
+
);
|
|
564
|
+
return groundedDates.length === 1 ? groundedDates[0] : null;
|
|
565
|
+
}
|
|
566
|
+
|
|
328
567
|
/**
|
|
329
568
|
* Deterministic post-check on extracted/admitted fact.
|
|
330
569
|
*/
|
|
@@ -356,10 +595,15 @@ export function guardFact(fact, segMap, { mentionedAt = null } = {}) {
|
|
|
356
595
|
let occurredStart = fact.occurred_start ? String(fact.occurred_start).trim() : null;
|
|
357
596
|
let occurredEnd = fact.occurred_end ? String(fact.occurred_end).trim() : null;
|
|
358
597
|
|
|
359
|
-
|
|
598
|
+
let mDateStr = null;
|
|
599
|
+
if (mentionedAt) {
|
|
360
600
|
const mDate = ISO_DATE_PREFIX_RE.exec(String(mentionedAt));
|
|
601
|
+
if (mDate) mDateStr = mDate[0];
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
if (occurredStart && mDateStr) {
|
|
361
605
|
const oDate = ISO_DATE_PREFIX_RE.exec(occurredStart);
|
|
362
|
-
if (
|
|
606
|
+
if (oDate && mDateStr === oDate[0] && !evidenceBlob.includes(oDate[0])) {
|
|
363
607
|
occurredStart = null;
|
|
364
608
|
if (occurredEnd && occurredEnd.startsWith(oDate[0])) {
|
|
365
609
|
occurredEnd = null;
|
|
@@ -367,6 +611,13 @@ export function guardFact(fact, segMap, { mentionedAt = null } = {}) {
|
|
|
367
611
|
}
|
|
368
612
|
}
|
|
369
613
|
|
|
614
|
+
// Conservative deterministic backfill: if a single explicit grounded event date appears in fact text
|
|
615
|
+
// (grounded in evidence as ISO or YYYY年M月D日, not an `until:` tag, and distinct from record date)
|
|
616
|
+
// while occurred_start is null.
|
|
617
|
+
if (!occurredStart) {
|
|
618
|
+
occurredStart = inferGroundedOccurredStart(text, evidenceBlob, mentionedAt);
|
|
619
|
+
}
|
|
620
|
+
|
|
370
621
|
const whereLoc = fact.where ? redactCredentials(String(fact.where).trim()) : null;
|
|
371
622
|
const entities = [];
|
|
372
623
|
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
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { isEvidenceVerbatimInFact } from "./contracts.mjs";
|
|
14
15
|
import { deriveWorkspaceNamespace } from "./tools.mjs";
|
|
15
16
|
|
|
16
17
|
export const PLUGIN_ID = "zeromem";
|
|
@@ -92,13 +93,35 @@ export function readDshTranscriptTurns(events) {
|
|
|
92
93
|
|
|
93
94
|
export function formatRecallInjection(hits, namespace) {
|
|
94
95
|
if (!Array.isArray(hits) || !hits.length) return "";
|
|
96
|
+
const seenSegFirst = new Map();
|
|
95
97
|
const lines = hits.map((h, i) => {
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
98
|
+
const tags = [h.namespace];
|
|
99
|
+
if (h.occurred_start) tags.push(String(h.occurred_start));
|
|
100
|
+
if (h.supersedes_fact_id) tags.push(`替代 #${h.supersedes_fact_id}`);
|
|
101
|
+
if (Array.isArray(h.superseded_by) && h.superseded_by.length) {
|
|
102
|
+
tags.push(`已被 ${h.superseded_by.map((x) => `#${x}`).join(",")} 替代`);
|
|
103
|
+
}
|
|
104
|
+
if (h.until_expiry?.label) tags.push(h.until_expiry.label);
|
|
105
|
+
|
|
106
|
+
let ev = "";
|
|
107
|
+
if (Array.isArray(h.evidence) && h.evidence.length) {
|
|
108
|
+
const first = h.evidence[0];
|
|
109
|
+
const docId = String(h.doc_id || "");
|
|
110
|
+
const segId = String(first?.id || "");
|
|
111
|
+
const segText = String(first?.text || "");
|
|
112
|
+
const key = `${docId}\u0000${segId}`;
|
|
113
|
+
if (seenSegFirst.has(key)) {
|
|
114
|
+
ev = ` (证据: ${segId}同#${seenSegFirst.get(key)})`;
|
|
115
|
+
} else {
|
|
116
|
+
seenSegFirst.set(key, i + 1);
|
|
117
|
+
if (segText && !isEvidenceVerbatimInFact(h.text, segText)) {
|
|
118
|
+
ev = ` (证据: ${segText.slice(0, 120)})`;
|
|
119
|
+
} else if (segId) {
|
|
120
|
+
ev = ` (证据: ${segId}同正文)`;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return `${i + 1}. [${tags.join(" · ")}] ${h.text}${ev}`;
|
|
102
125
|
});
|
|
103
126
|
return [
|
|
104
127
|
INJECT_START,
|
package/lib/index.mjs
CHANGED
|
@@ -10,7 +10,10 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { attachZeroMemHooks } from "./hooks.mjs";
|
|
13
|
+
import { deduplicateRecallEvidence } from "./contracts.mjs";
|
|
13
14
|
import { ZeroMemEngine } from "./memory.mjs";
|
|
15
|
+
import { backupDatabase, exportMarkdown } from "./portability.mjs";
|
|
16
|
+
import { SQLiteMemoryStore } from "./store.mjs";
|
|
14
17
|
import { registerZeroMemTools } from "./tools.mjs";
|
|
15
18
|
import { mountWebServer, registerDesktopIndexInject } from "./web.mjs";
|
|
16
19
|
|
|
@@ -115,4 +118,4 @@ export function apply(root, config = {}) {
|
|
|
115
118
|
}
|
|
116
119
|
|
|
117
120
|
export default { name, apply };
|
|
118
|
-
export { ZeroMemEngine };
|
|
121
|
+
export { ZeroMemEngine, SQLiteMemoryStore, exportMarkdown, backupDatabase, deduplicateRecallEvidence };
|
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) {
|