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,15 +1,19 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import path from "node:path";
3
- import { readConfig, writeConfig } from "./config.js";
4
- import { deleteEntry, listEntries, parseEntry, readEntry, uniqueId, validateEntry, writeEntry, } from "./entries.js";
5
- import { applyGrade, dueItems, readQueue, writeQueue } from "./queue.js";
6
- import { appendResult, QUESTION_TYPES, readResults, testedEntryIds } from "./results.js";
3
+ import { BALANCES, configExists, designShare, describeFocus, effectiveFocus, FOCUS_MODES, readConfig, writeConfig, } from "./config.js";
4
+ import { inferLevel, inferOrigin, isSharp, listEntries, MERGE_SIMILARITY, normalizeSkill, normalizeTopics, ORIGINS, parseEntry, readEntry, similarity, splitBody, uniqueId, validateEntry, writeEntry, } from "./entries.js";
5
+ import { applyGrade, queuedItems, readQueue, writeQueue } from "./queue.js";
6
+ import { fileSig, freshness, rank, RECALL_MIN, toDoc } from "./recall.js";
7
+ import { appendResult, MAX_ANSWER_CHARS, QUESTION_TYPES, readResults, testedEntryIds, } from "./results.js";
7
8
  import { readSession, writeSession } from "./session.js";
9
+ import { readSignals, recordAsk } from "./signals.js";
10
+ import { computeHeat, hotAreas, renderHotAreas } from "./heat.js";
8
11
  import fs from "node:fs";
9
12
  import { renderNotes } from "./notes.js";
10
13
  import { buildNotesData, renderNotesHtml } from "./notes-html.js";
11
14
  import { openInBrowser } from "./open.js";
12
15
  import { paths } from "./paths.js";
16
+ import { ensureServer } from "./server-launch.js";
13
17
  import { renderStats } from "./stats.js";
14
18
  const ok = (out) => ({ code: 0, out });
15
19
  const fail = (out, code = 1) => ({ code, out });
@@ -30,6 +34,7 @@ export function projectInfo(cwd) {
30
34
  return {
31
35
  project: projectName(top || cwd),
32
36
  commit: top ? git(cwd, ["rev-parse", "--short", "HEAD"]) : "",
37
+ root: top || path.resolve(cwd),
33
38
  };
34
39
  }
