@jossuealcala/madre 0.3.3 → 0.4.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 +497 -3
- package/CONTRIBUTING.md +3 -1
- package/README.md +68 -186
- package/SECURITY.md +2 -1
- package/bin/madre.mjs +56 -13
- package/docs/INTERNALS.md +16 -0
- package/docs/REFERENCE.md +249 -0
- package/docs/SDK.md +121 -0
- package/docs/room.png +0 -0
- package/docs/sdk/hello-module.mjs +51 -0
- package/package.json +9 -1
- package/public/app.js +3979 -867
- package/public/es.js +2258 -0
- package/public/i18n.js +66 -0
- package/public/index.html +96 -15
- package/public/inquiry.js +220 -0
- package/public/resay.js +77 -0
- package/public/styles.css +622 -65
- package/public/troubleshooting.js +255 -46
- package/src/adapters/claude.mjs +2 -1
- package/src/adapters/codex.mjs +2 -1
- package/src/adapters/gemini.mjs +6 -5
- package/src/adapters/opencode.mjs +2 -1
- package/src/adapters/process.mjs +79 -20
- package/src/asking.mjs +128 -0
- package/src/auth-probe.mjs +58 -1
- package/src/chats.mjs +193 -0
- package/src/checkpoint.mjs +1 -1
- package/src/cold.mjs +56 -0
- package/src/commands.mjs +6 -0
- package/src/conversation-context.mjs +35 -3
- package/src/credentials.mjs +145 -0
- package/src/dataset.mjs +56 -4
- package/src/distiller.mjs +12 -5
- package/src/event-store.mjs +14 -8
- package/src/exam.mjs +240 -0
- package/src/extensions.mjs +3 -2
- package/src/eyecat-watch.mjs +100 -0
- package/src/eyecat.mjs +169 -0
- package/src/i18n.mjs +47 -0
- package/src/image-studio.mjs +2 -0
- package/src/launch.mjs +61 -0
- package/src/maturity.mjs +94 -0
- package/src/mcp/image-server.mjs +36 -3
- package/src/mcp/memory-server.mjs +1 -1
- package/src/memory.mjs +325 -17
- package/src/modules/ahp.mjs +9 -7
- package/src/modules/ash.mjs +36 -0
- package/src/modules/git-pulse.mjs +5 -3
- package/src/modules/helpers.mjs +31 -0
- package/src/modules/image-studio.mjs +10 -4
- package/src/modules/index.mjs +141 -9
- package/src/modules/ollama.mjs +66 -10
- package/src/modules/playwright.mjs +44 -23
- package/src/modules/ripley.mjs +5 -3
- package/src/modules/sdk.mjs +93 -2
- package/src/modules/updates.mjs +81 -0
- package/src/ollama.mjs +5 -2
- package/src/outbound.mjs +297 -0
- package/src/privacy.mjs +54 -7
- package/src/room/context.mjs +4 -4
- package/src/room/economy.mjs +161 -0
- package/src/room/prompt.mjs +118 -46
- package/src/room.mjs +443 -44
- package/src/runtime-detection.mjs +27 -8
- package/src/sentinel-errors.mjs +19 -1
- package/src/server.mjs +709 -71
- package/src/setup.mjs +1 -1
- package/src/updates.mjs +4 -2
- package/src/usage-sentinel.mjs +13 -8
- package/src/verdict.mjs +74 -0
- package/src/ashcode.mjs +0 -64
- package/src/modules/ashcode.mjs +0 -28
package/src/cold.mjs
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Cold zones: the part of the archive nothing has ever reached for.
|
|
2
|
+
//
|
|
3
|
+
// A memory is cold when three things are true at once, and the three together are what make the
|
|
4
|
+
// claim strong enough to act on:
|
|
5
|
+
//
|
|
6
|
+
// · no turn has ever carried it
|
|
7
|
+
// · it shares a subject with no other memory, so nothing can reach it sideways either
|
|
8
|
+
// · the room has reached into the archive often enough since it was written that it has plainly
|
|
9
|
+
// had its chances
|
|
10
|
+
//
|
|
11
|
+
// That third one is the whole point. Never-recalled is not cold; never-recalled is what every
|
|
12
|
+
// memory is on the day it is written. What makes a memory cold is opportunity that went by: the
|
|
13
|
+
// archive was opened forty times and it was never the answer. Chances are counted in turns that
|
|
14
|
+
// actually reached into the archive, because those are the only chances that existed.
|
|
15
|
+
//
|
|
16
|
+
// Pure functions. The room hands in what it already has.
|
|
17
|
+
|
|
18
|
+
export const COLD_CHANCES = 12; // turns that went into the archive without ever taking it
|
|
19
|
+
|
|
20
|
+
// How many of `times` (ascending) are at or after `from`.
|
|
21
|
+
function after(times, from) {
|
|
22
|
+
let low = 0;
|
|
23
|
+
let high = times.length;
|
|
24
|
+
while (low < high) {
|
|
25
|
+
const middle = (low + high) >> 1;
|
|
26
|
+
if (times[middle] < from) low = middle + 1; else high = middle;
|
|
27
|
+
}
|
|
28
|
+
return times.length - low;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Which memories are adrift, and how many chances each one has had. `since` is the day this room
|
|
32
|
+
// started keeping the trail: a memory older than that is only counted from there, because what
|
|
33
|
+
// happened before it was never written down and must not be held against the note.
|
|
34
|
+
export function coldNotes({ notes = [], links = [], batches = [], since = null, chances = COLD_CHANCES } = {}) {
|
|
35
|
+
const linked = new Set(links.flatMap((link) => [link.a, link.b]));
|
|
36
|
+
const times = batches.map((at) => Date.parse(at)).filter((at) => Number.isFinite(at)).sort((a, b) => a - b);
|
|
37
|
+
const floor = since ? Date.parse(since) : 0;
|
|
38
|
+
const cold = new Map();
|
|
39
|
+
for (const note of notes) {
|
|
40
|
+
if (!note || note.kind === 'aberration' || note.refutedBy) continue; // a refutation is not a cold memory
|
|
41
|
+
if (Number(note.recalled ?? 0) > 0) continue;
|
|
42
|
+
if (linked.has(note.id)) continue;
|
|
43
|
+
const written = Date.parse(note.created);
|
|
44
|
+
const from = Math.max(Number.isFinite(written) ? written : 0, Number.isFinite(floor) ? floor : 0);
|
|
45
|
+
const had = after(times, from);
|
|
46
|
+
if (had >= chances) cold.set(note.id, { chances: had });
|
|
47
|
+
}
|
|
48
|
+
return cold;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// What the room should say about it. Never a number on its own: a count of cold memories means
|
|
52
|
+
// nothing without what it is a count of.
|
|
53
|
+
export function coldReading(cold, notes = []) {
|
|
54
|
+
const standing = notes.filter((note) => note && note.kind !== 'aberration' && !note.refutedBy).length;
|
|
55
|
+
return { count: cold.size, standing, share: standing > 0 ? Number((cold.size / standing).toFixed(3)) : 0 };
|
|
56
|
+
}
|
package/src/commands.mjs
CHANGED
|
@@ -52,6 +52,12 @@ export const COMMANDS = [
|
|
|
52
52
|
// The human commits what the room produced. Everything in the tree, one message, local: reversible with git.
|
|
53
53
|
const message = args.slice(1).join(' ').replace(/^["'“]+|["'”]+$/g, '').trim();
|
|
54
54
|
if (!message) return { ok: false, title: 'Git Pulse · commit', text: 'Give the commit a message: /git commit "what and why".' };
|
|
55
|
+
// Without an identity git refuses the commit with a wall of advice; say the one thing to do.
|
|
56
|
+
const email = await run('git', ['config', '--get', 'user.email'], projectRoot);
|
|
57
|
+
const who = await run('git', ['config', '--get', 'user.name'], projectRoot);
|
|
58
|
+
if (!email.text.trim() || !who.text.trim()) {
|
|
59
|
+
return { ok: false, title: 'Git Pulse · commit', text: 'This computer has no git identity, so the commit would have no author. Set it once in your terminal:\n\n git config --global user.name "Your Name"\n git config --global user.email you@example.com' };
|
|
60
|
+
}
|
|
55
61
|
const staged = await run('git', ['add', '-A', '--', '.'], projectRoot);
|
|
56
62
|
if (!staged.ok) return { ok: false, title: 'Git Pulse · commit', text: staged.text };
|
|
57
63
|
const committed = await run('git', ['-c', 'color.ui=never', 'commit', '-m', message], projectRoot);
|
|
@@ -19,14 +19,44 @@ export function messageEntry(event) {
|
|
|
19
19
|
|
|
20
20
|
// `omitSynthetic` drops MADRE's own canned replies (identity, refusals, round-table plans):
|
|
21
21
|
// @madre must never read them back, or a small model starts echoing them.
|
|
22
|
-
|
|
22
|
+
// How much of the budget a window is cut back to when it finally has to let go of its oldest
|
|
23
|
+
// messages. Dropping one message per turn would move the start of the transcript on every turn;
|
|
24
|
+
// dropping a chunk at once and then holding still is what lets a CLI read most of it back from
|
|
25
|
+
// its own cache. Lower means longer stretches of stability and a leaner average window.
|
|
26
|
+
export const CONTEXT_KEEP = 0.62;
|
|
27
|
+
|
|
28
|
+
export function buildConversationContext(events, { excludeMessageId, maxChars = 16000, omitSynthetic = false, anchor = null } = {}) {
|
|
23
29
|
const messages = events
|
|
24
30
|
.map((event) => (omitSynthetic && event?.payload?.synthetic ? null : messageEntry(event)))
|
|
25
31
|
.filter((message) => message && message.messageId !== excludeMessageId);
|
|
32
|
+
const budget = Math.max(0, Number(maxChars) || 0);
|
|
33
|
+
|
|
34
|
+
// The window is anchored, not sliding. A sliding window starts one message later on every
|
|
35
|
+
// turn, so the transcript an agent reads begins with different words every time and none of
|
|
36
|
+
// it can be matched against what it read last turn. Held still, the whole of it but the tail
|
|
37
|
+
// is the same bytes as before, which is the difference between paying for it once and paying
|
|
38
|
+
// for it every turn. It only ever moves when what has been said since no longer fits.
|
|
39
|
+
const weigh = (from) => {
|
|
40
|
+
let used = 0;
|
|
41
|
+
for (let i = from; i < messages.length; i += 1) used += messages[i].sender.length + messages[i].role.length + messages[i].text.length + 4;
|
|
42
|
+
return used;
|
|
43
|
+
};
|
|
44
|
+
let start = 0;
|
|
45
|
+
if (Number.isInteger(anchor)) {
|
|
46
|
+
const held = messages.findIndex((message) => message.sequence >= anchor);
|
|
47
|
+
if (held >= 0 && weigh(held) <= budget) start = held;
|
|
48
|
+
}
|
|
49
|
+
if (!start || weigh(start) > budget) {
|
|
50
|
+
// Let go of a chunk and then hold: back off until the window sits well under its budget, so
|
|
51
|
+
// there is room for many turns of new words before it has to move again.
|
|
52
|
+
start = messages.length;
|
|
53
|
+
while (start > 0 && weigh(start - 1) <= budget * CONTEXT_KEEP) start -= 1;
|
|
54
|
+
}
|
|
55
|
+
|
|
26
56
|
const selected = [];
|
|
27
|
-
let remaining =
|
|
57
|
+
let remaining = budget;
|
|
28
58
|
|
|
29
|
-
for (let index = messages.length - 1; index >=
|
|
59
|
+
for (let index = messages.length - 1; index >= start && remaining > 0; index -= 1) {
|
|
30
60
|
const message = messages[index];
|
|
31
61
|
const label = `${message.sender} (${message.role})`;
|
|
32
62
|
const allowance = Math.max(0, remaining - label.length - 2);
|
|
@@ -42,6 +72,8 @@ export function buildConversationContext(events, { excludeMessageId, maxChars =
|
|
|
42
72
|
|
|
43
73
|
return {
|
|
44
74
|
messages: selected,
|
|
75
|
+
// Where this window begins, for the next turn to hold on to.
|
|
76
|
+
anchor: selected[0]?.sequence ?? null,
|
|
45
77
|
omittedMessages: messages.length - selected.length,
|
|
46
78
|
firstSequence: selected[0]?.sequence ?? null,
|
|
47
79
|
throughSequence: selected.at(-1)?.sequence ?? null,
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Handing a provider key to a CLI that signs in from its own prompt.
|
|
2
|
+
//
|
|
3
|
+
// MADRE keeps its promise: it never stores a credential of its own. The key the human pastes is
|
|
4
|
+
// written where that CLI looks for it, with the file locked to the owner, and MADRE keeps no
|
|
5
|
+
// copy: not in ~/.pulse/config.json, not in the room's ledger, not in a log line. What the room
|
|
6
|
+
// records is that a key was set, never the key.
|
|
7
|
+
//
|
|
8
|
+
// Every write is verified on the spot by asking the CLI (or MADRE's own probe) whether it is
|
|
9
|
+
// signed in now. If it is not, the previous files are put back, so a format MADRE guessed wrong
|
|
10
|
+
// leaves nothing behind.
|
|
11
|
+
|
|
12
|
+
import { execFile } from 'node:child_process';
|
|
13
|
+
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { promisify } from 'node:util';
|
|
17
|
+
|
|
18
|
+
const execFileAsync = promisify(execFile);
|
|
19
|
+
const OWNER_ONLY = 0o600;
|
|
20
|
+
|
|
21
|
+
// A key is one opaque token: no spaces, no newlines, and long enough to be one.
|
|
22
|
+
export function normalizeKey(value) {
|
|
23
|
+
const key = String(value ?? '').trim();
|
|
24
|
+
if (!key) return { ok: false, error: 'Paste the key first.' };
|
|
25
|
+
if (/\s/.test(key)) return { ok: false, error: 'That does not look like a key: it has spaces or line breaks.' };
|
|
26
|
+
if (key.length < 12 || key.length > 400) return { ok: false, error: 'That does not look like a key: check you copied all of it and nothing else.' };
|
|
27
|
+
return { ok: true, key };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// OpenCode brings no model of its own. These are the providers MADRE can wire with a key;
|
|
31
|
+
// any other still works through `opencode auth login` in a terminal.
|
|
32
|
+
export const OPENCODE_PROVIDERS = [
|
|
33
|
+
{ id: 'anthropic', label: 'Anthropic', keyUrl: 'https://console.anthropic.com/settings/keys' },
|
|
34
|
+
{ id: 'openai', label: 'OpenAI', keyUrl: 'https://platform.openai.com/api-keys' },
|
|
35
|
+
{ id: 'openrouter', label: 'OpenRouter', keyUrl: 'https://openrouter.ai/keys' },
|
|
36
|
+
{ id: 'google', label: 'Google AI Studio', keyUrl: 'https://aistudio.google.com/app/apikey' },
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
// What the room offers for each agent that cannot be signed in with a click.
|
|
40
|
+
export function keyPlanFor(id) {
|
|
41
|
+
if (id === 'gemini') {
|
|
42
|
+
return {
|
|
43
|
+
agent: 'gemini',
|
|
44
|
+
label: 'Gemini API key',
|
|
45
|
+
keyUrl: 'https://aistudio.google.com/app/apikey',
|
|
46
|
+
writesTo: '~/.gemini/.env',
|
|
47
|
+
note: 'The key is written where the Gemini CLI looks for it, readable only by you. MADRE keeps no copy.',
|
|
48
|
+
providers: null,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
if (id === 'opencode') {
|
|
52
|
+
return {
|
|
53
|
+
agent: 'opencode',
|
|
54
|
+
label: 'Provider key',
|
|
55
|
+
keyUrl: null,
|
|
56
|
+
writesTo: '~/.local/share/opencode/auth.json',
|
|
57
|
+
note: 'OpenCode brings no model of its own: pick the provider whose key you are pasting. The key is written where OpenCode looks for it, readable only by you. MADRE keeps no copy.',
|
|
58
|
+
providers: OPENCODE_PROVIDERS,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function readIfThere(path) {
|
|
65
|
+
try { return await readFile(path, 'utf8'); } catch { return null; }
|
|
66
|
+
}
|
|
67
|
+
async function restore(path, previous) {
|
|
68
|
+
if (previous === null) await rm(path, { force: true });
|
|
69
|
+
else await writeFile(path, previous, { mode: OWNER_ONLY });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---- Gemini: a line in ~/.gemini/.env, plus the auth type its settings must select.
|
|
73
|
+
async function applyGeminiKey(key, { home, probe }) {
|
|
74
|
+
const dir = join(home, '.gemini');
|
|
75
|
+
const envFile = join(dir, '.env');
|
|
76
|
+
const settingsFile = join(dir, 'settings.json');
|
|
77
|
+
await mkdir(dir, { recursive: true });
|
|
78
|
+
const beforeEnv = await readIfThere(envFile);
|
|
79
|
+
const beforeSettings = await readIfThere(settingsFile);
|
|
80
|
+
try {
|
|
81
|
+
const kept = (beforeEnv ?? '').split('\n').filter((line) => line.trim() && !/^\s*(GEMINI_API_KEY|GOOGLE_API_KEY)\s*=/.test(line));
|
|
82
|
+
await writeFile(envFile, `${[...kept, `GEMINI_API_KEY=${key}`].join('\n')}\n`, { mode: OWNER_ONLY });
|
|
83
|
+
await chmod(envFile, OWNER_ONLY).catch(() => {});
|
|
84
|
+
let settings = {};
|
|
85
|
+
try { settings = JSON.parse(beforeSettings ?? '{}') ?? {}; } catch { settings = {}; }
|
|
86
|
+
settings.security = { ...(settings.security ?? {}), auth: { ...(settings.security?.auth ?? {}), selectedType: 'gemini-api-key' } };
|
|
87
|
+
await writeFile(settingsFile, `${JSON.stringify(settings, null, 2)}\n`, { mode: OWNER_ONLY });
|
|
88
|
+
const state = await probe();
|
|
89
|
+
if (state?.state !== 'signed-in') {
|
|
90
|
+
await restore(envFile, beforeEnv);
|
|
91
|
+
await restore(settingsFile, beforeSettings);
|
|
92
|
+
return { ok: false, error: `The key was written but Gemini still reads as ${state?.state ?? 'unknown'}${state?.detail ? ` (${state.detail})` : ''}. Nothing was changed.` };
|
|
93
|
+
}
|
|
94
|
+
return { ok: true, detail: state.detail ?? 'via API key' };
|
|
95
|
+
} catch (error) {
|
|
96
|
+
await restore(envFile, beforeEnv);
|
|
97
|
+
await restore(settingsFile, beforeSettings);
|
|
98
|
+
return { ok: false, error: `The key could not be written: ${error.message}` };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ---- OpenCode: an entry in its auth.json, confirmed by asking `opencode auth list`.
|
|
103
|
+
async function applyOpenCodeKey(key, { home, provider, executable, run }) {
|
|
104
|
+
const known = OPENCODE_PROVIDERS.some((item) => item.id === provider);
|
|
105
|
+
if (!known) return { ok: false, error: 'Pick the provider this key belongs to.' };
|
|
106
|
+
const file = join(home, '.local', 'share', 'opencode', 'auth.json');
|
|
107
|
+
await mkdir(join(home, '.local', 'share', 'opencode'), { recursive: true });
|
|
108
|
+
const before = await readIfThere(file);
|
|
109
|
+
try {
|
|
110
|
+
let auth = {};
|
|
111
|
+
try { auth = JSON.parse(before ?? '{}') ?? {}; } catch { auth = {}; }
|
|
112
|
+
auth[provider] = { type: 'api', key };
|
|
113
|
+
await writeFile(file, `${JSON.stringify(auth, null, 2)}\n`, { mode: OWNER_ONLY });
|
|
114
|
+
await chmod(file, OWNER_ONLY).catch(() => {});
|
|
115
|
+
// OpenCode itself is the judge: if its own listing does not show the provider, the shape
|
|
116
|
+
// MADRE wrote is not the shape it reads, and nothing should be left behind.
|
|
117
|
+
const listed = await run(executable, ['auth', 'list']);
|
|
118
|
+
if (!new RegExp(provider, 'i').test(listed)) {
|
|
119
|
+
await restore(file, before);
|
|
120
|
+
return { ok: false, error: `OpenCode does not list ${provider} after the key was written, so MADRE put the file back. Run \`opencode auth login\` in a terminal for this one.` };
|
|
121
|
+
}
|
|
122
|
+
return { ok: true, detail: `${provider} (api)` };
|
|
123
|
+
} catch (error) {
|
|
124
|
+
await restore(file, before);
|
|
125
|
+
return { ok: false, error: `The key could not be written: ${error.message}` };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const runOpenCode = async (executable, args) => {
|
|
130
|
+
try {
|
|
131
|
+
const { stdout, stderr } = await execFileAsync(executable, args, { timeout: 15000, env: { ...process.env, NO_COLOR: '1' } });
|
|
132
|
+
return `${stdout}\n${stderr}`;
|
|
133
|
+
} catch (error) {
|
|
134
|
+
return `${error.stdout ?? ''}\n${error.stderr ?? error.message}`;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// Writes the key for one agent and answers whether that agent is signed in now.
|
|
139
|
+
export async function applyKey({ agent, key, provider = null, home = homedir(), probe, executable = 'opencode', run = runOpenCode }) {
|
|
140
|
+
const checked = normalizeKey(key);
|
|
141
|
+
if (!checked.ok) return checked;
|
|
142
|
+
if (agent === 'gemini') return applyGeminiKey(checked.key, { home, probe });
|
|
143
|
+
if (agent === 'opencode') return applyOpenCodeKey(checked.key, { home, provider, executable, run });
|
|
144
|
+
return { ok: false, error: `${agent} does not take a key here: it signs in with a click.` };
|
|
145
|
+
}
|
package/src/dataset.mjs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
9
9
|
import { join } from 'node:path';
|
|
10
10
|
import { redact } from './sentinel-errors.mjs';
|
|
11
|
+
import { ABERRATION } from './memory.mjs';
|
|
11
12
|
|
|
12
13
|
const MIN_ANSWER_CHARS = 40;
|
|
13
14
|
|
|
@@ -82,14 +83,22 @@ export function readiness(events, notes = [], { target = DATASET_TARGET } = {})
|
|
|
82
83
|
const turns = pairs.filter((pair) => pair.kind === 'turn').length;
|
|
83
84
|
const delegated = pairs.length - turns;
|
|
84
85
|
const good = pairs.filter((pair) => pair.rating === 'good').length;
|
|
85
|
-
|
|
86
|
-
|
|
86
|
+
// Aberrations are counted apart: they never become one of the pairs the model learns to
|
|
87
|
+
// answer with, so counting them toward readiness would say the room is further along than it is.
|
|
88
|
+
const standing = notes.filter((note) => note.kind !== ABERRATION && !note.refutedBy);
|
|
89
|
+
const aberrations = notes.filter((note) => note.kind === ABERRATION).length;
|
|
90
|
+
const total = pairs.length + standing.length;
|
|
91
|
+
return { pairs: total, turns, delegated, notes: standing.length, aberrations, good, bad, target, ready: total >= target };
|
|
87
92
|
}
|
|
88
93
|
|
|
89
94
|
// Distilled notes become recall pairs: "what does the room remember about …" → the note.
|
|
95
|
+
// Two kinds of note never come through here. An aberration is a claim the room decided is false,
|
|
96
|
+
// and teaching a model to recall it would be teaching it the hallucination. A note that has been
|
|
97
|
+
// refuted is no longer what the room believes. Both are still exported, as preference pairs
|
|
98
|
+
// below, where being wrong is the point.
|
|
90
99
|
export function pairsFromNotes(notes, { project = 'project', home, user, privacy = null } = {}) {
|
|
91
100
|
const clean = guard(privacy);
|
|
92
|
-
return notes.map((note) => ({
|
|
101
|
+
return notes.filter((note) => note.kind !== ABERRATION && !note.refutedBy).map((note) => ({
|
|
93
102
|
kind: 'note',
|
|
94
103
|
agent: 'madre',
|
|
95
104
|
mode: 1,
|
|
@@ -103,6 +112,45 @@ export function pairsFromNotes(notes, { project = 'project', home, user, privacy
|
|
|
103
112
|
}));
|
|
104
113
|
}
|
|
105
114
|
|
|
115
|
+
// What the room got wrong, in the shape that trains against it. Each aberration becomes one
|
|
116
|
+
// preference pair: the same ask, the false claim as what to avoid, the correction as what to say
|
|
117
|
+
// instead. A negative on its own teaches a model very little; a pair tells it which of two
|
|
118
|
+
// answers to prefer, which is what DPO and ORPO are built to read.
|
|
119
|
+
export function preferencesFromAberrations(notes, { project = 'project', home, user, privacy = null } = {}) {
|
|
120
|
+
const clean = guard(privacy);
|
|
121
|
+
const say = (text) => clean(redact(String(text ?? ''), { home, user }));
|
|
122
|
+
const byId = new Map(notes.map((note) => [note.id, note]));
|
|
123
|
+
const pairs = [];
|
|
124
|
+
for (const note of notes) {
|
|
125
|
+
if (note.kind !== ABERRATION) continue;
|
|
126
|
+
// Without something true to put in its place there is nothing to prefer, so it is left out.
|
|
127
|
+
const truth = note.correction || (note.contradicts && byId.get(note.contradicts)?.text) || null;
|
|
128
|
+
if (!truth) continue;
|
|
129
|
+
const claim = say(note.text);
|
|
130
|
+
const better = say(truth);
|
|
131
|
+
if (!claim || !better) continue;
|
|
132
|
+
// A correction that restates the claim teaches nothing, and a model asked to prefer one of
|
|
133
|
+
// two near-identical answers learns the wrong lesson from the noise between them. A weak
|
|
134
|
+
// archivist writes these, so they are caught here rather than shipped.
|
|
135
|
+
const words = (text) => new Set(String(text).toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^\p{L}\p{N}]+/gu, ' ').trim().split(' ').filter((word) => word.length > 2));
|
|
136
|
+
const [left, right] = [words(claim), words(better)];
|
|
137
|
+
if (!left.size || !right.size) continue;
|
|
138
|
+
let shared = 0;
|
|
139
|
+
for (const word of right) if (left.has(word)) shared += 1;
|
|
140
|
+
if (shared / Math.min(left.size, right.size) > 0.8) continue;
|
|
141
|
+
pairs.push({
|
|
142
|
+
kind: 'aberration',
|
|
143
|
+
sequence: note.throughSequence,
|
|
144
|
+
at: note.created,
|
|
145
|
+
detector: note.detector ?? null,
|
|
146
|
+
prompt: `Is this true of the project "${project}"? ${claim}`,
|
|
147
|
+
rejected: claim,
|
|
148
|
+
chosen: better,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
return pairs;
|
|
152
|
+
}
|
|
153
|
+
|
|
106
154
|
// Deterministic split: the sequence decides, so re-exports keep lines on the same side.
|
|
107
155
|
export function split(pairs, { validEvery = 10 } = {}) {
|
|
108
156
|
const train = [];
|
|
@@ -114,14 +162,18 @@ export function split(pairs, { validEvery = 10 } = {}) {
|
|
|
114
162
|
|
|
115
163
|
export async function exportDataset({ events, notes = [], dir, project = 'project', home, user, privacy = null }) {
|
|
116
164
|
const pairs = [...pairsFromEvents(events, { project, home, user, privacy }), ...pairsFromNotes(notes, { project, home, user, privacy })].sort((a, b) => a.sequence - b.sequence);
|
|
165
|
+
const preferences = preferencesFromAberrations(notes, { project, home, user, privacy });
|
|
117
166
|
const { train, valid } = split(pairs);
|
|
118
167
|
await mkdir(dir, { recursive: true });
|
|
119
168
|
const line = (pair) => JSON.stringify({ messages: pair.messages });
|
|
120
169
|
await writeFile(join(dir, 'train.jsonl'), train.map(line).join('\n') + (train.length ? '\n' : ''));
|
|
121
170
|
await writeFile(join(dir, 'valid.jsonl'), valid.map(line).join('\n') + (valid.length ? '\n' : ''));
|
|
171
|
+
// Kept in a file of its own: it is a different shape and a different kind of training, and
|
|
172
|
+
// nothing that reads the chat files should ever pick it up by accident.
|
|
173
|
+
await writeFile(join(dir, 'preferences.jsonl'), preferences.map((pair) => JSON.stringify({ prompt: pair.prompt, chosen: pair.chosen, rejected: pair.rejected })).join('\n') + (preferences.length ? '\n' : ''));
|
|
122
174
|
const byAgent = {};
|
|
123
175
|
for (const pair of pairs) byAgent[pair.agent] = (byAgent[pair.agent] ?? 0) + 1;
|
|
124
|
-
const manifest = { project, exportedAt: new Date().toISOString(), pairs: pairs.length, turns: pairs.filter((p) => p.kind === 'turn').length, delegated: pairs.filter((p) => p.kind === 'delegated').length, good: pairs.filter((p) => p.rating === 'good').length, notes: pairs.filter((p) => p.kind === 'note').length, train: train.length, valid: valid.length, byAgent, files: ['train.jsonl', 'valid.jsonl'], format: 'chat · {"messages":[{role,content}]} · mlx-lm / llama-factory / axolotl' };
|
|
176
|
+
const manifest = { project, exportedAt: new Date().toISOString(), pairs: pairs.length, turns: pairs.filter((p) => p.kind === 'turn').length, delegated: pairs.filter((p) => p.kind === 'delegated').length, good: pairs.filter((p) => p.rating === 'good').length, notes: pairs.filter((p) => p.kind === 'note').length, aberrations: preferences.length, train: train.length, valid: valid.length, byAgent, files: ['train.jsonl', 'valid.jsonl', 'preferences.jsonl'], format: 'chat · {"messages":[{role,content}]} · mlx-lm / llama-factory / axolotl', preferenceFormat: 'preference · {"prompt","chosen","rejected"} · DPO / ORPO' };
|
|
125
177
|
await writeFile(join(dir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
126
178
|
return { dir, ...manifest };
|
|
127
179
|
}
|
package/src/distiller.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// keeping for every later turn. Pure functions here; the room schedules and
|
|
4
4
|
// invokes. Nothing in this file talks to a model.
|
|
5
5
|
|
|
6
|
-
import { MEMORY_KINDS } from './memory.mjs';
|
|
6
|
+
import { ABERRATION, MEMORY_KINDS } from './memory.mjs';
|
|
7
7
|
|
|
8
8
|
// Cheapest first, by the models these CLIs run by default.
|
|
9
9
|
// Ollama, when the room has it, is the cheapest of all: local and free.
|
|
@@ -42,11 +42,12 @@ export function distillPrompt({ entries, projectName = 'the project', existing =
|
|
|
42
42
|
`- fact: a verified statement about the project or its environment that is not obvious from the code`,
|
|
43
43
|
`- preference: how the human wants things done or said`,
|
|
44
44
|
`- question: something left open that a later turn should not forget`,
|
|
45
|
+
`- aberration: a claim the exchanges themselves showed to be false. Only when it was refuted out loud: someone stated something about this project and someone else corrected it, or the exchanges proved it wrong. Put the false claim in "text" and what turned out to be true in "correction". Never guess, never file a disagreement of opinion, and never file something merely unverified.`,
|
|
45
46
|
'Skip greetings, restatements, transient status, anything a reader of the code would see anyway, and anything the exchanges do not actually establish.',
|
|
46
47
|
json
|
|
47
|
-
? `Output one JSON object and nothing else: {"memories":[...]} with at most ${MAX_MEMORIES_PER_RUN} items, each {"kind":"
|
|
48
|
+
? `Output one JSON object and nothing else: {"memories":[...]} with at most ${MAX_MEMORIES_PER_RUN} items, each {"kind":"${MEMORY_KINDS.join('|')}","text":"one self-contained sentence in the language the room uses, at most ${MAX_MEMORY_CHARS} characters, naming files, agents and numbers exactly","correction":"only on an aberration: what is true instead","sources":[sequence numbers it comes from]}. If nothing durable was said: {"memories":[]}`
|
|
48
49
|
: `Output only JSON lines, one object per memory, at most ${MAX_MEMORIES_PER_RUN}, nothing else:`,
|
|
49
|
-
json ? null : `{"kind":"
|
|
50
|
+
json ? null : `{"kind":"${MEMORY_KINDS.join('|')}","text":"one self-contained sentence in the language the room uses, at most ${MAX_MEMORY_CHARS} characters, naming files, agents and numbers exactly","correction":"only on an aberration: what is true instead","sources":[sequence numbers it comes from]}`,
|
|
50
51
|
json ? null : 'If nothing durable was said, output exactly: NONE',
|
|
51
52
|
known,
|
|
52
53
|
'<exchanges>',
|
|
@@ -76,13 +77,19 @@ export function parseDistillation(text, { fromSequence, throughSequence } = {})
|
|
|
76
77
|
if (!parsed || typeof parsed !== 'object') continue;
|
|
77
78
|
const memoryText = String(parsed.text ?? '').replace(/\s+/g, ' ').trim();
|
|
78
79
|
if (!memoryText) continue;
|
|
79
|
-
|
|
80
|
+
// An unknown kind used to be filed as a fact. That was harmless while every kind was
|
|
81
|
+
// knowledge; now the list has one that is not, and a typo would turn a hallucination into
|
|
82
|
+
// something the room believes. Anything unrecognised is dropped instead.
|
|
83
|
+
if (!MEMORY_KINDS.includes(parsed.kind)) continue;
|
|
84
|
+
const kind = parsed.kind;
|
|
80
85
|
const inRange = (n) => Number.isInteger(n) && (fromSequence == null || n >= fromSequence) && (throughSequence == null || n <= throughSequence);
|
|
81
86
|
const sources = (Array.isArray(parsed.sources) ? parsed.sources : []).map(Number).filter(inRange);
|
|
82
87
|
const key = memoryText.toLowerCase();
|
|
83
88
|
if (seen.has(key)) continue;
|
|
84
89
|
seen.add(key);
|
|
85
|
-
|
|
90
|
+
const clip = (value) => (value.length > MAX_MEMORY_CHARS ? `${value.slice(0, MAX_MEMORY_CHARS - 1)}…` : value);
|
|
91
|
+
const correction = kind === ABERRATION ? clip(String(parsed.correction ?? '').replace(/\s+/g, ' ').trim()) : '';
|
|
92
|
+
memories.push({ kind, text: clip(memoryText), sources, ...(correction ? { correction } : {}) });
|
|
86
93
|
if (memories.length >= MAX_MEMORIES_PER_RUN) break;
|
|
87
94
|
}
|
|
88
95
|
return memories;
|
package/src/event-store.mjs
CHANGED
|
@@ -8,16 +8,22 @@ export class EventStore {
|
|
|
8
8
|
#nextSequence = 1;
|
|
9
9
|
#writeQueue = Promise.resolve();
|
|
10
10
|
#lockDirectory;
|
|
11
|
+
#floor = 0;
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
// `floor` is the highest sequence the rest of the project has already used. A project keeps one
|
|
14
|
+
// numbering across all of its conversations, so #1411 means one exchange in this project and
|
|
15
|
+
// not one in each thread — the memory index, every citation and NOSTROMO all lean on that.
|
|
16
|
+
// Gaps in a single ledger are fine: sequences are an order, not a count.
|
|
17
|
+
constructor(file, { floor = 0 } = {}) {
|
|
13
18
|
this.#file = file;
|
|
19
|
+
this.#floor = Number.isFinite(floor) ? floor : 0;
|
|
14
20
|
this.#lockDirectory = `${file}.lock`;
|
|
15
21
|
}
|
|
16
22
|
|
|
17
23
|
async initialize() {
|
|
18
24
|
await mkdir(dirname(this.#file), { recursive: true });
|
|
19
25
|
const existing = await this.readAll();
|
|
20
|
-
this.#nextSequence = (existing.at(-1)?.sequence ?? 0) + 1;
|
|
26
|
+
this.#nextSequence = Math.max(existing.at(-1)?.sequence ?? 0, this.#floor) + 1;
|
|
21
27
|
return this;
|
|
22
28
|
}
|
|
23
29
|
|
|
@@ -85,14 +91,14 @@ export class EventStore {
|
|
|
85
91
|
return async () => {
|
|
86
92
|
try {
|
|
87
93
|
const owner = JSON.parse(await readFile(ownerFile, 'utf8'));
|
|
88
|
-
if (owner.token === token) await rm(this.#lockDirectory, { recursive: true, force: true });
|
|
94
|
+
if (owner.token === token) await rm(this.#lockDirectory, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 });
|
|
89
95
|
} catch (error) {
|
|
90
96
|
if (error.code !== 'ENOENT') throw error;
|
|
91
97
|
}
|
|
92
98
|
};
|
|
93
99
|
} catch (error) {
|
|
94
100
|
if (created) {
|
|
95
|
-
await rm(this.#lockDirectory, { recursive: true, force: true });
|
|
101
|
+
await rm(this.#lockDirectory, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 });
|
|
96
102
|
throw error;
|
|
97
103
|
}
|
|
98
104
|
if (error.code !== 'EEXIST') throw error;
|
|
@@ -102,7 +108,7 @@ export class EventStore {
|
|
|
102
108
|
process.kill(owner.pid, 0);
|
|
103
109
|
} catch (ownerError) {
|
|
104
110
|
if (ownerError.code === 'ESRCH') {
|
|
105
|
-
await rm(this.#lockDirectory, { recursive: true, force: true });
|
|
111
|
+
await rm(this.#lockDirectory, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 });
|
|
106
112
|
continue;
|
|
107
113
|
}
|
|
108
114
|
}
|
|
@@ -110,7 +116,7 @@ export class EventStore {
|
|
|
110
116
|
if (ownerError.code !== 'ENOENT' && !(ownerError instanceof SyntaxError)) throw ownerError;
|
|
111
117
|
const lock = await stat(this.#lockDirectory).catch(() => null);
|
|
112
118
|
if (lock && Date.now() - lock.mtimeMs > 10000) {
|
|
113
|
-
await rm(this.#lockDirectory, { recursive: true, force: true });
|
|
119
|
+
await rm(this.#lockDirectory, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 });
|
|
114
120
|
continue;
|
|
115
121
|
}
|
|
116
122
|
}
|
|
@@ -138,7 +144,7 @@ export class EventStore {
|
|
|
138
144
|
const temp = `${this.#file}.rewrite-${process.pid}`;
|
|
139
145
|
await writeFile(temp, next.map((event) => JSON.stringify(event)).join('\n') + (next.length ? '\n' : ''));
|
|
140
146
|
await rename(temp, this.#file);
|
|
141
|
-
this.#nextSequence = (next.at(-1)?.sequence ?? 0) + 1;
|
|
147
|
+
this.#nextSequence = Math.max(next.at(-1)?.sequence ?? 0, this.#floor) + 1;
|
|
142
148
|
return { total: next.length, changed };
|
|
143
149
|
} finally {
|
|
144
150
|
await release();
|
|
@@ -153,7 +159,7 @@ export class EventStore {
|
|
|
153
159
|
const release = await this.#acquireLock();
|
|
154
160
|
try {
|
|
155
161
|
const existing = await this.#readAllUnlocked();
|
|
156
|
-
const sequence = (existing.at(-1)?.sequence ?? 0) + 1;
|
|
162
|
+
const sequence = Math.max(existing.at(-1)?.sequence ?? 0, this.#floor) + 1;
|
|
157
163
|
const event = {
|
|
158
164
|
id: randomUUID(),
|
|
159
165
|
sequence,
|