selflore 0.0.2 → 0.2.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.
Files changed (51) hide show
  1. package/README.md +80 -17
  2. package/dist/cli.js +87 -17
  3. package/dist/hooks/capture-worker.js +27 -0
  4. package/dist/hooks/io.js +6 -1
  5. package/dist/hooks/session-start.js +2 -8
  6. package/dist/hooks/stop.js +3 -21
  7. package/dist/hooks/user-prompt-submit.js +10 -0
  8. package/dist/init.js +84 -18
  9. package/dist/lib/background.js +173 -0
  10. package/dist/lib/capture-prompt.js +39 -0
  11. package/dist/lib/commands.js +321 -67
  12. package/dist/lib/config.js +84 -5
  13. package/dist/lib/entries.js +82 -3
  14. package/dist/lib/heat.js +141 -0
  15. package/dist/lib/hook-logic.js +107 -0
  16. package/dist/lib/index-cache.js +46 -0
  17. package/dist/lib/install.js +2 -3
  18. package/dist/lib/links.js +58 -0
  19. package/dist/lib/logo.js +6 -0
  20. package/dist/lib/notes-graph.js +585 -0
  21. package/dist/lib/notes-html.js +148 -330
  22. package/dist/lib/notes-page-css.js +279 -0
  23. package/dist/lib/notes-page-js.js +959 -0
  24. package/dist/lib/notes.js +19 -6
  25. package/dist/lib/nudge.js +8 -1
  26. package/dist/lib/paths.js +6 -0
  27. package/dist/lib/question.js +19 -0
  28. package/dist/lib/queue.js +6 -4
  29. package/dist/lib/recall.js +149 -0
  30. package/dist/lib/results.js +11 -1
  31. package/dist/lib/retag.js +150 -0
  32. package/dist/lib/server-launch.js +73 -0
  33. package/dist/lib/server.js +120 -0
  34. package/dist/lib/session.js +27 -1
  35. package/dist/lib/settings.js +5 -1
  36. package/dist/lib/signals.js +51 -0
  37. package/dist/lib/stats.js +72 -40
  38. package/dist/lib/struggle.js +120 -0
  39. package/dist/lib/surface.js +75 -0
  40. package/dist/lib/transcript.js +205 -37
  41. package/dist/lib/ui.js +127 -0
  42. package/dist/notes-server.js +39 -0
  43. package/dist/sl.js +33 -14
  44. package/dist/vendor/graph3d.js +5402 -0
  45. package/package.json +6 -3
  46. package/skill/SKILL.md +29 -14
  47. package/skill/references/capture.md +16 -12
  48. package/skill/references/log.md +2 -2
  49. package/skill/references/recall.md +44 -0
  50. package/skill/references/stats.md +5 -1
  51. package/skill/references/test.md +49 -31
@@ -1,11 +1,16 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { isQuestion } from "./question.js";
3
4
  /**
4
- * Cheap heuristics over a Claude Code transcript (JSONL) for the Stop-hook safety net.
5
- * Only the mechanically observable PRD triggers are detected here; tradeoffs and
6
- * corrections are left to the skill itself.
5
+ * Cheap heuristics over a Claude Code transcript (JSONL) that decide whether a stretch
6
+ * of work is worth a capture pass. Only mechanically observable triggers live here;
7
+ * tradeoffs and corrections are judged by the capture model itself.
7
8
  */
