selflore 0.1.0 → 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 (44) hide show
  1. package/README.md +64 -31
  2. package/dist/cli.js +81 -19
  3. package/dist/hooks/user-prompt-submit.js +2 -1
  4. package/dist/init.js +26 -10
  5. package/dist/lib/background.js +23 -4
  6. package/dist/lib/capture-prompt.js +13 -7
  7. package/dist/lib/commands.js +199 -35
  8. package/dist/lib/config.js +24 -4
  9. package/dist/lib/entries.js +56 -4
  10. package/dist/lib/heat.js +141 -0
  11. package/dist/lib/hook-logic.js +44 -9
  12. package/dist/lib/index-cache.js +46 -0
  13. package/dist/lib/links.js +58 -0
  14. package/dist/lib/logo.js +6 -0
  15. package/dist/lib/notes-graph.js +585 -0
  16. package/dist/lib/notes-html.js +148 -339
  17. package/dist/lib/notes-page-css.js +279 -0
  18. package/dist/lib/notes-page-js.js +959 -0
  19. package/dist/lib/notes.js +19 -13
  20. package/dist/lib/nudge.js +2 -1
  21. package/dist/lib/paths.js +6 -0
  22. package/dist/lib/question.js +19 -0
  23. package/dist/lib/queue.js +6 -4
  24. package/dist/lib/recall.js +149 -0
  25. package/dist/lib/results.js +1 -0
  26. package/dist/lib/retag.js +150 -0
  27. package/dist/lib/server-launch.js +73 -0
  28. package/dist/lib/server.js +120 -0
  29. package/dist/lib/session.js +1 -1
  30. package/dist/lib/signals.js +51 -0
  31. package/dist/lib/stats.js +71 -44
  32. package/dist/lib/struggle.js +120 -0
  33. package/dist/lib/surface.js +75 -0
  34. package/dist/lib/transcript.js +61 -15
  35. package/dist/lib/ui.js +127 -0
  36. package/dist/notes-server.js +39 -0
  37. package/dist/sl.js +29 -4
  38. package/dist/vendor/graph3d.js +5402 -0
  39. package/package.json +6 -3
  40. package/skill/SKILL.md +6 -5
  41. package/skill/references/capture.md +6 -5
  42. package/skill/references/recall.md +44 -0
  43. package/skill/references/stats.md +5 -1
  44. package/skill/references/test.md +35 -30
@@ -0,0 +1,51 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { paths } from "./paths.js";
4
+ export const DAY_MS = 86_400_000;
5
+ export const REASK_AFTER_DAYS = 7; // the same question this much later means it didn't stick
6
+ export const OFFER_SNOOZE_DAYS = 30; // never offer about the same thing twice in this long
7
+ export function appendSignal(s) {
8
+ fs.mkdirSync(path.dirname(paths.signals()), { recursive: true });
9
+ fs.appendFileSync(paths.signals(), JSON.stringify(s) + "\n");
10
+ }
11
+ export function readSignals() {
12
+ let text;
13
+ try {
14
+ text = fs.readFileSync(paths.signals(), "utf8");
15
+ }
16
+ catch {
17
+ return [];
18
+ }
19
+ const out = [];
20
+ for (const line of text.split("\n")) {
21
+ if (!line.trim())
22
+ continue;
23
+ try {
24
+ const s = JSON.parse(line);
25
+ if (s && typeof s.type === "string" && typeof s.ts === "string")
26
+ out.push(s);
27
+ }
28
+ catch {
29
+ // skip a corrupt line rather than losing the whole history
30
+ }
31
+ }
32
+ return out;
33
+ }
34
+ /** Record that a note answered a question in this session. Once per note per session. */
35
+ export function recordAsk(entryId, session, project, now = new Date(), signals = readSignals()) {
36
+ if (signals.some((s) => s.type === "ask" && s.entry_id === entryId && s.session === session))
37
+ return false;
38
+ appendSignal({ type: "ask", ts: now.toISOString(), session, project, entry_id: entryId });
39
+ return true;
40
+ }
41
+ /** The earliest time another session used this note at least REASK_AFTER_DAYS ago, or null. */
42
+ export function earlierAsk(entryId, session, now, signals) {
43
+ const cutoff = now.getTime() - REASK_AFTER_DAYS * DAY_MS;
44
+ const hits = signals.filter((s) => s.type === "ask" && s.entry_id === entryId && s.session !== session && new Date(s.ts).getTime() <= cutoff);
45
+ return hits.length ? hits.map((s) => s.ts).sort()[0] : null;
46
+ }
47
+ /** Was an offer about this key made in the last OFFER_SNOOZE_DAYS? */
48
+ export function snoozed(key, project, now, signals) {
49
+ const cutoff = now.getTime() - OFFER_SNOOZE_DAYS * DAY_MS;
50
+ return signals.some((s) => s.type === "offer" && s.key === key && s.project === project && new Date(s.ts).getTime() > cutoff);
51
+ }
package/dist/lib/stats.js CHANGED
@@ -1,10 +1,5 @@
1
- /** Monday (UTC) of the week containing `d`, as YYYY-MM-DD. */
2
- export function weekOf(d) {
3
- const date = new Date(typeof d === "string" && d.length === 10 ? `${d}T00:00:00Z` : d);
4
- const day = (date.getUTCDay() + 6) % 7; // Mon=0
5
- const monday = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() - day));
6
- return monday.toISOString().slice(0, 10);
7
- }
1
+ import { normalizeSkill } from "./entries.js";
2
+ import { weekOfDate } from "./notes.js";
8
3
  function pct(pass, total) {
9
4
  return total === 0 ? "–" : `${Math.round((pass / total) * 100)}%`;
10
5
  }
