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
@@ -1,15 +1,19 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import path from "node:path";
3
3
  import { BALANCES, configExists, designShare, describeFocus, effectiveFocus, FOCUS_MODES, readConfig, writeConfig, } from "./config.js";
4
- import { inferLevel, listEntries, MERGE_SIMILARITY, parseEntry, readEntry, similarity, 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";
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
- import { renderNotes, staleBefore } from "./notes.js";
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,7 +43,7 @@ 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.level}/${e.skill}] ${e.testable}`;
46
+ return `- ${e.id} [${e.kind}/${e.level}/${e.topics.join(", ")}] ${e.testable}`;
42
47
  }
43
48
  /**
44
49
  * Find an untested entry this one should be merged into: same project, a shared path,
@@ -71,15 +76,22 @@ export function storeEntry(parsed, opts) {
71
76
  const paths = Array.isArray(parsed.paths) ? parsed.paths.map(String) : [];
72
77
  const testable = String(parsed.testable);
73
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);
74
81
  const session = readSession(opts.session);
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) : "");
75
84
  const target = findMergeTarget({ project, paths, testable }, testedEntryIds(readResults()));
76
85
  if (target) {
77
86
  const merged = {
78
87
  ...target,
79
88
  kind: parsed.kind,
80
89
  level,
81
- skill: String(parsed.skill),
90
+ skill: topics[0] ?? "",
91
+ topics,
92
+ origin,
82
93
  paths: [...new Set([...target.paths, ...paths])],
94
+ sig: sigOf([...new Set([...target.paths, ...paths])]),
83
95
  testable,
84
96
  commit: commit || target.commit,
85
97
  body: parsed.body ?? target.body,
@@ -98,8 +110,11 @@ export function storeEntry(parsed, opts) {
98
110
  commit,
99
111
  kind: parsed.kind,
100
112
  level,
101
- skill: String(parsed.skill),
113
+ skill: topics[0] ?? "",
114
+ topics,
115
+ origin,
102
116
  paths,
117
+ sig: sigOf(paths),
103
118
  testable,
104
119
  suppressed: false,
105
120
  body: parsed.body ?? "",
@@ -127,6 +142,62 @@ export function listCmd(session) {
127
142
  }
128
143
  return ok(entries.length ? entries.map(summarize).join("\n") : "no entries");
129
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
+ }
130
201
  export const QUIZ_SIZE = 10;
131
202
  /** Split QUIZ_SIZE into design/detail counts from the candidates' effective focus (per project). */
132
203
  export function targetSplit(entries, config = readConfig()) {
@@ -138,34 +209,114 @@ export function targetSplit(entries, config = readConfig()) {
138
209
  const design = Math.round(QUIZ_SIZE * share);
139
210
  return { design, detail: QUIZ_SIZE - design };
140
211
  }
141
- /** Everything the skill needs to build this week's quiz, as JSON. */
142
- export function quizInput(now = new Date()) {
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 = {}) {
143
233
  const config = readConfig();
144
234
  const results = readResults();
145
235
  const tested = testedEntryIds(results);
146
236
  const queue = readQueue();
147
- const due = dueItems(queue, now);
148
- const dueIds = new Set(due.map((d) => d.entry_id));
149
- const entries = listEntries().filter((e) => !e.suppressed);
150
- const cutoff = staleBefore(now);
151
- const withFocus = (e) => ({ ...e, focus: effectiveFocus(config, e.project).mode });
152
- const retests = entries
153
- .filter((e) => dueIds.has(e.id))
154
- .map((e) => ({ ...withFocus(e), retest: { streak: queue[e.id].streak, due: queue[e.id].due[0] } }));
155
- const untested = entries.filter((e) => !tested.has(e.id) && !queue[e.id]);
156
- // Untested for 3+ weeks: out of the quiz pool (still visible in notes), so a heavy week can't create an endless backlog.
157
- const fresh = untested.filter((e) => e.date >= cutoff);
158
- 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 {
159
261
  now: now.toISOString(),
160
- config: { rating: config.rating, keep_sharp: config.keep_sharp, last_test_at: config.last_test_at },
161
- 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,
162
264
  target_split: targetSplit([...retests, ...fresh], config),
163
- stale_count: untested.length - fresh.length,
265
+ retests_total: waiting.length,
266
+ fresh_total: untested.length,
164
267
  retests,
165
268
  fresh: fresh.map(withFocus),
166
- }, null, 2));
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)));
167
300
  }
168
- 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 = {}) {
169
320
  if (!["got", "partial", "missed"].includes(grade))
170
321
  return fail("grade must be got | partial | missed");
171
322
  if (!QUESTION_TYPES.includes(type))
@@ -184,16 +335,18 @@ export function recordCmd(entryId, grade, type, now = new Date()) {
184
335
  question_type: type,
185
336
  grade: grade,
186
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) } : {}),
187
340
  });
188
341
  const next = applyGrade(queue, entryId, grade, now);
189
342
  writeQueue(next);
190
343
  let status;
191
344
  if (next[entryId])
192
- 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)`;
193
346
  else if (isRetest)
