@slatesvideo/shared 0.7.18 → 0.7.19

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.
@@ -0,0 +1,126 @@
1
+ // ============================================================
2
+ // MY BRAIN, THE WRITE SIDE: a lesson the user teaches lands in their own brain
3
+ // (second-brain plans/2026-10-25-slates-brain.md § My brain, step 5).
4
+ //
5
+ // One lesson is one line in the operative summary of one file, with its source
6
+ // and date, so the loader (my-brain.ts) reads it first and every line can be
7
+ // traced and reverted. A lesson already there is not written twice; one that
8
+ // replaces an older line removes it, and the older line is kept in
9
+ // .history.jsonl (the newest wins, the loser is logged). After every write the
10
+ // file is checked with the loader's own checks; a write that would leave it
11
+ // unloaded (over a cap, a passage the shared brain already holds) is undone and
12
+ // the reason returned, so the agent consolidates instead.
13
+ // ============================================================
14
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { MY_BRAIN_PROFILE, loadMyBrain, myBrainDir } from './my-brain.js';
17
+ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
+ const SUMMARY_RE = /(<!--\s*@operative:start\s*-->\r?\n)([\s\S]*?)(<!--\s*@operative:end\s*-->)/;
19
+ const LESSON_RE = /^- (.*?) _\(from (.*?), (\d{4}-\d{2}-\d{2})\)_$/;
20
+ const HISTORY_FILE = '.history.jsonl';
21
+ /** The file a lesson goes to when the agent names none. */
22
+ export const MY_BRAIN_RULES = 'my-rules';
23
+ const norm = (text) => text.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
24
+ const oneLine = (text) => text.replace(/\s+/g, ' ').trim();
25
+ function newFile(name) {
26
+ const title = name === MY_BRAIN_PROFILE ? 'My profile' : name === MY_BRAIN_RULES ? 'My rules' : `My ${name.replace(/-/g, ' ')}`;
27
+ const what = name === MY_BRAIN_PROFILE ? 'who they are, what they make, for whom, in what voice' : 'rules and presets they taught Slates';
28
+ return `---\nname: ${name}\ndescription: "${title}: ${what}. Theirs, and it wins over the shared brain."\n---\n\n# ${title}\n\n<!-- @operative:start -->\n**Operative summary.**\n<!-- @operative:end -->\n`;
29
+ }
30
+ function writeAtomic(path, text) {
31
+ const temp = `${path}.${process.pid}.tmp`;
32
+ writeFileSync(temp, text);
33
+ renameSync(temp, path);
34
+ }
35
+ const SETTINGS_FILE = '.settings.json';
36
+ /** Whether agents may save lessons on their own. On unless the user switched it off (the desktop's My brain panel). */
37
+ export function myBrainLearning(dir = myBrainDir()) {
38
+ try {
39
+ return JSON.parse(readFileSync(join(dir, SETTINGS_FILE), 'utf8')).learning !== false;
40
+ }
41
+ catch {
42
+ return true;
43
+ }
44
+ }
45
+ export function setMyBrainLearning(on, dir = myBrainDir()) {
46
+ mkdirSync(dir, { recursive: true });
47
+ writeAtomic(join(dir, SETTINGS_FILE), JSON.stringify({ learning: on }, null, 2));
48
+ }
49
+ /** Every saved lesson, file by file, for a panel that lists them; lines written by hand are not lessons and are left out. */
50
+ export function myBrainLessons(dir = myBrainDir()) {
51
+ const { files } = loadMyBrain(dir);
52
+ return Object.entries(files).map(([file, text]) => ({
53
+ file,
54
+ lessons: (SUMMARY_RE.exec(text)?.[2] ?? '').split(/\r?\n/).flatMap((l) => {
55
+ const m = LESSON_RE.exec(l);
56
+ return m ? [{ text: m[1], source: m[2], date: m[3] }] : [];
57
+ }),
58
+ })).filter((f) => f.lessons.length);
59
+ }
60
+ /** Add, replace or remove one lesson. Throws with a reason the agent can act on. */
61
+ export function remember(input, dir = myBrainDir(), now = new Date()) {
62
+ if (input.lesson && !myBrainLearning(dir))
63
+ throw new Error('not saved: the user turned learning off (Settings → AI tools → My brain). Tell them in one line; nothing was saved.');
64
+ const file = (input.file ?? MY_BRAIN_RULES).trim().toLowerCase();
65
+ if (!NAME_RE.test(file))
66
+ throw new Error('file must be lowercase words joined by hyphens, for example "hooks" or "profile"');
67
+ const lesson = input.lesson ? oneLine(input.lesson) : '';
68
+ const replaces = input.replaces ? norm(input.replaces) : '';
69
+ if (!lesson && !replaces)
70
+ throw new Error('pass a lesson to save, or replaces alone to remove a line');
71
+ if (lesson.includes('_(from '))
72
+ throw new Error('write the lesson alone; the source goes in source');
73
+ const path = join(dir, `${file}.md`);
74
+ const before = existsSync(path) ? readFileSync(path, 'utf8') : null;
75
+ if (before === null && !lesson)
76
+ throw new Error(`${file}.md does not exist, so there is nothing to remove`);
77
+ const text = before ?? newFile(file);
78
+ const match = SUMMARY_RE.exec(text);
79
+ if (!match)
80
+ throw new Error(`${file}.md has no operative summary to add to; fix the file or name another`);
81
+ const lines = match[2].split(/\r?\n/).filter((l) => l.trim());
82
+ const lessonText = (l) => {
83
+ const m = LESSON_RE.exec(l);
84
+ return m ? norm(m[1]) : null;
85
+ };
86
+ if (lesson && lines.some((l) => lessonText(l) === norm(lesson)))
87
+ return { file, saved: lesson, unchanged: true };
88
+ let removed;
89
+ if (replaces) {
90
+ const at = lines.findIndex((l) => lessonText(l) === replaces) >= 0
91
+ ? lines.findIndex((l) => lessonText(l) === replaces)
92
+ : lines.findIndex((l) => lessonText(l)?.includes(replaces));
93
+ if (at >= 0) {
94
+ removed = LESSON_RE.exec(lines[at])[1];
95
+ lines.splice(at, 1);
96
+ }
97
+ else if (!lesson)
98
+ throw new Error(`no line in ${file}.md matches "${input.replaces}"`);
99
+ }
100
+ if (lesson)
101
+ lines.push(`- ${lesson} _(from ${oneLine(input.source || 'the user')}, ${now.toISOString().slice(0, 10)})_`);
102
+ const next = text.replace(SUMMARY_RE, (_all, start, _body, end) => `${start}${lines.join('\n')}\n${end}`);
103
+ mkdirSync(dir, { recursive: true });
104
+ // A file this op made, left with no lesson, is removed whole; a file with anything else of theirs is kept.
105
+ const empty = next.trim() === newFile(file).trim();
106
+ if (empty)
107
+ rmSync(path);
108
+ else
109
+ writeAtomic(path, next);
110
+ const problem = empty ? undefined : loadMyBrain(dir).skipped.find((s) => s.file === `${file}.md`);
111
+ if (problem) {
112
+ if (before === null)
113
+ rmSync(path);
114
+ else
115
+ writeAtomic(path, before);
116
+ throw new Error(`not saved: ${problem.reason}. Merge it into a line ${file}.md already has (pass replaces), or remove one first.`);
117
+ }
118
+ try {
119
+ appendFileSync(join(dir, HISTORY_FILE), `${JSON.stringify({ at: now.toISOString(), file, saved: lesson || undefined, removed, source: input.source })}\n`);
120
+ }
121
+ catch {
122
+ // The history is for tracing; the lesson is saved either way.
123
+ }
124
+ return { file, ...(lesson ? { saved: lesson } : {}), ...(removed ? { removed } : {}) };
125
+ }
126
+ //# sourceMappingURL=my-brain-write.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slatesvideo/shared",
3
- "version": "0.7.18",
3
+ "version": "0.7.19",
4
4
  "description": "Shared operations layer for the Slates MCP server and CLI: auth, cloud/desktop clients, and the single tool surface both consume. Most users want @slatesvideo/mcp-server or @slatesvideo/cli instead.",
5
5
  "license": "MIT",
6
6
  "type": "module",