Compare commits

..

2 Commits

Author SHA1 Message Date
0a6f1e4d62 Refined memory management prompts
All checks were successful
Publish Library / Build NPM Project (push) Successful in 1m18s
Publish Library / Tag Version (push) Successful in 20s
2026-08-25 10:03:36 -04:00
08a351e028 Better memory management
All checks were successful
Publish Library / Build NPM Project (push) Successful in 59s
Publish Library / Tag Version (push) Successful in 11s
2026-08-24 14:42:10 -04:00
2 changed files with 175 additions and 66 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@ztimson/ai-utils", "name": "@ztimson/ai-utils",
"version": "1.6.2", "version": "1.6.4",
"description": "AI Utility library", "description": "AI Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@@ -2,9 +2,10 @@ import {MemoryNode, rebuildGraph} from './helpers.ts';
import {LLMRequest, LLMMessage} from './llm.ts'; import {LLMRequest, LLMMessage} from './llm.ts';
import {AiTool} from './tools.ts'; import {AiTool} from './tools.ts';
import {KDPoint, KDTree} from './kd-tree.ts'; import {KDPoint, KDTree} from './kd-tree.ts';
import {escapeRegex} from '@ztimson/utils';
const FACTS_HEADING = '## Facts'; const MERGE_THRESHOLD = 0.88;
const PENDING_HEADING = '## Pending';
const GENERIC_TEMPLATE = `# {{Title}} const GENERIC_TEMPLATE = `# {{Title}}
## Summary ## Summary
@@ -32,6 +33,11 @@ type FactBucket = {
facts: string[]; facts: string[];
} }
type FactAgentResult = {
buckets: FactBucket[];
journal: string;
}
function dedupeFacts(facts: string[]): string[] { function dedupeFacts(facts: string[]): string[] {
const seen = new Map<string, string>(); const seen = new Map<string, string>();
for (const f of facts) { for (const f of facts) {
@@ -101,8 +107,8 @@ export class MemoryCache {
} }
update(memory: Memory): void { update(memory: Memory): void {
const idx = this.memories.findIndex(m => m.name === memory.name); const existing = this.memories.find(m => m.name === memory.name);
if (idx !== -1) this.memories[idx] = memory; if (existing) Object.assign(existing, memory);
else this.memories.push(memory); else this.memories.push(memory);
this.rebuild(); this.rebuild();
} }
@@ -163,7 +169,7 @@ class MemoryAccessor {
const missing = this.list.filter(m => !m.embedding?.length); const missing = this.list.filter(m => !m.embedding?.length);
if (!missing.length) return 0; if (!missing.length) return 0;
await Promise.all(missing.map(async node => { await Promise.all(missing.map(async node => {
const [e] = await llm.embedding(node.content); const [e] = await llm.embedding(`${node.description}\n\n${stripHeader(node.content)}`.trim());
if (e) node.embedding = e.embedding; if (e) node.embedding = e.embedding;
})); }));
this.commit(); this.commit();
@@ -251,14 +257,13 @@ ${m.content}
return new MemoryAccessor(memories); return new MemoryAccessor(memories);
} }
private appendFacts(node: Memory, facts: string[]): void { private stage(node: Memory, block: string): void {
this.ensureDoc(node); this.ensureDoc(node);
const body = stripHeader(node.content); const body = stripHeader(node.content);
const bullets = facts.map(f => `- ${f}`).join('\n'); const idx = body.indexOf(PENDING_HEADING);
const idx = body.indexOf(FACTS_HEADING);
const newBody = idx === -1 const newBody = idx === -1
? `${body.trimEnd()}\n\n${FACTS_HEADING}\n${bullets}\n` ? `${body.trimEnd()}\n\n${PENDING_HEADING}\n${block}\n`
: `${body.slice(0, idx + FACTS_HEADING.length)}\n${bullets}${body.slice(idx + FACTS_HEADING.length)}`; : `${body.slice(0, idx + PENDING_HEADING.length)}\n${block}${body.slice(idx + PENDING_HEADING.length)}`;
node.content = this.touchHeader(node, newBody); node.content = this.touchHeader(node, newBody);
} }
@@ -268,42 +273,52 @@ ${m.content}
node.content = this.touchHeader(node, `# ${title}\n`); node.content = this.touchHeader(node, `# ${title}\n`);
} }
private async factAgent(conversation: string, store: MemoryAccessor, options: LLMRequest, weekKey: string): Promise<FactBucket[]> { private sanitizeDescription(text: string): string {
return (text ?? '').replace(/\s+/g, ' ').trim().slice(0, 240);
}
private relink(memories: Memory[], from: string, to: string): void {
const pattern = new RegExp(`\\[\\[${escapeRegex(from)}\\]\\]`, 'g');
for (const m of memories) if (pattern.test(m.content)) m.content = m.content.replace(pattern, `[[${to}]]`);
}
private async factAgent(conversation: string, store: MemoryAccessor, options: LLMRequest): Promise<FactAgentResult> {
const ghosts = store.ghosts(); const ghosts = store.ghosts();
const response = await this.llm.ask(conversation, { const response = await this.llm.ask(conversation, {
model: options.model, model: options.model,
temperature: 0.2, temperature: 0.2,
system: `You are a fact extractor to build obsidian knowledge vaults. system: `You are a fact extractor for Obsidian-style knowledge vaults. Analyze the conversation and produce:
Analyze this conversation and extract facts worth remembering long-term.
Rules: 1. Journal recap (single paragraph)
- Always extract facts that the user explicitly told you to remember - "Captains Log" style record keeping
- ONLY extract current facts the USER explicitly stated about themselves, their work, projects or decisions that were MADE during this conversation - What was discussed/worked on, decisions, user's events/state/mood, general context
- DO NOT extract greetings, pleasantries, or generic exchanges - Leave empty only for trivial/empty exchanges/small talk
- DO NOT extract deltas or changes in facts; ONLY the end fact
- DO NOT extract anything the AI/assistant itself said
- If nothing worth remembering was said, return an empty buckets array
When extracting facts, you MUST also decide the exact destination path: 2. Fact buckets
- Reuse node names (including ghost) as much as possible IF the facts belongs there - ONLY facts the USER explicitly stated about themselves, their work, projects, or decisions made during this conversation
- All information primarily about the user should go under "People/User" - NEVER extract greetings, pleasantries, or anything the assistant itself said
- When required, create a new path following collection/subject format (e.g., People/Sarah, Projects/Oxide) — you are not limited to any fixed list of collections, use whatever fits - Extract the final/end state, not deltas
- For journal entries, use "Journal"
Path assignment rules:
- Reuse existing node names whenever possible
- Documents should be grouped and named by the root subject
- Person → People/Name
- Project → Projects/Name
- Concept → Concepts/Name
- A bug report, its investigation, should be nested and attached to the same root subject node
- Tickets/one-off tasks → file under the project/name/component they belong to
- Only create a new top-level node when the fact belongs to a genuinely new subject (person/project/concept)\`
Available nodes: Available nodes:
- Journal ${this.listNodes(store.list).map(n => `- ${n.name}: ${n.description}`).join('\n') || 'None yet.'}
${this.listNodes(store.list).filter(n => !n.name.includes('Journal')).map(n => `- ${n.name}: ${n.description}`).join('\n') || 'None yet.'}
${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`, ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
schema: { schema: {
buckets: {type: 'array', description: 'Groups of facts to remember, each assigned to a different node. Return an empty array if there is nothing worth storing in an obsidian vault', items: { journal: {type: 'string', description: 'Short day-to-day recap; empty if nothing happened.', required: false},
buckets: {type: 'array', description: 'Groups of facts to remember; empty array if nothing worth storing.', items: {
type: 'object', items: { type: 'object', items: {
subject: {type: 'string', description: 'Exact existing node name OR new path (e.g. "People/Sarah", "Projects/Oxide"), or "Journal"', required: true}, subject: {type: 'string', description: 'Exact node name or new path (e.g. "People/Sarah", "Projects/Oxide")', required: true},
facts: { facts: {type: 'array', description: 'Facts to store here', items: {type: 'string'}},
type: 'array',
description: 'Facts to store at this destination',
items: {type: 'string', description: 'A single fact'},
},
}, },
}, },
}, },
@@ -312,14 +327,16 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
const buckets = new Map<string, string[]>(); const buckets = new Map<string, string[]>();
for (const bucket of response.buckets ?? []) { for (const bucket of response.buckets ?? []) {
const subject = bucket.subject.trim().toLowerCase() === 'journal' const subject = bucket.subject.trim();
? `Journal/${weekKey}` : bucket.subject.trim();
const facts = buckets.get(subject) ?? []; const facts = buckets.get(subject) ?? [];
facts.push(...dedupeFacts(bucket.facts)); facts.push(...dedupeFacts(bucket.facts));
buckets.set(subject, facts); buckets.set(subject, facts);
} }
return buckets.entries().toArray().map(([subject, facts]) => ({subject, facts})); return {
buckets: buckets.entries().toArray().map(([subject, facts]) => ({subject, facts})),
journal: (response.journal ?? '').trim(),
};
} }
private getWeekMonday(date: Date = new Date()): string { private getWeekMonday(date: Date = new Date()): string {
@@ -334,6 +351,42 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
return memories.map(m => ({name: m.name, description: m.description})); return memories.map(m => ({name: m.name, description: m.description}));
} }
/** Find the nearest node above the similarity threshold and fold the smaller/less-connected one into
* the other. Journals are exempt — they're partitioned by date, not topic, and merging across weeks
* would wreck the timeline. Returns 'merged' if `node` absorbed another (caller should re-run the doc
* agent), 'absorbed' if `node` itself got folded away (caller should stop touching it), or null. */
private async checkMerge(node: Memory, memories: Memory[] | MemoryCache, options: LLMRequest, threshold = MERGE_THRESHOLD): Promise<Memory | null> {
if (!node.embedding?.length || node.name.startsWith('Journal/')) return null;
const store = this.access(memories);
let closest: Memory | null = null, closestDist = Infinity;
for (const other of store.list) {
if (other.name === node.name || other.name.startsWith('Journal/') || !other.embedding?.length) continue;
const d = cosineDistance(node.embedding, other.embedding);
if (d < closestDist) { closestDist = d; closest = other; }
}
if (!closest || closestDist > threshold) return null;
const result = await this.mergeAgent(node, closest, options);
const merged: Memory = {name: result.name, description: this.sanitizeDescription(result.description), content: '', embedding: [], links: [], backlinks: []};
merged.content = this.touchHeader(merged, result.content);
const [e] = await this.llm.embedding(`${merged.description}\n\n${result.content}`.trim());
if (e) merged.embedding = e.embedding;
this.relink(store.list, node.name, merged.name);
this.relink(store.list, closest.name, merged.name);
this.queues.get(closest.name)?.request?.abort?.();
this.queues.delete(closest.name);
store.forget(node.name);
store.forget(closest.name);
store.list.push(merged);
store.commit();
return merged;
}
private reconcile(node: Memory, memories: Memory[] | MemoryCache, options: LLMRequest): Promise<void> { private reconcile(node: Memory, memories: Memory[] | MemoryCache, options: LLMRequest): Promise<void> {
const key = node.name; const key = node.name;
const existing = this.queues.get(key); const existing = this.queues.get(key);
@@ -347,9 +400,12 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
this.queues.set(key, entry); this.queues.set(key, entry);
const store = this.access(memories); const store = this.access(memories);
entry.task = (async () => { entry.task = (async () => {
let current = node;
do { do {
entry.dirty = false; entry.dirty = false;
await this.docAgent(node, store.list, options, entry); await this.docAgent(current, store.list, options, entry);
const merged = await this.checkMerge(current, memories, options);
if (merged) { current = merged; entry.dirty = true; }
} while (entry.dirty); } while (entry.dirty);
})().finally(() => { })().finally(() => {
this.queues.delete(key); this.queues.delete(key);
@@ -359,6 +415,7 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
} }
private async docAgent(node: Memory, memories: Memory[], options: LLMRequest, entry: {request: {abort?: () => void} | null}): Promise<void> { private async docAgent(node: Memory, memories: Memory[], options: LLMRequest, entry: {request: {abort?: () => void} | null}): Promise<void> {
if(!memories.includes(node)) return;
const currentBody = stripHeader(node.content); const currentBody = stripHeader(node.content);
let update; let update;
try { try {
@@ -367,27 +424,29 @@ ${ghosts.length ? `${ghosts.map(g => `- ${g}: (Ghost)`).join('\n')}` : ''}`,
model: options.model, model: options.model,
temperature: 0.3, temperature: 0.3,
schema: { schema: {
description: {type: 'string', description: 'One-line description of what this document covers, no formatting or emojis', required: true}, description: {type: 'string', description: 'One factual sentence describing the document\'s ENTIRE SUBJECT MATTER — for use as a search/merge fingerprint', required: true},
content: {type: 'string', description: 'Rewritten document body in markdown, without the frontmatter block', required: true}, content: {type: 'string', description: 'Rewritten document body in markdown, without the frontmatter block', required: true},
}, },
system: `You are a knowledge base editor maintaining one document in an Obsidian-style vault. system: `You are a knowledge base editor maintaining one Obsidian-style document.
If the document has a "${FACTS_HEADING}" section, integrate every bullet under it into the appropriate part of the document, then remove the "${FACTS_HEADING}" section entirely. If there is no such section, just tidy the document per the rules below. If it has a "## Pending" section, fold all new material into the appropriate part, resolve overlap, then remove the section entirely. If no section, just tidy per the rules below.
Structure: follow this generic shape loosely, adapting section names/order to what the content actually needs (e.g. journal-style docs may want a timeline instead of "Details"): Use this loose structure, adapting headings to what the content needs:
\`\`\`markdown
${GENERIC_TEMPLATE}
\`\`\`
Formatting rules: # Title
- Use Obsidian-style markdown: # headings, **bold** for emphasis, bullet & numbered lists for grouped 1D data, tables for 2D data ## Summary
- Link related concepts with [[WikiLink]] notation using full paths like [[People/Sarah]] or [[Projects/Website]] ## Details
- Create links for specific entities (person, place, project, program) and abstract concepts, but skip generics (car, red, dog) ## Related
- Keep the document concise, factual, and human-readable
- Resolve contradictions: newer facts always win — delete the outdated statement entirely, never keep both
- Do not add frontmatter blocks, filler, preamble, or AI commentary
Other nodes in the vault (link to these instead of duplicating their content): Rules:
- Contradictions: newer facts always win — delete outdated statements entirely
- Journals (Journal/...): keep entries as a chronological timeline; clean up grammar within entries but never delete history
- Use Obsidian markdown: # headings, **bold**, bullet/numbered lists, tables for 2D data
- Link specific entities and concepts with [[WikiLink]] (e.g., [[Projects/KiwixServer]]); skip generics
- Keep concise, factual, human-readable
- NO frontmatter, filler, preamble, or AI commentary
Available nodes to link to (don't duplicate their content):
${this.listNodes(memories).filter(n => n.name !== node.name).map(n => n.name).join(', ') || 'none'} ${this.listNodes(memories).filter(n => n.name !== node.name).map(n => n.name).join(', ') || 'none'}
Current document: Current document:
@@ -406,12 +465,44 @@ ${currentBody}
} }
if (!update?.content) return; if (!update?.content) return;
node.description = node.name !== 'People/User' ? update.description : 'All information about the current user'; node.description = node.name !== 'People/User' ? this.sanitizeDescription(update.description) : 'All information about the current user';
node.content = this.touchHeader(node, update.content); node.content = this.touchHeader(node, update.content);
const [e] = await this.llm.embedding(node.content); const [e] = await this.llm.embedding(`${node.description}\n\n${update.content}`.trim());
if (e) node.embedding = e.embedding; if (e) node.embedding = e.embedding;
} }
private async mergeAgent(a: Memory, b: Memory, options: LLMRequest): Promise<{name: string, description: string, content: string}> {
return this.llm.ask('', {
model: options.model,
temperature: 0.3,
schema: {
name: {type: 'string', description: 'New path for the merged doc, collection/subject format (e.g. Projects/Oxide) — only reuse an old title if it\'s genuinely the best fit', required: true},
description: {type: 'string', description: 'One factual sentence describing the merged document\'s subject matter', required: true},
content: {type: 'string', description: 'Fully reconciled body in markdown, without frontmatter', required: true},
},
system: `You are a knowledge base editor merging two overlapping Obsidian documents into one. Newer facts win on contradiction.
Structure loosely:
# Title
## Summary
## Details
## Related
Combine both documents, resolve duplication and contradictions.
Document A ("${a.name}"):
\`\`\`markdown
${stripHeader(a.content)}
\`\`\`
Document B ("${b.name}"):
\`\`\`markdown
${stripHeader(b.content)}
\`\`\``,
});
}
private parseFrontmatter(content: string): {fm: Map<string, string>, body: string} { private parseFrontmatter(content: string): {fm: Map<string, string>, body: string} {
const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/); const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
if (!match) return {fm: new Map(), body: content}; if (!match) return {fm: new Map(), body: content};
@@ -419,7 +510,11 @@ ${currentBody}
for (const line of match[1].split('\n')) { for (const line of match[1].split('\n')) {
const i = line.indexOf(':'); const i = line.indexOf(':');
if (i === -1) continue; if (i === -1) continue;
fm.set(line.slice(0, i).trim(), line.slice(i + 1).trim()); const key = line.slice(0, i).trim();
const raw = line.slice(i + 1).trim();
let value = raw;
try { value = JSON.parse(raw); } catch { /* legacy unquoted value, keep raw */ }
fm.set(key, value);
} }
return {fm, body: match[2]}; return {fm, body: match[2]};
} }
@@ -433,7 +528,7 @@ ${currentBody}
} }
private writeFrontmatter(fm: Map<string, string>, body: string): string { private writeFrontmatter(fm: Map<string, string>, body: string): string {
const lines = [...fm.entries()].map(([k, v]) => `${k}: ${v}`); const lines = [...fm.entries()].map(([k, v]) => `${k}: ${JSON.stringify(String(v).replace(/\s+/g, ' ').trim())}`);
return `---\n${lines.join('\n')}\n---\n\n${body.trimStart()}`; return `---\n${lines.join('\n')}\n---\n\n${body.trimStart()}`;
} }
@@ -498,20 +593,34 @@ ${currentBody}
history.push(pending); history.push(pending);
const store = this.access(memories); const store = this.access(memories);
const buckets = await this.factAgent(conversation, store, options, this.getWeekMonday()); const {buckets, journal} = await this.factAgent(conversation, store, options);
const touched: Memory[] = []; const touched: Memory[] = [];
if (journal) {
const journalName = `Journal/${this.getWeekMonday()}`;
let jnode = store.find(journalName);
if (!jnode) {
jnode = {name: journalName, description: '', content: '', embedding: [], links: [], backlinks: []};
store.list.push(jnode);
}
this.stage(jnode, `### ${new Date().toISOString().slice(0, 10)}\n${journal}`);
touched.push(jnode);
}
for (const {subject, facts} of buckets) { for (const {subject, facts} of buckets) {
let node = store.find(subject); let node = store.find(subject);
if (!node) { if (!node) {
node = {name: subject, description: '', content: '', embedding: [], links: [], backlinks: []}; node = {name: subject, description: '', content: '', embedding: [], links: [], backlinks: []};
store.list.push(node); store.list.push(node);
} }
this.appendFacts(node, facts); this.stage(node, facts.map(f => `- ${f}`).join('\n'));
const [e] = await this.llm.embedding(node.content); touched.push(node);
}
for (const node of touched) {
const [e] = await this.llm.embedding(`${node.description}\n\n${stripHeader(node.content)}`.trim());
if (e) node.embedding = e.embedding; if (e) node.embedding = e.embedding;
this.touch(node.name); this.touch(node.name);
touched.push(node);
} }
if (touched.length) { if (touched.length) {
@@ -526,9 +635,9 @@ ${currentBody}
return touched; return touched;
} }
async reconcileVault(memories: Memory[] | MemoryCache, options: LLMRequest, scope: 'touched' | 'all' = 'touched'): Promise<void> { async reconcileAll(memories: Memory[] | MemoryCache, options: LLMRequest, scope: 'touched' | 'all' = 'touched'): Promise<void> {
const store = this.access(memories); const store = this.access(memories);
const targets = scope === 'all' ? store.list : store.list.filter(m => m.content.includes(FACTS_HEADING)); const targets = scope === 'all' ? store.list : store.list.filter(m => m.content.includes(PENDING_HEADING));
await Promise.all(targets.map(node => this.reconcile(node, memories, options))); await Promise.all(targets.map(node => this.reconcile(node, memories, options)));
store.commit(); store.commit();
} }