selflore 0.0.2 → 0.1.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.
@@ -1,7 +1,16 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { paths } from "./paths.js";
4
- export const QUESTION_TYPES = ["explain-why", "predict-behavior", "find-the-bug", "rewrite-from-spec", "recall"];
4
+ // detail-level: predict-behavior, find-the-bug, rewrite-from-spec; design-level: explain-why, what-breaks, tradeoff-at-scale.
5
+ export const QUESTION_TYPES = [
6
+ "explain-why",
7
+ "what-breaks",
8
+ "tradeoff-at-scale",
9
+ "predict-behavior",
10
+ "find-the-bug",
11
+ "rewrite-from-spec",
12
+ "recall",
13
+ ];
5
14
  export function appendResult(r) {
6
15
  fs.mkdirSync(path.dirname(paths.results()), { recursive: true });
7
16
  fs.appendFileSync(paths.results(), JSON.stringify(r) + "\n");
@@ -1,12 +1,38 @@
1
1
  import path from "node:path";
2
2
  import { readJson, writeJson } from "./fsutil.js";
3
3
  import { paths } from "./paths.js";
4
+ const EMPTY = { entries: [], scanned_offset: 0, pending: null, capturing_since: null };
4
5
  function file(sessionId) {
5
6
  return path.join(paths.state(), `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
6
7
  }
7
8
  export function readSession(sessionId) {
8
- return readJson(file(sessionId), { entries: [], nudged: false });
9
+ // Spread over defaults so v0.2 state files ({entries, nudged}) keep working.
10
+ const { nudged: _legacy, ...raw } = readJson(file(sessionId), {});
11
+ return { ...EMPTY, ...raw };
9
12
  }
10
13
  export function writeSession(sessionId, s) {
11
14
  writeJson(file(sessionId), s);
12
15
  }
16
+ export function updateSession(sessionId, change) {
17
+ const next = { ...readSession(sessionId), ...change };
18
+ writeSession(sessionId, next);
19
+ return next;
20
+ }
21
+ export const LOCK_TTL_MS = 10 * 60 * 1000;
22
+ export function isCapturing(s, now = new Date()) {
23
+ return s.capturing_since !== null && now.getTime() - new Date(s.capturing_since).getTime() < LOCK_TTL_MS;
24
+ }
25
+ // Background captures not yet mentioned to the user; announced once at the next session start.
26
+ const announceFile = () => path.join(paths.state(), "_announce.json");
27
+ export function addAnnounce(n) {
28
+ if (n <= 0)
29
+ return;
30
+ const cur = readJson(announceFile(), { count: 0 });
31
+ writeJson(announceFile(), { count: cur.count + n });
32
+ }
33
+ export function takeAnnounce() {
34
+ const cur = readJson(announceFile(), { count: 0 });
35
+ if (cur.count > 0)
36
+ writeJson(announceFile(), { count: 0 });
37
+ return cur.count;
38
+ }
@@ -2,7 +2,11 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { readJson, writeJson } from "./fsutil.js";
4
4
  import { paths } from "./paths.js";
5
- export const HOOK_SCRIPTS = { SessionStart: "session-start.js", Stop: "stop.js" };
5
+ export const HOOK_SCRIPTS = {
6
+ SessionStart: "session-start.js",
7
+ Stop: "stop.js",
8
+ UserPromptSubmit: "user-prompt-submit.js",
9
+ };
6
10
  export function hookCommand(appDir, script) {
7
11
  return `node "${path.join(appDir, "hooks", script)}"`;
8
12
  }
package/dist/lib/stats.js CHANGED
@@ -47,12 +47,17 @@ export function renderStats({ entries, results, queue, rating, project }) {
47
47
  const backlog = Object.values(queue);
48
48
  const overdue = backlog.filter((q) => q.due[0] && new Date(q.due[0]).getTime() <= now).length;
49
49
  const observed = results.length ? passes / results.length : null;
50
+ const entryLevel = new Map(entries.map((e) => [e.id, e.level]));
51
+ const levelOf = (r) => r.level ?? entryLevel.get(r.entry_id) ?? "detail";
52
+ const byLevel = (l) => results.filter((r) => levelOf(r) === l);
50
53
  const lines = [
51
54
  `selflore stats${project ? ` — ${project}` : ""}`,
52
55
  "",
53
56
  table(["week of", "entries", "questions", "pass", ...skills.map((s) => `pass:${s}`)], rows),
54
57
  "",
55
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)}`,
56
61
  `first-attempt pass ${pct(passCount(first), first.length)}`,
57
62
  `retest pass ${pct(passCount(retest), retest.length)}`,
58
63
  `retest backlog ${backlog.length} queued, ${overdue} due now`,
@@ -1,11 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  /**
4
- * Cheap heuristics over a Claude Code transcript (JSONL) for the Stop-hook safety net.
5
- * Only the mechanically observable PRD triggers are detected here; tradeoffs and
6
- * corrections are left to the skill itself.
4
+ * Cheap heuristics over a Claude Code transcript (JSONL) that decide whether a stretch
5
+ * of work is worth a capture pass. Only mechanically observable triggers live here;
6
+ * tradeoffs and corrections are judged by the capture model itself.
7
7
  */
8
- export const LARGE_WRITE_LINES = 30;
8
+ export const MIN_LINES = { light: 80, normal: 30, thorough: 15 };
9
9
  const DEP_FILES = new Set([
10
10
  "package.json",
11
11
  "requirements.txt",
@@ -19,6 +19,8 @@ const DEP_FILES = new Set([
19
19
  "build.gradle.kts",
20
20
  "pom.xml",
21
21
  ]);
22
+ // Reports, notes and data the agent wrote for the user to read, not code to understand later.
23
+ const DOC_EXTS = new Set([".md", ".mdx", ".markdown", ".txt", ".rst", ".csv", ".tsv", ".log", ".json", ".html", ".pdf"]);
22
24
  const TEST_CMD = /\b(test|tests|jest|vitest|pytest|mocha|rspec|cargo test|go test|phpunit|tsc)\b/;
23
25
  const FAIL_TEXT = /\b(FAIL|FAILED|failed|Error:|error TS\d+|Traceback|panic:)\b/;
24
26
  function lineCount(s) {
@@ -31,11 +33,22 @@ function contentText(c) {
31
33
  return c.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("\n");
32
34
  return "";
33
35
  }
34
- export function detectTriggers(jsonl) {
35
- const largeWrites = new Set();
36
+ /** Files never worth capturing from, regardless of size. */
37
+ export function isIgnoredPath(file) {
38
+ const norm = file.split(path.sep).join("/");
39
+ if (norm.includes("/.claude/") || norm.includes("/.selflore/"))
40
+ return true;
41
+ const base = path.basename(file);
42
+ if (DEP_FILES.has(base))
43
+ return false;
44
+ return DOC_EXTS.has(path.extname(base).toLowerCase());
45
+ }
46
+ export function detectTriggers(jsonl, opts = {}) {
47
+ const minLines = opts.minLines ?? MIN_LINES.normal;
48
+ const added = new Map(); // largest single write per file
49
+ const edits = new Map();
36
50
  const depChanges = new Set();
37
51
  const testCmds = new Map(); // tool_use id -> is a test command
38
- // Sequence of events: "fail" | "pass" | "edit"
39
52
  const seq = [];
40
53
  for (const raw of jsonl.split("\n")) {
41
54
  if (!raw.trim())
@@ -55,18 +68,18 @@ export function detectTriggers(jsonl) {
55
68
  const tu = block;
56
69
  const input = tu.input ?? {};
57
70
  const file = typeof input.file_path === "string" ? input.file_path : "";
58
- if (file.includes(`${path.sep}.selflore${path.sep}`))
59
- continue;
60
- let added = 0;
61
- if (tu.name === "Write")
62
- added = lineCount(input.content);
63
- else if (tu.name === "Edit")
64
- added = lineCount(input.new_string) - lineCount(input.old_string);
65
- else if (tu.name === "MultiEdit" && Array.isArray(input.edits))
66
- added = input.edits.reduce((n, e) => n + lineCount(e.new_string) - lineCount(e.old_string), 0);
67
71
  if (["Write", "Edit", "MultiEdit"].includes(tu.name)) {
68
- if (added >= LARGE_WRITE_LINES)
69
- largeWrites.add(file);
72
+ if (!file || isIgnoredPath(file))
73
+ continue;
74
+ let n = 0;
75
+ if (tu.name === "Write")
76
+ n = lineCount(input.content);
77
+ else if (tu.name === "Edit")
78
+ n = lineCount(input.new_string) - lineCount(input.old_string);
79
+ else if (Array.isArray(input.edits))
80
+ n = input.edits.reduce((sum, e) => sum + lineCount(e.new_string) - lineCount(e.old_string), 0);
81
+ added.set(file, Math.max(added.get(file) ?? 0, n));
82
+ edits.set(file, (edits.get(file) ?? 0) + 1);
70
83
  if (DEP_FILES.has(path.basename(file)))
71
84
  depChanges.add(file);
72
85
  seq.push("edit");
@@ -86,6 +99,9 @@ export function detectTriggers(jsonl) {
86
99
  }
87
100
  }
88
101
  }
102
+ const largeWrites = [...added]
103
+ .filter(([file, n]) => n >= minLines && (opts.keepWrite?.({ file, editCount: edits.get(file) ?? 1 }) ?? true))
104
+ .map(([file]) => file);
89
105
  // fail → (edit)+ → pass
90
106
  let bugFixLoop = false;
91
107
  let state = "idle";
@@ -101,7 +117,7 @@ export function detectTriggers(jsonl) {
101
117
  else if (ev === "pass")
102
118
  state = "idle";
103
119
  }
104
- return { largeWrites: [...largeWrites], depChanges: [...depChanges], bugFixLoop };
120
+ return { largeWrites, depChanges: [...depChanges], bugFixLoop };
105
121
  }
106
122
  export function anyTrigger(t) {
107
123
  return t.largeWrites.length > 0 || t.depChanges.length > 0 || t.bugFixLoop;
@@ -109,20 +125,126 @@ export function anyTrigger(t) {
109
125
  export function describeTriggers(t) {
110
126
  const parts = [];
111
127
  if (t.largeWrites.length)
112
- parts.push(`large writes (${t.largeWrites.map((f) => path.basename(f)).join(", ")})`);
128
+ parts.push(`changes to ${t.largeWrites.map((f) => path.basename(f)).join(", ")}`);
113
129
  if (t.depChanges.length)
114
130
  parts.push("new dependencies");
115
131
  if (t.bugFixLoop)
116
132
  parts.push("a fail → fix → pass loop");
117
133
  return parts.join("; ");
118
134
  }
119
- export function readTranscript(file) {
135
+ /**
136
+ * Read the transcript from a byte offset (optionally up to `to`), ending at the last complete line.
137
+ * Returns the text plus the actual start and the offset to resume from. A shrunk file restarts at 0.
138
+ */
139
+ export function readTranscriptFrom(file, from, to) {
120
140
  if (!file)
121
- return "";
141
+ return { text: "", start: from, end: from };
142
+ let size;
122
143
  try {
123
- return fs.readFileSync(file, "utf8");
144
+ size = fs.statSync(file).size;
124
145
  }
125
146
  catch {
126
- return "";
147
+ return { text: "", start: from, end: from };
148
+ }
149
+ const start = from > size ? 0 : from;
150
+ const stop = to !== undefined && to > start ? Math.min(to, size) : size;
151
+ if (stop <= start)
152
+ return { text: "", start, end: start };
153
+ const fd = fs.openSync(file, "r");
154
+ try {
155
+ const buf = Buffer.alloc(stop - start);
156
+ fs.readSync(fd, buf, 0, buf.length, start);
157
+ const lastNl = buf.lastIndexOf(0x0a);
158
+ if (lastNl < 0)
159
+ return { text: "", start, end: start };
160
+ return { text: buf.subarray(0, lastNl + 1).toString("utf8"), start, end: start + lastNl + 1 };
161
+ }
162
+ finally {
163
+ fs.closeSync(fd);
164
+ }
165
+ }
166
+ /** Model id of the most recent assistant message in a transcript chunk, if any. */
167
+ export function lastModel(jsonl) {
168
+ let model = null;
169
+ for (const raw of jsonl.split("\n")) {
170
+ if (!raw.includes('"model"'))
171
+ continue;
172
+ try {
173
+ const line = JSON.parse(raw);
174
+ if (line.type === "assistant" && typeof line.message?.model === "string" && !line.message.model.startsWith("<"))
175
+ model = line.message.model;
176
+ }
177
+ catch {
178
+ // ignore
179
+ }
180
+ }
181
+ return model;
182
+ }
183
+ const MAX_BLOCK_LINES = 60;
184
+ function clip(s, maxLines = MAX_BLOCK_LINES) {
185
+ const lines = s.split("\n");
186
+ return lines.length <= maxLines ? s : `${lines.slice(0, maxLines).join("\n")}\n… (${lines.length - maxLines} more lines)`;
187
+ }
188
+ /**
189
+ * A compact, readable excerpt of a transcript chunk for the capture model:
190
+ * user prompts, assistant prose, and tool calls with paths and (clipped) code.
191
+ * Keeps the most recent `maxChars` if the chunk is long.
192
+ */
193
+ export function buildExcerpt(jsonl, maxChars = 60_000) {
194
+ const out = [];
195
+ const bashIds = new Set();
196
+ for (const raw of jsonl.split("\n")) {
197
+ if (!raw.trim())
198
+ continue;
199
+ let line;
200
+ try {
201
+ line = JSON.parse(raw);
202
+ }
203
+ catch {
204
+ continue;
205
+ }
206
+ if (line.isMeta)
207
+ continue;
208
+ const content = line.message?.content;
209
+ if (line.type === "user") {
210
+ if (typeof content === "string") {
211
+ if (!content.startsWith("<"))
212
+ out.push(`USER: ${clip(content, 40)}`);
213
+ continue;
214
+ }
215
+ if (!Array.isArray(content))
216
+ continue;
217
+ for (const b of content) {
218
+ if (b.type === "text" && typeof b.text === "string" && !b.text.startsWith("<"))
219
+ out.push(`USER: ${clip(b.text, 40)}`);
220
+ else if (b.type === "tool_result" && bashIds.has(String(b.tool_use_id))) {
221
+ const text = contentText(b.content);
222
+ if (b.is_error === true || FAIL_TEXT.test(text))
223
+ out.push(`RESULT (failed): ${clip(text, 20)}`);
224
+ }
225
+ }
226
+ }
227
+ else if (line.type === "assistant" && Array.isArray(content)) {
228
+ for (const b of content) {
229
+ if (b.type === "text" && typeof b.text === "string" && b.text.trim())
230
+ out.push(`ASSISTANT: ${clip(b.text, 40)}`);
231
+ else if (b.type === "tool_use") {
232
+ const input = (b.input ?? {});
233
+ const file = typeof input.file_path === "string" ? input.file_path : "";
234
+ if (b.name === "Write" && file && !isIgnoredPath(file))
235
+ out.push(`WRITE ${file}:\n${clip(String(input.content ?? ""))}`);
236
+ else if (b.name === "Edit" && file && !isIgnoredPath(file))
237
+ out.push(`EDIT ${file}:\n- ${clip(String(input.old_string ?? ""), 20)}\n+ ${clip(String(input.new_string ?? ""))}`);
238
+ else if (b.name === "MultiEdit" && file && !isIgnoredPath(file) && Array.isArray(input.edits))
239
+ out.push(`EDIT ${file}:\n${input.edits.map((e) => `+ ${clip(String(e.new_string ?? ""), 30)}`).join("\n")}`);
240
+ else if (b.name === "Bash" && typeof input.command === "string") {
241
+ bashIds.add(String(b.id));
242
+ out.push(`RUN: ${clip(input.command, 5)}`);
243
+ }
244
+ }
245
+ }
246
+ }
127
247
  }
248
+ const text = out.join("\n\n");
249
+ return text.length <= maxChars ? text : `… (earlier work omitted)\n\n${text.slice(text.length - maxChars)}`;
128
250
  }
package/dist/sl.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  // Data CLI the selflore skill calls for bookkeeping that must be exact.
3
3
  import { readStdin } from "./hooks/io.js";
4
- import { addEntry, finishTest, listCmd, notesCmd, quizInput, recordCmd, statsCmd, suppressCmd, } from "./lib/commands.js";
4
+ import { addEntry, finishTest, focusArgs, focusCmd, listCmd, notesCmd, quizInput, recordCmd, statsCmd, suppressCmd, } from "./lib/commands.js";
5
5
  const USAGE = `usage: sl <command>
6
- entry add --session <id> [--manual] read entry markdown from stdin and store it
7
- entry replace <id> --session <id> swap a weaker entry from this session for the one on stdin
6
+ entry add --session <id> read entry markdown from stdin and store it (merges near-duplicates)
8
7
  entry list [--session <id>]
9
8
  quiz-input JSON of fresh entries + due retests
10
9
  record --entry <id> --grade got|partial|missed --type <question-type>
11
10
  suppress <id> flag an entry as unfair; never test it again
12
11
  finish-test
13
12
  stats [--project <name>]
14
- notes [--all] [--project <name>] [--text] open the notes page (or print text)`;
13
+ notes [--all] [--project <name>] [--text] open the notes page (or print text)
14
+ focus [details|design|mixed] [--balance design|balanced|details] [--project] [--reset]`;
15
15
  function flag(args, name) {
16
16
  const i = args.indexOf(`--${name}`);
17
17
  return i >= 0 ? args[i + 1] : undefined;
@@ -24,19 +24,11 @@ async function main(argv) {
24
24
  const session = flag(args, "session");
25
25
  if (sub === "list")
26
26
  return listCmd(session);
27
- if (sub !== "add" && sub !== "replace")
27
+ if (sub !== "add")
28
28
  break;
29
29
  if (!session)
30
30
  return { code: 1, out: "missing --session <id> (it is in the session context as selflore session_id=…)" };
31
- const replace = sub === "replace" ? rest[0] : undefined;
32
- if (sub === "replace" && (!replace || replace.startsWith("--")))
33
- return { code: 1, out: "usage: entry replace <id> --session <id>" };
34
- return addEntry(await readStdin(), {
35
- session,
36
- cwd: process.cwd(),
37
- manual: args.includes("--manual"),
38
- replace,
39
- });
31
+ return addEntry(await readStdin(), { session, cwd: process.cwd() });
40
32
  }
41
33
  case "quiz-input":
42
34
  return quizInput();
@@ -56,6 +48,8 @@ async function main(argv) {
56
48
  return finishTest();
57
49
  case "stats":
58
50
  return statsCmd(flag(args, "project"));
51
+ case "focus":
52
+ return focusCmd(focusArgs(args));
59
53
  case "notes":
60
54
  return notesCmd({ all: args.includes("--all"), project: flag(args, "project"), text: args.includes("--text") });
61
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "selflore",
3
- "version": "0.0.2",
3
+ "version": "0.1.0",
4
4
  "description": "Own what your agent builds. A Claude Code skill that captures what your agent did for you and tests you on it weekly.",
5
5
  "keywords": [
6
6
  "claude",
package/skill/SKILL.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: selflore
3
- description: Captures "lore-worthy" moments from Claude Code sessions and runs a weekly comprehension test on them so the developer keeps understanding code the agent wrote. Use it proactively, without being asked, right after any of these happen in a session - you wrote a function or module of ~30+ lines the user did not read or edit; a non-obvious tradeoff was made and a reason stated; a bug was root-caused and fixed; a new library, API or pattern entered the codebase; the user corrected you or you talked the user out of an approach. Also handles /selflore test, /selflore log, /selflore notes and /selflore stats, and the selflore Stop-hook nudge.
4
- argument-hint: "test | log | notes | stats"
3
+ description: Captures "lore" from Claude Code sessions (what the agent did for the developer) and runs a weekly comprehension test on it, so the developer keeps understanding code the agent wrote. Handles /selflore test, /selflore log, /selflore notes, /selflore stats and /selflore focus, and selflore hints that appear in the session context. Capture normally happens automatically in the background; check the session context line "selflore capture=<mode>" before logging anything yourself.
4
+ argument-hint: "test | log | notes | stats | focus"
5
5
  ---
6
6
 
7
7
  # selflore
@@ -23,15 +23,29 @@ Look at the arguments the skill was invoked with:
23
23
  | `test` | Read [references/test.md](references/test.md) and run the weekly test. |
24
24
  | `log` | Read [references/log.md](references/log.md) and write a manual entry. |
25
25
  | `notes` | Run `{{SL}} notes` (add `--all` or `--project <name>` if the user asks). It opens the notes page in the browser. Reply with one line: that it opened, or the `file://` path if it couldn't open. Don't repeat the entries in chat. |
26
+ | `focus` | Run `{{SL}} focus <arguments>` and show the output verbatim. |
26
27
  | `stats` | Run `{{SL}} stats` (add `--project <name>` if the user names one) and show the output verbatim in a code block. Add at most two sentences of interpretation. |
27
- | none, or invoked by a capture trigger / Stop-hook nudge | Capture: follow the rules below and [references/capture.md](references/capture.md). |
28
+ | none, or a `selflore:` hint in quiet mode | Capture: follow the rules below and [references/capture.md](references/capture.md). |
28
29
 
29
- ## Capture rules (summary)
30
+ ## Capture mode
30
31
 
31
- - **Triggers:** only the five in the description. Routine edits, renames, config tweaks and anything the user wrote themselves are not lore.
32
- - **The `testable` line is the gate.** If you cannot write one sharp question that tests *understanding* (why / what breaks / what happens if), don't log it.
33
- - **Cap:** at most `max_entries_per_session` per session (3–7, enforced by `entry add`). When the cap is hit, keep the entries that best match the user's `keep_sharp` areas, and replace a weaker one only if the new moment is clearly better.
34
- - **Session id:** this comes from the session context line `selflore session_id=<id>`. If it is missing, use `manual-<YYYY-MM-DD>`.
35
- - **Cost to the user:** near zero. Log quietly in one short tool call, then say a single line like `selflore: logged 1 entry (webhook idempotency)`. Never interrupt the user's task to discuss logging, and never ask permission to log.
36
- - **Timing:** log when a unit of work wraps up (the bug is fixed, the module is written). Do not log mid-debugging.
37
- - **Stop-hook nudge:** if a `selflore:` Stop-hook message says nothing was logged, either log up to the cap or reply with one line saying nothing was lore-worthy. Then stop.
32
+ The session context has a line `selflore capture=<mode>`:
33
+ - **background** (default): selflore captures automatically after turns, outside this session. **Don't log entries yourself.** Only log when the user runs `/selflore log`.
34
+ - **quiet**: you may receive a `selflore:` hint along with a user prompt. Act on it only at a natural pause in the task, after doing what the user asked. Never block or delay their work for it.
35
+ - **off**: log only when the user runs `/selflore log`.
36
+
37
+ ## Focus
38
+
39
+ Run `{{SL}} focus` to see the effective focus for this project: details, design or mixed (with a balance). A project override beats the global setting.
40
+ - **details:** language, library and API specifics. How things behave, edge cases, gotchas.
41
+ - **design:** architecture, data flow, tradeoffs, failure modes, scale.
42
+ - **mixed:** both. Tag each entry honestly and lean toward the chosen balance.
43
+
44
+ `/selflore focus …` passes its arguments straight to `{{SL}} focus …` (e.g. `/selflore focus details --project`). Show the output as-is.
45
+
46
+ ## Capture rules (when you do log)
47
+
48
+ - **The `testable` line is the gate.** If you can't write one sharp question that tests *understanding* (why / what breaks / what happens if / what does this print and why), don't log it.
49
+ - **There's no cap.** Log each real unit of work once. `entry add` merges near-duplicates into the existing untested entry automatically.
50
+ - **Session id:** this comes from the session context line `selflore session_id=<id>`. If it's missing, use `manual-<YYYY-MM-DD>`.
51
+ - **Cost to the user:** near zero. Log quietly in one short tool call, then say a single line like `selflore: logged 1 entry (webhook idempotency)`. Never ask permission to log.
@@ -8,6 +8,7 @@ Write one markdown entry with frontmatter and pipe it to `entry add`. `id`, `dat
8
8
  {{SL}} entry add --session <session_id> <<'LORE'
9
9
  ---
10
10
  kind: bug # bug | decision | concept | pattern
11
+ level: detail # detail | design (must match the effective focus)
11
12
  skill: debugging # debugging | architecture | fundamentals | <a keep_sharp stack name>
12
13
  paths: ["src/payments/webhook.ts"]
13
14
  testable: "Why must the Stripe webhook handler be idempotent, and what fails without it?"
@@ -34,6 +35,10 @@ Run it from the project's working directory so `project` and `commit` are detect
34
35
  - `decision`: a tradeoff was made, either by you or after the user corrected you.
35
36
  - `concept`: an idea the user needs, such as how an API or library actually behaves.
36
37
  - `pattern`: a reusable structure that entered the codebase.
38
+ - **level** (check `{{SL}} focus` first):
39
+ - `detail`: language, library or API specifics. Good: "What does this `await` inside `forEach` actually do, and why did the writes run out of order?" Bad: "Which method sorts the array?"
40
+ - `design`: architecture and tradeoffs. Good: "Why a queue instead of cron here, and what breaks with two replicas?" Bad: "What is the queue library called?"
41
+ - If the focus is `details` or `design`, log only that level. In `mixed`, tag each entry honestly.
37
42
  - **skill:** use the user's `keep_sharp` area that fits best. Use the stack name, such as `postgres`, when the lore is stack-specific.
38
43
  - **paths:** the files involved, relative to the repo root.
39
44
  - **testable:** a single question written *now*, while context is fresh. It should test understanding, not trivia:
@@ -44,17 +49,15 @@ Run it from the project's working directory so `project` and `commit` are detect
44
49
 
45
50
  ## Responses from `entry add`
46
51
 
47
- - `logged <id> (n/cap this session)`: done. Tell the user in one line.
48
- - `entry rejected: …`: fix the listed problems and retry once. If there is no good `testable` line, drop the entry.
49
- - `cap reached` (exit code 2): compare the new moment against the listed entries using the user's `keep_sharp` areas. If the new one is clearly better, run:
50
- `{{SL}} entry replace <weaker-id> --session <session_id> <<'LORE' … LORE`
51
- Otherwise drop it silently.
52
+ - `logged <id> [level]`: done. Tell the user in one line.
53
+ - `updated <id> (merged …)`: the moment was close to an existing untested entry, which has been refreshed. Also done.
54
+ - `entry rejected: …`: fix the listed problems and retry once. If there's no good `testable` line, drop the entry.
52
55
 
53
- ## Choosing what to log when several triggers fired
56
+ ## Choosing what to log
54
57
 
55
- Rank the candidates and keep the top ones up to the cap:
56
- 1. A match with the user's `keep_sharp` areas.
58
+ When several moments are candidates, prefer:
59
+ 1. A match with the user's `keep_sharp` areas and the effective focus.
57
60
  2. Bugs and corrected decisions. These are the moments the user is most likely to have missed.
58
- 3. Anything the user did not visibly read.
61
+ 3. Anything the user didn't visibly read.
59
62
 
60
63
  Prefer one deep entry over two shallow ones.
@@ -4,9 +4,9 @@ The user said "this was important". It is also the escape hatch for work done ou
4
4
 
5
5
  1. Work out what they mean from the current conversation. If the conversation has no such context (for example, the work happened in Cursor or Codex), ask for a 2–3 sentence description and any code worth keeping.
6
6
  2. Write the entry exactly as described in [capture.md](capture.md). The same quality bar applies: a real `testable` line and a body that works as an answer key.
7
- 3. Store it with the `--manual` flag. Manual entries may exceed the session cap; the CLI warns instead of refusing:
7
+ 3. Store it. Check `{{SL}} focus` for the level unless the user said otherwise:
8
8
  ```bash
9
- {{SL}} entry add --session <session_id> --manual <<'LORE'
9
+ {{SL}} entry add --session <session_id> <<'LORE'
10
10
  …
11
11
  LORE
12
12
  ```
@@ -8,21 +8,34 @@ Target: about 10 questions in about 20 minutes. Tests are meant to measure **und
8
8
  {{SL}} quiz-input
9
9
  ```
10
10
 
11
- This returns JSON with `config` (`rating`, `keep_sharp`), `target_questions`, `retests` (due misses from earlier weeks) and `fresh` (entries never tested). Each entry has `testable`, a `body` (the answer key, usually with a code snippet), `kind`, `skill`, `paths` and `commit`.
11
+ This returns JSON with:
12
+ - `config` (`rating`, `keep_sharp`);
13
+ - `target_questions`, plus `target_split`, the number of `design` and `detail` questions to aim for, set by the user's focus;
14
+ - `retests`: due misses from earlier weeks;
15
+ - `fresh`: entries never tested and less than 3 weeks old;
16
+ - `stale_count`: older untested entries, which are left out on purpose.
17
+
18
+ Each entry has `testable`, a `body` (the answer key, usually with a code snippet), `kind`, `level` (`detail` or `design`), `skill`, `paths` and `commit`.
12
19
 
13
20
  - If both lists are empty, say there is nothing to test yet and stop.
14
- - **Include every due retest.** Then fill the rest up to `target_questions` with `fresh` entries, weighted toward the `keep_sharp` areas. If there are fewer than 10 entries in total, ask fewer questions. Never pad.
21
+ - **Include every due retest.** Then fill the rest up to `target_questions` with `fresh` entries. Match `target_split` as closely as the available entries allow, and within each level weight toward the `keep_sharp` areas. If there are fewer than 10 entries in total, ask fewer questions. Never pad.
15
22
  - Fresh entries you skip stay untested and roll into next week.
16
23
 
17
24
  ## 2. Build the questions (before asking the first one)
18
25
 
19
- There is one question per entry. Pick the best type for each, in this priority order:
26
+ There is one question per entry. The entry's `level` decides the question family. Pick the best type within it:
27
+
28
+ **Design entries:**
29
+ 1. **explain-why:** "Why did we choose X over Y?" The entry's `testable` line is the starting point; you can sharpen it.
30
+ 2. **what-breaks:** "What fails if we remove or change X?" Ask for the concrete failure, not a vague "it breaks".
31
+ 3. **tradeoff-at-scale:** "What happens to this design at 10× load, with two replicas, or when the dependency is slow?"
32
+
33
+ **Detail entries:**
34
+ 1. **predict-behavior:** show the snippet (or a trimmed piece of it) and ask what happens for a specific, concrete input or condition, and why.
35
+ 2. **find-the-bug:** take the snippet, reintroduce the logged bug from a `bug` entry, and ask the user to locate it and explain the failure. Don't mark the bug in any way, and don't let the change stand out visually.
36
+ 3. **rewrite-from-spec:** "Without looking, write the signature and core logic of…". **At most one per test.**
20
37
 
21
- 1. **explain-why** (from `decision` entries, and others where it fits): "Why did we choose X over Y? What breaks if we hadn't?" The entry's `testable` line is the starting point; you can sharpen it.
22
- 2. **predict-behavior:** show the snippet (or a trimmed piece of it) and ask what happens for a specific, concrete input or condition.
23
- 3. **find-the-bug:** take the snippet, reintroduce the logged bug from a `bug` entry, and ask the user to locate it and explain the failure. Don't mark the bug in any way, and don't let the change stand out visually.
24
- 4. **rewrite-from-spec:** "Without looking, write the signature and core logic of…". **At most one per test.**
25
- 5. **recall:** only when nothing better fits.
38
+ **recall:** only when nothing better fits, at either level.
26
39
 
27
40
  Calibrate to `config.rating`:
28
41
 
@@ -50,7 +63,7 @@ For each question:
50
63
  4. **Explain immediately**, before the next question. Give the verdict, then the correct explanation in 2–5 sentences: what they got right, the gap and the real answer. For a miss, add the single sentence they should remember.
51
64
  5. Record it:
52
65
  ```bash
53
- {{SL}} record --entry <id> --grade got|partial|missed --type explain-why|predict-behavior|find-the-bug|rewrite-from-spec|recall
66
+ {{SL}} record --entry <id> --grade got|partial|missed --type explain-why|what-breaks|tradeoff-at-scale|predict-behavior|find-the-bug|rewrite-from-spec|recall
54
67
  ```
55
68
  The CLI decides whether this was a retest and schedules misses and partials for +7 and +21 days. Retests retire after two consecutive passes.
56
69