selflore 0.0.1 → 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.
package/README.md CHANGED
@@ -1,5 +1,92 @@
1
1
  # selflore
2
2
 
3
- A Claude skill — coming soon.
3
+ **Own what your agent builds.**
4
4
 
5
- This package is a placeholder reserving the name while the skill is in development.
5
+ selflore is a Claude Code skill. It captures the moments where Claude did real work *for* you (a bug root-caused, a tradeoff made, a 40-line module you never read), then tests you on them once a week. Misses come back at +7 and +21 days until they stick. Getting it wrong is the feature.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npx selflore init
11
+ ```
12
+
13
+ A few questions:
14
+ - a self-rating from 1 to 10 (←/→ on a scale, starting at 5);
15
+ - what you want to keep sharp;
16
+ - **capture intensity** (light, normal or thorough);
17
+ - **focus**: details, design or mixed, plus a balance if you pick mixed;
18
+ - **how capture happens**: background, quiet or off;
19
+ - the model for background capture;
20
+ - whether you want a nudge when a test is overdue.
21
+
22
+ Re-run `init` at any time to change your answers. Your data is kept. Restart any open Claude Code sessions afterwards.
23
+
24
+ ## Use
25
+
26
+ Work normally. selflore never interrupts you:
27
+ - **background** (default): after turns with real code work, a separate headless Claude reads the new part of the session and writes entries. Your next session starts with a one-line "captured N entries" mention.
28
+ - **quiet**: Claude gets a one-line hint with your next message and logs at a natural pause.
29
+ - **off**: only `/selflore log`.
30
+
31
+ There's no cap. Near-duplicates are merged into the existing entry. Entries untested for 3 weeks drop out of the quiz but stay in notes.
32
+
33
+ **Focus** sets what gets captured:
34
+ - `details`: language and library specifics;
35
+ - `design`: architecture and tradeoffs;
36
+ - `mixed`: both, with a balance you choose.
37
+
38
+ It's set globally and can be overridden per project; the project setting wins:
39
+
40
+ ```bash
41
+ selflore focus design # global
42
+ selflore focus details --project # just this repo (e.g. while learning a new language)
43
+ selflore focus mixed --balance design # mostly design
44
+ selflore focus --reset --project # back to the global setting
45
+ ```
46
+
47
+ | Command | What it does |
48
+ |---|---|
49
+ | `/selflore test` | Weekly quiz, about 10 questions and about 20 minutes. Each answer is graded immediately as got it, partial or missed, with an explanation. Say `unfair` to drop a question for good. |
50
+ | `/selflore log` | Log the current thing manually. Also covers work done outside Claude Code. |
51
+ | `/selflore notes` | Opens a page in your browser with everything captured this week, grouped by day, with answers hidden until you click. You can browse weeks and filter. In the terminal, run `npx selflore notes` (`--all`, `--project <name>`, or `--text` for plain text). |
52
+ | `/selflore focus` | Same as `selflore focus` above, from inside Claude Code. |
53
+ | `/selflore stats` | Weekly table: entries, questions, pass rate overall and by skill, retest backlog, and self-rating vs. observed pass rate. |
54
+
55
+ ## Remove
56
+
57
+ ```bash
58
+ npx selflore remove # remove skill + hooks, keep data
59
+ npx selflore remove --purge # remove everything
60
+ ```
61
+
62
+ ## How it works
63
+
64
+ - **Skill** at `~/.claude/skills/selflore/`. Claude writes entries, builds quizzes and grades answers.
65
+ - **Hooks** are merged into `~/.claude/settings.json`; existing hooks are never touched, and a backup is written to `settings.json.selflore-bak`.
66
+ - `SessionStart` gives Claude the session id and capture mode, mentions background captures, and (if enabled) reminds you when a test is overdue.
67
+ - `Stop` never blocks. It looks only at work since the last capture: real code changes (not docs, reports or one-off scripts), new dependencies, and fail → fix → pass loops. It then starts a background capture or, in quiet mode, leaves a hint.
68
+ - `UserPromptSubmit` delivers that hint in quiet mode.
69
+ - **Data** lives globally in `~/.selflore/`, because learning spans projects:
70
+
71
+ ```
72
+ ~/.selflore/
73
+ config.json rating, keep_sharp, capture_intensity, focus, projects, capture, capture_model, nudge, last_test_at
74
+ entries/ YYYY-MM-DD-slug.md (frontmatter + ≤120 words + an optional code snippet)
75
+ results.jsonl one line per graded answer
76
+ queue.json retest due dates
77
+ state/ per-session capture progress, background-capture log
78
+ app/ the runtime the hooks call
79
+ ```
80
+
81
+ Each entry stores the `testable` question written at capture time, while context is fresh. It also stores a code snippet and the commit SHA, so quiz questions still work after the code moves on.
82
+
83
+ ## Develop
84
+
85
+ ```bash
86
+ npm install
87
+ npm run build
88
+ npm test
89
+ SELFLORE_HOME=/tmp/sl CLAUDE_HOME=/tmp/cl node dist/cli.js init --yes # sandboxed install
90
+ ```
91
+
92
+ MIT
package/dist/cli.js ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ import { focusArgs, focusCmd, notesCmd } from "./lib/commands.js";
3
+ import { removeFiles } from "./lib/install.js";
4
+ import { selfloreHome } from "./lib/paths.js";
5
+ const USAGE = `selflore — own what your agent builds
6
+
7
+ usage:
8
+ npx selflore init install skill + hooks, run onboarding (re-run to change answers)
9
+ npx selflore init --yes non-interactive; keep existing config or use defaults
10
+ npx selflore notes open this week's notes in your browser (--all, --project <name>, --text)
11
+ npx selflore focus [mode] show or set what gets captured: details | design | mixed
12
+ --balance design|balanced|details (mixed), --project (this repo only), --reset
13
+ npx selflore remove remove skill + hooks, keep your data
14
+ npx selflore remove --purge remove everything, including ${selfloreHome()}
15
+
16
+ inside Claude Code: /selflore test /selflore log /selflore notes /selflore stats /selflore focus`;
17
+ async function main() {
18
+ const [cmd, ...args] = process.argv.slice(2);
19
+ switch (cmd) {
20
+ case "init": {
21
+ // Imported lazily: the prompt library is only needed here, not in the hook runtime.
22
+ const { init } = await import("./init.js");
23
+ await init({ yes: args.includes("--yes") || args.includes("-y") });
24
+ return;
25
+ }
26
+ case "notes": {
27
+ const i = args.indexOf("--project");
28
+ console.log(notesCmd({ all: args.includes("--all"), project: i >= 0 ? args[i + 1] : undefined, text: args.includes("--text") }).out);
29
+ return;
30
+ }
31
+ case "focus": {
32
+ const r = focusCmd(focusArgs(args));
33
+ (r.code === 0 ? console.log : console.error)(r.out);
34
+ process.exitCode = r.code;
35
+ return;
36
+ }
37
+ case "remove": {
38
+ const purge = args.includes("--purge");
39
+ removeFiles(purge);
40
+ console.log(purge ? `selflore removed, including ${selfloreHome()}` : `selflore removed; data kept in ${selfloreHome()}`);
41
+ return;
42
+ }
43
+ default:
44
+ console.log(USAGE);
45
+ if (cmd && cmd !== "help" && cmd !== "--help" && cmd !== "-h")
46
+ process.exitCode = 1;
47
+ }
48
+ }
49
+ main().catch((err) => {
50
+ console.error(`selflore: ${err instanceof Error ? err.message : String(err)}`);
51
+ process.exit(1);
52
+ });
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ // Detached background capture, started by the Stop hook: reads one transcript range,
3
+ // asks a headless Claude for lore entries, stores them, then releases the session lock.
4
+ import { logWorkerError, runCapture } from "../lib/background.js";
5
+ import { addAnnounce, updateSession } from "../lib/session.js";
6
+ import { buildExcerpt, lastModel, readTranscriptFrom } from "../lib/transcript.js";
7
+ const [session, transcript, from, to, cwd] = process.argv.slice(2);
8
+ try {
9
+ if (session && transcript) {
10
+ const { text } = readTranscriptFrom(transcript, Number(from) || 0, Number(to) || undefined);
11
+ const stored = runCapture({ session, cwd: cwd || process.cwd(), excerpt: buildExcerpt(text), sessionModel: lastModel(text) });
12
+ addAnnounce(stored);
13
+ }
14
+ }
15
+ catch (err) {
16
+ logWorkerError(err);
17
+ }
18
+ finally {
19
+ if (session) {
20
+ try {
21
+ updateSession(session, { capturing_since: null });
22
+ }
23
+ catch {
24
+ // ignore
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,25 @@
1
+ export async function readStdin() {
2
+ if (process.stdin.isTTY)
3
+ return "";
4
+ const chunks = [];
5
+ for await (const c of process.stdin)
6
+ chunks.push(c);
7
+ return Buffer.concat(chunks).toString("utf8");
8
+ }
9
+ export async function readHookInput() {
10
+ try {
11
+ return JSON.parse((await readStdin()) || "{}");
12
+ }
13
+ catch {
14
+ return {};
15
+ }
16
+ }
17
+ /**
18
+ * Hooks must never break the user's session: swallow everything and exit 0.
19
+ * Inside selflore's own background capture (SELFLORE_BG), hooks do nothing, so a capture can't trigger another.
20
+ */
21
+ export function runHook(fn) {
22
+ if (process.env.SELFLORE_BG)
23
+ process.exit(0);
24
+ fn().catch(() => { }).finally(() => process.exit(0));
25
+ }
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { handleSessionStart } from "../lib/hook-logic.js";
3
+ import { readHookInput, runHook } from "./io.js";
4
+ runHook(async () => {
5
+ const out = handleSessionStart(await readHookInput());
6
+ if (out)
7
+ process.stdout.write(out + "\n");
8
+ });
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { handleStop } from "../lib/hook-logic.js";
3
+ import { readHookInput, runHook } from "./io.js";
4
+ // Stop fires after every assistant turn. It never blocks: capture happens in the background or via a later hint.
5
+ runHook(async () => {
6
+ handleStop(await readHookInput());
7
+ });
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { handlePromptSubmit } from "../lib/hook-logic.js";
3
+ import { readHookInput, runHook } from "./io.js";
4
+ // Quiet capture mode: turns a pending trigger into one line of context for the next turn. Never blocks.
5
+ runHook(async () => {
6
+ const out = handlePromptSubmit(await readHookInput());
7
+ if (out)
8
+ process.stdout.write(out + "\n");
9
+ });
package/dist/init.js ADDED
@@ -0,0 +1,137 @@
1
+ import * as p from "@clack/prompts";
2
+ import { configExists, DEFAULT_CONFIG, readConfig, writeConfig, } from "./lib/config.js";
3
+ import { installFiles } from "./lib/install.js";
4
+ import { paths } from "./lib/paths.js";
5
+ import { ratingPrompt } from "./rating-prompt.js";
6
+ const BUILTIN_SHARP = ["debugging", "architecture", "fundamentals"];
7
+ function bail(v) {
8
+ if (p.isCancel(v)) {
9
+ p.cancel("selflore init cancelled; nothing changed.");
10
+ process.exit(1);
11
+ }
12
+ return v;
13
+ }
14
+ async function ask(existing, reinstall) {
15
+ // Starts on 5 (or the previous answer on re-run).
16
+ const rating = bail(await ratingPrompt("Rate yourself as a software engineer, 1–10.", existing.rating));
17
+ const prevStack = existing.keep_sharp.filter((k) => !BUILTIN_SHARP.includes(k));
18
+ const sharp = bail(await p.multiselect({
19
+ message: "What do you most want to keep sharp? (pick one or more: space to select, enter to confirm)",
20
+ options: [
21
+ { value: "debugging", label: "Debugging" },
22
+ { value: "architecture", label: "Architecture & tradeoffs" },
23
+ { value: "fundamentals", label: "Language & framework fundamentals" },
24
+ { value: "__stack", label: "A named stack", hint: "you'll type it next" },
25
+ ],
26
+ // Nothing pre-ticked on a fresh install, so enter alone can't silently submit a default.
27
+ initialValues: reinstall
28
+ ? [...existing.keep_sharp.filter((k) => BUILTIN_SHARP.includes(k)), ...(prevStack.length ? ["__stack"] : [])]
29
+ : [],
30
+ required: true,
31
+ }));
32
+ const keep_sharp = sharp.filter((s) => s !== "__stack");
33
+ if (sharp.includes("__stack")) {
34
+ const stack = bail(await p.text({
35
+ message: "Which stack? (comma-separated, e.g. postgres, react)",
36
+ initialValue: prevStack.join(", "),
37
+ validate: (v) => ((v ?? "").trim() ? undefined : "Name at least one"),
38
+ }));
39
+ keep_sharp.push(...stack.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean));
40
+ }
41
+ const capture_intensity = bail(await p.select({
42
+ message: "Capture intensity: how much should count as worth capturing?",
43
+ options: [
44
+ { value: "light", label: "Light", hint: "only the big moments: major bugs and design decisions" },
45
+ { value: "normal", label: "Normal", hint: "every real unit of work: bugs, tradeoffs, new APIs, unread modules" },
46
+ { value: "thorough", label: "Thorough", hint: "smaller gotchas and edge cases too" },
47
+ ],
48
+ initialValue: existing.capture_intensity,
49
+ }));
50
+ const mode = bail(await p.select({
51
+ message: "What should selflore capture? (you can override this per project later)",
52
+ options: [
53
+ { value: "details", label: "Details", hint: "language & library specifics, edge cases, gotchas" },
54
+ { value: "design", label: "Design", hint: "architecture, tradeoffs, failure modes" },
55
+ { value: "mixed", label: "Mixed", hint: "both; you choose the balance next" },
56
+ ],
57
+ initialValue: existing.focus.mode,
58
+ }));
59
+ let balance = existing.focus.balance;
60
+ if (mode === "mixed") {
61
+ balance = bail(await p.select({
62
+ message: "Mixed: what balance?",
63
+ options: [
64
+ { value: "design", label: "Mostly design", hint: "~70% design, 30% details" },
65
+ { value: "balanced", label: "Balanced", hint: "50/50" },
66
+ { value: "details", label: "Mostly details", hint: "~70% details, 30% design" },
67
+ ],
68
+ initialValue: existing.focus.balance,
69
+ }));
70
+ }
71
+ const capture = bail(await p.select({
72
+ message: "How should capture happen?",
73
+ options: [
74
+ { value: "background", label: "In the background", hint: "recommended; never interrupts, runs a separate Claude call" },
75
+ { value: "quiet", label: "Quiet hint", hint: "Claude logs at a natural pause in your session; no extra calls" },
76
+ { value: "off", label: "Off", hint: "only when you run /selflore log" },
77
+ ],
78
+ initialValue: existing.capture,
79
+ }));
80
+ let capture_model = existing.capture_model;
81
+ if (capture === "background") {
82
+ capture_model = bail(await p.select({
83
+ message: "Which model should background capture use?",
84
+ options: [
85
+ { value: "session", label: "Same as the session", hint: "default" },
86
+ { value: "sonnet", label: "Sonnet", hint: "sharp questions, moderate cost" },
87
+ { value: "haiku", label: "Haiku", hint: "cheapest and fastest" },
88
+ ],
89
+ initialValue: existing.capture_model,
90
+ }));
91
+ }
92
+ const nudge = bail(await p.select({
93
+ message: "How pushy should selflore be?",
94
+ options: [
95
+ { value: false, label: "Quiz only" },
96
+ { value: true, label: "Quiz + a nudge when a test is overdue" },
97
+ ],
98
+ initialValue: existing.nudge,
99
+ }));
100
+ return {
101
+ ...existing,
102
+ rating,
103
+ keep_sharp,
104
+ capture_intensity,
105
+ focus: { mode, balance },
106
+ capture,
107
+ capture_model,
108
+ nudge,
109
+ };
110
+ }
111
+ export async function init(opts) {
112
+ const reinstall = configExists();
113
+ const existing = reinstall ? readConfig() : DEFAULT_CONFIG;
114
+ if (opts.yes || !process.stdin.isTTY) {
115
+ writeConfig(existing);
116
+ installFiles();
117
+ console.log(`selflore installed (${reinstall ? "kept existing config" : "default config"}) → ${paths.config()}`);
118
+ return;
119
+ }
120
+ p.intro("selflore — own what your agent builds");
121
+ if (reinstall)
122
+ p.log.info("Existing config found; your previous answers are pre-filled. Data is kept.");
123
+ const config = await ask(existing, reinstall);
124
+ writeConfig(config);
125
+ installFiles();
126
+ p.note([
127
+ `config ${paths.config()}`,
128
+ `skill ${paths.skill()}`,
129
+ `hooks SessionStart + Stop + UserPromptSubmit in ${paths.settings()}`,
130
+ "",
131
+ "Work normally. selflore never interrupts; lore is captured as you go.",
132
+ "Per-project focus: run `selflore focus details --project` inside a repo.",
133
+ "Once a week, run /selflore test (~20 min). /selflore stats shows the trend.",
134
+ "Restart any open Claude Code sessions to pick up the skill and hooks.",
135
+ ].join("\n"), "Installed");
136
+ p.outro("Getting it wrong is the feature.");
137
+ }
@@ -0,0 +1,154 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { effectiveFocus, readConfig } from "./config.js";
6
+ import { validateEntry } from "./entries.js";
7
+ import { capturePrompt } from "./capture-prompt.js";
8
+ import { projectInfo, storeEntry } from "./commands.js";
9
+ import { paths } from "./paths.js";
10
+ /** Env flag set on everything selflore spawns, so its own hooks never fire inside a capture. */
11
+ export const BG_ENV = "SELFLORE_BG";
12
+ function gitRoot(cwd) {
13
+ try {
14
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
15
+ }
16
+ catch {
17
+ return "";
18
+ }
19
+ }
20
+ function isTracked(root, file) {
21
+ try {
22
+ execFileSync("git", ["ls-files", "--error-unmatch", file], { cwd: root, stdio: "ignore" });
23
+ return true;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ /**
30
+ * Filter for large writes: drop files outside the project, and one-off scripts
31
+ * (untracked, sitting in the repo root, written once and never touched again).
32
+ */
33
+ export function keepWriteFor(cwd, tracked = isTracked) {
34
+ const root = gitRoot(cwd) || cwd;
35
+ return ({ file, editCount }) => {
36
+ const abs = path.resolve(cwd, file);
37
+ const rel = path.relative(root, abs);
38
+ if (rel.startsWith("..") || path.isAbsolute(rel))
39
+ return false;
40
+ const inRoot = !rel.includes(path.sep);
41
+ if (inRoot && editCount <= 1 && !tracked(root, rel))
42
+ return false;
43
+ return true;
44
+ };
45
+ }
46
+ /** Resolve the model flag for the capture call. "session" uses the model the session itself used. */
47
+ export function captureModel(config, sessionModel) {
48
+ if (config.capture_model === "sonnet" || config.capture_model === "haiku")
49
+ return config.capture_model;
50
+ return sessionModel;
51
+ }
52
+ /** Start the capture worker fully detached; the Stop hook returns immediately. */
53
+ export const spawnWorker = (a) => {
54
+ try {
55
+ const worker = path.join(paths.app(), "hooks", "capture-worker.js");
56
+ const child = spawn(process.execPath, [worker, a.session, a.transcript, String(a.from), String(a.to), a.cwd], {
57
+ detached: true,
58
+ stdio: "ignore",
59
+ env: { ...process.env, [BG_ENV]: "1" },
60
+ });
61
+ child.on("error", () => { });
62
+ child.unref();
63
+ return true;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ };
69
+ /** Pull the JSON array out of the model's reply (tolerates stray prose or code fences). */
70
+ export function parseCaptureReply(reply) {
71
+ const start = reply.indexOf("[");
72
+ const end = reply.lastIndexOf("]");
73
+ if (start < 0 || end <= start)
74
+ return [];
75
+ try {
76
+ const parsed = JSON.parse(reply.slice(start, end + 1));
77
+ return Array.isArray(parsed) ? parsed : [];
78
+ }
79
+ catch {
80
+ return [];
81
+ }
82
+ }
83
+ /** Convert one model-produced object into an entry draft (body = prose + fenced snippet). */
84
+ export function toDraft(raw, focusMode) {
85
+ if (!raw || typeof raw !== "object")
86
+ return null;
87
+ const r = raw;
88
+ const snippet = typeof r.snippet === "string" && r.snippet.trim() ? r.snippet.replace(/\s+$/, "") : "";
89
+ const lang = typeof r.snippet_lang === "string" ? r.snippet_lang.replace(/[^\w+-]/g, "") : "";
90
+ const draft = {
91
+ kind: r.kind,
92
+ level: r.level,
93
+ skill: typeof r.skill === "string" ? r.skill : "",
94
+ paths: Array.isArray(r.paths) ? r.paths.filter((p) => typeof p === "string") : [],
95
+ testable: typeof r.testable === "string" ? r.testable.trim() : "",
96
+ body: `${typeof r.body === "string" ? r.body.trim() : ""}${snippet ? `\n\n\`\`\`${lang}\n${snippet}\n\`\`\`` : ""}`,
97
+ };
98
+ if (validateEntry(draft).length)
99
+ return null;
100
+ // A single-level focus is a hard filter, in case the model drifted.
101
+ if (focusMode === "details" && draft.level !== "detail")
102
+ return null;
103
+ if (focusMode === "design" && draft.level !== "design")
104
+ return null;
105
+ return draft;
106
+ }
107
+ export function askClaude(systemPrompt, input, model) {
108
+ const bin = process.env.SELFLORE_CLAUDE_BIN || "claude";
109
+ const args = ["-p", "--output-format", "json", "--tools", "", "--no-session-persistence", "--system-prompt", systemPrompt];
110
+ if (model)
111
+ args.push("--model", model);
112
+ // Run from a scratch dir so no project CLAUDE.md is picked up.
113
+ const out = execFileSync(bin, args, {
114
+ input,
115
+ cwd: os.tmpdir(),
116
+ env: { ...process.env, [BG_ENV]: "1" },
117
+ timeout: 5 * 60 * 1000,
118
+ maxBuffer: 16 * 1024 * 1024,
119
+ stdio: ["pipe", "pipe", "ignore"],
120
+ }).toString();
121
+ try {
122
+ const json = JSON.parse(out);
123
+ return json.is_error ? "" : (json.result ?? "");
124
+ }
125
+ catch {
126
+ return out;
127
+ }
128
+ }
129
+ /** Ask the capture model for entries from an excerpt and store them. Returns how many were stored. */
130
+ export function runCapture(opts) {
131
+ if (!opts.excerpt.trim())
132
+ return 0;
133
+ const config = readConfig();
134
+ const focus = effectiveFocus(config, projectInfo(opts.cwd).project);
135
+ const reply = (opts.ask ?? askClaude)(capturePrompt(config, focus), `Session excerpt (most recent work):\n\n${opts.excerpt}`, captureModel(config, opts.sessionModel));
136
+ let stored = 0;
137
+ for (const raw of parseCaptureReply(reply)) {
138
+ const draft = toDraft(raw, focus.mode);
139
+ if (!draft)
140
+ continue;
141
+ storeEntry(draft, { session: opts.session, cwd: opts.cwd, now: opts.now });
142
+ stored++;
143
+ }
144
+ return stored;
145
+ }
146
+ export function logWorkerError(err) {
147
+ try {
148
+ fs.mkdirSync(paths.state(), { recursive: true });
149
+ fs.appendFileSync(path.join(paths.state(), "capture-errors.log"), `${new Date().toISOString()} ${err instanceof Error ? err.message : String(err)}\n`);
150
+ }
151
+ catch {
152
+ // nothing else we can do
153
+ }
154
+ }
@@ -0,0 +1,33 @@
1
+ import { describeFocus } from "./config.js";
2
+ const INTENSITY_BAR = {
3
+ light: "Only the biggest moments: a significant bug root-caused, a major design decision, or a substantial module the user clearly did not read. Most chunks yield 0 entries.",
4
+ normal: "Real units of work: a bug root-caused and fixed, a non-obvious tradeoff with a stated reason, a new library/API/pattern, a ~30+ line module the user did not read, or the user correcting the agent. Routine edits yield 0 entries.",
5
+ thorough: "Anything the user would benefit from understanding, including smaller gotchas, edge cases and API behaviour discovered along the way. Still skip renames, formatting and config tweaks.",
6
+ };
7
+ function focusRule(focus) {
8
+ if (focus.mode === "details")
9
+ return 'Capture only level "detail": language, library and API specifics — how something behaves, edge cases, gotchas, what a snippet does.';
10
+ if (focus.mode === "design")
11
+ return 'Capture only level "design": architecture, data flow, tradeoffs, failure modes, why it is built this way, what breaks at scale.';
12
+ const lean = { design: "Lean toward design (about 70/30).", balanced: "Aim for a balance of both.", details: "Lean toward detail (about 70/30)." }[focus.balance];
13
+ return `Capture both levels, tagging each honestly ("detail" = language/library specifics; "design" = architecture and tradeoffs). ${lean}`;
14
+ }
15
+ /** System prompt for the headless background capture call. Output: a JSON array, nothing else. */
16
+ export function capturePrompt(config, focus) {
17
+ return `You are selflore's capture step. You read an excerpt of a Claude Code session in which an AI agent did work for a developer, and you extract "lore": moments the developer should understand but probably doesn't, because the agent did the work. Each entry becomes a quiz question in the developer's weekly test.
18
+
19
+ Bar for logging (intensity: ${config.capture_intensity}): ${INTENSITY_BAR[config.capture_intensity]}
20
+ Focus (${describeFocus(focus)}): ${focusRule(focus)}
21
+ The developer wants to keep sharp: ${config.keep_sharp.join(", ") || "anything"}. Prefer moments in those areas.
22
+ Self-rating ${config.rating}/10: ${config.rating <= 3 ? "favour fundamentals" : config.rating >= 8 ? "favour tradeoffs and failure modes" : "balanced depth"}.
23
+
24
+ Rules:
25
+ - The "testable" question is the gate. It must test understanding (why / what breaks / what happens if / what does this print and why), never trivia like names or file locations. If you cannot write one sharp question, skip the moment.
26
+ - Prefer one deep entry over several shallow ones. Do not log the same idea twice.
27
+ - Skip anything the developer wrote themselves, reports/docs the agent wrote for them to read, and throwaway one-off scripts.
28
+ - "body" is the answer key: at most ~120 words with the facts a correct answer must contain (the why, the root cause, the alternative rejected).
29
+ - "snippet" (optional, max 40 lines): the essential code as it is now. For a bug, the fixed code; name the original bug in the body.
30
+
31
+ Output ONLY a JSON array (possibly empty, []), no prose, no code fences. Each element:
32
+ {"kind": "bug"|"decision"|"concept"|"pattern", "level": "detail"|"design", "skill": "<one of the keep-sharp areas or a stack name>", "paths": ["relative/path"], "testable": "<question>", "body": "<answer key>", "snippet": "<code or omit>", "snippet_lang": "<ts|py|…|omit>"}`;
33
+ }