selflore 0.0.1 → 0.0.2

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,62 @@
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
+ Four questions: a self-rating from 1 to 10 (←/→ on a scale, starting at 5), what you want to keep sharp, how many entries to capture per session (3–7), and whether you want a nudge when a test is overdue. Re-run `init` at any time to change your answers. Your data is kept. Restart any open Claude Code sessions afterwards.
14
+
15
+ ## Use
16
+
17
+ Work normally. When something lore-worthy happens, Claude logs an entry with a one-line note. At most `max_entries_per_session` entries are logged per session.
18
+
19
+ | Command | What it does |
20
+ |---|---|
21
+ | `/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. |
22
+ | `/selflore log` | Log the current thing manually. Also covers work done outside Claude Code. |
23
+ | `/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). |
24
+ | `/selflore stats` | Weekly table: entries, questions, pass rate overall and by skill, retest backlog, and self-rating vs. observed pass rate. |
25
+
26
+ ## Remove
27
+
28
+ ```bash
29
+ npx selflore remove # remove skill + hooks, keep data
30
+ npx selflore remove --purge # remove everything
31
+ ```
32
+
33
+ ## How it works
34
+
35
+ - **Skill** at `~/.claude/skills/selflore/`. Claude writes entries, builds quizzes and grades answers.
36
+ - **Hooks** are merged into `~/.claude/settings.json`; existing hooks are never touched, and a backup is written to `settings.json.selflore-bak`.
37
+ - `SessionStart` gives Claude the session id and, if enabled, a one-line reminder when a test is overdue.
38
+ - `Stop` is a safety net. If the session had a large write, a dependency change or a fail → fix → pass loop and nothing was logged, it nudges once per session.
39
+ - **Data** lives globally in `~/.selflore/`, because learning spans projects:
40
+
41
+ ```
42
+ ~/.selflore/
43
+ config.json rating, keep_sharp, max_entries_per_session, nudge, cadence, last_test_at
44
+ entries/ YYYY-MM-DD-slug.md (frontmatter + ≤120 words + an optional code snippet)
45
+ results.jsonl one line per graded answer
46
+ queue.json retest due dates
47
+ state/ per-session capture counters
48
+ app/ the runtime the hooks call
49
+ ```
50
+
51
+ 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.
52
+
53
+ ## Develop
54
+
55
+ ```bash
56
+ npm install
57
+ npm run build
58
+ npm test
59
+ SELFLORE_HOME=/tmp/sl CLAUDE_HOME=/tmp/cl node dist/cli.js init --yes # sandboxed install
60
+ ```
61
+
62
+ MIT
package/dist/cli.js ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ import { 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 remove remove skill + hooks, keep your data
12
+ npx selflore remove --purge remove everything, including ${selfloreHome()}
13
+
14
+ inside Claude Code: /selflore test /selflore log /selflore notes /selflore stats`;
15
+ async function main() {
16
+ const [cmd, ...args] = process.argv.slice(2);
17
+ switch (cmd) {
18
+ case "init": {
19
+ // Imported lazily: the prompt library is only needed here, not in the hook runtime.
20
+ const { init } = await import("./init.js");
21
+ await init({ yes: args.includes("--yes") || args.includes("-y") });
22
+ return;
23
+ }
24
+ case "notes": {
25
+ const i = args.indexOf("--project");
26
+ console.log(notesCmd({ all: args.includes("--all"), project: i >= 0 ? args[i + 1] : undefined, text: args.includes("--text") }).out);
27
+ return;
28
+ }
29
+ case "remove": {
30
+ const purge = args.includes("--purge");
31
+ removeFiles(purge);
32
+ console.log(purge ? `selflore removed, including ${selfloreHome()}` : `selflore removed; data kept in ${selfloreHome()}`);
33
+ return;
34
+ }
35
+ default:
36
+ console.log(USAGE);
37
+ if (cmd && cmd !== "help" && cmd !== "--help" && cmd !== "-h")
38
+ process.exitCode = 1;
39
+ }
40
+ }
41
+ main().catch((err) => {
42
+ console.error(`selflore: ${err instanceof Error ? err.message : String(err)}`);
43
+ process.exit(1);
44
+ });
@@ -0,0 +1,20 @@
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
+ /** Hooks must never break the user's session: swallow everything and exit 0. */
18
+ export function runHook(fn) {
19
+ fn().catch(() => { }).finally(() => process.exit(0));
20
+ }
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { configExists, readConfig } from "../lib/config.js";
3
+ import { listEntries } from "../lib/entries.js";
4
+ import { sessionStartContext } from "../lib/nudge.js";
5
+ import { readHookInput, runHook } from "./io.js";
6
+ runHook(async () => {
7
+ const input = await readHookInput();
8
+ if (!configExists())
9
+ return;
10
+ const oldest = listEntries()[0]?.date ?? null; // ids are date-prefixed, so sorted oldest first
11
+ const out = sessionStartContext(input.session_id, readConfig(), oldest, new Date());
12
+ if (out)
13
+ process.stdout.write(out + "\n");
14
+ });
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { configExists, readConfig } from "../lib/config.js";
3
+ import { readSession, writeSession } from "../lib/session.js";
4
+ import { anyTrigger, describeTriggers, detectTriggers, readTranscript } from "../lib/transcript.js";
5
+ import { readHookInput, runHook } from "./io.js";
6
+ // Stop fires after every assistant turn. The session state file makes this nudge at most once per session.
7
+ runHook(async () => {
8
+ const input = await readHookInput();
9
+ if (input.stop_hook_active || !input.session_id || !configExists())
10
+ return;
11
+ const session = readSession(input.session_id);
12
+ if (session.nudged || session.entries.length > 0)
13
+ return;
14
+ const triggers = detectTriggers(readTranscript(input.transcript_path));
15
+ if (!anyTrigger(triggers))
16
+ return;
17
+ writeSession(input.session_id, { ...session, nudged: true });
18
+ const cap = readConfig().max_entries_per_session;
19
+ process.stdout.write(JSON.stringify({
20
+ decision: "block",
21
+ reason: `selflore: this session had ${describeTriggers(triggers)} but nothing was logged. ` +
22
+ `Use the selflore skill to log up to ${cap} lore entries (session_id=${input.session_id}), ` +
23
+ `or reply in one line that nothing here is lore-worthy. Do not continue other work.`,
24
+ }) + "\n");
25
+ });
package/dist/init.js ADDED
@@ -0,0 +1,87 @@
1
+ import * as p from "@clack/prompts";
2
+ import { clampCap, 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 cap = bail(await p.select({
42
+ message: "How much should Claude capture per session?",
43
+ options: [3, 4, 5, 6, 7].map((n) => ({ value: n, label: `${n} entries`, hint: n === 3 ? "default" : undefined })),
44
+ initialValue: existing.max_entries_per_session,
45
+ }));
46
+ const nudge = bail(await p.select({
47
+ message: "How pushy should selflore be?",
48
+ options: [
49
+ { value: false, label: "Quiz only" },
50
+ { value: true, label: "Quiz + a nudge when a test is overdue" },
51
+ ],
52
+ initialValue: existing.nudge,
53
+ }));
54
+ return {
55
+ ...existing,
56
+ rating,
57
+ keep_sharp,
58
+ max_entries_per_session: clampCap(cap),
59
+ nudge,
60
+ };
61
+ }
62
+ export async function init(opts) {
63
+ const reinstall = configExists();
64
+ const existing = reinstall ? readConfig() : DEFAULT_CONFIG;
65
+ if (opts.yes || !process.stdin.isTTY) {
66
+ writeConfig(existing);
67
+ installFiles();
68
+ console.log(`selflore installed (${reinstall ? "kept existing config" : "default config"}) → ${paths.config()}`);
69
+ return;
70
+ }
71
+ p.intro("selflore — own what your agent builds");
72
+ if (reinstall)
73
+ p.log.info("Existing config found; your previous answers are pre-filled. Data is kept.");
74
+ const config = await ask(existing, reinstall);
75
+ writeConfig(config);
76
+ installFiles();
77
+ p.note([
78
+ `config ${paths.config()}`,
79
+ `skill ${paths.skill()}`,
80
+ `hooks SessionStart + Stop in ${paths.settings()}`,
81
+ "",
82
+ "Work normally. Claude logs lore-worthy moments as they happen.",
83
+ "Once a week, run /selflore test (~20 min). /selflore stats shows the trend.",
84
+ "Restart any open Claude Code sessions to pick up the skill and hooks.",
85
+ ].join("\n"), "Installed");
86
+ p.outro("Getting it wrong is the feature.");
87
+ }
@@ -0,0 +1,197 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import path from "node:path";
3
+ import { readConfig, writeConfig } from "./config.js";
4
+ import { deleteEntry, listEntries, parseEntry, readEntry, uniqueId, validateEntry, writeEntry, } from "./entries.js";
5
+ import { applyGrade, dueItems, readQueue, writeQueue } from "./queue.js";
6
+ import { appendResult, QUESTION_TYPES, readResults, testedEntryIds } from "./results.js";
7
+ import { readSession, writeSession } from "./session.js";
8
+ import fs from "node:fs";
9
+ import { renderNotes } from "./notes.js";
10
+ import { buildNotesData, renderNotesHtml } from "./notes-html.js";
11
+ import { openInBrowser } from "./open.js";
12
+ import { paths } from "./paths.js";
13
+ import { renderStats } from "./stats.js";
14
+ const ok = (out) => ({ code: 0, out });
15
+ const fail = (out, code = 1) => ({ code, out });
16
+ function git(cwd, args) {
17
+ try {
18
+ return execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
19
+ }
20
+ catch {
21
+ return "";
22
+ }
23
+ }
24
+ /** Last two path segments ("selflore/v0"), so same-named folders in different parents stay distinct. */
25
+ export function projectName(dir) {
26
+ return path.resolve(dir).split(path.sep).filter(Boolean).slice(-2).join("/") || dir;
27
+ }
28
+ export function projectInfo(cwd) {
29
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]);
30
+ return {
31
+ project: projectName(top || cwd),
32
+ commit: top ? git(cwd, ["rev-parse", "--short", "HEAD"]) : "",
33
+ };
34
+ }
35
+ function today(now) {
36
+ // Local calendar date: an entry logged at 1am belongs to the user's today, not UTC's.
37
+ const pad = (n) => String(n).padStart(2, "0");
38
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
39
+ }
40
+ function summarize(e) {
41
+ return `- ${e.id} [${e.kind}/${e.skill}] ${e.testable}`;
42
+ }
43
+ /** Validate, enrich and store an entry. Enforces max_entries_per_session (manual logs warn instead). */
44
+ export function addEntry(markdown, opts) {
45
+ const now = opts.now ?? new Date();
46
+ const parsed = parseEntry(markdown);
47
+ const errors = validateEntry(parsed);
48
+ if (errors.length)
49
+ return fail(`entry rejected:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
50
+ const config = readConfig();
51
+ const session = readSession(opts.session);
52
+ const sessionEntries = session.entries.filter((id) => readEntry(id) !== null);
53
+ let warning = "";
54
+ if (opts.replace) {
55
+ if (!sessionEntries.includes(opts.replace))
56
+ return fail(`cannot replace ${opts.replace}: it was not logged in this session`);
57
+ if (testedEntryIds(readResults()).has(opts.replace))
58
+ return fail(`cannot replace ${opts.replace}: it has already been tested`);
59
+ deleteEntry(opts.replace);
60
+ sessionEntries.splice(sessionEntries.indexOf(opts.replace), 1);
61
+ }
62
+ else if (sessionEntries.length >= config.max_entries_per_session) {
63
+ if (!opts.manual) {
64
+ const current = sessionEntries.map((id) => readEntry(id)).filter((e) => e !== null);
65
+ return fail([
66
+ `cap reached: ${sessionEntries.length}/${config.max_entries_per_session} entries this session.`,
67
+ `Keep the ones that best match keep_sharp (${config.keep_sharp.join(", ")}).`,
68
+ `If the new one is better, rerun with \`entry replace <id>\`; otherwise drop it.`,
69
+ ...current.map(summarize),
70
+ ].join("\n"), 2);
71
+ }
72
+ warning = `\nnote: over the session cap (${config.max_entries_per_session}); logged anyway because it was manual.`;
73
+ }
74
+ const { project, commit } = projectInfo(opts.cwd);
75
+ const date = typeof parsed.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(parsed.date) ? parsed.date : today(now);
76
+ const entry = {
77
+ id: uniqueId(date, String(parsed.testable)),
78
+ date,
79
+ session: opts.session,
80
+ project: parsed.project ? String(parsed.project) : project,
81
+ commit: parsed.commit ? String(parsed.commit) : commit,
82
+ kind: parsed.kind,
83
+ skill: String(parsed.skill),
84
+ paths: Array.isArray(parsed.paths) ? parsed.paths.map(String) : [],
85
+ testable: String(parsed.testable),
86
+ suppressed: false,
87
+ body: parsed.body ?? "",
88
+ };
89
+ writeEntry(entry);
90
+ writeSession(opts.session, { ...session, entries: [...sessionEntries, entry.id] });
91
+ const count = sessionEntries.length + 1;
92
+ return ok(`logged ${entry.id} (${count}/${config.max_entries_per_session} this session)${warning}`);
93
+ }
94
+ export function listCmd(session) {
95
+ let entries = listEntries();
96
+ if (session) {
97
+ const ids = new Set(readSession(session).entries);
98
+ entries = entries.filter((e) => ids.has(e.id));
99
+ }
100
+ return ok(entries.length ? entries.map(summarize).join("\n") : "no entries");
101
+ }
102
+ export const QUIZ_SIZE = 10;
103
+ /** Everything the skill needs to build this week's quiz, as JSON. */
104
+ export function quizInput(now = new Date()) {
105
+ const config = readConfig();
106
+ const results = readResults();
107
+ const tested = testedEntryIds(results);
108
+ const queue = readQueue();
109
+ const due = dueItems(queue, now);
110
+ const dueIds = new Set(due.map((d) => d.entry_id));
111
+ const entries = listEntries().filter((e) => !e.suppressed);
112
+ const retests = entries
113
+ .filter((e) => dueIds.has(e.id))
114
+ .map((e) => ({ ...e, retest: { streak: queue[e.id].streak, due: queue[e.id].due[0] } }));
115
+ const fresh = entries.filter((e) => !tested.has(e.id) && !queue[e.id]);
116
+ return ok(JSON.stringify({
117
+ now: now.toISOString(),
118
+ config: { rating: config.rating, keep_sharp: config.keep_sharp, last_test_at: config.last_test_at },
119
+ target_questions: QUIZ_SIZE,
120
+ retests,
121
+ fresh,
122
+ }, null, 2));
123
+ }
124
+ export function recordCmd(entryId, grade, type, now = new Date()) {
125
+ if (!["got", "partial", "missed"].includes(grade))
126
+ return fail("grade must be got | partial | missed");
127
+ if (!QUESTION_TYPES.includes(type))
128
+ return fail(`type must be one of ${QUESTION_TYPES.join(" | ")}`);
129
+ const entry = readEntry(entryId);
130
+ if (!entry)
131
+ return fail(`no entry ${entryId}`);
132
+ const queue = readQueue();
133
+ const isRetest = Boolean(queue[entryId]);
134
+ appendResult({
135
+ ts: now.toISOString(),
136
+ entry_id: entryId,
137
+ project: entry.project,
138
+ skill: entry.skill,
139
+ question_type: type,
140
+ grade: grade,
141
+ is_retest: isRetest,
142
+ });
143
+ const next = applyGrade(queue, entryId, grade, now);
144
+ writeQueue(next);
145
+ let status;
146
+ if (next[entryId])
147
+ status = `queued, next retest ${next[entryId].due[0].slice(0, 10)} (streak ${next[entryId].streak}/2)`;
148
+ else if (isRetest)
149
+ status = "retired after two consecutive passes";
150
+ else
151
+ status = "passed, not queued";
152
+ return ok(`recorded ${grade} for ${entryId}: ${status}`);
153
+ }
154
+ export function suppressCmd(entryId) {
155
+ const entry = readEntry(entryId);
156
+ if (!entry)
157
+ return fail(`no entry ${entryId}`);
158
+ writeEntry({ ...entry, suppressed: true });
159
+ const queue = readQueue();
160
+ if (queue[entryId]) {
161
+ delete queue[entryId];
162
+ writeQueue(queue);
163
+ }
164
+ return ok(`suppressed ${entryId}; it will not appear in future tests`);
165
+ }
166
+ export function finishTest(now = new Date()) {
167
+ const config = readConfig();
168
+ writeConfig({ ...config, last_test_at: now.toISOString() });
169
+ const backlog = Object.keys(readQueue()).length;
170
+ return ok(`test finished at ${now.toISOString()}; retest backlog: ${backlog}`);
171
+ }
172
+ export function statsCmd(project) {
173
+ return ok(renderStats({
174
+ entries: listEntries(),
175
+ results: readResults(),
176
+ queue: readQueue(),
177
+ rating: readConfig().rating,
178
+ project,
179
+ }));
180
+ }
181
+ /** Write the notes page and open it in the browser; `text` prints the plain-text list instead. */
182
+ export function notesCmd(opts = {}, now = new Date()) {
183
+ if (!opts.text) {
184
+ const file = paths.notesHtml();
185
+ fs.mkdirSync(path.dirname(file), { recursive: true });
186
+ fs.writeFileSync(file, renderNotesHtml({ ...buildNotesData(now), initial: { all: !!opts.all, project: opts.project ?? null } }));
187
+ return ok(openInBrowser(file) ? `opened ${file}` : `notes page written: file://${file}`);
188
+ }
189
+ return ok(renderNotes({
190
+ entries: listEntries(),
191
+ tested: testedEntryIds(readResults()),
192
+ queue: readQueue(),
193
+ now,
194
+ all: opts.all,
195
+ project: opts.project,
196
+ }));
197
+ }
@@ -0,0 +1,22 @@
1
+ import { readJson, writeJson } from "./fsutil.js";
2
+ import { paths } from "./paths.js";
3
+ export const DEFAULT_CONFIG = {
4
+ rating: 5,
5
+ keep_sharp: ["debugging"],
6
+ max_entries_per_session: 3,
7
+ nudge: true,
8
+ cadence: "weekly",
9
+ last_test_at: null,
10
+ };
11
+ export function readConfig() {
12
+ return { ...DEFAULT_CONFIG, ...readJson(paths.config(), {}) };
13
+ }
14
+ export function configExists() {
15
+ return readJson(paths.config(), null) !== null;
16
+ }
17
+ export function writeConfig(config) {
18
+ writeJson(paths.config(), config);
19
+ }
20
+ export function clampCap(n) {
21
+ return Math.min(7, Math.max(3, Math.round(n)));
22
+ }
@@ -0,0 +1,175 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { paths } from "./paths.js";
4
+ export const KINDS = ["bug", "decision", "concept", "pattern"];
5
+ export const MAX_BODY_WORDS = 150; // PRD says ~120; small grace before rejecting
6
+ export const MAX_SNIPPET_LINES = 40;
7
+ const FIELD_ORDER = [
8
+ "id",
9
+ "date",
10
+ "session",
11
+ "project",
12
+ "commit",
13
+ "kind",
14
+ "skill",
15
+ "paths",
16
+ "testable",
17
+ "suppressed",
18
+ ];
19
+ function parseValue(raw) {
20
+ const v = raw.trim();
21
+ if (v === "true")
22
+ return true;
23
+ if (v === "false")
24
+ return false;
25
+ if (v.startsWith("[") && v.endsWith("]")) {
26
+ try {
27
+ return JSON.parse(v);
28
+ }
29
+ catch {
30
+ return v
31
+ .slice(1, -1)
32
+ .split(",")
33
+ .map((s) => s.trim().replace(/^["']|["']$/g, ""))
34
+ .filter(Boolean);
35
+ }
36
+ }
37
+ if (v.startsWith('"') && v.endsWith('"')) {
38
+ try {
39
+ return JSON.parse(v);
40
+ }
41
+ catch {
42
+ return v.slice(1, -1);
43
+ }
44
+ }
45
+ if (v.startsWith("'") && v.endsWith("'"))
46
+ return v.slice(1, -1).replace(/''/g, "'");
47
+ return v;
48
+ }
49
+ /** Parse frontmatter markdown. Unknown keys are ignored; missing ones are left undefined. */
50
+ export function parseEntry(text) {
51
+ const m = text.replace(/^/, "").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
52
+ if (!m)
53
+ return { body: text.trim() };
54
+ const out = {};
55
+ for (const line of m[1].split(/\r?\n/)) {
56
+ const idx = line.indexOf(":");
57
+ if (idx <= 0)
58
+ continue;
59
+ const key = line.slice(0, idx).trim();
60
+ // Strip trailing YAML comments on unquoted scalars (e.g. `kind: bug # bug | decision`).
61
+ let raw = line.slice(idx + 1);
62
+ if (!/^\s*["'[]/.test(raw))
63
+ raw = raw.replace(/\s+#.*$/, "");
64
+ out[key] = parseValue(raw);
65
+ }
66
+ out.body = m[2].trim();
67
+ return out;
68
+ }
69
+ export function serializeEntry(e) {
70
+ const lines = FIELD_ORDER.map((k) => {
71
+ const v = e[k];
72
+ if (Array.isArray(v))
73
+ return `${k}: ${JSON.stringify(v)}`;
74
+ if (typeof v === "boolean")
75
+ return `${k}: ${v}`;
76
+ if (k === "testable")
77
+ return `${k}: ${JSON.stringify(v)}`;
78
+ return `${k}: ${v}`;
79
+ });
80
+ return `---\n${lines.join("\n")}\n---\n${e.body.trim()}\n`;
81
+ }
82
+ /** Split body into prose and fenced code so each limit can be checked separately. */
83
+ export function splitBody(body) {
84
+ const fence = body.match(/```[^\n]*\n([\s\S]*?)```/);
85
+ if (!fence)
86
+ return { prose: body, snippet: null };
87
+ return { prose: body.replace(fence[0], "").trim(), snippet: fence[1] };
88
+ }
89
+ export function validateEntry(e) {
90
+ const errors = [];
91
+ if (!e.testable || !String(e.testable).trim())
92
+ errors.push("missing `testable` — if you cannot write a test question, the moment is not worth logging");
93
+ if (!e.kind || !KINDS.includes(e.kind))
94
+ errors.push(`\`kind\` must be one of ${KINDS.join(" | ")}`);
95
+ if (!e.skill || !String(e.skill).trim())
96
+ errors.push("missing `skill`");
97
+ const { prose, snippet } = splitBody(e.body ?? "");
98
+ const words = prose.split(/\s+/).filter(Boolean).length;
99
+ if (words === 0)
100
+ errors.push("body is empty");
101
+ if (words > MAX_BODY_WORDS)
102
+ errors.push(`body is ${words} words; keep it to ~120`);
103
+ if (snippet && snippet.trimEnd().split("\n").length > MAX_SNIPPET_LINES)
104
+ errors.push(`snippet exceeds ${MAX_SNIPPET_LINES} lines; trim to the essential part`);
105
+ return errors;
106
+ }
107
+ export function slugify(s) {
108
+ return (s
109
+ .toLowerCase()
110
+ .replace(/[^a-z0-9]+/g, "-")
111
+ .replace(/^-+|-+$/g, "")
112
+ .split("-")
113
+ .slice(0, 6)
114
+ .join("-") || "entry");
115
+ }
116
+ export function entryFile(id) {
117
+ return path.join(paths.entries(), `${id}.md`);
118
+ }
119
+ export function uniqueId(date, testable) {
120
+ const base = `${date}-${slugify(testable)}`;
121
+ let id = base;
122
+ for (let i = 2; fs.existsSync(entryFile(id)); i++)
123
+ id = `${base}-${i}`;
124
+ return id;
125
+ }
126
+ export function writeEntry(e) {
127
+ fs.mkdirSync(paths.entries(), { recursive: true });
128
+ fs.writeFileSync(entryFile(e.id), serializeEntry(e));
129
+ }
130
+ export function readEntry(id) {
131
+ try {
132
+ const parsed = parseEntry(fs.readFileSync(entryFile(id), "utf8"));
133
+ return normalize(parsed, id);
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ }
139
+ export function deleteEntry(id) {
140
+ try {
141
+ fs.unlinkSync(entryFile(id));
142
+ return true;
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
148
+ export function listEntries() {
149
+ let files;
150
+ try {
151
+ files = fs.readdirSync(paths.entries()).filter((f) => f.endsWith(".md"));
152
+ }
153
+ catch {
154
+ return [];
155
+ }
156
+ return files
157
+ .sort()
158
+ .map((f) => readEntry(f.slice(0, -3)))
159
+ .filter((e) => e !== null);
160
+ }
161
+ function normalize(p, id) {
162
+ return {
163
+ id: p.id ?? id,
164
+ date: String(p.date ?? id.slice(0, 10)),
165
+ session: String(p.session ?? ""),
166
+ project: String(p.project ?? ""),
167
+ commit: String(p.commit ?? ""),
168
+ kind: (p.kind ?? "concept"),
169
+ skill: String(p.skill ?? ""),
170
+ paths: Array.isArray(p.paths) ? p.paths.map(String) : p.paths ? [String(p.paths)] : [],
171
+ testable: String(p.testable ?? ""),
172
+ suppressed: p.suppressed === true,
173
+ body: p.body ?? "",
174
+ };
175
+ }
@@ -0,0 +1,17 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ export function readJson(file, fallback) {
4
+ try {
5
+ return JSON.parse(fs.readFileSync(file, "utf8"));
6
+ }
7
+ catch {
8
+ return fallback;
9
+ }
10
+ }
11
+ // Write via temp file + rename so a crash never leaves half-written JSON.
12
+ export function writeJson(file, data) {
13
+ fs.mkdirSync(path.dirname(file), { recursive: true });
14
+ const tmp = `${file}.${process.pid}.tmp`;
15
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n");
16
+ fs.renameSync(tmp, file);
17
+ }