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.
@@ -0,0 +1,287 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import path from "node:path";
3
+ import { BALANCES, configExists, designShare, describeFocus, effectiveFocus, FOCUS_MODES, readConfig, writeConfig, } from "./config.js";
4
+ import { inferLevel, listEntries, MERGE_SIMILARITY, parseEntry, readEntry, similarity, uniqueId, validateEntry, writeEntry, } from "./entries.js";
5
+ import { applyGrade, dueItems, readQueue, writeQueue } from "./queue.js";
6
+ import { appendResult, QUESTION_TYPES, readResults, testedEntryIds } from "./results.js";
7
+ import { readSession, writeSession } from "./session.js";
8
+ import fs from "node:fs";
9
+ import { renderNotes, staleBefore } 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.level}/${e.skill}] ${e.testable}`;
42
+ }
43
+ /**
44
+ * Find an untested entry this one should be merged into: same project, a shared path,
45
+ * and a similar question. Long sessions keep touching the same area; this keeps one
46
+ * entry per idea instead of a pile of near-duplicates.
47
+ */
48
+ export function findMergeTarget(candidate, tested) {
49
+ const queue = readQueue();
50
+ let best = null;
51
+ let bestScore = 0;
52
+ for (const e of listEntries()) {
53
+ if (e.suppressed || e.project !== candidate.project || tested.has(e.id) || queue[e.id])
54
+ continue;
55
+ const sharesPath = e.paths.some((p) => candidate.paths.includes(p));
56
+ const score = similarity(e.testable, candidate.testable);
57
+ const threshold = sharesPath ? MERGE_SIMILARITY : 0.8; // without a shared file, only near-identical questions merge
58
+ if (score >= threshold && score > bestScore) {
59
+ best = e;
60
+ bestScore = score;
61
+ }
62
+ }
63
+ return best;
64
+ }
65
+ /** Enrich, merge-or-create and store a validated entry. Shared by `entry add` and the background worker. */
66
+ export function storeEntry(parsed, opts) {
67
+ const now = opts.now ?? new Date();
68
+ const info = projectInfo(opts.cwd);
69
+ const project = parsed.project ? String(parsed.project) : info.project;
70
+ const commit = parsed.commit ? String(parsed.commit) : info.commit;
71
+ const paths = Array.isArray(parsed.paths) ? parsed.paths.map(String) : [];
72
+ const testable = String(parsed.testable);
73
+ const level = parsed.level ?? inferLevel(parsed.kind);
74
+ const session = readSession(opts.session);
75
+ const target = findMergeTarget({ project, paths, testable }, testedEntryIds(readResults()));
76
+ if (target) {
77
+ const merged = {
78
+ ...target,
79
+ kind: parsed.kind,
80
+ level,
81
+ skill: String(parsed.skill),
82
+ paths: [...new Set([...target.paths, ...paths])],
83
+ testable,
84
+ commit: commit || target.commit,
85
+ body: parsed.body ?? target.body,
86
+ };
87
+ writeEntry(merged);
88
+ if (!session.entries.includes(merged.id))
89
+ writeSession(opts.session, { ...session, entries: [...session.entries, merged.id] });
90
+ return { action: "updated", entry: merged };
91
+ }
92
+ const date = typeof parsed.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(parsed.date) ? parsed.date : today(now);
93
+ const entry = {
94
+ id: uniqueId(date, testable),
95
+ date,
96
+ session: opts.session,
97
+ project,
98
+ commit,
99
+ kind: parsed.kind,
100
+ level,
101
+ skill: String(parsed.skill),
102
+ paths,
103
+ testable,
104
+ suppressed: false,
105
+ body: parsed.body ?? "",
106
+ };
107
+ writeEntry(entry);
108
+ writeSession(opts.session, { ...session, entries: [...session.entries, entry.id] });
109
+ return { action: "logged", entry };
110
+ }
111
+ /** Validate and store an entry from markdown. There is no per-session cap; near-duplicates are merged. */
112
+ export function addEntry(markdown, opts) {
113
+ const parsed = parseEntry(markdown);
114
+ const errors = validateEntry(parsed);
115
+ if (errors.length)
116
+ return fail(`entry rejected:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
117
+ const { action, entry } = storeEntry(parsed, opts);
118
+ return ok(action === "updated"
119
+ ? `updated ${entry.id} (merged with a similar untested entry) [${entry.level}]`
120
+ : `logged ${entry.id} [${entry.level}]`);
121
+ }
122
+ export function listCmd(session) {
123
+ let entries = listEntries();
124
+ if (session) {
125
+ const ids = new Set(readSession(session).entries);
126
+ entries = entries.filter((e) => ids.has(e.id));
127
+ }
128
+ return ok(entries.length ? entries.map(summarize).join("\n") : "no entries");
129
+ }
130
+ export const QUIZ_SIZE = 10;
131
+ /** Split QUIZ_SIZE into design/detail counts from the candidates' effective focus (per project). */
132
+ export function targetSplit(entries, config = readConfig()) {
133
+ if (!entries.length) {
134
+ const design = Math.round(QUIZ_SIZE * designShare(effectiveFocus(config)));
135
+ return { design, detail: QUIZ_SIZE - design };
136
+ }
137
+ const share = entries.reduce((sum, e) => sum + designShare(effectiveFocus(config, e.project)), 0) / entries.length;
138
+ const design = Math.round(QUIZ_SIZE * share);
139
+ return { design, detail: QUIZ_SIZE - design };
140
+ }
141
+ /** Everything the skill needs to build this week's quiz, as JSON. */
142
+ export function quizInput(now = new Date()) {
143
+ const config = readConfig();
144
+ const results = readResults();
145
+ const tested = testedEntryIds(results);
146
+ const queue = readQueue();
147
+ const due = dueItems(queue, now);
148
+ const dueIds = new Set(due.map((d) => d.entry_id));
149
+ const entries = listEntries().filter((e) => !e.suppressed);
150
+ const cutoff = staleBefore(now);
151
+ const withFocus = (e) => ({ ...e, focus: effectiveFocus(config, e.project).mode });
152
+ const retests = entries
153
+ .filter((e) => dueIds.has(e.id))
154
+ .map((e) => ({ ...withFocus(e), retest: { streak: queue[e.id].streak, due: queue[e.id].due[0] } }));
155
+ const untested = entries.filter((e) => !tested.has(e.id) && !queue[e.id]);
156
+ // Untested for 3+ weeks: out of the quiz pool (still visible in notes), so a heavy week can't create an endless backlog.
157
+ const fresh = untested.filter((e) => e.date >= cutoff);
158
+ return ok(JSON.stringify({
159
+ now: now.toISOString(),
160
+ config: { rating: config.rating, keep_sharp: config.keep_sharp, last_test_at: config.last_test_at },
161
+ target_questions: QUIZ_SIZE,
162
+ target_split: targetSplit([...retests, ...fresh], config),
163
+ stale_count: untested.length - fresh.length,
164
+ retests,
165
+ fresh: fresh.map(withFocus),
166
+ }, null, 2));
167
+ }
168
+ export function recordCmd(entryId, grade, type, now = new Date()) {
169
+ if (!["got", "partial", "missed"].includes(grade))
170
+ return fail("grade must be got | partial | missed");
171
+ if (!QUESTION_TYPES.includes(type))
172
+ return fail(`type must be one of ${QUESTION_TYPES.join(" | ")}`);
173
+ const entry = readEntry(entryId);
174
+ if (!entry)
175
+ return fail(`no entry ${entryId}`);
176
+ const queue = readQueue();
177
+ const isRetest = Boolean(queue[entryId]);
178
+ appendResult({
179
+ ts: now.toISOString(),
180
+ entry_id: entryId,
181
+ project: entry.project,
182
+ skill: entry.skill,
183
+ level: entry.level,
184
+ question_type: type,
185
+ grade: grade,
186
+ is_retest: isRetest,
187
+ });
188
+ const next = applyGrade(queue, entryId, grade, now);
189
+ writeQueue(next);
190
+ let status;
191
+ if (next[entryId])
192
+ status = `queued, next retest ${next[entryId].due[0].slice(0, 10)} (streak ${next[entryId].streak}/2)`;
193
+ else if (isRetest)
194
+ status = "retired after two consecutive passes";
195
+ else
196
+ status = "passed, not queued";
197
+ return ok(`recorded ${grade} for ${entryId}: ${status}`);
198
+ }
199
+ export function suppressCmd(entryId) {
200
+ const entry = readEntry(entryId);
201
+ if (!entry)
202
+ return fail(`no entry ${entryId}`);
203
+ writeEntry({ ...entry, suppressed: true });
204
+ const queue = readQueue();
205
+ if (queue[entryId]) {
206
+ delete queue[entryId];
207
+ writeQueue(queue);
208
+ }
209
+ return ok(`suppressed ${entryId}; it will not appear in future tests`);
210
+ }
211
+ export function finishTest(now = new Date()) {
212
+ const config = readConfig();
213
+ writeConfig({ ...config, last_test_at: now.toISOString() });
214
+ const backlog = Object.keys(readQueue()).length;
215
+ return ok(`test finished at ${now.toISOString()}; retest backlog: ${backlog}`);
216
+ }
217
+ export function statsCmd(project) {
218
+ return ok(renderStats({
219
+ entries: listEntries(),
220
+ results: readResults(),
221
+ queue: readQueue(),
222
+ rating: readConfig().rating,
223
+ project,
224
+ }));
225
+ }
226
+ /** Write the notes page and open it in the browser; `text` prints the plain-text list instead. */
227
+ export function notesCmd(opts = {}, now = new Date()) {
228
+ if (!opts.text) {
229
+ const file = paths.notesHtml();
230
+ fs.mkdirSync(path.dirname(file), { recursive: true });
231
+ fs.writeFileSync(file, renderNotesHtml({ ...buildNotesData(now), initial: { all: !!opts.all, project: opts.project ?? null } }));
232
+ return ok(openInBrowser(file) ? `opened ${file}` : `notes page written: file://${file}`);
233
+ }
234
+ return ok(renderNotes({
235
+ entries: listEntries(),
236
+ tested: testedEntryIds(readResults()),
237
+ queue: readQueue(),
238
+ now,
239
+ all: opts.all,
240
+ project: opts.project,
241
+ }));
242
+ }
243
+ /** Parse `focus` CLI args: [mode] [--balance x] [--project] [--reset]. Shared by `selflore` and `sl`. */
244
+ export function focusArgs(args, cwd = process.cwd()) {
245
+ const i = args.indexOf("--balance");
246
+ const mode = args.find((a, j) => !a.startsWith("--") && (i < 0 || j !== i + 1));
247
+ return {
248
+ mode,
249
+ balance: i >= 0 ? args[i + 1] : undefined,
250
+ project: args.includes("--project"),
251
+ reset: args.includes("--reset"),
252
+ cwd,
253
+ };
254
+ }
255
+ /** Show or change the capture focus, globally or for the current project (which then takes priority). */
256
+ export function focusCmd(opts) {
257
+ if (!configExists())
258
+ return fail("selflore is not set up yet; run `npx selflore init` first");
259
+ const config = readConfig();
260
+ const project = projectInfo(opts.cwd).project;
261
+ if (opts.mode && !FOCUS_MODES.includes(opts.mode))
262
+ return fail(`focus must be one of ${FOCUS_MODES.join(" | ")}`);
263
+ if (opts.balance && !BALANCES.includes(opts.balance))
264
+ return fail(`--balance must be one of ${BALANCES.join(" | ")}`);
265
+ if (opts.reset) {
266
+ if (!opts.project)
267
+ return fail("--reset only applies with --project (it removes this project's override)");
268
+ const { [project]: _removed, ...rest } = config.projects;
269
+ writeConfig({ ...config, projects: rest });
270
+ }
271
+ else if (opts.mode || opts.balance) {
272
+ const change = {
273
+ ...(opts.mode ? { mode: opts.mode } : {}),
274
+ ...(opts.balance ? { balance: opts.balance } : {}),
275
+ };
276
+ if (opts.project)
277
+ writeConfig({ ...config, projects: { ...config.projects, [project]: { ...config.projects[project], ...change } } });
278
+ else
279
+ writeConfig({ ...config, focus: { ...config.focus, ...change } });
280
+ }
281
+ const next = readConfig();
282
+ const eff = effectiveFocus(next, project);
283
+ return ok([
284
+ `global focus: ${describeFocus(next.focus)}`,
285
+ `${project}: ${describeFocus(eff)} (${eff.source === "project" ? "project override" : "from global"})`,
286
+ ].join("\n"));
287
+ }
@@ -0,0 +1,81 @@
1
+ import { readJson, writeJson } from "./fsutil.js";
2
+ import { paths } from "./paths.js";
3
+ export const INTENSITIES = ["light", "normal", "thorough"];
4
+ export const FOCUS_MODES = ["details", "design", "mixed"];
5
+ export const BALANCES = ["design", "balanced", "details"];
6
+ export const CAPTURE_MODES = ["background", "quiet", "off"];
7
+ export const CAPTURE_MODELS = ["session", "sonnet", "haiku"];
8
+ export const DEFAULT_CONFIG = {
9
+ rating: 5,
10
+ keep_sharp: ["debugging"],
11
+ capture_intensity: "normal",
12
+ focus: { mode: "mixed", balance: "balanced" },
13
+ projects: {},
14
+ capture: "background",
15
+ capture_model: "session",
16
+ nudge: true,
17
+ cadence: "weekly",
18
+ last_test_at: null,
19
+ };
20
+ const pick = (v, allowed, fallback) => allowed.includes(v) ? v : fallback;
21
+ /** Fill in new fields and convert old ones (v0.2's max_entries_per_session → capture_intensity). */
22
+ export function migrateConfig(raw) {
23
+ const legacyCap = typeof raw.max_entries_per_session === "number" ? raw.max_entries_per_session : null;
24
+ const intensityFromCap = legacyCap === null ? null : legacyCap <= 3 ? "light" : legacyCap <= 5 ? "normal" : "thorough";
25
+ const focus = (raw.focus ?? {});
26
+ const projects = {};
27
+ for (const [name, f] of Object.entries((raw.projects ?? {}))) {
28
+ const o = {};
29
+ if (FOCUS_MODES.includes(f?.mode))
30
+ o.mode = f.mode;
31
+ if (BALANCES.includes(f?.balance))
32
+ o.balance = f.balance;
33
+ if (Object.keys(o).length)
34
+ projects[name] = o;
35
+ }
36
+ const { max_entries_per_session: _legacy, ...rest } = raw;
37
+ return {
38
+ ...DEFAULT_CONFIG,
39
+ ...rest,
40
+ capture_intensity: pick(raw.capture_intensity, INTENSITIES, intensityFromCap ?? DEFAULT_CONFIG.capture_intensity),
41
+ focus: {
42
+ mode: pick(focus.mode, FOCUS_MODES, DEFAULT_CONFIG.focus.mode),
43
+ balance: pick(focus.balance, BALANCES, DEFAULT_CONFIG.focus.balance),
44
+ },
45
+ projects,
46
+ capture: pick(raw.capture, CAPTURE_MODES, DEFAULT_CONFIG.capture),
47
+ capture_model: pick(raw.capture_model, CAPTURE_MODELS, DEFAULT_CONFIG.capture_model),
48
+ };
49
+ }
50
+ export function readConfig() {
51
+ return migrateConfig(readJson(paths.config(), {}));
52
+ }
53
+ export function configExists() {
54
+ return readJson(paths.config(), null) !== null;
55
+ }
56
+ export function writeConfig(config) {
57
+ writeJson(paths.config(), config);
58
+ }
59
+ /** The focus that applies to a project: its override wins, field by field, over the global focus. */
60
+ export function effectiveFocus(config, project) {
61
+ const o = project ? config.projects[project] : undefined;
62
+ return {
63
+ mode: o?.mode ?? config.focus.mode,
64
+ balance: o?.balance ?? config.focus.balance,
65
+ source: o && (o.mode || o.balance) ? "project" : "global",
66
+ };
67
+ }
68
+ /** How many of `total` quiz questions should be design-level for a focus. */
69
+ export function designShare(focus) {
70
+ if (focus.mode === "design")
71
+ return 1;
72
+ if (focus.mode === "details")
73
+ return 0;
74
+ return focus.balance === "design" ? 0.7 : focus.balance === "details" ? 0.3 : 0.5;
75
+ }
76
+ export function describeFocus(focus) {
77
+ if (focus.mode !== "mixed")
78
+ return focus.mode;
79
+ const b = { design: "mostly design", balanced: "balanced", details: "mostly details" }[focus.balance];
80
+ return `mixed (${b})`;
81
+ }
@@ -0,0 +1,202 @@
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 LEVELS = ["detail", "design"];
6
+ /** Entries from before `level` existed: decisions are design-level, everything else detail. */
7
+ export function inferLevel(kind) {
8
+ return kind === "decision" ? "design" : "detail";
9
+ }
10
+ export const MAX_BODY_WORDS = 150; // PRD says ~120; small grace before rejecting
11
+ export const MAX_SNIPPET_LINES = 40;
12
+ const FIELD_ORDER = [
13
+ "id",
14
+ "date",
15
+ "session",
16
+ "project",
17
+ "commit",
18
+ "kind",
19
+ "level",
20
+ "skill",
21
+ "paths",
22
+ "testable",
23
+ "suppressed",
24
+ ];
25
+ function parseValue(raw) {
26
+ const v = raw.trim();
27
+ if (v === "true")
28
+ return true;
29
+ if (v === "false")
30
+ return false;
31
+ if (v.startsWith("[") && v.endsWith("]")) {
32
+ try {
33
+ return JSON.parse(v);
34
+ }
35
+ catch {
36
+ return v
37
+ .slice(1, -1)
38
+ .split(",")
39
+ .map((s) => s.trim().replace(/^["']|["']$/g, ""))
40
+ .filter(Boolean);
41
+ }
42
+ }
43
+ if (v.startsWith('"') && v.endsWith('"')) {
44
+ try {
45
+ return JSON.parse(v);
46
+ }
47
+ catch {
48
+ return v.slice(1, -1);
49
+ }
50
+ }
51
+ if (v.startsWith("'") && v.endsWith("'"))
52
+ return v.slice(1, -1).replace(/''/g, "'");
53
+ return v;
54
+ }
55
+ /** Parse frontmatter markdown. Unknown keys are ignored; missing ones are left undefined. */
56
+ export function parseEntry(text) {
57
+ const m = text.replace(/^/, "").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
58
+ if (!m)
59
+ return { body: text.trim() };
60
+ const out = {};
61
+ for (const line of m[1].split(/\r?\n/)) {
62
+ const idx = line.indexOf(":");
63
+ if (idx <= 0)
64
+ continue;
65
+ const key = line.slice(0, idx).trim();
66
+ // Strip trailing YAML comments on unquoted scalars (e.g. `kind: bug # bug | decision`).
67
+ let raw = line.slice(idx + 1);
68
+ if (!/^\s*["'[]/.test(raw))
69
+ raw = raw.replace(/\s+#.*$/, "");
70
+ out[key] = parseValue(raw);
71
+ }
72
+ out.body = m[2].trim();
73
+ return out;
74
+ }
75
+ export function serializeEntry(e) {
76
+ const lines = FIELD_ORDER.map((k) => {
77
+ const v = e[k];
78
+ if (Array.isArray(v))
79
+ return `${k}: ${JSON.stringify(v)}`;
80
+ if (typeof v === "boolean")
81
+ return `${k}: ${v}`;
82
+ if (k === "testable")
83
+ return `${k}: ${JSON.stringify(v)}`;
84
+ return `${k}: ${v}`;
85
+ });
86
+ return `---\n${lines.join("\n")}\n---\n${e.body.trim()}\n`;
87
+ }
88
+ /** Split body into prose and fenced code so each limit can be checked separately. */
89
+ export function splitBody(body) {
90
+ const fence = body.match(/```[^\n]*\n([\s\S]*?)```/);
91
+ if (!fence)
92
+ return { prose: body, snippet: null };
93
+ return { prose: body.replace(fence[0], "").trim(), snippet: fence[1] };
94
+ }
95
+ export function validateEntry(e) {
96
+ const errors = [];
97
+ if (!e.testable || !String(e.testable).trim())
98
+ errors.push("missing `testable` — if you cannot write a test question, the moment is not worth logging");
99
+ if (!e.kind || !KINDS.includes(e.kind))
100
+ errors.push(`\`kind\` must be one of ${KINDS.join(" | ")}`);
101
+ if (e.level !== undefined && !LEVELS.includes(e.level))
102
+ errors.push(`\`level\` must be one of ${LEVELS.join(" | ")}`);
103
+ if (!e.skill || !String(e.skill).trim())
104
+ errors.push("missing `skill`");
105
+ const { prose, snippet } = splitBody(e.body ?? "");
106
+ const words = prose.split(/\s+/).filter(Boolean).length;
107
+ if (words === 0)
108
+ errors.push("body is empty");
109
+ if (words > MAX_BODY_WORDS)
110
+ errors.push(`body is ${words} words; keep it to ~120`);
111
+ if (snippet && snippet.trimEnd().split("\n").length > MAX_SNIPPET_LINES)
112
+ errors.push(`snippet exceeds ${MAX_SNIPPET_LINES} lines; trim to the essential part`);
113
+ return errors;
114
+ }
115
+ export function slugify(s) {
116
+ return (s
117
+ .toLowerCase()
118
+ .replace(/[^a-z0-9]+/g, "-")
119
+ .replace(/^-+|-+$/g, "")
120
+ .split("-")
121
+ .slice(0, 6)
122
+ .join("-") || "entry");
123
+ }
124
+ export function entryFile(id) {
125
+ return path.join(paths.entries(), `${id}.md`);
126
+ }
127
+ export function uniqueId(date, testable) {
128
+ const base = `${date}-${slugify(testable)}`;
129
+ let id = base;
130
+ for (let i = 2; fs.existsSync(entryFile(id)); i++)
131
+ id = `${base}-${i}`;
132
+ return id;
133
+ }
134
+ export function writeEntry(e) {
135
+ fs.mkdirSync(paths.entries(), { recursive: true });
136
+ fs.writeFileSync(entryFile(e.id), serializeEntry(e));
137
+ }
138
+ export function readEntry(id) {
139
+ try {
140
+ const parsed = parseEntry(fs.readFileSync(entryFile(id), "utf8"));
141
+ return normalize(parsed, id);
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ export function deleteEntry(id) {
148
+ try {
149
+ fs.unlinkSync(entryFile(id));
150
+ return true;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
156
+ export function listEntries() {
157
+ let files;
158
+ try {
159
+ files = fs.readdirSync(paths.entries()).filter((f) => f.endsWith(".md"));
160
+ }
161
+ catch {
162
+ return [];
163
+ }
164
+ return files
165
+ .sort()
166
+ .map((f) => readEntry(f.slice(0, -3)))
167
+ .filter((e) => e !== null);
168
+ }
169
+ function normalize(p, id) {
170
+ return {
171
+ id: p.id ?? id,
172
+ date: String(p.date ?? id.slice(0, 10)),
173
+ session: String(p.session ?? ""),
174
+ project: String(p.project ?? ""),
175
+ commit: String(p.commit ?? ""),
176
+ kind: (p.kind ?? "concept"),
177
+ level: LEVELS.includes(p.level) ? p.level : inferLevel(p.kind),
178
+ skill: String(p.skill ?? ""),
179
+ paths: Array.isArray(p.paths) ? p.paths.map(String) : p.paths ? [String(p.paths)] : [],
180
+ testable: String(p.testable ?? ""),
181
+ suppressed: p.suppressed === true,
182
+ body: p.body ?? "",
183
+ };
184
+ }
185
+ // Question scaffolding that says nothing about the topic ("why does … happen if …").
186
+ const STOPWORDS = new Set("the and for are was were why what when where which who how does did doesn don isn can could would should will this that these those with without from into than then there here have has had not but its it's you your our they them their about after before over under also just only use used using happen happens happened instead break breaks".split(" "));
187
+ function words(s) {
188
+ return new Set(s.toLowerCase().match(/[a-z0-9_]+/g)?.filter((w) => w.length > 2 && !STOPWORDS.has(w)) ?? []);
189
+ }
190
+ /** Jaccard similarity of the word sets of two strings (words of 3+ chars). */
191
+ export function similarity(a, b) {
192
+ const wa = words(a);
193
+ const wb = words(b);
194
+ if (!wa.size || !wb.size)
195
+ return 0;
196
+ let inter = 0;
197
+ for (const w of wa)
198
+ if (wb.has(w))
199
+ inter++;
200
+ return inter / (wa.size + wb.size - inter);
201
+ }
202
+ export const MERGE_SIMILARITY = 0.5;
@@ -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
+ }
@@ -0,0 +1,72 @@
1
+ import { configExists, readConfig } from "./config.js";
2
+ import { keepWriteFor, spawnWorker } from "./background.js";
3
+ import { isCapturing, readSession, takeAnnounce, updateSession } from "./session.js";
4
+ import { anyTrigger, describeTriggers, detectTriggers, MIN_LINES, readTranscriptFrom } from "./transcript.js";
5
+ import { listEntries } from "./entries.js";
6
+ import { sessionStartContext } from "./nudge.js";
7
+ /**
8
+ * The Stop hook. It never blocks the turn: it only looks at work since the last capture and,
9
+ * if that work has triggers, either starts a detached background capture or (quiet mode)
10
+ * leaves a hint for the next prompt.
11
+ */
12
+ export function handleStop(input, deps = {}) {
13
+ if (!input.session_id || !configExists())
14
+ return "none";
15
+ const config = readConfig();
16
+ if (config.capture === "off")
17
+ return "off";
18
+ const now = deps.now ?? new Date();
19
+ const session = readSession(input.session_id);
20
+ // Don't advance past work a running capture hasn't finished; it'll be picked up next turn.
21
+ if (config.capture === "background" && isCapturing(session, now))
22
+ return "locked";
23
+ const cwd = input.cwd ?? process.cwd();
24
+ const { text, start, end } = readTranscriptFrom(input.transcript_path, session.scanned_offset);
25
+ const triggers = detectTriggers(text, {
26
+ minLines: MIN_LINES[config.capture_intensity],
27
+ keepWrite: deps.keepWrite ?? keepWriteFor(cwd),
28
+ });
29
+ // No triggers: leave the offset where it is, so small steps across turns are judged together.
30
+ if (!anyTrigger(triggers))
31
+ return "none";
32
+ if (config.capture === "quiet") {
33
+ updateSession(input.session_id, { scanned_offset: end, pending: describeTriggers(triggers) });
34
+ return "pending";
35
+ }
36
+ const ok = (deps.spawn ?? spawnWorker)({
37
+ session: input.session_id,
38
+ transcript: input.transcript_path,
39
+ from: start,
40
+ to: end,
41
+ cwd,
42
+ });
43
+ if (!ok)
44
+ return "spawn-failed";
45
+ updateSession(input.session_id, { scanned_offset: end, capturing_since: now.toISOString() });
46
+ return "spawned";
47
+ }
48
+ /** UserPromptSubmit (quiet mode): one context line asking Claude to log at a natural pause. */
49
+ export function handlePromptSubmit(input) {
50
+ if (!input.session_id || !configExists())
51
+ return "";
52
+ if (readConfig().capture !== "quiet")
53
+ return "";
54
+ const session = readSession(input.session_id);
55
+ if (!session.pending)
56
+ return "";
57
+ updateSession(input.session_id, { pending: null });
58
+ return (`selflore: recent work had ${session.pending}. At a natural pause in this task (not mid-step, and never instead of answering the user), ` +
59
+ `use the selflore skill to log any lore-worthy moments (session_id=${input.session_id}). Don't mention this unless you log something.`);
60
+ }
61
+ export function handleSessionStart(input, now = new Date()) {
62
+ if (!configExists())
63
+ return "";
64
+ const config = readConfig();
65
+ const oldest = listEntries()[0]?.date ?? null; // ids are date-prefixed, so sorted oldest first
66
+ const lines = [sessionStartContext(input.session_id, config, oldest, now)];
67
+ const captured = takeAnnounce();
68
+ if (captured > 0)
69
+ lines.push(`selflore: captured ${captured} ${captured === 1 ? "entry" : "entries"} in the background since the last session. ` +
70
+ "Mention this once, in one short line, at the start of your first reply; then don't bring it up again.");
71
+ return lines.filter(Boolean).join("\n");
72
+ }