194
- status = "retired after two consecutive passes";
347
+ status = "retired after two passes in a row";
195
348
  else
196
- status = "passed, not queued";
349
+ status = "passed";
197
350
  return ok(`recorded ${grade} for ${entryId}: ${status}`);
198
351
  }
199
352
  export function suppressCmd(entryId) {
@@ -212,24 +365,35 @@ export function finishTest(now = new Date()) {
212
365
  const config = readConfig();
213
366
  writeConfig({ ...config, last_test_at: now.toISOString() });
214
367
  const backlog = Object.keys(readQueue()).length;
215
- return ok(`test finished at ${now.toISOString()}; retest backlog: ${backlog}`);
368
+ return ok(`test finished at ${now.toISOString()}; to revisit: ${backlog}`);
216
369
  }
217
- export function statsCmd(project) {
370
+ export function statsCmd(project, now = new Date()) {
371
+ const all = listEntries();
218
372
  return ok(renderStats({
219
- entries: listEntries(),
373
+ hot: renderHotAreas(hotAreas(all, heatNow(now, all), { project, limit: 3 }), !project),
374
+ entries: all,
220
375
  results: readResults(),
221
376
  queue: readQueue(),
222
377
  rating: readConfig().rating,
223
378
  project,
224
379
  }));
225
380
  }
226
- /** Write the notes page and open it in the browser; `text` prints the plain-text list instead. */
227
- 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()) {
228
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
+ }
229
393
  const file = paths.notesHtml();
230
394
  fs.mkdirSync(path.dirname(file), { recursive: true });
231
395
  fs.writeFileSync(file, renderNotesHtml({ ...buildNotesData(now), initial: { all: !!opts.all, project: opts.project ?? null } }));
232
- 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}`);
233
397
  }
234
398
  return ok(renderNotes({
235
399
  entries: listEntries(),
@@ -1,3 +1,4 @@
1
+ import fs from "node:fs";
1
2
  import { readJson, writeJson } from "./fsutil.js";
2
3
  import { paths } from "./paths.js";
3
4
  export const INTENSITIES = ["light", "normal", "thorough"];
@@ -5,6 +6,7 @@ export const FOCUS_MODES = ["details", "design", "mixed"];
5
6
  export const BALANCES = ["design", "balanced", "details"];
6
7
  export const CAPTURE_MODES = ["background", "quiet", "off"];
7
8
  export const CAPTURE_MODELS = ["session", "sonnet", "haiku"];
9
+ export const CADENCES = ["off", "weekly"];
8
10
  export const DEFAULT_CONFIG = {
9
11
  rating: 5,
10
12
  keep_sharp: ["debugging"],
@@ -15,11 +17,18 @@ export const DEFAULT_CONFIG = {
15
17
  capture_model: "session",
16
18
  nudge: true,
17
19
  cadence: "weekly",
20
+ offers: true,
18
21
  last_test_at: null,
19
22
  };
20
23
  const pick = (v, allowed, fallback) => allowed.includes(v) ? v : fallback;
21
- /** Fill in new fields and convert old ones (v0.2's max_entries_per_session → capture_intensity). */
22
- export function migrateConfig(raw) {
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);
23
32
  const legacyCap = typeof raw.max_entries_per_session === "number" ? raw.max_entries_per_session : null;
24
33
  const intensityFromCap = legacyCap === null ? null : legacyCap <= 3 ? "light" : legacyCap <= 5 ? "normal" : "thorough";
25
34
  const focus = (raw.focus ?? {});
@@ -45,10 +54,21 @@ export function migrateConfig(raw) {
45
54
  projects,
46
55
  capture: pick(raw.capture, CAPTURE_MODES, DEFAULT_CONFIG.capture),
47
56
  capture_model: pick(raw.capture_model, CAPTURE_MODELS, DEFAULT_CONFIG.capture_model),
57
+ cadence,
58
+ offers: raw.offers !== false,
48
59
  };
49
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
+ }
50
69
  export function readConfig() {
51
- return migrateConfig(readJson(paths.config(), {}));
70
+ const raw = readJson(paths.config(), {});
71
+ return migrateConfig(raw, "offers" in raw ? 0 : answerCount());
52
72
  }
53
73
  export function configExists() {
54
74
  return readJson(paths.config(), null) !== null;
@@ -7,6 +7,49 @@ export const LEVELS = ["detail", "design"];
7
7
  export function inferLevel(kind) {
8
8
  return kind === "decision" ? "design" : "detail";
9
9
  }
10
+ /** How an entry came to exist: the user asked for an explanation, a fail → fix loop, a dependency change, or a large write. */
11
+ export const ORIGINS = ["asked", "bugfix", "dependency", "write"];
12
+ /** Entries from before `origin` existed: a root-caused bug was a bug fix, everything else a write. */
13
+ export function inferOrigin(kind) {
14
+ return kind === "bug" ? "bugfix" : "write";
15
+ }
16
+ /** One spelling per topic ("React " and "react" are the same hub): trimmed, lowercased, single spaces. */
17
+ export function normalizeSkill(s) {
18
+ return String(s ?? "").trim().toLowerCase().replace(/\s+/g, " ");
19
+ }
20
+ export const MAX_TOPICS = 3;
21
+ /**
22
+ * Words that say what kind of work it was, not what it was about. They made every entry
23
+ * "architecture" or "debugging"; a topic names the technology or the concept instead.
24
+ */
25
+ export const GENERIC_TOPICS = new Set("architecture debugging fundamentals design bug bugs bugfix decision concept pattern code coding programming software general misc other".split(" "));
26
+ /**
27
+ * An entry's topics from whatever was stored: a list, a comma-separated string, or (entries from
28
+ * before topics existed) the single `skill`. Normalised, de-duplicated, at most MAX_TOPICS, and
29
+ * generic words dropped whenever a real topic is there too.
30
+ */
31
+ export function normalizeTopics(topics, skill) {
32
+ const raw = Array.isArray(topics) ? topics : typeof topics === "string" && topics.trim() ? topics.split(",") : [];
33
+ let list = [...new Set(raw.map(normalizeSkill).filter(Boolean))];
34
+ if (!list.length && normalizeSkill(skill))
35
+ list = [normalizeSkill(skill)];
36
+ const real = list.filter((t) => !GENERIC_TOPICS.has(t));
37
+ return (real.length ? real : list).slice(0, MAX_TOPICS);
38
+ }
39
+ /**
40
+ * Does an entry fall in one of the user's keep-sharp areas? A stack name matches a topic; the
41
+ * built-in areas match the kind of work, since they are no longer used as topic names.
42
+ */
43
+ export function isSharp(e, keepSharp) {
44
+ return keepSharp.map(normalizeSkill).some((k) => e.topics.includes(k) ||
45
+ (k === "debugging" && e.kind === "bug") ||
46
+ (k === "architecture" && (e.level === "design" || e.kind === "decision")) ||
47
+ (k === "fundamentals" && e.kind === "concept"));
48
+ }
49
+ /** True when an entry has no real topic yet (only generic words, or nothing). */
50
+ export function needsTopics(topics) {
51
+ return !topics.some((t) => !GENERIC_TOPICS.has(t));
52
+ }
10
53
  export const MAX_BODY_WORDS = 150; // PRD says ~120; small grace before rejecting
11
54
  export const MAX_SNIPPET_LINES = 40;
12
55
  const FIELD_ORDER = [
@@ -18,7 +61,10 @@ const FIELD_ORDER = [
18
61
  "kind",
19
62
  "level",
20
63
  "skill",
64
+ "topics",
65
+ "origin",
21
66
  "paths",
67
+ "sig",
22
68
  "testable",
23
69
  "suppressed",
24
70
  ];
@@ -100,8 +146,10 @@ export function validateEntry(e) {
100
146
  errors.push(`\`kind\` must be one of ${KINDS.join(" | ")}`);