@@ -13,58 +8,90 @@ function table(header, rows) {
13
8
  const fmt = (r) => r.map((c, i) => (c ?? "").padEnd(widths[i])).join(" ").trimEnd();
14
9
  return [fmt(header), widths.map((w) => "-".repeat(w)).join(" "), ...rows.map(fmt)].join("\n");
15
10
  }
16
- export function renderStats({ entries, results, queue, rating, project }) {
11
+ const rate = (rs) => ({ pass: rs.filter((r) => r.grade === "got").length, total: rs.length });
12
+ function groupRate(results, key) {
13
+ const groups = {};
14
+ for (const r of results) {
15
+ const k = key(r);
16
+ if (k)
17
+ (groups[k] ??= []).push(r);
18
+ }
19
+ return Object.fromEntries(Object.keys(groups).sort().map((k) => [k, rate(groups[k])]));
20
+ }
21
+ /** The numbers behind `selflore stats`. Weeks are local Mondays, the same weeks the notes page shows. */
22
+ export function computeStats({ entries, results, queue, rating, project }) {
23
+ // A result follows its entry's current primary topic, so answers recorded before a re-tag aren't stranded under the old name.
24
+ const topicOf = new Map(entries.map((e) => [e.id, e.skill]));
25
+ results = results.map((r) => ({ ...r, skill: topicOf.get(r.entry_id) || normalizeSkill(r.skill) }));
17
26
  if (project) {
18
27
  entries = entries.filter((e) => e.project === project);
19
28
  results = results.filter((r) => r.project === project);
20
29
  const ids = new Set(entries.map((e) => e.id));
21
30
  queue = Object.fromEntries(Object.entries(queue).filter(([id]) => ids.has(id)));
22
31
  }
23
- if (entries.length === 0 && results.length === 0) {
24
- return project ? `No selflore data for project "${project}" yet.` : "No selflore data yet. Work normally; entries appear as you go.";
25
- }
26
32
  const skills = [...new Set([...entries.map((e) => e.skill), ...results.map((r) => r.skill)])].filter(Boolean).sort();
27
- const weeks = [...new Set([...entries.map((e) => weekOf(e.date)), ...results.map((r) => weekOf(r.ts))])].sort();
28
- const rows = weeks.map((w) => {
29
- const wr = results.filter((r) => weekOf(r.ts) === w);
30
- const pass = (rs) => rs.filter((r) => r.grade === "got").length;
31
- return [
32
- w,
33
- String(entries.filter((e) => weekOf(e.date) === w).length),
34
- String(wr.length),
35
- pct(pass(wr), wr.length),
36
- ...skills.map((s) => {
37
- const sr = wr.filter((r) => r.skill === s);
38
- return pct(pass(sr), sr.length);
39
- }),
40
- ];
33
+ const weekKeys = [...new Set([...entries.map((e) => weekOfDate(e.date)), ...results.map((r) => weekOfDate(r.ts))])].sort();
34
+ const weeks = weekKeys.map((week) => {
35
+ const wr = results.filter((r) => weekOfDate(r.ts) === week);
36
+ return {
37
+ week,
38
+ entries: entries.filter((e) => weekOfDate(e.date) === week).length,
39
+ ...rate(wr),
40
+ by_skill: Object.fromEntries(skills.map((s) => [s, rate(wr.filter((r) => r.skill === s))])),
41
+ };
41
42
  });
42
- const passes = results.filter((r) => r.grade === "got").length;
43
- const first = results.filter((r) => !r.is_retest);
44
- const retest = results.filter((r) => r.is_retest);
45
- const passCount = (rs) => rs.filter((r) => r.grade === "got").length;
46
- const now = Date.now();
47
- const backlog = Object.values(queue);
48
- const overdue = backlog.filter((q) => q.due[0] && new Date(q.due[0]).getTime() <= now).length;
49
- const observed = results.length ? passes / results.length : null;
50
43
  const entryLevel = new Map(entries.map((e) => [e.id, e.level]));
51
44
  const levelOf = (r) => r.level ?? entryLevel.get(r.entry_id) ?? "detail";
52
- const byLevel = (l) => results.filter((r) => levelOf(r) === l);
45
+ const backlog = Object.values(queue);
46
+ const overall = rate(results);
47
+ return {
48
+ project: project ?? null,
49
+ entries: entries.length,
50
+ skills,
51
+ weeks,
52
+ overall,
53
+ detail: rate(results.filter((r) => levelOf(r) === "detail")),
54
+ design: rate(results.filter((r) => levelOf(r) === "design")),
55
+ first: rate(results.filter((r) => !r.is_retest)),
56
+ retest: rate(results.filter((r) => r.is_retest)),
57
+ by_skill: groupRate(results, (r) => r.skill),
58
+ by_project: groupRate(results, (r) => r.project),
59
+ backlog: backlog.length,
60
+ self_graded: results.filter((r) => r.source === "web").length,
61
+ rating,
62
+ observed: overall.total ? overall.pass / overall.total : null,
63
+ };
64
+ }
65
+ export function renderStats(input) {
66
+ const s = computeStats(input);
67
+ const { project } = input;
68
+ if (s.entries === 0 && s.overall.total === 0) {
69
+ return project ? `No selflore data for project "${project}" yet.` : "No selflore data yet. Work normally; entries appear as you go.";
70
+ }
71
+ const p = (r) => pct(r.pass, r.total);
72
+ // Topics are open-ended, so only the ones that have been tested get a column, most answered first.
73
+ const shown = Object.entries(s.by_skill)
74
+ .sort((a, b) => b[1].total - a[1].total || a[0].localeCompare(b[0]))
75
+ .slice(0, 5)
76
+ .map(([k]) => k);
77
+ const rows = s.weeks.map((w) => [w.week, String(w.entries), String(w.total), p(w), ...shown.map((k) => p(w.by_skill[k]))]);
53
78
  const lines = [
54
79
  `selflore stats${project ? ` — ${project}` : ""}`,
55
80
  "",
56
- table(["week of", "entries", "questions", "pass", ...skills.map((s) => `pass:${s}`)], rows),
81
+ ...(input.hot?.length ? [...input.hot, ""] : []),
82
+ table(["week of", "entries", "questions", "pass", ...shown.map((k) => `pass:${k}`)], rows),
57
83
  "",
58
- `overall pass rate ${pct(passes, results.length)} (${passes}/${results.length})`,
59
- `detail pass ${pct(passCount(byLevel("detail")), byLevel("detail").length)}`,
60
- `design pass ${pct(passCount(byLevel("design")), byLevel("design").length)}`,
61
- `first-attempt pass ${pct(passCount(first), first.length)}`,
62
- `retest pass ${pct(passCount(retest), retest.length)}`,
63
- `retest backlog ${backlog.length} queued, ${overdue} due now`,
64
- `self-rating ${rating}/10 (≈${rating * 10}%) vs observed ${observed === null ? "–" : `${Math.round(observed * 100)}%`}`,
84
+ `overall pass rate ${p(s.overall)} (${s.overall.pass}/${s.overall.total})`,
85
+ `detail pass ${p(s.detail)}`,
86
+ `design pass ${p(s.design)}`,
87
+ `first-attempt pass ${p(s.first)}`,
88
+ `retest pass ${p(s.retest)}`,
89
+ `to revisit ${s.backlog} (missed or partly right; asked first next time)`,
90
+ ...(s.self_graded ? [`self-graded (web) ${s.self_graded} of ${s.overall.total} answers`] : []),
91
+ `self-rating ${s.rating}/10 (≈${s.rating * 10}%) vs observed ${s.observed === null ? "–" : `${Math.round(s.observed * 100)}%`}`,
65
92
  ];
66
- if (observed !== null && results.length >= 10) {
67
- const gap = Math.round(observed * 100) - rating * 10;
93
+ if (s.observed !== null && s.overall.total >= 10) {
94
+ const gap = Math.round(s.observed * 100) - s.rating * 10;
68
95
  if (Math.abs(gap) >= 20)
69
96
  lines.push(` tests ${gap > 0 ? "rate you higher" : "rate you lower"} than you do; re-rate with \`npx selflore init\` if it holds`);
70
97
  }
@@ -0,0 +1,120 @@
1
+ import path from "node:path";
2
+ import { readJson, writeJson } from "./fsutil.js";
3
+ import { readIndex } from "./index-cache.js";
4
+ import { paths } from "./paths.js";
5
+ import { readSession, updateSession } from "./session.js";
6
+ import { appendSignal, DAY_MS, readSignals, snoozed } from "./signals.js";
7
+ import { projectOf, repoRoot } from "./surface.js";
8
+ /**
9
+ * Struggle detection. A fail → edit → pass loop is logged with the files that were fought with.
10
+ * When the same file (or the same folder) has had loops in STRUGGLE_SESSIONS different sessions
11
+ * inside STRUGGLE_WINDOW_DAYS, selflore says so once. Edits to files that have notes, with no
12
+ * loop, are logged as "touch": evidence that the area gives no trouble.
13
+ */
14
+ export const STRUGGLE_SESSIONS = 3;
15
+ export const STRUGGLE_WINDOW_DAYS = 60;
16
+ const PENDING_TTL_DAYS = 14; // an undelivered offer this old is about work the user has moved on from
17
+ export function normPath(p) {
18
+ return p.replace(/\\/g, "/").replace(/^\.\//, "");
19
+ }
20
+ export function dirOf(p) {
21
+ const clean = normPath(p);
22
+ const i = clean.lastIndexOf("/");
23
+ return i > 0 ? clean.slice(0, i) : "";
24
+ }
25
+ /** Does a file fall in an area? An area is a file, or a folder written with a trailing slash. */
26
+ export function inArea(file, area) {
27
+ const f = normPath(file);
28
+ return area.endsWith("/") ? dirOf(f) === area.slice(0, -1) : f === area;
29
+ }
30
+ /**
31
+ * The area among `files` with loops in the most different sessions over the window, if it reaches
32
+ * the bar. A file wins over its folder: "this file keeps biting you" is the more useful thing to say.
33
+ */
34
+ export function struggleArea(project, files, signals, now) {
35
+ const since = now.getTime() - STRUGGLE_WINDOW_DAYS * DAY_MS;
36
+ const loops = signals.filter((s) => s.type === "loop" && s.project === project && new Date(s.ts).getTime() >= since);
37
+ const count = (area) => new Set(loops.filter((l) => l.paths.some((p) => inArea(p, area))).map((l) => l.session)).size;
38
+ const best = (areas) => {
39
+ let top = null;
40
+ for (const area of new Set(areas)) {
41
+ const sessions = count(area);
42
+ if (sessions >= STRUGGLE_SESSIONS && (!top || sessions > top.sessions))
43
+ top = { area, sessions };
44
+ }
45
+ return top;
46
+ };
47
+ return best(files.map(normPath)) ?? best(files.map(dirOf).filter(Boolean).map((d) => `${d}/`));
48
+ }
49
+ export function readPending() {
50
+ return readJson(paths.pendingOffers(), {});
51
+ }
52
+ /** The offer waiting for this project, if it is still worth making. */
53
+ export function pendingFor(project, now, signals) {
54
+ const p = readPending()[project];
55
+ if (!p)
56
+ return null;
57
+ if (now.getTime() - new Date(p.ts).getTime() > PENDING_TTL_DAYS * DAY_MS)
58
+ return null;
59
+ return snoozed(p.area, project, now, signals) ? null : p;
60
+ }
61
+ export function clearPending(project) {
62
+ const all = readPending();
63
+ if (!(project in all))
64
+ return;
65
+ delete all[project];
66
+ writeJson(paths.pendingOffers(), all);
67
+ }
68
+ /**
69
+ * Called by the Stop hook with what it found in the transcript since the last capture. Logs loop
70
+ * and touch signals (each once per session, since a chunk can be scanned more than once) and
71
+ * queues a struggle offer when a loop tips an area over the bar.
72
+ */
73
+ export function recordWork(opts) {
74
+ const { triggers } = opts;
75
+ if (!triggers.edited.length && !triggers.loopFiles.length)
76
+ return;
77
+ const now = opts.now ?? new Date();
78
+ const root = repoRoot(opts.cwd);
79
+ const project = projectOf(opts.cwd);
80
+ const rel = (file) => {
81
+ const r = path.relative(root, path.resolve(opts.cwd, file));
82
+ return r && !r.startsWith("..") && !path.isAbsolute(r) ? normPath(r) : null;
83
+ };
84
+ const inRepo = (files) => [...new Set(files.map(rel).filter((f) => f !== null))];
85
+ const done = new Set(readSession(opts.session).signaled);
86
+ const added = [];
87
+ const loopFiles = triggers.bugFixLoop ? inRepo(triggers.loopFiles) : [];
88
+ const loopKey = `loop:${[...loopFiles].sort().join("|")}`;
89
+ if (loopFiles.length && !done.has(loopKey)) {
90
+ appendSignal({ type: "loop", ts: now.toISOString(), session: opts.session, project, paths: loopFiles });
91
+ added.push(loopKey);
92
+ if (opts.offers) {
93
+ const signals = readSignals();
94
+ const hit = struggleArea(project, loopFiles, signals, now);
95
+ if (hit && !snoozed(hit.area, project, now, signals))
96
+ writeJson(paths.pendingOffers(), { ...readPending(), [project]: { ...hit, ts: now.toISOString() } });
97
+ }
98
+ }
99
+ // Edits to files that have notes, with no loop around them.
100
+ const noted = new Set(readIndex().filter((d) => d.project === project).flatMap((d) => d.paths.map(normPath)));
101
+ const touched = inRepo(triggers.edited).filter((f) => noted.has(f) && !loopFiles.includes(f) && !done.has(`touch:${f}`) && !done.has(`loopfile:${f}`));
102
+ if (touched.length) {
103
+ appendSignal({ type: "touch", ts: now.toISOString(), session: opts.session, project, paths: touched });
104
+ added.push(...touched.map((f) => `touch:${f}`));
105
+ }
106
+ // A file that had a loop this session doesn't later count as trouble-free in the same session.
107
+ added.push(...loopFiles.filter((f) => !done.has(`loopfile:${f}`)).map((f) => `loopfile:${f}`));
108
+ if (added.length)
109
+ updateSession(opts.session, { signaled: [...done, ...added] });
110
+ }
111
+ const ORDINALS = ["", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh"];
112
+ /** The context line that asks Claude to make the struggle offer, once, at a natural pause. */
113
+ export function struggleLine(p, project, sl) {
114
+ const nth = ORDINALS[p.sessions] ?? `${p.sessions}th`;
115
+ const what = p.area.endsWith("/") ? `the files in ${p.area}` : p.area;
116
+ return (`selflore: offer — ${p.sessions} separate sessions in the last ${STRUGGLE_WINDOW_DAYS} days had a test fail, get fixed and pass again in ${what} (project ${project}). ` +
117
+ `At a natural pause, after doing what the user asked and never mid-task, say once, in one line: "${nth} time ${p.area} has bitten you. Want the 2-minute version?" ` +
118
+ `If they say yes: run \`${sl} recall "${p.area}" --limit 5\`, read the notes that fit with \`${sl} show <id>\`, and explain how that code works and why it is built that way in under 200 words, checked against the current files. Then ask whether they want 2 questions on it (references/test.md). ` +
119
+ `If they say no or don't answer, drop it and never raise it again.`);
120
+ }
@@ -0,0 +1,75 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { readIndex } from "./index-cache.js";
4
+ import { isQuestion } from "./question.js";
5
+ import { rank } from "./recall.js";
6
+ import { appendSignal, earlierAsk, readSignals, snoozed } from "./signals.js";
7
+ /**
8
+ * Surfacing: when the user asks a question, hand Claude the notes that may answer it. Runs inside
9
+ * the UserPromptSubmit hook, so: no model, no git, no network. A wrong match costs more trust than
10
+ * a miss, so the bar is higher than for an explicit `sl recall`.
11
+ */
12
+ export const SURFACE_MIN = 0.5;
13
+ export const SURFACE_LIMIT = 3;
14
+ /** The repo root (the nearest folder with `.git`), or `dir` itself. No git process: this runs on every prompt. */
15
+ export function repoRoot(dir) {
16
+ const start = path.resolve(dir);
17
+ for (let cur = start;;) {
18
+ if (fs.existsSync(path.join(cur, ".git")))
19
+ return cur;
20
+ const up = path.dirname(cur);
21
+ if (up === cur)
22
+ return start;
23
+ cur = up;
24
+ }
25
+ }
26
+ /** Last two path segments of the repo root. Matches projectInfo() without running git. */
27
+ export function projectOf(dir) {
28
+ const root = repoRoot(dir);
29
+ return root.split(path.sep).filter(Boolean).slice(-2).join("/") || root;
30
+ }
31
+ export function candidates(prompt, cwd) {
32
+ const project = projectOf(cwd);
33
+ if (!isQuestion(prompt))
34
+ return { project, hits: [] };
35
+ return { project, hits: rank(prompt, readIndex(), { project, limit: SURFACE_LIMIT, min: SURFACE_MIN }) };
36
+ }
37
+ function clip(s, n) {
38
+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;
39
+ }
40
+ function monthDay(iso) {
41
+ const d = new Date(iso.length === 10 ? `${iso}T12:00:00` : iso);
42
+ return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
43
+ }
44
+ /**
45
+ * The context block for a question that the user's notes may answer, or "" when there is nothing.
46
+ * If one of the candidates was already used to answer them a week or more ago, in another session,
47
+ * this is a re-ask: one offer of a short check is added (and logged, which snoozes that note).
48
+ */
49
+ export function surface(opts) {
50
+ const { project, hits } = candidates(opts.prompt, opts.cwd);
51
+ if (!hits.length)
52
+ return { text: "", offered: false };
53
+ const now = opts.now ?? new Date();
54
+ const lines = [
55
+ "selflore: the user's own notes may answer this question. Candidates, most likely first:",
56
+ ...hits.map((h) => `- ${h.doc.id} (${h.doc.date}; ${h.doc.topics.join(", ")}) ${clip(h.doc.testable, 150)}`),
57
+ `If one fits what they asked, run \`${opts.sl} show <id> --session ${opts.session}\` and answer as the selflore skill's references/recall.md says, opening with "From your notes, <date>: …". If none fits, ignore this completely and never mention it.`,
58
+ ];
59
+ let offered = false;
60
+ if (opts.mayOffer) {
61
+ const signals = opts.signals ?? readSignals();
62
+ for (const h of hits) {
63
+ const before = earlierAsk(h.doc.id, opts.session, now, signals);
64
+ if (!before || snoozed(h.doc.id, project, now, signals))
65
+ continue;
66
+ const topic = h.doc.topics[0] ?? "";
67
+ lines.push(`selflore: offer — a note on this (${h.doc.id}) already answered them on ${monthDay(before)}. Only if you answer from that note: end with one line, "Second time you've asked about this. Want a 2-minute check?", and nothing more about it. ` +
68
+ `If they say yes, follow references/test.md with \`${opts.sl} quiz-input --project "${project}"${topic ? ` --topic "${topic}"` : ""}\` and ask 2 questions. If they say no or ignore it, drop it.`);
69
+ appendSignal({ type: "offer", ts: now.toISOString(), session: opts.session, project, kind: "reask", key: h.doc.id });
70
+ offered = true;
71
+ break;
72
+ }
73
+ }
74
+ return { text: lines.join("\n"), offered };
75
+ }
@@ -1,11 +1,16 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { isQuestion } from "./question.js";
3
4
  /**
4
5
  * Cheap heuristics over a Claude Code transcript (JSONL) that decide whether a stretch
5
6
  * of work is worth a capture pass. Only mechanically observable triggers live here;
6
7
  * tradeoffs and corrections are judged by the capture model itself.
7
8
  */
8
- export const MIN_LINES = { light: 80, normal: 30, thorough: 15 };
9
+ // What the agent wrote is a weak sign of what the user doesn't know, so a write has to be big to
10
+ // count on its own. What the user asked to have explained (below) is the strong sign.
11
+ export const MIN_LINES = { light: 150, normal: 80, thorough: 30 };
12
+ /** An answer this long, to a question, with no code written, is an explanation worth keeping. */
13
+ export const MIN_EXPLANATION_WORDS = 120;
9
14
  const DEP_FILES = new Set([
10
15
  "package.json",
11
16
  "requirements.txt",
@@ -50,6 +55,24 @@ export function detectTriggers(jsonl, opts = {}) {
50
55
  const depChanges = new Set();
51
56
  const testCmds = new Map(); // tool_use id -> is a test command
52
57
  const seq = [];
58
+ // An explanation: the user asks a question, the agent answers in prose, and no code is written
59
+ // before the user speaks again.
60
+ let explained = 0;
61
+ let asked = false;
62
+ let prose = 0;
63
+ let wrote = false;
64
+ const closeTurn = () => {
65
+ if (asked && !wrote && prose >= MIN_EXPLANATION_WORDS)
66
+ explained++;
67
+ };
68
+ const userSpoke = (text) => {
69
+ if (!text.trim() || text.startsWith("<"))
70
+ return; // tool output, reminders, pasted blocks
71
+ closeTurn();
72
+ asked = isQuestion(text);
73
+ prose = 0;
74
+ wrote = false;
75
+ };
53
76
  for (const raw of jsonl.split("\n")) {
54
77
  if (!raw.trim())
55
78
  continue;
@@ -61,10 +84,18 @@ export function detectTriggers(jsonl, opts = {}) {
61
84
  continue;
62
85
  }
63
86
  const content = line.message?.content;
87
+ if (line.type === "user" && !line.isMeta && typeof content === "string")
88
+ userSpoke(content);
64
89
  if (!Array.isArray(content))
65
90
  continue;
66
91
  for (const block of content) {
67
- if (block.type === "tool_use") {
92
+ if (block.type === "text" && typeof block.text === "string") {
93
+ if (line.type === "user" && !line.isMeta)
94
+ userSpoke(block.text);
95
+ else if (line.type === "assistant")
96
+ prose += block.text.split(/\s+/).filter(Boolean).length;
97
+ }
98
+ else if (block.type === "tool_use") {
68
99
  const tu = block;
69
100
  const input = tu.input ?? {};
70
101
  const file = typeof input.file_path === "string" ? input.file_path : "";
@@ -82,7 +113,8 @@ export function detectTriggers(jsonl, opts = {}) {
82
113
  edits.set(file, (edits.get(file) ?? 0) + 1);
83
114
  if (DEP_FILES.has(path.basename(file)))
84
115
  depChanges.add(file);
85
- seq.push("edit");
116
+ seq.push({ ev: "edit", file });
117
+ wrote = true;
86
118
  }
87
119
  else if (tu.name === "Bash" && typeof input.command === "string") {
88
120
  testCmds.set(tu.id, TEST_CMD.test(input.command));
@@ -95,32 +127,44 @@ export function detectTriggers(jsonl, opts = {}) {
95
127
  if (!testCmds.get(id))
96
128
  continue;
97
129
  const failed = block.is_error === true || FAIL_TEXT.test(contentText(block.content));
98
- seq.push(failed ? "fail" : "pass");
130
+ seq.push({ ev: failed ? "fail" : "pass" });
99
131
  }
100
132
  }
101
133
  }
134
+ closeTurn();
102
135
  const largeWrites = [...added]
103
136
  .filter(([file, n]) => n >= minLines && (opts.keepWrite?.({ file, editCount: edits.get(file) ?? 1 }) ?? true))
104
137
  .map(([file]) => file);
105
- // fail → (edit)+ → pass
138
+ // fail → (edit)+ → pass, as many times as it happens; the files edited inside a loop are what was fought with.
106
139
  let bugFixLoop = false;
140
+ const loopFiles = new Set();
107
141
  let state = "idle";
108
- for (const ev of seq) {
109
- if (ev === "fail")
110
- state = "failed";
111
- else if (ev === "edit" && state !== "idle")
142
+ let current = [];
143
+ for (const { ev, file } of seq) {
144
+ if (ev === "fail") {
145
+ if (state === "idle")
146
+ current = [];
147
+ state = state === "edited" ? "edited" : "failed";
148
+ }
149
+ else if (ev === "edit" && state !== "idle") {
112
150
  state = "edited";
113
- else if (ev === "pass" && state === "edited") {
114
- bugFixLoop = true;
115
- break;
151
+ if (file)
152
+ current.push(file);
116
153
  }
117
- else if (ev === "pass")
154
+ else if (ev === "pass") {
155
+ if (state === "edited") {
156
+ bugFixLoop = true;
157
+ for (const f of current)
158
+ loopFiles.add(f);
159
+ }
118
160
  state = "idle";
161
+ current = [];
162
+ }
119
163
  }
120
- return { largeWrites, depChanges: [...depChanges], bugFixLoop };
164
+ return { largeWrites, depChanges: [...depChanges], bugFixLoop, loopFiles: [...loopFiles], explained, edited: [...edits.keys()] };
121
165
  }
122
166
  export function anyTrigger(t) {
123
- return t.largeWrites.length > 0 || t.depChanges.length > 0 || t.bugFixLoop;
167
+ return t.largeWrites.length > 0 || t.depChanges.length > 0 || t.bugFixLoop || t.explained > 0;
124
168
  }
125
169
  export function describeTriggers(t) {
126
170
  const parts = [];
@@ -130,6 +174,8 @@ export function describeTriggers(t) {
130
174
  parts.push("new dependencies");
131
175
  if (t.bugFixLoop)
132
176
  parts.push("a fail → fix → pass loop");
177
+ if (t.explained)
178
+ parts.push(t.explained === 1 ? "an explanation the user asked for" : `${t.explained} explanations the user asked for`);
133
179
  return parts.join("; ");
134
180
  }
135
181
  /**
package/dist/lib/ui.js ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Terminal styling for the human-facing CLI (`selflore …`). No dependencies.
3
+ *
4
+ * Only `cli.ts` and `init.ts` use this. Hooks and `sl` print text that Claude reads, so they stay plain.
5
+ * Colour goes to a real terminal only, never when NO_COLOR is set, and steps down from 24-bit to
6
+ * 256 colours to the basic 16, so piped output is clean and old terminals still get a readable mark.
7
+ */
8
+ export function colorLevel({ env = process.env, isTTY = !!process.stdout.isTTY } = {}) {
9
+ if ("NO_COLOR" in env)
10
+ return 0;
11
+ const force = env.FORCE_COLOR;
12
+ if (force !== undefined) {
13
+ if (force === "0" || force === "false")
14
+ return 0;
15
+ return force === "3" ? 3 : force === "2" ? 2 : 1;
16
+ }
17
+ if (!isTTY || env.TERM === "dumb")
18
+ return 0;
19
+ if (/truecolor|24bit/i.test(env.COLORTERM ?? ""))
20
+ return 3;
21
+ return /256/.test(env.TERM ?? "") ? 2 : 1;
22
+ }
23
+ // ANSI Shadow, six rows a letter. Kept per letter so the word is readable here and checkable in a test.
24
+ const GLYPHS = {
25
+ s: ["███████╗", "██╔════╝", "███████╗", "╚════██║", "███████║", "╚══════╝"],
26
+ e: ["███████╗", "██╔════╝", "█████╗ ", "██╔══╝ ", "███████╗", "╚══════╝"],
27
+ l: ["██╗ ", "██║ ", "██║ ", "██║ ", "███████╗", "╚══════╝"],
28
+ f: ["███████╗", "██╔════╝", "█████╗ ", "██╔══╝ ", "██║ ", "╚═╝ "],
29
+ o: [" ██████╗ ", "██╔═══██╗", "██║ ██║", "██║ ██║", "╚██████╔╝", " ╚═════╝ "],
30
+ r: ["██████╗ ", "██╔══██╗", "██████╔╝", "██╔══██╗", "██║ ██║", "╚═╝ ╚═╝"],
31
+ };
32
+ /** The big wordmark, one string per row, every row the same width. */
33
+ export const WORDMARK = [0, 1, 2, 3, 4, 5].map((row) => Array.from("selflore", (c) => GLYPHS[c][row]).join(""));
34
+ /** Columns the banner needs: the wordmark plus its left margin. */
35
+ export const BANNER_WIDTH = WORDMARK[0].length + 4;
36
+ export const TAGLINE = "your agent wrote it, selflore remembers why";
37
+ /**
38
+ * The wordmark's colours, left to right: the notes page's indigo accent over "self", then its heat
39
+ * scale (amber up to the red of a stuck note) over "lore". All mid-tones, so the word holds on a
40
+ * light terminal as well as a dark one.
41
+ */
42
+ const WORD = [
43
+ [129, 140, 248],
44
+ [150, 150, 220],
45
+ [236, 160, 60],
46
+ [248, 118, 48],
47
+ [255, 92, 66],
48
+ ];
49
+ const ACCENT = [129, 140, 248];
50
+ const AMBER = [232, 150, 50];
51
+ const GREEN = [52, 199, 142];
52
+ function sample(stops, t) {
53
+ const seg = Math.min(1, Math.max(0, t)) * (stops.length - 1);
54
+ const i = Math.min(stops.length - 2, Math.floor(seg));
55
+ const f = seg - i;
56
+ const a = stops[i];
57
+ const b = stops[i + 1];
58
+ return [0, 1, 2].map((k) => Math.round(a[k] + (b[k] - a[k]) * f));
59
+ }
60
+ /** Nearest entry in the 6×6×6 colour cube of a 256-colour terminal. */
61
+ function cube([r, g, b]) {
62
+ // The cube's levels are 0, 95, 135, 175, 215, 255.
63
+ const step = (v) => (v < 48 ? 0 : Math.max(1, Math.round((v - 55) / 40)));
64
+ return 16 + 36 * step(r) + 6 * step(g) + step(b);
65
+ }
66
+ export function createUi(opts = {}) {
67
+ const isTTY = opts.isTTY ?? !!process.stdout.isTTY;
68
+ const level = colorLevel({ env: opts.env, isTTY });
69
+ const columns = opts.columns ?? process.stdout.columns ?? (Number((opts.env ?? process.env).COLUMNS) || 0);
70
+ const sgr = (open, close) => (s) => (level ? `\x1b[${open}m${s}\x1b[${close}m` : s);
71
+ /** The escape that sets the text colour, at whatever depth this terminal has. */
72
+ const fg = (c, basic) => (level === 3 ? `38;2;${c[0]};${c[1]};${c[2]}` : level === 2 ? `38;5;${cube(c)}` : String(basic));
73
+ const ink = (c, basic) => sgr(fg(c, basic), 39);
74
+ const bold = sgr("1", 22);
75
+ const dim = sgr("2", 22);
76
+ const accent = ink(ACCENT, 94);
77
+ const amber = ink(AMBER, 33);
78
+ const green = ink(GREEN, 32);
79
+ /** Colour each character by its column: indigo at the left, the hottest red at column `span`. */
80
+ function gradient(s, span = s.length) {
81
+ if (!level)
82
+ return s;
83
+ let out = "\x1b[1m";
84
+ let last = "";
85
+ Array.from(s).forEach((ch, i) => {
86
+ if (ch !== " ") {
87
+ const t = span <= 1 ? 0 : i / (span - 1);
88
+ // With only 16 colours the word still splits the same way: blue "self", then yellow into red.
89
+ const code = fg(sample(WORD, t), t < 0.42 ? 94 : t < 0.8 ? 33 : 91);
90
+ if (code !== last)
91
+ out += `\x1b[${code}m`;
92
+ last = code;
93
+ }
94
+ out += ch;
95
+ });
96
+ return `${out}\x1b[39m\x1b[22m`;
97
+ }
98
+ const symbols = { ok: green("✓"), spark: amber("✦"), warn: amber("!"), dot: dim("·") };
99
+ const wide = columns === 0 || columns >= BANNER_WIDTH;
100
+ function banner(version) {
101
+ const width = WORDMARK[0].length;
102
+ const mark = wide
103
+ ? WORDMARK.map((line) => ` ${gradient(line.trimEnd(), width)}`).join("\n")
104
+ : ` ${gradient("✦ s e l f l o r e")}`;
105
+ const tail = version ? ` ${symbols.dot} ${dim(`v${version}`)}` : "";
106
+ return `\n${mark}\n ${dim(TAGLINE)}${tail}\n`;
107
+ }
108
+ function header(label) {
109
+ return ` ${symbols.spark} ${gradient("selflore")}${label ? ` ${dim(label)}` : ""}`;
110
+ }
111
+ function row(command, description, width = 30) {
112
+ return ` ${accent(command.padEnd(width))}${dim(description)}`;
113
+ }
114
+ function frame(label, body) {
115
+ if (!isTTY)
116
+ return body;
117
+ const lines = body.split("\n");
118
+ // A short result sits under the name; a long listing keeps nearly the full width.
119
+ const pad = lines.length <= 6 ? " " : " ";
120
+ return `\n${header(label)}\n\n${lines.map((l) => (l ? pad + l : l)).join("\n")}\n`;
121
+ }
122
+ return { level, bold, dim, accent, amber, green, wordmark: gradient, symbols, banner, header, row, frame };
123
+ }
124
+ /** Strip colour codes, for measuring or comparing what was printed. */
125
+ export function plain(s) {
126
+ return s.replace(/\x1b\[[0-9;]*m/g, "");
127
+ }