@inetafrica/open-claudia 2.4.2 → 2.6.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 +24 -0
- package/README.md +217 -120
- package/bin/cli.js +18 -0
- package/bin/dream.js +51 -0
- package/bin/entity.js +77 -0
- package/bin/pack.js +100 -0
- package/bot.js +2 -0
- package/core/dream.js +332 -0
- package/core/entities.js +329 -0
- package/core/pack-review.js +224 -0
- package/core/packs.js +334 -0
- package/core/persona.js +51 -0
- package/core/runner.js +26 -0
- package/core/subagent.js +3 -2
- package/core/system-prompt.js +130 -15
- package/package.json +1 -1
package/core/entities.js
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// Entity memory: short living notes on the people, places, projects,
|
|
2
|
+
// orgs and systems that come up in conversation (a Honcho-style store,
|
|
3
|
+
// our own version). Each entity is ~/.open-claudia/entities/<slug>.md
|
|
4
|
+
// with frontmatter and two sections:
|
|
5
|
+
// ## Notes — current truth about the entity (replaces wholesale)
|
|
6
|
+
// ## Log — dated one-line observations, newest last
|
|
7
|
+
// The pre-turn router injects matched entities alongside context packs;
|
|
8
|
+
// the post-turn reviewer extracts/updates them after each turn.
|
|
9
|
+
|
|
10
|
+
const fs = require("fs");
|
|
11
|
+
const path = require("path");
|
|
12
|
+
|
|
13
|
+
let DatabaseSync = null;
|
|
14
|
+
try { ({ DatabaseSync } = require("node:sqlite")); } catch (e) { /* old node — matching disabled */ }
|
|
15
|
+
|
|
16
|
+
const CONFIG_DIR = require("../config-dir");
|
|
17
|
+
const ENTITIES_DIR = process.env.ENTITIES_DIR ? path.resolve(process.env.ENTITIES_DIR) : path.join(CONFIG_DIR, "entities");
|
|
18
|
+
|
|
19
|
+
const TYPES = ["person", "place", "project", "org", "system", "thing"];
|
|
20
|
+
const MAX_LOG_ENTRIES = 40;
|
|
21
|
+
|
|
22
|
+
function ensureDir() {
|
|
23
|
+
fs.mkdirSync(ENTITIES_DIR, { recursive: true, mode: 0o700 });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function slugify(name) {
|
|
27
|
+
return String(name || "").toLowerCase().trim()
|
|
28
|
+
.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function normalizeType(type) {
|
|
32
|
+
const t = String(type || "").toLowerCase().trim();
|
|
33
|
+
return TYPES.includes(t) ? t : "thing";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parseFrontmatter(content) {
|
|
37
|
+
const m = String(content || "").match(/^---\n([\s\S]*?)\n---/);
|
|
38
|
+
if (!m) return { fm: {}, body: String(content || "") };
|
|
39
|
+
const fm = {};
|
|
40
|
+
for (const line of m[1].split("\n")) {
|
|
41
|
+
const kv = line.match(/^([a-z_]+):\s*(.*)$/);
|
|
42
|
+
if (kv) fm[kv[1]] = kv[2].trim().replace(/^["']|["']$/g, "");
|
|
43
|
+
}
|
|
44
|
+
return { fm, body: content.slice(m[0].length).replace(/^\n+/, "") };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parseSections(body) {
|
|
48
|
+
const out = { Notes: "", Log: "" };
|
|
49
|
+
let current = null;
|
|
50
|
+
for (const line of String(body || "").split("\n")) {
|
|
51
|
+
const h = line.match(/^##\s+(Notes|Log)\s*$/i);
|
|
52
|
+
if (h) {
|
|
53
|
+
current = h[1].toLowerCase() === "notes" ? "Notes" : "Log";
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (current) out[current] += line + "\n";
|
|
57
|
+
}
|
|
58
|
+
out.Notes = out.Notes.trim();
|
|
59
|
+
out.Log = out.Log.trim();
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function serialize(ent) {
|
|
64
|
+
return [
|
|
65
|
+
"---",
|
|
66
|
+
`name: ${ent.name}`,
|
|
67
|
+
`type: ${ent.type}`,
|
|
68
|
+
`aliases: ${(ent.aliases || []).join(", ")}`,
|
|
69
|
+
`description: ${ent.description || ""}`,
|
|
70
|
+
`created: ${ent.created || new Date().toISOString()}`,
|
|
71
|
+
`updated: ${ent.updated || new Date().toISOString()}`,
|
|
72
|
+
`last_seen: ${ent.last_seen || ""}`,
|
|
73
|
+
"---",
|
|
74
|
+
"",
|
|
75
|
+
`## Notes`,
|
|
76
|
+
"",
|
|
77
|
+
(ent.sections?.Notes || "").trim(),
|
|
78
|
+
"",
|
|
79
|
+
`## Log`,
|
|
80
|
+
"",
|
|
81
|
+
(ent.sections?.Log || "").trim(),
|
|
82
|
+
"",
|
|
83
|
+
].join("\n");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function entityFile(slug) {
|
|
87
|
+
return path.join(ENTITIES_DIR, slug + ".md");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function readEntity(slug) {
|
|
91
|
+
let content;
|
|
92
|
+
try { content = fs.readFileSync(entityFile(slug), "utf-8"); }
|
|
93
|
+
catch (e) { return null; }
|
|
94
|
+
const { fm, body } = parseFrontmatter(content);
|
|
95
|
+
return {
|
|
96
|
+
slug,
|
|
97
|
+
name: fm.name || slug,
|
|
98
|
+
type: normalizeType(fm.type),
|
|
99
|
+
aliases: (fm.aliases || "").split(",").map((a) => a.trim()).filter(Boolean),
|
|
100
|
+
description: fm.description || "",
|
|
101
|
+
created: fm.created || "",
|
|
102
|
+
updated: fm.updated || "",
|
|
103
|
+
last_seen: fm.last_seen || "",
|
|
104
|
+
sections: parseSections(body),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function listEntities() {
|
|
109
|
+
let names;
|
|
110
|
+
try { names = fs.readdirSync(ENTITIES_DIR); } catch (e) { return []; }
|
|
111
|
+
const out = [];
|
|
112
|
+
for (const f of names) {
|
|
113
|
+
if (!f.endsWith(".md") || f.startsWith(".")) continue;
|
|
114
|
+
const e = readEntity(f.slice(0, -3));
|
|
115
|
+
if (e) out.push(e);
|
|
116
|
+
}
|
|
117
|
+
out.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function findEntity(nameOrSlug) {
|
|
122
|
+
const needle = String(nameOrSlug || "").trim().toLowerCase();
|
|
123
|
+
if (!needle) return null;
|
|
124
|
+
const direct = readEntity(slugify(needle));
|
|
125
|
+
if (direct) return direct;
|
|
126
|
+
return listEntities().find((e) =>
|
|
127
|
+
e.slug === needle ||
|
|
128
|
+
e.name.toLowerCase() === needle ||
|
|
129
|
+
e.aliases.some((a) => a.toLowerCase() === needle)
|
|
130
|
+
) || null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function writeEntity(ent) {
|
|
134
|
+
ensureDir();
|
|
135
|
+
fs.writeFileSync(entityFile(ent.slug), serialize(ent), { mode: 0o600 });
|
|
136
|
+
markIndexDirty();
|
|
137
|
+
return ent.slug;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function today() {
|
|
141
|
+
return new Date().toISOString().slice(0, 10);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Create-or-merge. Notes replace (current truth); log lines append
|
|
145
|
+
// (capped); aliases union; description/type update when supplied.
|
|
146
|
+
function upsertEntity({ name, type, aliases, description, notes, log } = {}) {
|
|
147
|
+
const cleanName = String(name || "").trim();
|
|
148
|
+
if (!cleanName) throw new Error("entity needs a name");
|
|
149
|
+
const existing = findEntity(cleanName);
|
|
150
|
+
const ent = existing || {
|
|
151
|
+
slug: slugify(cleanName),
|
|
152
|
+
name: cleanName,
|
|
153
|
+
type: normalizeType(type),
|
|
154
|
+
aliases: [],
|
|
155
|
+
description: "",
|
|
156
|
+
created: new Date().toISOString(),
|
|
157
|
+
sections: { Notes: "", Log: "" },
|
|
158
|
+
};
|
|
159
|
+
if (!ent.slug) throw new Error("entity needs a name");
|
|
160
|
+
ent.updated = new Date().toISOString();
|
|
161
|
+
if (type) ent.type = normalizeType(type);
|
|
162
|
+
if (description) ent.description = String(description).trim();
|
|
163
|
+
for (const a of [].concat(aliases || [])) {
|
|
164
|
+
const alias = String(a).trim();
|
|
165
|
+
if (alias && alias.toLowerCase() !== ent.name.toLowerCase() &&
|
|
166
|
+
!ent.aliases.some((x) => x.toLowerCase() === alias.toLowerCase())) {
|
|
167
|
+
ent.aliases.push(alias);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
ent.aliases = ent.aliases.slice(0, 8);
|
|
171
|
+
if (typeof notes === "string" && notes.trim()) ent.sections.Notes = notes.trim();
|
|
172
|
+
if (typeof log === "string" && log.trim()) {
|
|
173
|
+
const entries = ent.sections.Log.split("\n").filter((l) => l.trim());
|
|
174
|
+
entries.push(`- [${today()}] ${log.trim().replace(/\n+/g, " ")}`);
|
|
175
|
+
ent.sections.Log = entries.slice(-MAX_LOG_ENTRIES).join("\n");
|
|
176
|
+
}
|
|
177
|
+
writeEntity(ent);
|
|
178
|
+
return { entity: ent, created: !existing };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function removeEntity(nameOrSlug) {
|
|
182
|
+
const ent = findEntity(nameOrSlug);
|
|
183
|
+
if (!ent) return null;
|
|
184
|
+
fs.rmSync(entityFile(ent.slug), { force: true });
|
|
185
|
+
markIndexDirty();
|
|
186
|
+
return ent;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function touchSeen(slugs) {
|
|
190
|
+
const now = new Date().toISOString();
|
|
191
|
+
for (const slug of [].concat(slugs || [])) {
|
|
192
|
+
const ent = readEntity(slug);
|
|
193
|
+
if (!ent) continue;
|
|
194
|
+
ent.last_seen = now;
|
|
195
|
+
try { writeEntity(ent); } catch (e) {}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Recognise a Write/Edit aimed at an entity file (for chat announcements).
|
|
200
|
+
function entityNameFromPath(filePath) {
|
|
201
|
+
if (!filePath) return null;
|
|
202
|
+
const resolved = path.resolve(String(filePath));
|
|
203
|
+
const rel = path.relative(ENTITIES_DIR, resolved);
|
|
204
|
+
if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
|
|
205
|
+
if (rel.includes(path.sep) || !rel.endsWith(".md")) return null;
|
|
206
|
+
return rel.slice(0, -3);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
// FTS matching — same field-weighted per-term scoring as packs (BM25 is
|
|
211
|
+
// unusable on a small corpus): a hit on name/aliases counts 2, anything
|
|
212
|
+
// else 1. Threshold 2 means a single name mention is enough to inject,
|
|
213
|
+
// but one stray body word is not.
|
|
214
|
+
|
|
215
|
+
let _db = null;
|
|
216
|
+
let _indexedAt = 0;
|
|
217
|
+
let _dirty = true;
|
|
218
|
+
|
|
219
|
+
function markIndexDirty() { _dirty = true; }
|
|
220
|
+
|
|
221
|
+
function openDb() {
|
|
222
|
+
if (!DatabaseSync) return null;
|
|
223
|
+
if (_db) return _db;
|
|
224
|
+
try {
|
|
225
|
+
ensureDir();
|
|
226
|
+
const dbPath = path.join(ENTITIES_DIR, "index.db");
|
|
227
|
+
const db = new DatabaseSync(dbPath);
|
|
228
|
+
try { fs.chmodSync(dbPath, 0o600); } catch (e) {}
|
|
229
|
+
db.exec("PRAGMA journal_mode=WAL");
|
|
230
|
+
db.exec("PRAGMA busy_timeout=3000");
|
|
231
|
+
db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS entities USING fts5(
|
|
232
|
+
name, aliases, description, content, slug UNINDEXED,
|
|
233
|
+
tokenize='porter unicode61'
|
|
234
|
+
)`);
|
|
235
|
+
_db = db;
|
|
236
|
+
return db;
|
|
237
|
+
} catch (e) {
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function latestMtime() {
|
|
243
|
+
let latest = 0;
|
|
244
|
+
let names = [];
|
|
245
|
+
try { names = fs.readdirSync(ENTITIES_DIR); } catch (e) { return 0; }
|
|
246
|
+
for (const f of names) {
|
|
247
|
+
if (!f.endsWith(".md")) continue;
|
|
248
|
+
try {
|
|
249
|
+
const m = fs.statSync(path.join(ENTITIES_DIR, f)).mtimeMs;
|
|
250
|
+
if (m > latest) latest = m;
|
|
251
|
+
} catch (e) {}
|
|
252
|
+
}
|
|
253
|
+
return latest;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function reindex() {
|
|
257
|
+
const db = openDb();
|
|
258
|
+
if (!db) return false;
|
|
259
|
+
const all = listEntities();
|
|
260
|
+
db.exec("BEGIN");
|
|
261
|
+
try {
|
|
262
|
+
db.exec("DELETE FROM entities");
|
|
263
|
+
const insert = db.prepare("INSERT INTO entities (name, aliases, description, content, slug) VALUES (?, ?, ?, ?, ?)");
|
|
264
|
+
for (const e of all) {
|
|
265
|
+
insert.run(e.name, e.aliases.join(" "), e.description, [e.sections.Notes, e.sections.Log].join("\n"), e.slug);
|
|
266
|
+
}
|
|
267
|
+
db.exec("COMMIT");
|
|
268
|
+
} catch (e) {
|
|
269
|
+
try { db.exec("ROLLBACK"); } catch (e2) {}
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
272
|
+
_dirty = false;
|
|
273
|
+
_indexedAt = Date.now();
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function ensureIndex() {
|
|
278
|
+
if (_dirty || latestMtime() > _indexedAt) reindex();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const STOPWORDS = new Set(("a an and are as at be but by can did do for from had has have how i if in is it its " +
|
|
282
|
+
"me my no not of on or our so that the their then there this to up us was we what when where which who why " +
|
|
283
|
+
"will with you your yes yeah ok okay please thanks just like dont don't im i'm its it's").split(" "));
|
|
284
|
+
|
|
285
|
+
function queryTerms(text) {
|
|
286
|
+
const seen = new Set();
|
|
287
|
+
const terms = [];
|
|
288
|
+
for (const raw of String(text || "").toLowerCase().split(/[^a-z0-9_.-]+/)) {
|
|
289
|
+
const t = raw.replace(/^[.-]+|[.-]+$/g, "");
|
|
290
|
+
if (t.length < 3 || STOPWORDS.has(t) || seen.has(t)) continue;
|
|
291
|
+
seen.add(t);
|
|
292
|
+
terms.push(t);
|
|
293
|
+
if (terms.length >= 40) break;
|
|
294
|
+
}
|
|
295
|
+
return terms;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function matchEntities(text, { limit = 4, threshold = null } = {}) {
|
|
299
|
+
const db = openDb();
|
|
300
|
+
if (!db) return [];
|
|
301
|
+
ensureIndex();
|
|
302
|
+
const terms = queryTerms(text);
|
|
303
|
+
if (terms.length === 0) return [];
|
|
304
|
+
const minScore = threshold ?? Number(process.env.ENTITY_MATCH_THRESHOLD || 2);
|
|
305
|
+
const scores = new Map();
|
|
306
|
+
let stmt;
|
|
307
|
+
try { stmt = db.prepare("SELECT slug FROM entities WHERE entities MATCH ?"); } catch (e) { return []; }
|
|
308
|
+
for (const t of terms) {
|
|
309
|
+
const quoted = `"${t.replace(/"/g, '""')}"`;
|
|
310
|
+
let strong = [];
|
|
311
|
+
let any = [];
|
|
312
|
+
try { strong = stmt.all(`{name aliases} : ${quoted}`); } catch (e) {}
|
|
313
|
+
try { any = stmt.all(quoted); } catch (e) {}
|
|
314
|
+
const strongSet = new Set(strong.map((r) => r.slug));
|
|
315
|
+
for (const r of any) scores.set(r.slug, (scores.get(r.slug) || 0) + (strongSet.has(r.slug) ? 2 : 1));
|
|
316
|
+
}
|
|
317
|
+
const names = new Map(listEntities().map((e) => [e.slug, e.name]));
|
|
318
|
+
return [...scores.entries()]
|
|
319
|
+
.filter(([, s]) => s >= minScore)
|
|
320
|
+
.sort((a, b) => b[1] - a[1])
|
|
321
|
+
.slice(0, Math.max(1, Math.min(10, limit)))
|
|
322
|
+
.map(([slug, score]) => ({ slug, name: names.get(slug) || slug, score }));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
module.exports = {
|
|
326
|
+
ENTITIES_DIR, TYPES, slugify,
|
|
327
|
+
listEntities, findEntity, readEntity, writeEntity, upsertEntity, removeEntity,
|
|
328
|
+
touchSeen, entityNameFromPath, matchEntities, reindex, markIndexDirty,
|
|
329
|
+
};
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// Post-turn pack reviewer (Hermes-inspired, selective-but-active).
|
|
2
|
+
// After each substantial turn a cheap model reviews the exchange and
|
|
3
|
+
// decides whether a context pack should be created or mutated. The model
|
|
4
|
+
// only RETURNS a JSON decision — all file writes are applied here by bot
|
|
5
|
+
// code, so the reviewer needs no tools and no permissions. Every applied
|
|
6
|
+
// mutation is announced in chat (one line), per the no-silent-learning
|
|
7
|
+
// rule.
|
|
8
|
+
|
|
9
|
+
const { spawnSubagent } = require("./subagent");
|
|
10
|
+
const packs = require("./packs");
|
|
11
|
+
const entities = require("./entities");
|
|
12
|
+
const { redactSensitive } = require("./redact");
|
|
13
|
+
|
|
14
|
+
const MIN_TURN_CHARS = 400;
|
|
15
|
+
const MAX_TEXT_CHARS = 7000;
|
|
16
|
+
const REVIEW_MODEL = process.env.PACK_REVIEW_MODEL || "haiku";
|
|
17
|
+
const MAX_ACTIONS = 2;
|
|
18
|
+
const MAX_ENTITY_ACTIONS = 3;
|
|
19
|
+
|
|
20
|
+
function enabled() {
|
|
21
|
+
return (process.env.PACK_REVIEW || "on").toLowerCase() !== "off";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function clip(text, n = MAX_TEXT_CHARS) {
|
|
25
|
+
const s = String(text || "");
|
|
26
|
+
return s.length > n ? s.slice(0, n) + "\n…[truncated]" : s;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Word-boundary clip for chat announcements — never cuts mid-word.
|
|
30
|
+
function clipWords(text, max = 180) {
|
|
31
|
+
const s = String(text || "").replace(/\s+/g, " ").trim();
|
|
32
|
+
if (s.length <= max) return s;
|
|
33
|
+
const cut = s.slice(0, max);
|
|
34
|
+
const sp = cut.lastIndexOf(" ");
|
|
35
|
+
return (sp > max * 0.6 ? cut.slice(0, sp) : cut).replace(/[,;:.\-—]+$/, "") + "…";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const ENTITY_EMOJI = { person: "👤", place: "📍", project: "🚀", org: "🏢", system: "🖥️", thing: "🔖" };
|
|
39
|
+
|
|
40
|
+
const ANNOUNCE_HEADERS = [
|
|
41
|
+
"🧠 Took some notes while we worked:",
|
|
42
|
+
"🧠 Filed a few things away:",
|
|
43
|
+
"🧠 Jotted this down for next time:",
|
|
44
|
+
"🧠 Memory updated:",
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
function formatAnnouncement(lines) {
|
|
48
|
+
if (lines.length === 0) return "";
|
|
49
|
+
const header = ANNOUNCE_HEADERS[Math.floor(Math.random() * ANNOUNCE_HEADERS.length)];
|
|
50
|
+
return [header, ...lines].join("\n\n");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function buildReviewPrompt(userText, assistantText) {
|
|
54
|
+
const index = packs.listPacks().map((p) =>
|
|
55
|
+
`- ${p.dir}: ${p.name} — ${p.description}${p.tags.length ? ` [${p.tags.join(", ")}]` : ""}`
|
|
56
|
+
).join("\n") || "(none yet)";
|
|
57
|
+
|
|
58
|
+
const entityIndex = entities.listEntities().map((e) =>
|
|
59
|
+
`- ${e.slug}: ${e.name} (${e.type})${e.aliases.length ? ` aka ${e.aliases.join(", ")}` : ""} — ${e.description}`
|
|
60
|
+
).join("\n") || "(none yet)";
|
|
61
|
+
|
|
62
|
+
return `You are the memory reviewer for a personal AI assistant. After each conversation turn you decide whether the assistant's long-term "context packs" and "entity notes" should change.
|
|
63
|
+
|
|
64
|
+
A context pack is a living document about ONE topic (a project, a system, a recurring task, a domain). It has four sections:
|
|
65
|
+
- Stance: how to think about the topic — preferences, framing, hard rules the user has expressed.
|
|
66
|
+
- Procedure: verified how-to steps and commands.
|
|
67
|
+
- State: where work on the topic stands NOW — decisions made, open questions, next steps. Replaces wholesale.
|
|
68
|
+
- Journal: one-line dated log of what happened each session.
|
|
69
|
+
|
|
70
|
+
An entity note is a short memory file about ONE specific named entity — a person, place, project, org, or system. It has:
|
|
71
|
+
- Notes: current truth about the entity (who/what it is, role, preferences, relationships). Replaces wholesale.
|
|
72
|
+
- Log: one-line dated observations, appended.
|
|
73
|
+
|
|
74
|
+
Existing packs:
|
|
75
|
+
${index}
|
|
76
|
+
|
|
77
|
+
Known entities:
|
|
78
|
+
${entityIndex}
|
|
79
|
+
|
|
80
|
+
The turn to review:
|
|
81
|
+
|
|
82
|
+
<user_message>
|
|
83
|
+
${clip(userText)}
|
|
84
|
+
</user_message>
|
|
85
|
+
|
|
86
|
+
<assistant_reply>
|
|
87
|
+
${clip(assistantText)}
|
|
88
|
+
</assistant_reply>
|
|
89
|
+
|
|
90
|
+
Decide. Rules:
|
|
91
|
+
- Bias toward action: if the turn did real work on an identifiable topic (a named system, project, server, app, person, or domain), record it — at minimum a journal line. Most working turns deserve one. Reserve empty actions for small talk, pure status checks, and turns that contain nothing new.
|
|
92
|
+
- UPDATE an existing pack when the turn touched that topic: append a journal line, and rewrite State if where-things-stand changed. Update Stance when the user expressed a lasting preference or rule; Procedure when a verified working method emerged.
|
|
93
|
+
- CREATE a pack when the turn worked on a durable topic no existing pack covers. Topics recur more than you expect — a named system or project is durable by default. Do not create packs for one-off trivia, and prefer update when an existing pack fits.
|
|
94
|
+
- Never store secrets, tokens, passwords, or credentials.
|
|
95
|
+
- State should be concise (under 150 words). Journal entries one sentence. Never start a journal or log sentence with a date — dates are prepended automatically.
|
|
96
|
+
- At most ${MAX_ACTIONS} pack actions.
|
|
97
|
+
- Entities: add an item when the turn revealed something durable about a specific named person, place, project, org, or system — their role, status, preferences, or relationship to other work. Use the existing entity name when one matches (check aliases). Skip entities mentioned only in passing with nothing learned. Notes under 100 words; "notes" null means leave Notes unchanged. At most ${MAX_ENTITY_ACTIONS} entity items.
|
|
98
|
+
- Packs and entities are independent — a turn can update both, either, or neither. Do not duplicate the same fact in a pack AND an entity unless it genuinely belongs to both.
|
|
99
|
+
|
|
100
|
+
Reply with ONLY a JSON object, no prose, no code fences:
|
|
101
|
+
{"actions": [
|
|
102
|
+
{"action": "update", "pack": "<existing dir>", "journal": "<one sentence>", "state": "<full new State or null>", "stance": null, "procedure": null}
|
|
103
|
+
| {"action": "create", "dir": "<kebab-slug>", "name": "<title>", "description": "<one line: when this pack is relevant>", "tags": ["..."], "stance": "<or empty>", "procedure": "<or empty>", "state": "<where things stand>", "journal": "<one sentence>"}
|
|
104
|
+
],
|
|
105
|
+
"entities": [
|
|
106
|
+
{"name": "<canonical name>", "type": "person|place|project|org|system|thing", "aliases": ["..."], "description": "<one line: who/what this is>", "notes": "<full new Notes or null>", "log": "<one sentence observation>"}
|
|
107
|
+
]}
|
|
108
|
+
or {"actions": [], "entities": []}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function parseDecision(text) {
|
|
112
|
+
const raw = String(text || "").trim().replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/, "");
|
|
113
|
+
const start = raw.indexOf("{");
|
|
114
|
+
const end = raw.lastIndexOf("}");
|
|
115
|
+
if (start === -1 || end <= start) return null;
|
|
116
|
+
try {
|
|
117
|
+
const obj = JSON.parse(raw.slice(start, end + 1));
|
|
118
|
+
const actions = Array.isArray(obj.actions) ? obj.actions.slice(0, MAX_ACTIONS) : (obj.action ? [obj] : []);
|
|
119
|
+
const entityActions = Array.isArray(obj.entities) ? obj.entities.slice(0, MAX_ENTITY_ACTIONS) : [];
|
|
120
|
+
return { actions, entities: entityActions };
|
|
121
|
+
} catch (e) {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function applyAction(a) {
|
|
127
|
+
if (!a || typeof a !== "object") return null;
|
|
128
|
+
if (a.action === "update" && a.pack) {
|
|
129
|
+
const existing = packs.readPack(a.pack);
|
|
130
|
+
if (!existing) return null;
|
|
131
|
+
packs.updatePack(a.pack, {
|
|
132
|
+
journal: a.journal || "",
|
|
133
|
+
state: typeof a.state === "string" ? a.state : "",
|
|
134
|
+
stance: typeof a.stance === "string" ? a.stance : "",
|
|
135
|
+
procedure: typeof a.procedure === "string" ? a.procedure : "",
|
|
136
|
+
});
|
|
137
|
+
return { kind: "update", dir: a.pack, name: existing.name, note: a.journal || "state updated" };
|
|
138
|
+
}
|
|
139
|
+
if (a.action === "create" && (a.dir || a.name)) {
|
|
140
|
+
const dir = packs.slugify(a.dir || a.name);
|
|
141
|
+
if (packs.readPack(dir)) {
|
|
142
|
+
packs.updatePack(dir, { journal: a.journal || "", state: a.state || "" });
|
|
143
|
+
return { kind: "update", dir, name: a.name || dir, note: a.journal || "state updated" };
|
|
144
|
+
}
|
|
145
|
+
const pack = packs.createPack({
|
|
146
|
+
dir,
|
|
147
|
+
name: a.name,
|
|
148
|
+
description: a.description,
|
|
149
|
+
tags: Array.isArray(a.tags) ? a.tags.slice(0, 6) : [],
|
|
150
|
+
stance: a.stance || "",
|
|
151
|
+
procedure: a.procedure || "",
|
|
152
|
+
state: a.state || "",
|
|
153
|
+
journal: a.journal || "",
|
|
154
|
+
});
|
|
155
|
+
return { kind: "create", dir: pack.dir, name: pack.name, note: a.description || "" };
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function applyEntityAction(e) {
|
|
161
|
+
if (!e || typeof e !== "object" || !String(e.name || "").trim()) return null;
|
|
162
|
+
const { entity, created } = entities.upsertEntity({
|
|
163
|
+
name: e.name,
|
|
164
|
+
type: e.type,
|
|
165
|
+
aliases: Array.isArray(e.aliases) ? e.aliases.slice(0, 5) : [],
|
|
166
|
+
description: e.description,
|
|
167
|
+
notes: typeof e.notes === "string" ? e.notes : "",
|
|
168
|
+
log: e.log || "",
|
|
169
|
+
});
|
|
170
|
+
return { kind: created ? "create" : "update", slug: entity.slug, name: entity.name, type: entity.type, note: e.log || e.description || "" };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Fire-and-forget. `announce` is an async (text) => void bound to the
|
|
174
|
+
// originating channel; failures are logged, never thrown into the turn.
|
|
175
|
+
function reviewTurn({ userText, assistantText, channelId, announce }) {
|
|
176
|
+
if (!enabled()) return;
|
|
177
|
+
const combined = (String(userText || "") + String(assistantText || "")).trim();
|
|
178
|
+
if (combined.length < MIN_TURN_CHARS) return;
|
|
179
|
+
|
|
180
|
+
const prompt = buildReviewPrompt(redactSensitive(String(userText || "")), redactSensitive(String(assistantText || "")));
|
|
181
|
+
|
|
182
|
+
spawnSubagent(prompt, {
|
|
183
|
+
model: REVIEW_MODEL,
|
|
184
|
+
channelId,
|
|
185
|
+
timeoutMs: 3 * 60 * 1000,
|
|
186
|
+
systemPrompt: "You are a background memory reviewer. Reply with ONLY the requested JSON object. No prose, no markdown, no tool use.",
|
|
187
|
+
}).then(({ text }) => {
|
|
188
|
+
const decision = parseDecision(text);
|
|
189
|
+
if (!decision || (decision.actions.length === 0 && decision.entities.length === 0)) return;
|
|
190
|
+
const lines = [];
|
|
191
|
+
for (const a of decision.actions) {
|
|
192
|
+
try {
|
|
193
|
+
const r = applyAction(a);
|
|
194
|
+
if (r) {
|
|
195
|
+
lines.push(r.kind === "create"
|
|
196
|
+
? `📦 New pack: ${r.name}\n${clipWords(r.note, 180)}\n↳ open-claudia pack show ${r.dir}`
|
|
197
|
+
: `✏️ ${r.name} — ${clipWords(r.note, 180)}`);
|
|
198
|
+
}
|
|
199
|
+
} catch (e) {
|
|
200
|
+
console.warn(`[pack-review] apply failed: ${e.message}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
for (const ea of decision.entities) {
|
|
204
|
+
try {
|
|
205
|
+
const r = applyEntityAction(ea);
|
|
206
|
+
if (r) {
|
|
207
|
+
const emoji = ENTITY_EMOJI[r.type] || ENTITY_EMOJI.thing;
|
|
208
|
+
lines.push(r.kind === "create"
|
|
209
|
+
? `${emoji} Now tracking ${r.name} (${r.type}) — ${clipWords(r.note, 160)}`
|
|
210
|
+
: `${emoji} ${r.name} — ${clipWords(r.note, 160)}`);
|
|
211
|
+
}
|
|
212
|
+
} catch (e) {
|
|
213
|
+
console.warn(`[pack-review] entity apply failed: ${e.message}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (lines.length > 0 && typeof announce === "function") {
|
|
217
|
+
announce(formatAnnouncement(lines)).catch(() => {});
|
|
218
|
+
}
|
|
219
|
+
}).catch((e) => {
|
|
220
|
+
console.warn(`[pack-review] reviewer failed: ${e.message}`);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
module.exports = { reviewTurn, parseDecision, applyAction, applyEntityAction, buildReviewPrompt, clipWords, ENTITY_EMOJI };
|