35
40
  function today(now) {
@@ -38,58 +43,96 @@ function today(now) {
38
43
  return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
39
44
  }
40
45
  function summarize(e) {
41
- return `- ${e.id} [${e.kind}/${e.skill}] ${e.testable}`;
46
+ return `- ${e.id} [${e.kind}/${e.level}/${e.topics.join(", ")}] ${e.testable}`;
42
47
  }
43
- /** Validate, enrich and store an entry. Enforces max_entries_per_session (manual logs warn instead). */
44
- export function addEntry(markdown, opts) {
48
+ /**
49
+ * Find an untested entry this one should be merged into: same project, a shared path,
50
+ * and a similar question. Long sessions keep touching the same area; this keeps one
51
+ * entry per idea instead of a pile of near-duplicates.
52
+ */
53
+ export function findMergeTarget(candidate, tested) {
54
+ const queue = readQueue();
55
+ let best = null;
56
+ let bestScore = 0;
57
+ for (const e of listEntries()) {
58
+ if (e.suppressed || e.project !== candidate.project || tested.has(e.id) || queue[e.id])
59
+ continue;
60
+ const sharesPath = e.paths.some((p) => candidate.paths.includes(p));
61
+ const score = similarity(e.testable, candidate.testable);
62
+ const threshold = sharesPath ? MERGE_SIMILARITY : 0.8; // without a shared file, only near-identical questions merge
63
+ if (score >= threshold && score > bestScore) {
64
+ best = e;
65
+ bestScore = score;
66
+ }
67
+ }
68
+ return best;
69
+ }
70
+ /** Enrich, merge-or-create and store a validated entry. Shared by `entry add` and the background worker. */
71
+ export function storeEntry(parsed, opts) {
45
72
  const now = opts.now ?? new Date();
46
- const parsed = parseEntry(markdown);
47
- const errors = validateEntry(parsed);
48
- if (errors.length)
49
- return fail(`entry rejected:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
50
- const config = readConfig();
73
+ const info = projectInfo(opts.cwd);
74
+ const project = parsed.project ? String(parsed.project) : info.project;
75
+ const commit = parsed.commit ? String(parsed.commit) : info.commit;
76
+ const paths = Array.isArray(parsed.paths) ? parsed.paths.map(String) : [];
77
+ const testable = String(parsed.testable);
78
+ const level = parsed.level ?? inferLevel(parsed.kind);
79
+ const topics = normalizeTopics(parsed.topics, parsed.skill);
80
+ const origin = ORIGINS.includes(parsed.origin) ? parsed.origin : inferOrigin(parsed.kind);
51
81
  const session = readSession(opts.session);
52
- const sessionEntries = session.entries.filter((id) => readEntry(id) !== null);
53
- let warning = "";
54
- if (opts.replace) {
55
- if (!sessionEntries.includes(opts.replace))
56
- return fail(`cannot replace ${opts.replace}: it was not logged in this session`);
57
- if (testedEntryIds(readResults()).has(opts.replace))
58
- return fail(`cannot replace ${opts.replace}: it has already been tested`);
59
- deleteEntry(opts.replace);
60
- sessionEntries.splice(sessionEntries.indexOf(opts.replace), 1);
61
- }
62
- else if (sessionEntries.length >= config.max_entries_per_session) {
63
- if (!opts.manual) {
64
- const current = sessionEntries.map((id) => readEntry(id)).filter((e) => e !== null);
65
- return fail([
66
- `cap reached: ${sessionEntries.length}/${config.max_entries_per_session} entries this session.`,
67
- `Keep the ones that best match keep_sharp (${config.keep_sharp.join(", ")}).`,
68
- `If the new one is better, rerun with \`entry replace <id>\`; otherwise drop it.`,
69
- ...current.map(summarize),
70
- ].join("\n"), 2);
71
- }
72
- warning = `\nnote: over the session cap (${config.max_entries_per_session}); logged anyway because it was manual.`;
82
+ // Fingerprint the files now, so a later recall can tell whether the code has moved on.
83
+ const sigOf = (ps) => (project === info.project ? fileSig(info.root, ps) : "");
84
+ const target = findMergeTarget({ project, paths, testable }, testedEntryIds(readResults()));
85
+ if (target) {
86
+ const merged = {
87
+ ...target,
88
+ kind: parsed.kind,
89
+ level,
90
+ skill: topics[0] ?? "",
91
+ topics,
92
+ origin,
93
+ paths: [...new Set([...target.paths, ...paths])],
94
+ sig: sigOf([...new Set([...target.paths, ...paths])]),
95
+ testable,
96
+ commit: commit || target.commit,
97
+ body: parsed.body ?? target.body,
98
+ };
99
+ writeEntry(merged);
100
+ if (!session.entries.includes(merged.id))
101
+ writeSession(opts.session, { ...session, entries: [...session.entries, merged.id] });
102
+ return { action: "updated", entry: merged };
73
103
  }
74
- const { project, commit } = projectInfo(opts.cwd);
75
104
  const date = typeof parsed.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(parsed.date) ? parsed.date : today(now);
76
105
  const entry = {
77
- id: uniqueId(date, String(parsed.testable)),
106
+ id: uniqueId(date, testable),
78
107
  date,
79
108
  session: opts.session,
80
- project: parsed.project ? String(parsed.project) : project,
81
- commit: parsed.commit ? String(parsed.commit) : commit,
109
+ project,
110
+ commit,
82
111
  kind: parsed.kind,
83
- skill: String(parsed.skill),
84
- paths: Array.isArray(parsed.paths) ? parsed.paths.map(String) : [],
85
- testable: String(parsed.testable),
112
+ level,
113
+ skill: topics[0] ?? "",
114
+ topics,
115
+ origin,
116
+ paths,
117
+ sig: sigOf(paths),
118
+ testable,
86
119
  suppressed: false,
87
120
  body: parsed.body ?? "",
88
121
  };
89
122
  writeEntry(entry);
90
- writeSession(opts.session, { ...session, entries: [...sessionEntries, entry.id] });
91
- const count = sessionEntries.length + 1;
92
- return ok(`logged ${entry.id} (${count}/${config.max_entries_per_session} this session)${warning}`);
123
+ writeSession(opts.session, { ...session, entries: [...session.entries, entry.id] });
124
+ return { action: "logged", entry };
125
+ }
126
+ /** Validate and store an entry from markdown. There is no per-session cap; near-duplicates are merged. */
127
+ export function addEntry(markdown, opts) {
128
+ const parsed = parseEntry(markdown);
129
+ const errors = validateEntry(parsed);
130
+ if (errors.length)
131
+ return fail(`entry rejected:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
132
+ const { action, entry } = storeEntry(parsed, opts);
133
+ return ok(action === "updated"
134
+ ? `updated ${entry.id} (merged with a similar untested entry) [${entry.level}]`
135
+ : `logged ${entry.id} [${entry.level}]`);
93
136
  }
94
137
  export function listCmd(session) {
95
138
  let entries = listEntries();
@@ -99,29 +142,181 @@ export function listCmd(session) {
99
142
  }
100
143
  return ok(entries.length ? entries.map(summarize).join("\n") : "no entries");
101
144
  }
145
+ /** `sl recall "<question>"`: the notes that best answer it, from this project unless told otherwise. */
146
+ export function recallCmd(query, opts) {
147
+ if (!query.trim())
148
+ return fail('usage: sl recall "<question>" [--project <name> | --all] [--limit n] [--json]');
149
+ const project = opts.all ? undefined : (opts.project ?? projectInfo(opts.cwd).project);
150
+ const docs = listEntries().filter((e) => !e.suppressed).map(toDoc);
151
+ const hits = rank(query, docs, { project, limit: opts.limit ?? 5, min: RECALL_MIN });
152
+ if (opts.json)
153
+ return ok(JSON.stringify(hits.map((h) => ({ id: h.doc.id, date: h.doc.date, project: h.doc.project, topics: h.doc.topics, question: h.doc.testable, score: Number(h.score.toFixed(2)) })), null, 2));
154
+ if (!hits.length)
155
+ return ok(`no notes match${project ? ` in ${project} (add --all to search every project)` : ""}`);
156
+ return ok(hits
157
+ .map((h) => `${h.score.toFixed(2)} ${h.doc.date} ${h.doc.id}${project ? "" : ` (${h.doc.project})`}
158
+ [${h.doc.topics.join(", ")}] ${h.doc.testable}`)
159
+ .join("\n"));
160
+ }
161
+ /**
162
+ * `sl show <id>`: one note in full, and whether the files it describes have changed since.
163
+ * With a session id, it also records that this note was used to answer the user (an "ask").
164
+ */
165
+ export function showCmd(entryId, opts) {
166
+ const e = readEntry(entryId);
167
+ if (!e)
168
+ return fail(`no entry ${entryId}`);
169
+ if (opts.session)
170
+ recordAsk(e.id, opts.session, e.project, opts.now);
171
+ const info = projectInfo(opts.cwd);
172
+ const fresh = freshness(e, info.project === e.project ? info.root : null);
173
+ const verdict = {
174
+ unchanged: "unchanged since capture",
175
+ changed: "CHANGED since capture — read the current files before relying on this note, and say what is different",
176
+ missing: "the files are GONE — this note may describe code that no longer exists",
177
+ unknown: "not checked",
178
+ }[fresh.status];
179
+ return ok([
180
+ `${e.id} · ${e.date} · ${e.project} · ${e.kind}/${e.level} · ${e.topics.join(", ")}`,
181
+ `Q: ${e.testable}`,
182
+ "",
183
+ e.body.trim(),
184
+ "",
185
+ `files: ${e.paths.join(", ") || "(none)"}${e.commit ? ` @ ${e.commit}` : ""}`,
186
+ `code: ${verdict} (${fresh.detail})`,
187
+ ].join("\n"));
188
+ }
189
+ /** Heat for every entry, from everything recorded so far. */
190
+ export function heatNow(now = new Date(), entries = listEntries()) {
191
+ return computeHeat({ entries, results: readResults(), signals: readSignals(), now });
192
+ }
193
+ /** `sl heat`: where the user gets stuck, hottest first. */
194
+ export function heatCmd(opts = {}, now = new Date()) {
195
+ const entries = listEntries();
196
+ const areas = hotAreas(entries, heatNow(now, entries), { project: opts.project, limit: opts.limit ?? 5 });
197
+ if (opts.json)
198
+ return ok(JSON.stringify(areas, null, 2));
199
+ return ok(renderHotAreas(areas, !opts.project).join("\n"));
200
+ }
102
201
  export const QUIZ_SIZE = 10;
103
- /** Everything the skill needs to build this week's quiz, as JSON. */
104
- export function quizInput(now = new Date()) {
202
+ /** Split QUIZ_SIZE into design/detail counts from the candidates' effective focus (per project). */
203
+ export function targetSplit(entries, config = readConfig()) {
204
+ if (!entries.length) {
205
+ const design = Math.round(QUIZ_SIZE * designShare(effectiveFocus(config)));
206
+ return { design, detail: QUIZ_SIZE - design };
207
+ }
208
+ const share = entries.reduce((sum, e) => sum + designShare(effectiveFocus(config, e.project)), 0) / entries.length;
209
+ const design = Math.round(QUIZ_SIZE * share);
210
+ return { design, detail: QUIZ_SIZE - design };
211
+ }
212
+ /** A test on something the user described or picked is short. */
213
+ export const QUERY_SIZE = 5;
214
+ const QUERY_CANDIDATES = 12;
215
+ export function scopeTopic(scope) {
216
+ return normalizeSkill(scope?.topic || scope?.skill);
217
+ }
218
+ export function isScoped(scope) {
219
+ return Boolean(scope?.project || scopeTopic(scope) || isPicked(scope));
220
+ }
221
+ /** A free-text or hand-picked scope: the user chose these notes, so they are asked as given. */
222
+ export function isPicked(scope) {
223
+ return Boolean(scope?.query?.trim() || scope?.ids?.length);
224
+ }
225
+ /** Untested entries handed to a quiz: enough to choose from without dumping hundreds of notes. */
226
+ export const FRESH_LIMIT = 30;
227
+ /**
228
+ * The material for a quiz: questions missed last time (they come back first, whenever that is) and
229
+ * untested entries, newest first. Nothing goes stale and nothing is due: an entry waits until the
230
+ * user asks to be tested on its area. With a scope, only that project/topic.
231
+ */
232
+ export function quizPool(now = new Date(), scope = {}) {
105
233
  const config = readConfig();
106
234
  const results = readResults();
107
235
  const tested = testedEntryIds(results);
108
236
  const queue = readQueue();
109
- const due = dueItems(queue, now);
110
- const dueIds = new Set(due.map((d) => d.entry_id));
111
- const entries = listEntries().filter((e) => !e.suppressed);
112
- const retests = entries
113
- .filter((e) => dueIds.has(e.id))
114
- .map((e) => ({ ...e, retest: { streak: queue[e.id].streak, due: queue[e.id].due[0] } }));
115
- const fresh = entries.filter((e) => !tested.has(e.id) && !queue[e.id]);
116
- return ok(JSON.stringify({
237
+ const topic = scopeTopic(scope);
238
+ const ids = scope.ids?.length ? new Set(scope.ids) : null;
239
+ let entries = listEntries().filter((e) => !e.suppressed && (!scope.project || e.project === scope.project) && (!topic || e.topics.includes(topic)) && (!ids || ids.has(e.id)));
240
+ // Free text: the notes that best match what the user typed, best first.
241
+ const picked = isPicked(scope);
242
+ if (scope.query?.trim()) {
243
+ const order = rank(scope.query, entries.map(toDoc), { limit: QUERY_CANDIDATES, min: RECALL_MIN }).map((h) => h.doc.id);
244
+ const found = new Map(entries.map((e) => [e.id, e]));
245
+ entries = order.map((id) => found.get(id));
246
+ }
247
+ const size = picked ? QUERY_SIZE : QUIZ_SIZE;
248
+ const byId = new Map(entries.map((e) => [e.id, e]));
249
+ const heat = heatNow(now, entries);
250
+ const warmth = (e) => heat.get(e.id)?.heat ?? 0.5;
251
+ const withFocus = (e) => ({ ...e, focus: effectiveFocus(config, e.project).mode, heat: heat.get(e.id)?.heat ?? null });
252
+ const waiting = queuedItems(queue).filter((q) => byId.has(q.entry_id));
253
+ const retests = waiting
254
+ .slice(0, size)
255
+ .map((q) => ({ ...withFocus(byId.get(q.entry_id)), retest: { streak: q.streak } }));
256
+ // A picked scope may ask again about something already passed: the user chose it.
257
+ const untested = entries.filter((e) => !queue[e.id] && (picked || !tested.has(e.id)));
258
+ // Where the user gets stuck comes first; among the rest, the newest. A query keeps its own order: best match first.
259
+ const fresh = scope.query?.trim() ? untested : [...untested].sort((a, b) => warmth(b) - warmth(a) || b.id.localeCompare(a.id)).slice(0, FRESH_LIMIT);
260
+ return {
117
261
  now: now.toISOString(),
118
- config: { rating: config.rating, keep_sharp: config.keep_sharp, last_test_at: config.last_test_at },
119
- target_questions: QUIZ_SIZE,
262
+ config: { rating: config.rating, keep_sharp: config.keep_sharp, cadence: config.cadence, last_test_at: config.last_test_at },
263
+ target_questions: size,
264
+ target_split: targetSplit([...retests, ...fresh], config),
265
+ retests_total: waiting.length,
266
+ fresh_total: untested.length,
120
267
  retests,
121
- fresh,
122
- }, null, 2));
268
+ fresh: fresh.map(withFocus),
269
+ };
270
+ }
271
+ /** Everything the skill needs to build this week's quiz, as JSON. */
272
+ export function quizInput(now = new Date(), scope = {}) {
273
+ return ok(JSON.stringify(quizPool(now, scope), null, 2));
274
+ }
275
+ /**
276
+ * The web test: the selection test.md asks Claude to make, done in code. What was missed last
277
+ * time first, then untested entries up to QUIZ_SIZE following the focus split (keep-sharp areas
278
+ * first, then newest). Never padded: if a level runs short, the other level fills in.
279
+ */
280
+ export function buildWebQuiz(now = new Date(), scope = {}) {
281
+ const pool = quizPool(now, scope);
282
+ const retestIds = new Set(pool.retests.map((e) => e.id));
283
+ // The user picked these notes: ask them as given, what was missed last time first.
284
+ if (isPicked(scope))
285
+ return [...pool.retests, ...pool.fresh].slice(0, pool.target_questions).map((e) => toQuestion(e, retestIds.has(e.id)));
286
+ // Hot first; keep-sharp areas break ties, then the newest.
287
+ const sharp = (e) => Number(isSharp(e, pool.config.keep_sharp));
288
+ const warmth = (e) => e.heat ?? 0.5;
289
+ const rank = (a, b) => warmth(b) - warmth(a) || sharp(b) - sharp(a) || b.id.localeCompare(a.id);
290
+ const room = Math.max(0, QUIZ_SIZE - pool.retests.length);
291
+ const design = pool.fresh.filter((e) => e.level === "design").sort(rank);
292
+ const detail = pool.fresh.filter((e) => e.level === "detail").sort(rank);
293
+ const scale = room / QUIZ_SIZE;
294
+ let wantDesign = Math.min(design.length, Math.round(pool.target_split.design * scale));
295
+ const wantDetail = Math.min(detail.length, room - wantDesign);
296
+ wantDesign = Math.min(design.length, room - wantDetail);
297
+ // The split decides which entries are in; heat decides the order they are asked in.
298
+ const picked = [...pool.retests, ...[...design.slice(0, wantDesign), ...detail.slice(0, wantDetail)].sort(rank)];
299
+ return picked.map((e) => toQuestion(e, retestIds.has(e.id)));
123
300
  }
124
- export function recordCmd(entryId, grade, type, now = new Date()) {
301
+ function toQuestion(e, retest) {
302
+ const { prose, snippet } = splitBody(e.body);
303
+ return {
304
+ id: e.id,
305
+ project: e.project,
306
+ kind: e.kind,
307
+ level: e.level,
308
+ skill: e.skill,
309
+ topics: e.topics,
310
+ paths: e.paths,
311
+ commit: e.commit,
312
+ testable: e.testable,
313
+ prose,
314
+ snippet: snippet ? snippet.replace(/\s+$/, "") : null,
315
+ snippetLang: e.body.match(/```([\w+-]+)/)?.[1] ?? "",
316
+ retest,
317
+ };
318
+ }
319
+ export function recordCmd(entryId, grade, type, now = new Date(), opts = {}) {
125
320
  if (!["got", "partial", "missed"].includes(grade))
126
321
  return fail("grade must be got | partial | missed");
127
322
  if (!QUESTION_TYPES.includes(type))
@@ -136,19 +331,22 @@ export function recordCmd(entryId, grade, type, now = new Date()) {
136
331
  entry_id: entryId,
137
332
  project: entry.project,
138
333
  skill: entry.skill,
334
+ level: entry.level,
139
335
  question_type: type,
140
336
  grade: grade,
141
337
  is_retest: isRetest,
338
+ ...(opts.source && opts.source !== "claude" ? { source: opts.source } : {}),
339
+ ...(opts.answer?.trim() ? { answer: opts.answer.trim().slice(0, MAX_ANSWER_CHARS) } : {}),
142
340
  });
