selflore 0.1.0 → 0.3.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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -32
  3. package/dist/cli.js +81 -19
  4. package/dist/hooks/user-prompt-submit.js +2 -1
  5. package/dist/init.js +29 -11
  6. package/dist/lib/background.js +23 -4
  7. package/dist/lib/capture-prompt.js +13 -7
  8. package/dist/lib/commands.js +199 -35
  9. package/dist/lib/config.js +23 -3
  10. package/dist/lib/entries.js +56 -4
  11. package/dist/lib/heat.js +141 -0
  12. package/dist/lib/hook-logic.js +44 -9
  13. package/dist/lib/index-cache.js +46 -0
  14. package/dist/lib/links.js +58 -0
  15. package/dist/lib/logo.js +6 -0
  16. package/dist/lib/notes-graph.js +585 -0
  17. package/dist/lib/notes-html.js +149 -340
  18. package/dist/lib/notes-page-css.js +279 -0
  19. package/dist/lib/notes-page-js.js +959 -0
  20. package/dist/lib/notes.js +19 -13
  21. package/dist/lib/nudge.js +2 -1
  22. package/dist/lib/paths.js +6 -0
  23. package/dist/lib/question.js +19 -0
  24. package/dist/lib/queue.js +6 -4
  25. package/dist/lib/recall.js +149 -0
  26. package/dist/lib/results.js +1 -0
  27. package/dist/lib/retag.js +150 -0
  28. package/dist/lib/server-launch.js +73 -0
  29. package/dist/lib/server.js +120 -0
  30. package/dist/lib/session.js +1 -1
  31. package/dist/lib/signals.js +51 -0
  32. package/dist/lib/stats.js +71 -44
  33. package/dist/lib/struggle.js +120 -0
  34. package/dist/lib/surface.js +75 -0
  35. package/dist/lib/transcript.js +61 -15
  36. package/dist/lib/ui.js +127 -0
  37. package/dist/notes-server.js +39 -0
  38. package/dist/sl.js +29 -4
  39. package/dist/vendor/graph3d.js +5402 -0
  40. package/package.json +11 -4
  41. package/skill/SKILL.md +6 -5
  42. package/skill/references/capture.md +6 -5
  43. package/skill/references/recall.md +44 -0
  44. package/skill/references/stats.md +5 -1
  45. package/skill/references/test.md +35 -30
package/dist/lib/notes.js CHANGED
@@ -10,23 +10,29 @@ export function weekStart(now) {
10
10
  d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
11
11
  return localDate(d);
12
12
  }