8
- export const LARGE_WRITE_LINES = 30;
9
+ // What the agent wrote is a weak sign of what the user doesn't know, so a write has to be big to
10
+ // count on its own. What the user asked to have explained (below) is the strong sign.
11
+ export const MIN_LINES = { light: 150, normal: 80, thorough: 30 };
12
+ /** An answer this long, to a question, with no code written, is an explanation worth keeping. */
13
+ export const MIN_EXPLANATION_WORDS = 120;
9
14
  const DEP_FILES = new Set([
10
15
  "package.json",
11
16
  "requirements.txt",
@@ -19,6 +24,8 @@ const DEP_FILES = new Set([
19
24
  "build.gradle.kts",
20
25
  "pom.xml",
21
26
  ]);
27
+ // Reports, notes and data the agent wrote for the user to read, not code to understand later.
28
+ const DOC_EXTS = new Set([".md", ".mdx", ".markdown", ".txt", ".rst", ".csv", ".tsv", ".log", ".json", ".html", ".pdf"]);
22
29
  const TEST_CMD = /\b(test|tests|jest|vitest|pytest|mocha|rspec|cargo test|go test|phpunit|tsc)\b/;
23
30
  const FAIL_TEXT = /\b(FAIL|FAILED|failed|Error:|error TS\d+|Traceback|panic:)\b/;
24
31
  function lineCount(s) {
@@ -31,12 +38,41 @@ function contentText(c) {
31
38
  return c.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("\n");
32
39
  return "";
33
40
  }
34
- export function detectTriggers(jsonl) {
35
- const largeWrites = new Set();
41
+ /** Files never worth capturing from, regardless of size. */
42
+ export function isIgnoredPath(file) {
43
+ const norm = file.split(path.sep).join("/");
44
+ if (norm.includes("/.claude/") || norm.includes("/.selflore/"))
45
+ return true;
46
+ const base = path.basename(file);
47
+ if (DEP_FILES.has(base))
48
+ return false;
49
+ return DOC_EXTS.has(path.extname(base).toLowerCase());
50
+ }
51
+ export function detectTriggers(jsonl, opts = {}) {
52
+ const minLines = opts.minLines ?? MIN_LINES.normal;
53
+ const added = new Map(); // largest single write per file
54
+ const edits = new Map();
36
55
  const depChanges = new Set();
37
56
  const testCmds = new Map(); // tool_use id -> is a test command
38
- // Sequence of events: "fail" | "pass" | "edit"
39
57
  const seq = [];
58
+ // An explanation: the user asks a question, the agent answers in prose, and no code is written
59
+ // before the user speaks again.
60
+ let explained = 0;
61
+ let asked = false;
62
+ let prose = 0;
63
+ let wrote = false;
64
+ const closeTurn = () => {
65
+ if (asked && !wrote && prose >= MIN_EXPLANATION_WORDS)
66
+ explained++;
67
+ };
68
+ const userSpoke = (text) => {
69
+ if (!text.trim() || text.startsWith("<"))
70
+ return; // tool output, reminders, pasted blocks
71
+ closeTurn();
72
+ asked = isQuestion(text);
73
+ prose = 0;
74
+ wrote = false;
75
+ };
40
76
  for (const raw of jsonl.split("\n")) {
41
77
  if (!raw.trim())
42
78
  continue;
@@ -48,28 +84,37 @@ export function detectTriggers(jsonl) {
48
84
  continue;
49
85
  }
50
86
  const content = line.message?.content;
87
+ if (line.type === "user" && !line.isMeta && typeof content === "string")
88
+ userSpoke(content);
51
89
  if (!Array.isArray(content))
52
90
  continue;
53
91
  for (const block of content) {
54
- if (block.type === "tool_use") {
92
+ if (block.type === "text" && typeof block.text === "string") {
93
+ if (line.type === "user" && !line.isMeta)
94
+ userSpoke(block.text);
95
+ else if (line.type === "assistant")
96
+ prose += block.text.split(/\s+/).filter(Boolean).length;
97
+ }
98
+ else if (block.type === "tool_use") {
55
99
  const tu = block;
56
100
  const input = tu.input ?? {};
57
101
  const file = typeof input.file_path === "string" ? input.file_path : "";
58
- if (file.includes(`${path.sep}.selflore${path.sep}`))
59
- continue;
60
- let added = 0;
61
- if (tu.name === "Write")
62
- added = lineCount(input.content);
63
- else if (tu.name === "Edit")
64
- added = lineCount(input.new_string) - lineCount(input.old_string);
65
- else if (tu.name === "MultiEdit" && Array.isArray(input.edits))
66
- added = input.edits.reduce((n, e) => n + lineCount(e.new_string) - lineCount(e.old_string), 0);
67
102
  if (["Write", "Edit", "MultiEdit"].includes(tu.name)) {
68
- if (added >= LARGE_WRITE_LINES)
69
- largeWrites.add(file);
103
+ if (!file || isIgnoredPath(file))
104
+ continue;
105
+ let n = 0;
106
+ if (tu.name === "Write")
107
+ n = lineCount(input.content);
108
+ else if (tu.name === "Edit")
109
+ n = lineCount(input.new_string) - lineCount(input.old_string);
110
+ else if (Array.isArray(input.edits))
111
+ n = input.edits.reduce((sum, e) => sum + lineCount(e.new_string) - lineCount(e.old_string), 0);
112
+ added.set(file, Math.max(added.get(file) ?? 0, n));
113
+ edits.set(file, (edits.get(file) ?? 0) + 1);
70
114
  if (DEP_FILES.has(path.basename(file)))
71
115
  depChanges.add(file);
72
- seq.push("edit");
116
+ seq.push({ ev: "edit", file });
117
+ wrote = true;
73
118
  }
74
119
  else if (tu.name === "Bash" && typeof input.command === "string") {
75
120
  testCmds.set(tu.id, TEST_CMD.test(input.command));
@@ -82,47 +127,170 @@ export function detectTriggers(jsonl) {
82
127
  if (!testCmds.get(id))
83
128
  continue;
84
129
  const failed = block.is_error === true || FAIL_TEXT.test(contentText(block.content));
85
- seq.push(failed ? "fail" : "pass");
130
+ seq.push({ ev: failed ? "fail" : "pass" });
86
131
  }
87
132
  }
88
133
  }
89
- // fail → (edit)+ → pass
134
+ closeTurn();
135
+ const largeWrites = [...added]
136
+ .filter(([file, n]) => n >= minLines && (opts.keepWrite?.({ file, editCount: edits.get(file) ?? 1 }) ?? true))
137
+ .map(([file]) => file);
138
+ // fail → (edit)+ → pass, as many times as it happens; the files edited inside a loop are what was fought with.
90
139
  let bugFixLoop = false;
140
+ const loopFiles = new Set();
91
141
  let state = "idle";
92
- for (const ev of seq) {
93
- if (ev === "fail")
94
- state = "failed";
95
- else if (ev === "edit" && state !== "idle")
142
+ let current = [];
143
+ for (const { ev, file } of seq) {
144
+ if (ev === "fail") {
145
+ if (state === "idle")
146
+ current = [];
147
+ state = state === "edited" ? "edited" : "failed";
148
+ }
149
+ else if (ev === "edit" && state !== "idle") {
96
150
  state = "edited";
97
- else if (ev === "pass" && state === "edited") {
98
- bugFixLoop = true;
99
- break;
151
+ if (file)
152
+ current.push(file);
100
153
  }
101
- else if (ev === "pass")
154
+ else if (ev === "pass") {
155
+ if (state === "edited") {
156
+ bugFixLoop = true;
157
+ for (const f of current)
158
+ loopFiles.add(f);
159
+ }
102
160
  state = "idle";
161
+ current = [];
162
+ }
103
163
  }
104
- return { largeWrites: [...largeWrites], depChanges: [...depChanges], bugFixLoop };
164
+ return { largeWrites, depChanges: [...depChanges], bugFixLoop, loopFiles: [...loopFiles], explained, edited: [...edits.keys()] };
105
165
  }
106
166
  export function anyTrigger(t) {
107
- return t.largeWrites.length > 0 || t.depChanges.length > 0 || t.bugFixLoop;
167
+ return t.largeWrites.length > 0 || t.depChanges.length > 0 || t.bugFixLoop || t.explained > 0;
108
168
  }
109
169
  export function describeTriggers(t) {
110
170
  const parts = [];
111
171
  if (t.largeWrites.length)
112
- parts.push(`large writes (${t.largeWrites.map((f) => path.basename(f)).join(", ")})`);
172
+ parts.push(`changes to ${t.largeWrites.map((f) => path.basename(f)).join(", ")}`);
113
173
  if (t.depChanges.length)
114
174
  parts.push("new dependencies");
115
175
  if (t.bugFixLoop)
116
176
  parts.push("a fail → fix → pass loop");
177
+ if (t.explained)
178
+ parts.push(t.explained === 1 ? "an explanation the user asked for" : `${t.explained} explanations the user asked for`);
117
179
  return parts.join("; ");
118
180
  }
119
- export function readTranscript(file) {
181
+ /**
182
+ * Read the transcript from a byte offset (optionally up to `to`), ending at the last complete line.
183
+ * Returns the text plus the actual start and the offset to resume from. A shrunk file restarts at 0.
184
+ */
185
+ export function readTranscriptFrom(file, from, to) {
120
186
  if (!file)
121
- return "";
187
+ return { text: "", start: from, end: from };
188
+ let size;
122
189
  try {
123
- return fs.readFileSync(file, "utf8");
190
+ size = fs.statSync(file).size;
124
191
  }
125
192
  catch {
126
- return "";
193
+ return { text: "", start: from, end: from };
194
+ }
195
+ const start = from > size ? 0 : from;
196
+ const stop = to !== undefined && to > start ? Math.min(to, size) : size;
197
+ if (stop <= start)
198
+ return { text: "", start, end: start };
199
+ const fd = fs.openSync(file, "r");
200
+ try {
201
+ const buf = Buffer.alloc(stop - start);
202
+ fs.readSync(fd, buf, 0, buf.length, start);
203
+ const lastNl = buf.lastIndexOf(0x0a);
204
+ if (lastNl < 0)
205
+ return { text: "", start, end: start };
206
+ return { text: buf.subarray(0, lastNl + 1).toString("utf8"), start, end: start + lastNl + 1 };
207
+ }
208
+ finally {
209
+ fs.closeSync(fd);
210
+ }
211
+ }
212
+ /** Model id of the most recent assistant message in a transcript chunk, if any. */
213
+ export function lastModel(jsonl) {
214
+ let model = null;
215
+ for (const raw of jsonl.split("\n")) {
216
+ if (!raw.includes('"model"'))
217
+ continue;
218
+ try {
219
+ const line = JSON.parse(raw);
220
+ if (line.type === "assistant" && typeof line.message?.model === "string" && !line.message.model.startsWith("<"))
221
+ model = line.message.model;
222
+ }
223
+ catch {
224
+ // ignore
225
+ }
226
+ }
227
+ return model;
228
+ }
229
+ const MAX_BLOCK_LINES = 60;
230
+ function clip(s, maxLines = MAX_BLOCK_LINES) {
231
+ const lines = s.split("\n");
232
+ return lines.length <= maxLines ? s : `${lines.slice(0, maxLines).join("\n")}\n… (${lines.length - maxLines} more lines)`;
233
+ }
234
+ /**
235
+ * A compact, readable excerpt of a transcript chunk for the capture model:
236
+ * user prompts, assistant prose, and tool calls with paths and (clipped) code.
237
+ * Keeps the most recent `maxChars` if the chunk is long.
238
+ */
239
+ export function buildExcerpt(jsonl, maxChars = 60_000) {
240
+ const out = [];
241
+ const bashIds = new Set();
242
+ for (const raw of jsonl.split("\n")) {
243
+ if (!raw.trim())
244
+ continue;
245
+ let line;
246
+ try {
247
+ line = JSON.parse(raw);
248
+ }
249
+ catch {
250
+ continue;
251
+ }
252
+ if (line.isMeta)
253
+ continue;
254
+ const content = line.message?.content;
255
+ if (line.type === "user") {
256
+ if (typeof content === "string") {
257
+ if (!content.startsWith("<"))
258
+ out.push(`USER: ${clip(content, 40)}`);
259
+ continue;
260
+ }
261
+ if (!Array.isArray(content))
262
+ continue;
263
+ for (const b of content) {
264
+ if (b.type === "text" && typeof b.text === "string" && !b.text.startsWith("<"))
265
+ out.push(`USER: ${clip(b.text, 40)}`);
266
+ else if (b.type === "tool_result" && bashIds.has(String(b.tool_use_id))) {
267
+ const text = contentText(b.content);
268
+ if (b.is_error === true || FAIL_TEXT.test(text))
269
+ out.push(`RESULT (failed): ${clip(text, 20)}`);
270
+ }
271
+ }
272
+ }
273
+ else if (line.type === "assistant" && Array.isArray(content)) {
274
+ for (const b of content) {
275
+ if (b.type === "text" && typeof b.text === "string" && b.text.trim())
276
+ out.push(`ASSISTANT: ${clip(b.text, 40)}`);
277
+ else if (b.type === "tool_use") {
278
+ const input = (b.input ?? {});
279
+ const file = typeof input.file_path === "string" ? input.file_path : "";
280
+ if (b.name === "Write" && file && !isIgnoredPath(file))
281
+ out.push(`WRITE ${file}:\n${clip(String(input.content ?? ""))}`);
282
+ else if (b.name === "Edit" && file && !isIgnoredPath(file))
283
+ out.push(`EDIT ${file}:\n- ${clip(String(input.old_string ?? ""), 20)}\n+ ${clip(String(input.new_string ?? ""))}`);
284
+ else if (b.name === "MultiEdit" && file && !isIgnoredPath(file) && Array.isArray(input.edits))
285
+ out.push(`EDIT ${file}:\n${input.edits.map((e) => `+ ${clip(String(e.new_string ?? ""), 30)}`).join("\n")}`);
286
+ else if (b.name === "Bash" && typeof input.command === "string") {
287
+ bashIds.add(String(b.id));
288
+ out.push(`RUN: ${clip(input.command, 5)}`);
289
+ }
290
+ }
291
+ }
292
+ }
127
293
  }
294
+ const text = out.join("\n\n");
295
+ return text.length <= maxChars ? text : `… (earlier work omitted)\n\n${text.slice(text.length - maxChars)}`;
128
296
  }
package/dist/lib/ui.js ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Terminal styling for the human-facing CLI (`selflore …`). No dependencies.
3
+ *
4
+ * Only `cli.ts` and `init.ts` use this. Hooks and `sl` print text that Claude reads, so they stay plain.
5
+ * Colour goes to a real terminal only, never when NO_COLOR is set, and steps down from 24-bit to
6
+ * 256 colours to the basic 16, so piped output is clean and old terminals still get a readable mark.
7
+ */
8
+ export function colorLevel({ env = process.env, isTTY = !!process.stdout.isTTY } = {}) {
9
+ if ("NO_COLOR" in env)
10
+ return 0;
11
+ const force = env.FORCE_COLOR;
12
+ if (force !== undefined) {
13
+ if (force === "0" || force === "false")
14
+ return 0;
15
+ return force === "3" ? 3 : force === "2" ? 2 : 1;
16
+ }
17
+ if (!isTTY || env.TERM === "dumb")
18
+ return 0;
19
+ if (/truecolor|24bit/i.test(env.COLORTERM ?? ""))
20
+ return 3;
21
+ return /256/.test(env.TERM ?? "") ? 2 : 1;
22
+ }
23
+ // ANSI Shadow, six rows a letter. Kept per letter so the word is readable here and checkable in a test.
24
+ const GLYPHS = {
25
+ s: ["███████╗", "██╔════╝", "███████╗", "╚════██║", "███████║", "╚══════╝"],
26
+ e: ["███████╗", "██╔════╝", "█████╗ ", "██╔══╝ ", "███████╗", "╚══════╝"],
27
+ l: ["██╗ ", "██║ ", "██║ ", "██║ ", "███████╗", "╚══════╝"],
28
+ f: ["███████╗", "██╔════╝", "█████╗ ", "██╔══╝ ", "██║ ", "╚═╝ "],
29
+ o: [" ██████╗ ", "██╔═══██╗", "██║ ██║", "██║ ██║", "╚██████╔╝", " ╚═════╝ "],
30
+ r: ["██████╗ ", "██╔══██╗", "██████╔╝", "██╔══██╗", "██║ ██║", "╚═╝ ╚═╝"],
31
+ };
32
+ /** The big wordmark, one string per row, every row the same width. */
33
+ export const WORDMARK = [0, 1, 2, 3, 4, 5].map((row) => Array.from("selflore", (c) => GLYPHS[c][row]).join(""));
34
+ /** Columns the banner needs: the wordmark plus its left margin. */
35
+ export const BANNER_WIDTH = WORDMARK[0].length + 4;
36
+ export const TAGLINE = "your agent wrote it, selflore remembers why";
37
+ /**
38
+ * The wordmark's colours, left to right: the notes page's indigo accent over "self", then its heat
39
+ * scale (amber up to the red of a stuck note) over "lore". All mid-tones, so the word holds on a
40
+ * light terminal as well as a dark one.
41
+ */
42
+ const WORD = [
43
+ [129, 140, 248],
44
+ [150, 150, 220],
45
+ [236, 160, 60],
46
+ [248, 118, 48],
47
+ [255, 92, 66],
48
+ ];
49
+ const ACCENT = [129, 140, 248];
50
+ const AMBER = [232, 150, 50];
51
+ const GREEN = [52, 199, 142];
52
+ function sample(stops, t) {
53
+ const seg = Math.min(1, Math.max(0, t)) * (stops.length - 1);
54
+ const i = Math.min(stops.length - 2, Math.floor(seg));
55
+ const f = seg - i;
56
+ const a = stops[i];
57
+ const b = stops[i + 1];
58
+ return [0, 1, 2].map((k) => Math.round(a[k] + (b[k] - a[k]) * f));
59
+ }
60
+ /** Nearest entry in the 6×6×6 colour cube of a 256-colour terminal. */
61
+ function cube([r, g, b]) {
62
+ // The cube's levels are 0, 95, 135, 175, 215, 255.
63
+ const step = (v) => (v < 48 ? 0 : Math.max(1, Math.round((v - 55) / 40)));
64
+ return 16 + 36 * step(r) + 6 * step(g) + step(b);
65
+ }
66
+ export function createUi(opts = {}) {
67
+ const isTTY = opts.isTTY ?? !!process.stdout.isTTY;
68
+ const level = colorLevel({ env: opts.env, isTTY });
69
+ const columns = opts.columns ?? process.stdout.columns ?? (Number((opts.env ?? process.env).COLUMNS) || 0);
70
+ const sgr = (open, close) => (s) => (level ? `\x1b[${open}m${s}\x1b[${close}m` : s);
71
+ /** The escape that sets the text colour, at whatever depth this terminal has. */
72
+ const fg = (c, basic) => (level === 3 ? `38;2;${c[0]};${c[1]};${c[2]}` : level === 2 ? `38;5;${cube(c)}` : String(basic));
73
+ const ink = (c, basic) => sgr(fg(c, basic), 39);
74
+ const bold = sgr("1", 22);
75
+ const dim = sgr("2", 22);
76
+ const accent = ink(ACCENT, 94);
77
+ const amber = ink(AMBER, 33);
78
+ const green = ink(GREEN, 32);
79
+ /** Colour each character by its column: indigo at the left, the hottest red at column `span`. */
80
+ function gradient(s, span = s.length) {
81
+ if (!level)
82
+ return s;
83
+ let out = "\x1b[1m";
84
+ let last = "";
85
+ Array.from(s).forEach((ch, i) => {
86
+ if (ch !== " ") {
87
+ const t = span <= 1 ? 0 : i / (span - 1);
88
+ // With only 16 colours the word still splits the same way: blue "self", then yellow into red.
89
+ const code = fg(sample(WORD, t), t < 0.42 ? 94 : t < 0.8 ? 33 : 91);
90
+ if (code !== last)
91
+ out += `\x1b[${code}m`;
92
+ last = code;
93
+ }
94
+ out += ch;
95
+ });
96
+ return `${out}\x1b[39m\x1b[22m`;
97
+ }
98
+ const symbols = { ok: green("✓"), spark: amber("✦"), warn: amber("!"), dot: dim("·") };
99
+ const wide = columns === 0 || columns >= BANNER_WIDTH;
100
+ function banner(version) {
101
+ const width = WORDMARK[0].length;
102
+ const mark = wide
103
+ ? WORDMARK.map((line) => ` ${gradient(line.trimEnd(), width)}`).join("\n")
104
+ : ` ${gradient("✦ s e l f l o r e")}`;
105
+ const tail = version ? ` ${symbols.dot} ${dim(`v${version}`)}` : "";
106
+ return `\n${mark}\n ${dim(TAGLINE)}${tail}\n`;
107
+ }
108
+ function header(label) {
109
+ return ` ${symbols.spark} ${gradient("selflore")}${label ? ` ${dim(label)}` : ""}`;
110
+ }
111
+ function row(command, description, width = 30) {
112
+ return ` ${accent(command.padEnd(width))}${dim(description)}`;
113
+ }
114
+ function frame(label, body) {
115
+ if (!isTTY)
116
+ return body;
117
+ const lines = body.split("\n");
118
+ // A short result sits under the name; a long listing keeps nearly the full width.
119
+ const pad = lines.length <= 6 ? " " : " ";
120
+ return `\n${header(label)}\n\n${lines.map((l) => (l ? pad + l : l)).join("\n")}\n`;
121
+ }
122
+ return { level, bold, dim, accent, amber, green, wordmark: gradient, symbols, banner, header, row, frame };
123
+ }
124
+ /** Strip colour codes, for measuring or comparing what was printed. */
125
+ export function plain(s) {
126
+ return s.replace(/\x1b\[[0-9;]*m/g, "");
127
+ }
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // Local notes server, started detached by `selflore notes`: serves the notes page and records
3
+ // answers from the in-page test. Prints its port once, then exits after a while with no requests.
4
+ import { randomBytes } from "node:crypto";
5
+ import fs from "node:fs";
6
+ import { writeJson } from "./lib/fsutil.js";
7
+ import { paths } from "./lib/paths.js";
8
+ import { createNotesServer } from "./lib/server.js";
9
+ const IDLE_MS = Number(process.env.SELFLORE_SERVER_IDLE_MS) || 30 * 60 * 1000;
10
+ const token = randomBytes(16).toString("hex");
11
+ let timer;
12
+ function shutdown() {
13
+ try {
14
+ const state = JSON.parse(fs.readFileSync(paths.serverState(), "utf8"));
15
+ if (state.pid === process.pid)
16
+ fs.rmSync(paths.serverState(), { force: true });
17
+ }
18
+ catch {
19
+ // no state file to clean up
20
+ }
21
+ process.exit(0);
22
+ }
23
+ function touch() {
24
+ if (timer)
25
+ clearTimeout(timer);
26
+ timer = setTimeout(shutdown, IDLE_MS);
27
+ }
28
+ const server = createNotesServer({ token, onRequest: touch });
29
+ server.on("error", () => process.exit(1));
30
+ server.listen(0, "127.0.0.1", () => {
31
+ const address = server.address();
32
+ const port = address && typeof address === "object" ? address.port : 0;
33
+ writeJson(paths.serverState(), { port, pid: process.pid, token });
34
+ touch();
35
+ // The parent reads this line, then stops listening; nothing is written to stdout after it.
36
+ process.stdout.write(`${port}\n`);
37
+ });
38
+ process.on("SIGTERM", shutdown);
39
+ process.on("SIGINT", shutdown);
package/dist/sl.js CHANGED
@@ -1,17 +1,24 @@
1
1
  #!/usr/bin/env node
2
2
  // Data CLI the selflore skill calls for bookkeeping that must be exact.
3
3
  import { readStdin } from "./hooks/io.js";
4
- import { addEntry, finishTest, listCmd, notesCmd, quizInput, recordCmd, statsCmd, suppressCmd, } from "./lib/commands.js";
4
+ import { addEntry, finishTest, heatCmd, recallCmd, showCmd, focusArgs, focusCmd, listCmd, notesCmd, quizInput, recordCmd, statsCmd, suppressCmd, } from "./lib/commands.js";
5
5
  const USAGE = `usage: sl <command>
6
- entry add --session <id> [--manual] read entry markdown from stdin and store it
7
- entry replace <id> --session <id> swap a weaker entry from this session for the one on stdin
6
+ entry add --session <id> read entry markdown from stdin and store it (merges near-duplicates)
8
7
  entry list [--session <id>]
9
- quiz-input JSON of fresh entries + due retests
8
+ recall "<question>" [--project <name> | --all] [--limit n] [--json]
9
+ the notes that best answer a question (this project unless told otherwise)
10
+ show <id> [--session <id>] one note in full, and whether its files changed since it was captured;
11
+ with a session id, records that the note was used to answer the user
12
+ quiz-input [--project <name>] [--topic <name>] [--query "<anything>"]
13
+ JSON of what was missed last time + untested entries; with a scope, that cluster only;
14
+ with --query, the notes that best match those words (at most 5 questions)
10
15
  record --entry <id> --grade got|partial|missed --type <question-type>
11
16
  suppress <id> flag an entry as unfair; never test it again
12
17
  finish-test
13
18
  stats [--project <name>]
14
- notes [--all] [--project <name>] [--text] open the notes page (or print text)`;
19
+ heat [--project <name>] [--json] where the user gets stuck: the hottest project + topic areas, and why
20
+ notes [--all] [--project <name>] [--text] open the notes page, with an in-page test (or print text)
21
+ focus [details|design|mixed] [--balance design|balanced|details] [--project] [--reset]`;
15
22
  function flag(args, name) {
16
23
  const i = args.indexOf(`--${name}`);
17
24
  return i >= 0 ? args[i + 1] : undefined;
@@ -24,22 +31,30 @@ async function main(argv) {
24
31
  const session = flag(args, "session");
25
32
  if (sub === "list")
26
33
  return listCmd(session);
27
- if (sub !== "add" && sub !== "replace")
34
+ if (sub !== "add")
28
35
  break;
29
36
  if (!session)
30
37
  return { code: 1, out: "missing --session <id> (it is in the session context as selflore session_id=…)" };
31
- const replace = sub === "replace" ? rest[0] : undefined;
32
- if (sub === "replace" && (!replace || replace.startsWith("--")))
33
- return { code: 1, out: "usage: entry replace <id> --session <id>" };
34
- return addEntry(await readStdin(), {
35
- session,
38
+ return addEntry(await readStdin(), { session, cwd: process.cwd() });
39
+ }
40
+ case "recall": {
41
+ const flags = new Set(["--project", "--limit"]);
42
+ const text = args.filter((a, i) => !a.startsWith("--") && !flags.has(args[i - 1] ?? "")).join(" ");
43
+ const limit = Number(flag(args, "limit"));
44
+ return recallCmd(text, {
36
45
  cwd: process.cwd(),
37
- manual: args.includes("--manual"),
38
- replace,
46
+ project: flag(args, "project"),
47
+ all: args.includes("--all"),
48
+ limit: Number.isFinite(limit) && limit > 0 ? limit : undefined,
49
+ json: args.includes("--json"),
39
50
  });
40
51
  }
52
+ case "show":
53
+ if (!sub)
54
+ break;
55
+ return showCmd(sub, { cwd: process.cwd(), session: flag(args, "session") });
41
56
  case "quiz-input":
42
- return quizInput();
57
+ return quizInput(new Date(), { project: flag(args, "project"), topic: flag(args, "topic") ?? flag(args, "skill"), query: flag(args, "query") });
43
58
  case "record": {
44
59
  const entry = flag(args, "entry");
45
60
  const grade = flag(args, "grade");
@@ -54,8 +69,12 @@ async function main(argv) {
54
69
  return suppressCmd(sub);
55
70
  case "finish-test":
56
71
  return finishTest();
72
+ case "heat":
73
+ return heatCmd({ project: flag(args, "project"), json: args.includes("--json") });
57
74
  case "stats":
58
75
  return statsCmd(flag(args, "project"));
76
+ case "focus":
77
+ return focusCmd(focusArgs(args));
59
78
  case "notes":
60
79
  return notesCmd({ all: args.includes("--all"), project: flag(args, "project"), text: args.includes("--text") });
61
80
  }