143
341
  const next = applyGrade(queue, entryId, grade, now);
144
342
  writeQueue(next);
145
343
  let status;
146
344
  if (next[entryId])
147
- status = `queued, next retest ${next[entryId].due[0].slice(0, 10)} (streak ${next[entryId].streak}/2)`;
345
+ status = `it comes back first the next time this area is tested (${next[entryId].streak}/2 passes in a row)`;
148
346
  else if (isRetest)
149
- status = "retired after two consecutive passes";
347
+ status = "retired after two passes in a row";
150
348
  else
151
- status = "passed, not queued";
349
+ status = "passed";
152
350
  return ok(`recorded ${grade} for ${entryId}: ${status}`);
153
351
  }
154
352
  export function suppressCmd(entryId) {
@@ -167,24 +365,35 @@ export function finishTest(now = new Date()) {
167
365
  const config = readConfig();
168
366
  writeConfig({ ...config, last_test_at: now.toISOString() });
169
367
  const backlog = Object.keys(readQueue()).length;
170
- return ok(`test finished at ${now.toISOString()}; retest backlog: ${backlog}`);
368
+ return ok(`test finished at ${now.toISOString()}; to revisit: ${backlog}`);
171
369
  }
172
- export function statsCmd(project) {
370
+ export function statsCmd(project, now = new Date()) {
371
+ const all = listEntries();
173
372
  return ok(renderStats({
174
- entries: listEntries(),
373
+ hot: renderHotAreas(hotAreas(all, heatNow(now, all), { project, limit: 3 }), !project),
374
+ entries: all,
175
375
  results: readResults(),
176
376
  queue: readQueue(),
177
377
  rating: readConfig().rating,
178
378
  project,
179
379
  }));
180
380
  }
181
- /** Write the notes page and open it in the browser; `text` prints the plain-text list instead. */
182
- export function notesCmd(opts = {}, now = new Date()) {
381
+ /**
382
+ * Open the notes page, served by the local notes server so the in-page test can record answers.
383
+ * Falls back to a static file (no test) if the server can't start; `text` prints the plain-text list.
384
+ */
385
+ export async function notesCmd(opts = {}, now = new Date()) {
183
386
  if (!opts.text) {
387
+ const server = await ensureServer();
388
+ if (server) {
389
+ const hash = [opts.all ? "all" : "", opts.project ? `project=${encodeURIComponent(opts.project)}` : ""].filter(Boolean).join("&");
390
+ const url = `http://127.0.0.1:${server.port}/?t=${server.token}${hash ? `#${hash}` : ""}`;
391
+ return ok(openInBrowser(url) ? `opened ${url}` : `notes page: ${url}`);
392
+ }
184
393
  const file = paths.notesHtml();
185
394
  fs.mkdirSync(path.dirname(file), { recursive: true });
186
395
  fs.writeFileSync(file, renderNotesHtml({ ...buildNotesData(now), initial: { all: !!opts.all, project: opts.project ?? null } }));
187
- return ok(openInBrowser(file) ? `opened ${file}` : `notes page written: file://${file}`);
396
+ return ok(openInBrowser(file) ? `opened ${file} (test unavailable: notes server didn't start)` : `notes page written: file://${file}`);
188
397
  }
189
398
  return ok(renderNotes({
190
399
  entries: listEntries(),
@@ -195,3 +404,48 @@ export function notesCmd(opts = {}, now = new Date()) {
195
404
  project: opts.project,
196
405
  }));
197
406
  }
407
+ /** Parse `focus` CLI args: [mode] [--balance x] [--project] [--reset]. Shared by `selflore` and `sl`. */
408
+ export function focusArgs(args, cwd = process.cwd()) {
409
+ const i = args.indexOf("--balance");
410
+ const mode = args.find((a, j) => !a.startsWith("--") && (i < 0 || j !== i + 1));
411
+ return {
412
+ mode,
413
+ balance: i >= 0 ? args[i + 1] : undefined,
414
+ project: args.includes("--project"),
415
+ reset: args.includes("--reset"),
416
+ cwd,
417
+ };
418
+ }
419
+ /** Show or change the capture focus, globally or for the current project (which then takes priority). */
420
+ export function focusCmd(opts) {
421
+ if (!configExists())
422
+ return fail("selflore is not set up yet; run `npx selflore init` first");
423
+ const config = readConfig();
424
+ const project = projectInfo(opts.cwd).project;
425
+ if (opts.mode && !FOCUS_MODES.includes(opts.mode))
426
+ return fail(`focus must be one of ${FOCUS_MODES.join(" | ")}`);
427
+ if (opts.balance && !BALANCES.includes(opts.balance))
428
+ return fail(`--balance must be one of ${BALANCES.join(" | ")}`);
429
+ if (opts.reset) {
430
+ if (!opts.project)
431
+ return fail("--reset only applies with --project (it removes this project's override)");
432
+ const { [project]: _removed, ...rest } = config.projects;
433
+ writeConfig({ ...config, projects: rest });
434
+ }
435
+ else if (opts.mode || opts.balance) {
436
+ const change = {
437
+ ...(opts.mode ? { mode: opts.mode } : {}),
438
+ ...(opts.balance ? { balance: opts.balance } : {}),
439
+ };
440
+ if (opts.project)
441
+ writeConfig({ ...config, projects: { ...config.projects, [project]: { ...config.projects[project], ...change } } });
442
+ else
443
+ writeConfig({ ...config, focus: { ...config.focus, ...change } });
444
+ }
445
+ const next = readConfig();
446
+ const eff = effectiveFocus(next, project);
447
+ return ok([
448
+ `global focus: ${describeFocus(next.focus)}`,
449
+ `${project}: ${describeFocus(eff)} (${eff.source === "project" ? "project override" : "from global"})`,
450
+ ].join("\n"));
451
+ }
@@ -1,15 +1,74 @@
1
+ import fs from "node:fs";
1
2
  import { readJson, writeJson } from "./fsutil.js";
2
3
  import { paths } from "./paths.js";
4
+ export const INTENSITIES = ["light", "normal", "thorough"];
5
+ export const FOCUS_MODES = ["details", "design", "mixed"];
6
+ export const BALANCES = ["design", "balanced", "details"];
7
+ export const CAPTURE_MODES = ["background", "quiet", "off"];
8
+ export const CAPTURE_MODELS = ["session", "sonnet", "haiku"];
9
+ export const CADENCES = ["off", "weekly"];
3
10
  export const DEFAULT_CONFIG = {
4
11
  rating: 5,
5
12
  keep_sharp: ["debugging"],
6
- max_entries_per_session: 3,
13
+ capture_intensity: "normal",
14
+ focus: { mode: "mixed", balance: "balanced" },
15
+ projects: {},
16
+ capture: "background",
17
+ capture_model: "session",
7
18
  nudge: true,
8
- cadence: "weekly",
19
+ cadence: "off",
20
+ offers: true,
9
21
  last_test_at: null,
10
22
  };
23
+ const pick = (v, allowed, fallback) => allowed.includes(v) ? v : fallback;
24
+ /**
25
+ * Fill in new fields and convert old ones (v0.2's max_entries_per_session → capture_intensity).
26
+ * A config without `offers` is from before v1, when the weekly test was the default for everyone:
27
+ * it keeps the weekly cadence only if the user actually took tests (`answers` > 1).
28
+ */
29
+ export function migrateConfig(raw, answers = 0) {
30
+ const legacy = !("offers" in raw);
31
+ const cadence = legacy ? (raw.cadence === "weekly" && answers > 1 ? "weekly" : "off") : pick(raw.cadence, CADENCES, DEFAULT_CONFIG.cadence);
32
+ const legacyCap = typeof raw.max_entries_per_session === "number" ? raw.max_entries_per_session : null;
33
+ const intensityFromCap = legacyCap === null ? null : legacyCap <= 3 ? "light" : legacyCap <= 5 ? "normal" : "thorough";
34
+ const focus = (raw.focus ?? {});
35
+ const projects = {};
36
+ for (const [name, f] of Object.entries((raw.projects ?? {}))) {
37
+ const o = {};
38
+ if (FOCUS_MODES.includes(f?.mode))
39
+ o.mode = f.mode;
40
+ if (BALANCES.includes(f?.balance))
41
+ o.balance = f.balance;
42
+ if (Object.keys(o).length)
43
+ projects[name] = o;
44
+ }
45
+ const { max_entries_per_session: _legacy, ...rest } = raw;
46
+ return {
47
+ ...DEFAULT_CONFIG,
48
+ ...rest,
49
+ capture_intensity: pick(raw.capture_intensity, INTENSITIES, intensityFromCap ?? DEFAULT_CONFIG.capture_intensity),
50
+ focus: {
51
+ mode: pick(focus.mode, FOCUS_MODES, DEFAULT_CONFIG.focus.mode),
52
+ balance: pick(focus.balance, BALANCES, DEFAULT_CONFIG.focus.balance),
53
+ },
54
+ projects,
55
+ capture: pick(raw.capture, CAPTURE_MODES, DEFAULT_CONFIG.capture),
56
+ capture_model: pick(raw.capture_model, CAPTURE_MODELS, DEFAULT_CONFIG.capture_model),
57
+ cadence,
58
+ offers: raw.offers !== false,
59
+ };
60
+ }
61
+ function answerCount() {
62
+ try {
63
+ return fs.readFileSync(paths.results(), "utf8").split("\n").filter((l) => l.trim()).length;
64
+ }
65
+ catch {
66
+ return 0;
67
+ }
68
+ }
11
69
  export function readConfig() {
12
- return { ...DEFAULT_CONFIG, ...readJson(paths.config(), {}) };
70
+ const raw = readJson(paths.config(), {});
71
+ return migrateConfig(raw, "offers" in raw ? 0 : answerCount());
13
72
  }
14
73
  export function configExists() {
15
74
  return readJson(paths.config(), null) !== null;
@@ -17,6 +76,26 @@ export function configExists() {
17
76
  export function writeConfig(config) {
18
77
  writeJson(paths.config(), config);
19
78
  }
20
- export function clampCap(n) {
21
- return Math.min(7, Math.max(3, Math.round(n)));
79
+ /** The focus that applies to a project: its override wins, field by field, over the global focus. */
80
+ export function effectiveFocus(config, project) {
81
+ const o = project ? config.projects[project] : undefined;
82
+ return {
83
+ mode: o?.mode ?? config.focus.mode,
84
+ balance: o?.balance ?? config.focus.balance,
85
+ source: o && (o.mode || o.balance) ? "project" : "global",
86
+ };
87
+ }
88
+ /** How many of `total` quiz questions should be design-level for a focus. */
89
+ export function designShare(focus) {
90
+ if (focus.mode === "design")
91
+ return 1;
92
+ if (focus.mode === "details")
93
+ return 0;
94
+ return focus.balance === "design" ? 0.7 : focus.balance === "details" ? 0.3 : 0.5;
95
+ }
96
+ export function describeFocus(focus) {
97
+ if (focus.mode !== "mixed")
98
+ return focus.mode;
99
+ const b = { design: "mostly design", balanced: "balanced", details: "mostly details" }[focus.balance];
100
+ return `mixed (${b})`;
22
101
  }