13
- /** Untested entries older than this leave the quiz pool (they stay visible in notes as "stale"). */
14
- export const STALE_AFTER_DAYS = 21;
15
- export function staleBefore(now) {
16
- return localDate(new Date(now.getTime() - STALE_AFTER_DAYS * 86_400_000));
13
+ /**
14
+ * Local Monday of the week an entry date (YYYY-MM-DD) or a timestamp falls in. Entry dates are
15
+ * local calendar days, so a date-only string is read as that local day, never as UTC midnight.
16
+ */
17
+ export function weekOfDate(d) {
18
+ if (typeof d === "string" && /^\d{4}-\d{2}-\d{2}$/.test(d)) {
19
+ const [y, m, day] = d.split("-").map(Number);
20
+ return weekStart(new Date(y, m - 1, day));
21
+ }
22
+ return weekStart(new Date(d));
17
23
  }
18
- export function entryStatus(e, tested, queue, now = new Date()) {
24
+ export function entryStatus(e, tested, queue) {
19
25
  if (e.suppressed)
20
- return { status: "suppressed", retest_due: null };
26
+ return { status: "suppressed" };
21
27
  if (queue[e.id])
22
- return { status: "retest", retest_due: queue[e.id].due[0] ?? null };
28
+ return { status: "retest" };
23
29
  if (tested.has(e.id))
24
- return { status: "tested", retest_due: null };
25
- return { status: e.date < staleBefore(now) ? "stale" : "untested", retest_due: null };
30
+ return { status: "tested" };
31
+ return { status: "untested" };
26
32
  }
27
- function status(e, tested, queue, now) {
28
- const s = entryStatus(e, tested, queue, now);
29
- return s.status === "retest" ? `retest ${s.retest_due?.slice(0, 10) ?? ""}`.trim() : s.status;
33
+ function status(e, tested, queue) {
34
+ const s = entryStatus(e, tested, queue).status;
35
+ return s === "retest" ? "to revisit" : s;
30
36
  }
31
37
  /** Plain-text list of captured entries, grouped by day. Defaults to the current week. */
32
38
  export function renderNotes({ entries, tested, queue, now, all, project }) {
@@ -48,7 +54,7 @@ export function renderNotes({ entries, tested, queue, now, all, project }) {
48
54
  }
49
55
  const { prose, snippet } = splitBody(e.body);
50
56
  const where = [e.project, e.paths.join(", ")].filter(Boolean).join(" · ");
51
- out.push(` • [${e.kind} · ${e.level} · ${e.skill}] ${where} (${status(e, tested, queue, now)})`);
57
+ out.push(` • [${e.kind} · ${e.level} · ${e.topics.join(", ")}] ${where} (${status(e, tested, queue)})`);
52
58
  out.push(` Q: ${e.testable}`);
53
59
  for (const line of prose.split("\n"))
54
60
  if (line.trim())
package/dist/lib/nudge.js CHANGED
@@ -16,7 +16,8 @@ export function sessionStartContext(sessionId, config, oldestEntryDate, now) {
16
16
  if (sessionId)
17
17
  lines.push(`selflore session_id=${sessionId}`);
18
18
  lines.push(CAPTURE_LINE[config.capture]);
19
- if (config.nudge && testOverdue(config, oldestEntryDate, now))
19
+ // The weekly test is on by default; turning it off in `init`, or turning off its reminder, silences this.
20
+ if (config.cadence === "weekly" && config.nudge && testOverdue(config, oldestEntryDate, now))
20
21
  lines.push("selflore: weekly test overdue — mention once that the user can run /selflore test (~20 min).");
21
22
  return lines.join("\n");
22
23
  }
package/dist/lib/paths.js CHANGED
@@ -12,9 +12,15 @@ export const paths = {
12
12
  entries: () => path.join(selfloreHome(), "entries"),
13
13
  results: () => path.join(selfloreHome(), "results.jsonl"),
14
14
  queue: () => path.join(selfloreHome(), "queue.json"),
15
+ signals: () => path.join(selfloreHome(), "signals.jsonl"),
16
+ index: () => path.join(selfloreHome(), "state", "index.json"),
17
+ pendingOffers: () => path.join(selfloreHome(), "state", "_offers.json"),
15
18
  state: () => path.join(selfloreHome(), "state"),
19
+ backups: () => path.join(selfloreHome(), "backups"),
20
+ retagProposal: () => path.join(selfloreHome(), "state", "retag-proposal.json"),
16
21
  app: () => path.join(selfloreHome(), "app"),
17
22
  notesHtml: () => path.join(selfloreHome(), "notes.html"),
23
+ serverState: () => path.join(selfloreHome(), "state", "server.json"),
18
24
  skill: () => path.join(claudeHome(), "skills", "selflore"),
19
25
  settings: () => path.join(claudeHome(), "settings.json"),
20
26
  };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Is this prompt a question about how or why something works, rather than a task?
3
+ * Cheap pattern matching only: it runs on every prompt, and a miss just means selflore stays quiet.
4
+ */
5
+ const MAX_CHARS = 1500; // longer prompts are specs or pasted logs, not a question
6
+ // "Can you add a retry?" ends in a question mark and is a task.
7
+ const TASK = /^(?:please\s+)?(?:can|could|would|will)\s+(?:you|we)\s+(?:please\s+)?(?:just\s+)?(?:add|fix|make|create|write|update|change|remove|delete|implement|refactor|rename|run|build|install|move|convert|set\s?up|generate|deploy|commit|push|merge|bump|clean|format|test|open|start|stop|revert|undo|apply|try|do|go|take|use|put|show me the (?:diff|output|logs?))\b/i;
8
+ const OPENER = /^(?:ok(?:ay)?[,.]?\s+|so[,]?\s+|hey[,]?\s+|wait[,.]?\s+|hmm+[,.]?\s+)*(?:why|how|what|where|when|which|who|explain|describe|remind me|walk me through|tell me (?:about|why|how|what)|help me understand|can you (?:explain|remind|tell me|walk me)|could you (?:explain|remind|tell me|walk me))\b/i;
9
+ const PHRASE = /\b(?:don'?t understand|do not understand|didn'?t understand|never understood|confused (?:by|about)|makes? no sense|not sure (?:why|how)|no idea (?:why|how)|can'?t figure out (?:why|how)|keep(?:s)? (?:hitting|getting|running into)|what does \S.{0,60}? (?:do|mean)|how does \S.{0,60}? work)\b/i;
10
+ export function isQuestion(prompt) {
11
+ const text = (prompt ?? "").trim();
12
+ if (!text || text.length > MAX_CHARS)
13
+ return false;
14
+ if (text.startsWith("/") || text.startsWith("<") || text.startsWith("!"))
15
+ return false; // commands, pasted blocks
16
+ if (TASK.test(text))
17
+ return false;
18
+ return text.endsWith("?") || OPENER.test(text) || PHRASE.test(text.slice(0, 400));
19
+ }
package/dist/lib/queue.js CHANGED
@@ -35,10 +35,12 @@ export function applyGrade(queue, entryId, grade, now) {
35
35
  };
36
36
  return next;
37
37
  }
38
- export function dueItems(queue, now) {
39
- return Object.values(queue)
40
- .filter((q) => q.due.length > 0 && new Date(q.due[0]).getTime() <= now.getTime())
41
- .sort((a, b) => a.due[0].localeCompare(b.due[0]));
38
+ /**
39
+ * Everything waiting to be revisited, longest-waiting first. The dates in `due` are no longer a
40
+ * schedule: a missed question simply comes back first the next time its area is tested.
41
+ */
42
+ export function queuedItems(queue) {
43
+ return Object.values(queue).sort((a, b) => a.added_at.localeCompare(b.added_at) || a.entry_id.localeCompare(b.entry_id));
42
44
  }
43
45
  export function readQueue() {
44
46
  return readJson(paths.queue(), {});
@@ -0,0 +1,149 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { splitBody, words } from "./entries.js";
6
+ /**
7
+ * Recall: find the notes that answer a question asked in plain words, and say whether the code
8
+ * they describe has changed since. No model, no network: word overlap weighted by how rare each
9
+ * word is, so it is cheap enough to run on every prompt.
10
+ */
11
+ /** "retries", "retrying" and "retry" are the same word to someone asking a question. */
12
+ export function stem(w) {
13
+ if (w.length > 5 && w.endsWith("ing"))
14
+ return w.slice(0, -3);
15
+ if (w.length > 4 && w.endsWith("ies"))
16
+ return `${w.slice(0, -3)}y`;
17
+ if (w.length > 4 && w.endsWith("ed"))
18
+ return w.slice(0, -2);
19
+ if (w.length > 3 && w.endsWith("s") && !w.endsWith("ss"))
20
+ return w.slice(0, -1);
21
+ return w;
22
+ }
23
+ /** Content words of a text, stemmed: 3+ characters, no question scaffolding. camelCase and paths are split. */
24
+ export function terms(text) {
25
+ const spaced = text.replace(/([a-z0-9])([A-Z])/g, "$1 $2");
26
+ return [...new Set([...words(spaced)].flatMap((w) => w.split("_")).filter((w) => w.length > 2).map(stem))];
27
+ }
28
+ export function toDoc(e) {
29
+ return {
30
+ id: e.id,
31
+ project: e.project,
32
+ date: e.date,
33
+ topics: e.topics,
34
+ paths: e.paths,
35
+ testable: e.testable,
36
+ tw: terms(e.topics.join(" ")),
37
+ pw: terms(e.paths.join(" ")),
38
+ qw: terms(e.testable),
39
+ bw: terms(splitBody(e.body).prose),
40
+ };
41
+ }
42
+ // A word found in a topic or a path says more about what the note is about than one in its prose.
43
+ const W_TOPIC = 2;
44
+ const W_PATH = 2;
45
+ const W_QUESTION = 1.5;
46
+ const W_BODY = 0.75;
47
+ const W_MAX = 2;
48
+ export const RECALL_MIN = 0.3;
49
+ /**
50
+ * Rank notes against a query. The score is the share of the query's words found in the note,
51
+ * each word weighted by how rare it is among the candidates and by the field it was found in.
52
+ * One shared word is never enough unless the query is that short.
53
+ */
54
+ export function rank(query, docs, opts = {}) {
55
+ const pool = opts.project ? docs.filter((d) => d.project === opts.project) : docs;
56
+ const q = terms(query);
57
+ if (!q.length || !pool.length)
58
+ return [];
59
+ const df = new Map();
60
+ const fields = pool.map((d) => ({ d, t: new Set(d.tw), p: new Set(d.pw), q: new Set(d.qw), b: new Set(d.bw) }));
61
+ for (const f of fields)
62
+ for (const w of q)
63
+ if (f.t.has(w) || f.p.has(w) || f.q.has(w) || f.b.has(w))
64
+ df.set(w, (df.get(w) ?? 0) + 1);
65
+ const idf = (w) => Math.log(1 + pool.length / (1 + (df.get(w) ?? 0)));
66
+ const total = q.reduce((sum, w) => sum + idf(w) * W_MAX, 0);
67
+ const need = q.length >= 3 ? 2 : 1;
68
+ const hits = [];
69
+ for (const f of fields) {
70
+ let got = 0;
71
+ const matched = [];
72
+ for (const w of q) {
73
+ const weight = Math.max(f.t.has(w) ? W_TOPIC : 0, f.p.has(w) ? W_PATH : 0, f.q.has(w) ? W_QUESTION : 0, f.b.has(w) ? W_BODY : 0);
74
+ if (!weight)
75
+ continue;
76
+ got += idf(w) * weight;
77
+ matched.push(w);
78
+ }
79
+ if (matched.length < need)
80
+ continue;
81
+ const score = got / total;
82
+ if (score >= (opts.min ?? RECALL_MIN))
83
+ hits.push({ doc: f.d, score, matched });
84
+ }
85
+ return hits.sort((a, b) => b.score - a.score || b.doc.date.localeCompare(a.doc.date) || a.doc.id.localeCompare(b.doc.id)).slice(0, opts.limit ?? 5);
86
+ }
87
+ // ---- has the code moved on since the note was written? ----
88
+ function git(cwd, args) {
89
+ try {
90
+ return execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ }
96
+ /** Fingerprint of a set of files as they are now ("" when none of them exist). Stored on an entry at capture. */
97
+ export function fileSig(root, paths) {
98
+ const hash = createHash("sha1");
99
+ let any = false;
100
+ for (const p of [...paths].sort()) {
101
+ try {
102
+ const buf = fs.readFileSync(path.resolve(root, p));
103
+ hash.update(`${p}\0`).update(buf).update("\0");
104
+ any = true;
105
+ }
106
+ catch {
107
+ hash.update(`${p}\0missing\0`);
108
+ }
109
+ }
110
+ return any ? hash.digest("hex").slice(0, 12) : "";
111
+ }
112
+ /**
113
+ * Compare an entry with the code as it is now. `root` is the project folder the entry's paths are
114
+ * relative to; pass null when the current folder isn't that project.
115
+ * - Entries with a fingerprint: exact.
116
+ * - Older entries: any commit or uncommitted edit to their files after the capture date counts as
117
+ * changed. That errs toward "changed", which only costs a look at the file.
118
+ */
119
+ export function freshness(e, root) {
120
+ if (!root)
121
+ return { status: "unknown", detail: "this folder isn't the project the note is from" };
122
+ if (!e.paths.length)
123
+ return { status: "unknown", detail: "the note names no files" };
124
+ const present = e.paths.filter((p) => fs.existsSync(path.resolve(root, p)));
125
+ const gone = e.paths.filter((p) => !present.includes(p));
126
+ if (!present.length)
127
+ return { status: "missing", detail: `${gone.join(", ")} no longer ${gone.length === 1 ? "exists" : "exist"}` };
128
+ const goneNote = gone.length ? `; ${gone.join(", ")} no longer ${gone.length === 1 ? "exists" : "exist"}` : "";
129
+ if (e.sig) {
130
+ return fileSig(root, e.paths) === e.sig
131
+ ? { status: "unchanged", detail: "the files are as they were when this was captured" }
132
+ : { status: "changed", detail: `${present.join(", ")} changed since ${e.date}${goneNote}` };
133
+ }
134
+ const [y, m, d] = e.date.split("-").map(Number);
135
+ const dayAfter = new Date(y, m - 1, d + 1);
136
+ const commits = git(root, ["log", "--oneline", `--since=${dayAfter.toISOString()}`, "--", ...present]);
137
+ if (commits === null) {
138
+ const touched = present.filter((p) => fs.statSync(path.resolve(root, p)).mtime.getTime() >= dayAfter.getTime());
139
+ return touched.length || gone.length
140
+ ? { status: "changed", detail: `${touched.join(", ") || "files"} modified since ${e.date}${goneNote}` }
141
+ : { status: "unchanged", detail: `no file modified since ${e.date}` };
142
+ }
143
+ const n = commits ? commits.split("\n").length : 0;
144
+ const dirty = Boolean(git(root, ["status", "--porcelain", "--", ...present]));
145
+ if (!n && !dirty && !gone.length)
146
+ return { status: "unchanged", detail: `no commits to these files since ${e.date}` };
147
+ const why = [n ? `${n} ${n === 1 ? "commit" : "commits"} since ${e.date}` : "", dirty ? "uncommitted edits" : ""].filter(Boolean).join(" and ");
148
+ return { status: "changed", detail: `${present.join(", ")}: ${why || "see below"}${goneNote}` };
149
+ }
@@ -11,6 +11,7 @@ export const QUESTION_TYPES = [
11
11
  "rewrite-from-spec",
12
12
  "recall",
13
13
  ];
14
+ export const MAX_ANSWER_CHARS = 2000;
14
15
  export function appendResult(r) {
15
16
  fs.mkdirSync(path.dirname(paths.results()), { recursive: true });
16
17
  fs.appendFileSync(paths.results(), JSON.stringify(r) + "\n");
@@ -0,0 +1,150 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { askClaude, captureModel, knownTopics, parseCaptureReply } from "./background.js";
4
+ import { readConfig } from "./config.js";
5
+ import { GENERIC_TOPICS, listEntries, needsTopics, normalizeTopics, splitBody, writeEntry } from "./entries.js";
6
+ import { readJson, writeJson } from "./fsutil.js";
7
+ import { paths } from "./paths.js";
8
+ /**
9
+ * One-time re-tag: entries captured before topics existed are all "architecture" or "debugging".
10
+ * A dry run asks the capture model for real topics and saves the proposal; `--apply` backs the
11
+ * entries up and writes exactly that proposal, so what gets applied is what was shown.
12
+ */
13
+ export const RETAG_BATCH = 20;
14
+ const MAX_NOTE_WORDS = 70;
15
+ export function retagPrompt() {
16
+ return `You are selflore's re-tag step. You are given notes about work an AI agent did in a developer's codebases. Give each note 1 to 3 topics so the developer can find and group them.
17
+
18
+ Rules:
19
+ - The FIRST topic is the group the note sits in: the technology, framework, service or subsystem ("fastapi", "postgres", "stripe", "remotion", "claude code hooks", "notes server"). Notes are grouped by it, so keep these few and broad: a project with 30 notes should end up with roughly 4 to 8 distinct first topics, never one per note.
20
+ - The second and third topics, if any, are the concept ("retry logic", "idempotency", "race condition", "caching"). These can be more specific.
21
+ - Lowercase, short, the name a developer would search for. No file names, no sentences.
22
+ - Never a kind of work: not ${[...GENERIC_TOPICS].slice(0, 8).join(", ")}.
23
+ - Reuse a topic from "known topics" whenever it fits, spelled exactly, so one subject keeps one name. The number after each is how many notes use it; prefer the well-used ones, above all for the first topic.
24
+
25
+ Output ONLY a JSON array, no prose, no code fences, one element per note: {"id": "<id as given>", "topics": ["<technology>", "<concept>"]}`;
26
+ }
27
+ function clipWords(s, n) {
28
+ const w = s.split(/\s+/).filter(Boolean);
29
+ return w.length <= n ? w.join(" ") : `${w.slice(0, n).join(" ")} …`;
30
+ }
31
+ /** Known topics with their use counts, this project's first: "postgres (12)". */
32
+ function knownTopicCounts(project, entries) {
33
+ const counts = new Map();
34
+ for (const e of entries)
35
+ for (const t of e.topics)
36
+ counts.set(t, (counts.get(t) ?? 0) + 1);
37
+ return knownTopics(project, entries, 40).map((t) => `${t} (${counts.get(t)})`);
38
+ }
39
+ function batchInput(batch, known) {
40
+ const notes = batch.map((e) => ({
41
+ id: e.id,
42
+ project: e.project,
43
+ paths: e.paths.slice(0, 4),
44
+ question: e.testable,
45
+ note: clipWords(splitBody(e.body).prose, MAX_NOTE_WORDS),
46
+ }));
47
+ return `Known topics: ${known.length ? known.join(", ") : "(none yet)"}\n\nNotes:\n${JSON.stringify(notes, null, 1)}`;
48
+ }
49
+ /** Ask the model for topics, batch by batch, feeding the topics chosen so far back in. Writes nothing to entries. */
50
+ export function proposeRetag(opts = {}) {
51
+ const config = readConfig();
52
+ const ask = opts.ask ?? askClaude;
53
+ // There is no session to copy a model from; naming things doesn't need the largest one.
54
+ const model = captureModel(config, "sonnet");
55
+ const all = listEntries();
56
+ const todo = all.filter((e) => (!opts.project || e.project === opts.project) && (opts.all || needsTopics(e.topics)));
57
+ const size = opts.batch ?? RETAG_BATCH;
58
+ // Work on a copy so each batch sees the topics the earlier batches chose.
59
+ const working = new Map(all.map((e) => [e.id, { ...e }]));
60
+ const items = [];
61
+ // One project at a time, so a project's notes are named against each other.
62
+ const ordered = [...todo].sort((a, b) => a.project.localeCompare(b.project) || a.id.localeCompare(b.id));
63
+ for (let i = 0; i < ordered.length; i += size) {
64
+ const batch = ordered.slice(i, i + size);
65
+ const ids = new Set(batch.map((e) => e.id));
66
+ const known = knownTopicCounts(batch[0].project, [...working.values()].filter((e) => !ids.has(e.id)));
67
+ const reply = ask(retagPrompt(), batchInput(batch, known), model);
68
+ for (const raw of parseCaptureReply(reply)) {
69
+ const r = raw;
70
+ const entry = typeof r?.id === "string" ? working.get(r.id) : undefined;
71
+ if (!entry || !ids.has(entry.id))
72
+ continue;
73
+ const topics = normalizeTopics(r.topics);
74
+ if (!topics.length || needsTopics(topics))
75
+ continue; // the model had nothing better: leave the entry alone
76
+ if (topics.join("\n") === entry.topics.join("\n"))
77
+ continue;
78
+ items.push({ id: entry.id, from: entry.topics, topics });
79
+ entry.topics = topics;
80
+ ids.delete(entry.id);
81
+ }
82
+ opts.onBatch?.(Math.min(i + size, ordered.length), ordered.length);
83
+ }
84
+ return { generated_at: (opts.now ?? new Date()).toISOString(), items: items.sort((a, b) => a.id.localeCompare(b.id)) };
85
+ }
86
+ export function saveProposal(p) {
87
+ writeJson(paths.retagProposal(), p);
88
+ }
89
+ export function readProposal() {
90
+ const p = readJson(paths.retagProposal(), null);
91
+ return p && Array.isArray(p.items) ? p : null;
92
+ }
93
+ export function describeProposal(p, total) {
94
+ if (!p.items.length)
95
+ return "Nothing to re-tag: every entry already has a real topic.";
96
+ const counts = new Map();
97
+ for (const it of p.items)
98
+ for (const t of it.topics)
99
+ counts.set(t, (counts.get(t) ?? 0) + 1);
100
+ const top = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
101
+ const singles = top.filter(([, n]) => n === 1).length;
102
+ return [
103
+ `Proposed topics for ${p.items.length} of ${total} entries (${counts.size} distinct topics, ${singles} used once):`,
104
+ "",
105
+ ...top.slice(0, 40).map(([t, n]) => ` ${String(n).padStart(3)} ${t}`),
106
+ ...(top.length > 40 ? [` … and ${top.length - 40} more`] : []),
107
+ "",
108
+ ...p.items.slice(0, 12).map((it) => ` ${it.id}\n ${it.from.join(", ") || "(none)"} → ${it.topics.join(", ")}`),
109
+ ...(p.items.length > 12 ? [` … and ${p.items.length - 12} more in ${paths.retagProposal()}`] : []),
110
+ ].join("\n");
111
+ }
112
+ function timestamp(now) {
113
+ return now.toISOString().replace(/[:.]/g, "-");
114
+ }
115
+ /** Copy the entries folder aside, then write the proposal's topics. Entries that have gone are skipped. */
116
+ export function applyRetag(p, now = new Date()) {
117
+ const backup = path.join(paths.backups(), `entries-${timestamp(now)}`);
118
+ fs.mkdirSync(backup, { recursive: true });
119
+ for (const f of fs.readdirSync(paths.entries()))
120
+ fs.copyFileSync(path.join(paths.entries(), f), path.join(backup, f));
121
+ const byId = new Map(listEntries().map((e) => [e.id, e]));
122
+ let changed = 0;
123
+ for (const it of p.items) {
124
+ const e = byId.get(it.id);
125
+ const topics = normalizeTopics(it.topics);
126
+ if (!e || !topics.length)
127
+ continue;
128
+ writeEntry({ ...e, topics, skill: topics[0] });
129
+ changed++;
130
+ }
131
+ return { changed, backup };
132
+ }
133
+ /** `selflore retag`: propose (default), or `--apply` the saved proposal. */
134
+ export function retagCmd(opts = {}) {
135
+ const total = listEntries().length;
136
+ if (opts.apply) {
137
+ const p = readProposal();
138
+ if (!p)
139
+ return { code: 1, out: "No proposal to apply. Run `selflore retag` first; it shows the new topics without changing anything." };
140
+ if (!p.items.length)
141
+ return { code: 0, out: "Nothing to apply: the proposal is empty." };
142
+ const { changed, backup } = applyRetag(p, opts.now);
143
+ fs.rmSync(paths.retagProposal(), { force: true });
144
+ return { code: 0, out: `Re-tagged ${changed} ${changed === 1 ? "entry" : "entries"}. The old ones are in ${backup}` };
145
+ }
146
+ const p = proposeRetag(opts);
147
+ saveProposal(p);
148
+ const out = describeProposal(p, total);
149
+ return { code: 0, out: p.items.length ? `${out}\n\nNothing has changed yet. Run \`selflore retag --apply\` to write these (the entries are backed up first).` : out };
150
+ }
@@ -0,0 +1,73 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { readJson } from "./fsutil.js";
6
+ import { paths } from "./paths.js";
7
+ function alive(pid) {
8
+ try {
9
+ process.kill(pid, 0);
10
+ return true;
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ async function healthy(s) {
17
+ try {
18
+ const r = await fetch(`http://127.0.0.1:${s.port}/api/health`, {
19
+ headers: { "x-selflore-token": s.token },
20
+ signal: AbortSignal.timeout(1000),
21
+ });
22
+ return r.ok;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ /** The running notes server, if there is one and it answers. */
29
+ export async function runningServer() {
30
+ const s = readJson(paths.serverState(), null);
31
+ if (!s || !s.port || !s.pid || !s.token || !alive(s.pid))
32
+ return null;
33
+ return (await healthy(s)) ? s : null;
34
+ }
35
+ /** notes-server.js sits next to this file's parent: dist/lib/server-launch.js → dist/notes-server.js. */
36
+ function serverScript() {
37
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "notes-server.js");
38
+ }
39
+ /** Reuse the running notes server or start a detached one. Resolves to null if it can't start. */
40
+ export async function ensureServer(timeoutMs = 5000) {
41
+ const running = await runningServer();
42
+ if (running)
43
+ return running;
44
+ const script = serverScript();
45
+ if (!fs.existsSync(script))
46
+ return null;
47
+ return new Promise((resolve) => {
48
+ let done = false;
49
+ const finish = (v) => {
50
+ if (done)
51
+ return;
52
+ done = true;
53
+ clearTimeout(timer);
54
+ child.stdout?.destroy();
55
+ child.unref();
56
+ resolve(v);
57
+ };
58
+ const child = spawn(process.execPath, [script], { detached: true, stdio: ["ignore", "pipe", "ignore"] });
59
+ const timer = setTimeout(() => finish(null), timeoutMs);
60
+ let out = "";
61
+ child.on("error", () => finish(null));
62
+ child.on("exit", () => finish(null));
63
+ child.stdout?.setEncoding("utf8");
64
+ child.stdout?.on("data", (c) => {
65
+ out += c;
66
+ if (!out.includes("\n"))
67
+ return;
68
+ // The child wrote server.json before printing its port.
69
+ const s = readJson(paths.serverState(), null);
70
+ finish(s && s.port === Number(out.trim()) ? s : null);
71
+ });
72
+ });
73
+ }
@@ -0,0 +1,120 @@
1
+ import fs from "node:fs";
2
+ import http from "node:http";
3
+ import path from "node:path";
4
+ import { timingSafeEqual } from "node:crypto";
5
+ import { fileURLToPath } from "node:url";
6
+ import { buildWebQuiz, finishTest, recordCmd, suppressCmd } from "./commands.js";
7
+ import { buildNotesData, renderNotesHtml } from "./notes-html.js";
8
+ const json = (status, data) => ({ status, type: "application/json", body: JSON.stringify(data) });
9
+ /** Bundled browser code shipped next to the runtime (dist/vendor, copied to ~/.selflore/app/vendor). */
10
+ export function vendorDir() {
11
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "vendor");
12
+ }
13
+ // The only files served besides the page: no path from the request ever reaches the filesystem.
14
+ const VENDOR_FILES = { "/vendor/graph3d.js": "graph3d.js" };
15
+ function sameToken(a, b) {
16
+ const x = Buffer.from(a);
17
+ const y = Buffer.from(b);
18
+ return x.length === y.length && timingSafeEqual(x, y);
19
+ }
20
+ function parseBody(body) {
21
+ try {
22
+ const v = JSON.parse(body || "{}");
23
+ return v && typeof v === "object" ? v : {};
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ /**
30
+ * The notes server's routes, without sockets. Only 127.0.0.1/localhost on our own port is served
31
+ * (blocks DNS rebinding), and every /api call needs the per-run token from the opened URL.
32
+ */
33
+ export function handle(req, opts) {
34
+ const now = opts.now ?? new Date();
35
+ if (req.host !== `127.0.0.1:${opts.port}` && req.host !== `localhost:${opts.port}`)
36
+ return json(403, { error: "bad host" });
37
+ const [path, search = ""] = req.url.split("?");
38
+ if (req.method === "GET" && path === "/")
39
+ return { status: 200, type: "text/html; charset=utf-8", body: renderNotesHtml({ ...buildNotesData(now), server: true }) };
40
+ // The 3D graph bundle: a static file with nothing private in it, so it needs no token (a <script> tag can't send one).
41
+ if (req.method === "GET" && VENDOR_FILES[path]) {
42
+ try {
43
+ return { status: 200, type: "text/javascript; charset=utf-8", body: fs.readFileSync(`${opts.vendor ?? vendorDir()}/${VENDOR_FILES[path]}`, "utf8") };
44
+ }
45
+ catch {
46
+ return json(404, { error: "not found" });
47
+ }
48
+ }
49
+ if (!path.startsWith("/api/"))
50
+ return json(404, { error: "not found" });
51
+ if (!sameToken(req.token, opts.token))
52
+ return json(403, { error: "bad token" });
53
+ if (req.method === "GET" && path === "/api/health")
54
+ return json(200, { ok: true });
55
+ if (req.method === "GET" && path === "/api/quiz") {
56
+ const q = new URLSearchParams(search);
57
+ const ids = (q.get("ids") || "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, 50);
58
+ const scope = {
59
+ project: q.get("project") || undefined,
60
+ topic: q.get("topic") || q.get("skill") || undefined,
61
+ query: q.get("q") || undefined,
62
+ ids: ids.length ? ids : undefined,
63
+ };
64
+ return json(200, { questions: buildWebQuiz(now, scope) });
65
+ }
66
+ const body = parseBody(req.body);
67
+ const id = typeof body.entry_id === "string" ? body.entry_id : "";
68
+ if (req.method === "POST" && path === "/api/answer") {
69
+ const r = recordCmd(id, String(body.grade ?? ""), "recall", now, {
70
+ source: "web",
71
+ answer: typeof body.answer === "string" ? body.answer : undefined,
72
+ });
73
+ if (r.code !== 0)
74
+ return json(400, { error: r.out });
75
+ // Any answer counts as having tested this week, so a test left halfway still resets the nudge.
76
+ // A cluster test doesn't: a few questions on one project are not the weekly test.
77
+ if (body.scoped !== true)
78
+ finishTest(now);
79
+ return json(200, { message: r.out });
80
+ }
81
+ if (req.method === "POST" && path === "/api/suppress") {
82
+ const r = suppressCmd(id);
83
+ return r.code === 0 ? json(200, { message: r.out }) : json(400, { error: r.out });
84
+ }
85
+ return json(404, { error: "not found" });
86
+ }
87
+ const MAX_BODY = 64 * 1024;
88
+ /** Wrap `handle` in an http server. `onRequest` lets the caller reset its idle timer. */
89
+ export function createNotesServer(opts) {
90
+ const server = http.createServer((req, res) => {
91
+ opts.onRequest?.();
92
+ let body = "";
93
+ req.setEncoding("utf8");
94
+ req.on("data", (c) => {
95
+ body += c;
96
+ if (body.length > MAX_BODY)
97
+ req.destroy();
98
+ });
99
+ req.on("end", () => {
100
+ const address = server.address();
101
+ const port = address && typeof address === "object" ? address.port : 0;
102
+ let out;
103
+ try {
104
+ out = handle({
105
+ method: req.method ?? "GET",
106
+ url: req.url ?? "/",
107
+ host: req.headers.host ?? "",
108
+ token: String(req.headers["x-selflore-token"] ?? ""),
109
+ body,
110
+ }, { port, token: opts.token });
111
+ }
112
+ catch (err) {
113
+ out = json(500, { error: err instanceof Error ? err.message : String(err) });
114
+ }
115
+ res.writeHead(out.status, { "content-type": out.type, "cache-control": "no-store" });
116
+ res.end(out.body);
117
+ });
118
+ });
119
+ return server;
120
+ }
@@ -1,7 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { readJson, writeJson } from "./fsutil.js";
3
3
  import { paths } from "./paths.js";
4
- const EMPTY = { entries: [], scanned_offset: 0, pending: null, capturing_since: null };
4
+ const EMPTY = { entries: [], scanned_offset: 0, pending: null, capturing_since: null, offered: false, signaled: [] };
5
5
  function file(sessionId) {
6
6
  return path.join(paths.state(), `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
7
7
  }