101
147
  if (e.level !== undefined && !LEVELS.includes(e.level))
102
148
  errors.push(`\`level\` must be one of ${LEVELS.join(" | ")}`);
103
- if (!e.skill || !String(e.skill).trim())
104
- errors.push("missing `skill`");
149
+ if (!normalizeTopics(e.topics, e.skill).length)
150
+ errors.push("missing `topics` (1–3: the technology, then the concept)");
151
+ if (e.origin !== undefined && !ORIGINS.includes(e.origin))
152
+ errors.push(`\`origin\` must be one of ${ORIGINS.join(" | ")}`);
105
153
  const { prose, snippet } = splitBody(e.body ?? "");
106
154
  const words = prose.split(/\s+/).filter(Boolean).length;
107
155
  if (words === 0)
@@ -167,6 +215,7 @@ export function listEntries() {
167
215
  .filter((e) => e !== null);
168
216
  }
169
217
  function normalize(p, id) {
218
+ const topics = normalizeTopics(p.topics, p.skill);
170
219
  return {
171
220
  id: p.id ?? id,
172
221
  date: String(p.date ?? id.slice(0, 10)),
@@ -175,8 +224,11 @@ function normalize(p, id) {
175
224
  commit: String(p.commit ?? ""),
176
225
  kind: (p.kind ?? "concept"),
177
226
  level: LEVELS.includes(p.level) ? p.level : inferLevel(p.kind),
178
- skill: String(p.skill ?? ""),
227
+ skill: topics[0] ?? "",
228
+ topics,
229
+ origin: ORIGINS.includes(p.origin) ? p.origin : inferOrigin(p.kind),
179
230
  paths: Array.isArray(p.paths) ? p.paths.map(String) : p.paths ? [String(p.paths)] : [],
231
+ sig: typeof p.sig === "string" ? p.sig : "",
180
232
  testable: String(p.testable ?? ""),
181
233
  suppressed: p.suppressed === true,
182
234
  body: p.body ?? "",
@@ -184,7 +236,7 @@ function normalize(p, id) {
184
236
  }
185
237
  // Question scaffolding that says nothing about the topic ("why does … happen if …").
186
238
  const STOPWORDS = new Set("the and for are was were why what when where which who how does did doesn don isn can could would should will this that these those with without from into than then there here have has had not but its it's you your our they them their about after before over under also just only use used using happen happens happened instead break breaks".split(" "));
187
- function words(s) {
239
+ export function words(s) {
188
240
  return new Set(s.toLowerCase().match(/[a-z0-9_]+/g)?.filter((w) => w.length > 2 && !STOPWORDS.has(w)) ?? []);
189
241
  }
190
242
  /** Jaccard similarity of the word sets of two strings (words of 3+ chars). */
@@ -0,0 +1,141 @@
1
+ import { DAY_MS, REASK_AFTER_DAYS } from "./signals.js";
2
+ import { normPath } from "./struggle.js";
3
+ /**
4
+ * Heat: where the user gets stuck, read from what they did. One number per entry, 0 (cool,
5
+ * settled) to 1 (hot), or null when there is no signal either way. It is a map, not a grade:
6
+ * nothing here says "weak" or "failing", and every piece of evidence fades with a 30-day
7
+ * half-life, so nothing stays hot (or cool) forever without new evidence.
8
+ */
9
+ export const HALF_LIFE_DAYS = 30;
10
+ /** Below this much surviving evidence, an entry is neutral again. */
11
+ const MIN_EVIDENCE = 0.05;
12
+ const STEEPNESS = 2;
13
+ // How much each kind of evidence counts. Positive heats, negative cools.
14
+ const W = {
15
+ originAsked: 0.35, // you asked for this explanation: warm from day one
16
+ originBugfix: 0.3, // it came out of a fail → fix loop
17
+ ask: 0.3, // a note was needed to answer you
18
+ reask: 0.8, // …and needed again a week or more later
19
+ loop: 0.5, // a fail → fix loop on its files
20
+ missed: 1.0,
21
+ partial: 0.6,
22
+ got: -0.9,
23
+ touch: -0.3, // its files were edited with no trouble
24
+ };
25
+ function day(ts) {
26
+ return new Date(ts).toLocaleDateString("en-US", { month: "short", day: "numeric" });
27
+ }
28
+ function plural(n, one, many) {
29
+ return n === 1 ? one : `${n} ${many}`;
30
+ }
31
+ /** Heat for every entry. Suppressed entries get none. */
32
+ export function computeHeat({ entries, results, signals, now }) {
33
+ const t = now.getTime();
34
+ const byEntry = new Map();
35
+ const add = (id, e) => byEntry.set(id, [...(byEntry.get(id) ?? []), e]);
36
+ const live = entries.filter((e) => !e.suppressed);
37
+ for (const e of live) {
38
+ const [y, m, d] = e.date.split("-").map(Number);
39
+ const captured = new Date(y, m - 1, d, 12).getTime();
40
+ if (e.origin === "asked")
41
+ add(e.id, { w: W.originAsked, ts: captured, label: "you asked to have this explained" });
42
+ else if (e.origin === "bugfix")
43
+ add(e.id, { w: W.originBugfix, ts: captured, label: "it came out of a fix that took several tries" });
44
+ }
45
+ for (const r of results) {
46
+ const ts = new Date(r.ts).getTime();
47
+ if (r.grade === "got")
48
+ add(r.entry_id, { w: W.got, ts, label: `answered right (${day(ts)})` });
49
+ else
50
+ add(r.entry_id, { w: r.grade === "missed" ? W.missed : W.partial, ts, label: `${r.grade === "missed" ? "missed" : "partly right"} in a test (${day(ts)})` });
51
+ }
52
+ // Asks, in order: the first is mild, one a week or more after an earlier ask is a re-ask.
53
+ const asks = new Map();
54
+ for (const s of signals)
55
+ if (s.type === "ask")
56
+ asks.set(s.entry_id, [...(asks.get(s.entry_id) ?? []), new Date(s.ts).getTime()]);
57
+ for (const [id, times] of asks) {
58
+ times.sort((a, b) => a - b);
59
+ times.forEach((ts, i) => {
60
+ const again = i > 0 && ts - times[0] >= REASK_AFTER_DAYS * DAY_MS;
61
+ add(id, again ? { w: W.reask, ts, label: `asked about it again (${day(ts)})` } : { w: i === 0 ? W.ask : W.ask / 2, ts, label: `asked about it (${day(ts)})` });
62
+ });
63
+ }
64
+ // Loops and trouble-free edits, matched to entries through their files.
65
+ const byFile = new Map();
66
+ for (const e of live)
67
+ for (const p of e.paths)
68
+ byFile.set(`${e.project}\n${normPath(p)}`, [...(byFile.get(`${e.project}\n${normPath(p)}`) ?? []), e]);
69
+ for (const s of signals) {
70
+ if (s.type !== "loop" && s.type !== "touch")
71
+ continue;
72
+ const ts = new Date(s.ts).getTime();
73
+ const hit = new Set();
74
+ for (const p of s.paths)
75
+ for (const e of byFile.get(`${s.project}\n${normPath(p)}`) ?? [])
76
+ hit.add(e.id);
77
+ for (const id of hit)
78
+ add(id, s.type === "loop" ? { w: W.loop, ts, label: `a fix in its files took several tries (${day(ts)})` } : { w: W.touch, ts, label: `its files were edited without trouble (${day(ts)})` });
79
+ }
80
+ const out = new Map();
81
+ for (const e of live) {
82
+ const ev = (byEntry.get(e.id) ?? []).map((x) => ({ ...x, now: x.w * 0.5 ** (Math.max(0, t - x.ts) / DAY_MS / HALF_LIFE_DAYS) }));
83
+ const total = ev.reduce((sum, x) => sum + Math.abs(x.now), 0);
84
+ if (total < MIN_EVIDENCE) {
85
+ out.set(e.id, { heat: null, why: [] });
86
+ continue;
87
+ }
88
+ const net = ev.reduce((sum, x) => sum + x.now, 0);
89
+ const heat = 1 / (1 + Math.exp(-STEEPNESS * net));
90
+ // The reasons that point the way the entry ended up, strongest first.
91
+ const side = ev.filter((x) => (heat >= 0.5 ? x.now > 0 : x.now < 0)).sort((a, b) => Math.abs(b.now) - Math.abs(a.now));
92
+ out.set(e.id, { heat: Math.round(heat * 100) / 100, why: side.slice(0, 3).map((x) => x.label) });
93
+ }
94
+ return out;
95
+ }
96
+ /** Heat of a group: pulled toward its hottest entry, so one real trouble spot shows from a distance. Null if no entry has a signal. */
97
+ export function groupHeat(values) {
98
+ const known = values.filter((v) => v !== null);
99
+ if (!known.length)
100
+ return null;
101
+ const mean = known.reduce((a, b) => a + b, 0) / known.length;
102
+ return Math.round((0.6 * mean + 0.4 * Math.max(...known)) * 100) / 100;
103
+ }
104
+ // From here up an entry counts as a place the user gets stuck. Set above what a warm start alone
105
+ // can reach: being captured from a bug fix, or asked about once, is not yet "stuck".
106
+ export const HOT = 0.7;
107
+ /** The hottest project + topic groups, for "where you get stuck". Only groups with a hot entry are listed. */
108
+ export function hotAreas(entries, heat, opts = {}) {
109
+ const groups = new Map();
110
+ for (const e of entries) {
111
+ if (e.suppressed || (opts.project && e.project !== opts.project))
112
+ continue;
113
+ const key = `${e.project}\n${e.skill}`;
114
+ groups.set(key, [...(groups.get(key) ?? []), e]);
115
+ }
116
+ const areas = [];
117
+ for (const [key, list] of groups) {
118
+ const [project, topic] = key.split("\n");
119
+ const values = list.map((e) => heat.get(e.id)?.heat ?? null);
120
+ const h = groupHeat(values);
121
+ const hot = list.filter((e) => (heat.get(e.id)?.heat ?? 0) >= HOT);
122
+ if (h === null || !hot.length)
123
+ continue;
124
+ // What heated it, across its hot entries: "missed in a test (Nov 3)" ×2 → counted once per label kind.
125
+ const kinds = new Map();
126
+ for (const e of hot)
127
+ for (const w of heat.get(e.id).why)
128
+ kinds.set(w.replace(/ \([^)]*\)$/, ""), (kinds.get(w.replace(/ \([^)]*\)$/, "")) ?? 0) + 1);
129
+ const why = [...kinds.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([label, n]) => (n > 1 ? `${label} ×${n}` : label));
130
+ areas.push({ project, topic, heat: h, notes: list.length, hot_notes: hot.length, why });
131
+ }
132
+ return areas.sort((a, b) => b.heat - a.heat || b.hot_notes - a.hot_notes || a.topic.localeCompare(b.topic)).slice(0, opts.limit ?? 5);
133
+ }
134
+ export function renderHotAreas(areas, showProject) {
135
+ if (!areas.length)
136
+ return ["Where you get stuck", " nothing stands out yet"];
137
+ return [
138
+ "Where you get stuck",
139
+ ...areas.map((a) => ` ${a.topic}${showProject ? ` · ${a.project}` : ""} — ${plural(a.hot_notes, "1 note", "notes")} of ${a.notes}: ${a.why.join("; ")}`),
140
+ ];
141
+ }