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 +89 -2
- package/dist/cli.js +52 -0
- package/dist/hooks/capture-worker.js +27 -0
- package/dist/hooks/io.js +25 -0
- package/dist/hooks/session-start.js +8 -0
- package/dist/hooks/stop.js +7 -0
- package/dist/hooks/user-prompt-submit.js +9 -0
- package/dist/init.js +137 -0
- package/dist/lib/background.js +154 -0
- package/dist/lib/capture-prompt.js +33 -0
- package/dist/lib/commands.js +287 -0
- package/dist/lib/config.js +81 -0
- package/dist/lib/entries.js +202 -0
- package/dist/lib/fsutil.js +17 -0
- package/dist/lib/hook-logic.js +72 -0
- package/dist/lib/install.js +47 -0
- package/dist/lib/notes-html.js +395 -0
- package/dist/lib/notes.js +63 -0
- package/dist/lib/nudge.js +22 -0
- package/dist/lib/open.js +20 -0
- package/dist/lib/paths.js +20 -0
- package/dist/lib/queue.js +48 -0
- package/dist/lib/results.js +41 -0
- package/dist/lib/session.js +38 -0
- package/dist/lib/settings.js +64 -0
- package/dist/lib/stats.js +72 -0
- package/dist/lib/transcript.js +250 -0
- package/dist/rating-prompt.js +49 -0
- package/dist/sl.js +64 -0
- package/package.json +22 -11
- package/skill/SKILL.md +51 -0
- package/skill/references/capture.md +63 -0
- package/skill/references/log.md +13 -0
- package/skill/references/stats.md +8 -0
- package/skill/references/test.md +87 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -2
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { paths } from "./paths.js";
|
|
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
|
+
];
|
|
14
|
+
export function appendResult(r) {
|
|
15
|
+
fs.mkdirSync(path.dirname(paths.results()), { recursive: true });
|
|
16
|
+
fs.appendFileSync(paths.results(), JSON.stringify(r) + "\n");
|
|
17
|
+
}
|
|
18
|
+
export function readResults() {
|
|
19
|
+
let text;
|
|
20
|
+
try {
|
|
21
|
+
text = fs.readFileSync(paths.results(), "utf8");
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
const out = [];
|
|
27
|
+
for (const line of text.split("\n")) {
|
|
28
|
+
if (!line.trim())
|
|
29
|
+
continue;
|
|
30
|
+
try {
|
|
31
|
+
out.push(JSON.parse(line));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// skip a corrupt line rather than losing the whole history
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
export function testedEntryIds(results) {
|
|
40
|
+
return new Set(results.map((r) => r.entry_id));
|
|
41
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { readJson, writeJson } from "./fsutil.js";
|
|
3
|
+
import { paths } from "./paths.js";
|
|
4
|
+
const EMPTY = { entries: [], scanned_offset: 0, pending: null, capturing_since: null };
|
|
5
|
+
function file(sessionId) {
|
|
6
|
+
return path.join(paths.state(), `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
|
|
7
|
+
}
|
|
8
|
+
export function readSession(sessionId) {
|
|
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 };
|
|
12
|
+
}
|
|
13
|
+
export function writeSession(sessionId, s) {
|
|
14
|
+
writeJson(file(sessionId), s);
|
|
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
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readJson, writeJson } from "./fsutil.js";
|
|
4
|
+
import { paths } from "./paths.js";
|
|
5
|
+
export const HOOK_SCRIPTS = {
|
|
6
|
+
SessionStart: "session-start.js",
|
|
7
|
+
Stop: "stop.js",
|
|
8
|
+
UserPromptSubmit: "user-prompt-submit.js",
|
|
9
|
+
};
|
|
10
|
+
export function hookCommand(appDir, script) {
|
|
11
|
+
return `node "${path.join(appDir, "hooks", script)}"`;
|
|
12
|
+
}
|
|
13
|
+
function isOurs(cmd, appDir) {
|
|
14
|
+
const c = cmd.command ?? "";
|
|
15
|
+
return c.includes(path.join(appDir, "hooks")) || /[\\/]\.selflore[\\/]app[\\/]hooks[\\/]/.test(c);
|
|
16
|
+
}
|
|
17
|
+
/** Remove selflore hook commands, dropping groups/events that end up empty. Other hooks are untouched. */
|
|
18
|
+
export function stripHooks(settings, appDir) {
|
|
19
|
+
if (!settings.hooks)
|
|
20
|
+
return settings;
|
|
21
|
+
const hooks = {};
|
|
22
|
+
for (const [event, groups] of Object.entries(settings.hooks)) {
|
|
23
|
+
const kept = groups
|
|
24
|
+
.map((g) => (Array.isArray(g.hooks) ? { ...g, hooks: g.hooks.filter((h) => !isOurs(h, appDir)) } : g))
|
|
25
|
+
.filter((g) => !Array.isArray(g.hooks) || g.hooks.length > 0);
|
|
26
|
+
if (kept.length)
|
|
27
|
+
hooks[event] = kept;
|
|
28
|
+
}
|
|
29
|
+
const { hooks: _old, ...rest } = settings;
|
|
30
|
+
return Object.keys(hooks).length ? { ...rest, hooks } : rest;
|
|
31
|
+
}
|
|
32
|
+
/** Idempotently add selflore's hooks (strip then append). */
|
|
33
|
+
export function mergeHooks(settings, appDir) {
|
|
34
|
+
const base = stripHooks(settings, appDir);
|
|
35
|
+
const hooks = { ...(base.hooks ?? {}) };
|
|
36
|
+
for (const [event, script] of Object.entries(HOOK_SCRIPTS)) {
|
|
37
|
+
hooks[event] = [...(hooks[event] ?? []), { hooks: [{ type: "command", command: hookCommand(appDir, script) }] }];
|
|
38
|
+
}
|
|
39
|
+
return { ...base, hooks };
|
|
40
|
+
}
|
|
41
|
+
function loadSettings() {
|
|
42
|
+
const file = paths.settings();
|
|
43
|
+
if (!fs.existsSync(file))
|
|
44
|
+
return {};
|
|
45
|
+
const parsed = readJson(file, null);
|
|
46
|
+
if (parsed === null)
|
|
47
|
+
throw new Error(`${file} is not valid JSON; fix it before running selflore`);
|
|
48
|
+
return parsed;
|
|
49
|
+
}
|
|
50
|
+
export function installHooks() {
|
|
51
|
+
const file = paths.settings();
|
|
52
|
+
const settings = loadSettings();
|
|
53
|
+
if (fs.existsSync(file))
|
|
54
|
+
fs.copyFileSync(file, `${file}.selflore-bak`);
|
|
55
|
+
writeJson(file, mergeHooks(settings, paths.app()));
|
|
56
|
+
}
|
|
57
|
+
export function uninstallHooks() {
|
|
58
|
+
const file = paths.settings();
|
|
59
|
+
if (!fs.existsSync(file))
|
|
60
|
+
return;
|
|
61
|
+
const settings = loadSettings();
|
|
62
|
+
fs.copyFileSync(file, `${file}.selflore-bak`);
|
|
63
|
+
writeJson(file, stripHooks(settings, paths.app()));
|
|
64
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Monday (UTC) of the week containing `d`, as YYYY-MM-DD. */
|
|
2
|
+
export function weekOf(d) {
|
|
3
|
+
const date = new Date(typeof d === "string" && d.length === 10 ? `${d}T00:00:00Z` : d);
|
|
4
|
+
const day = (date.getUTCDay() + 6) % 7; // Mon=0
|
|
5
|
+
const monday = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() - day));
|
|
6
|
+
return monday.toISOString().slice(0, 10);
|
|
7
|
+
}
|
|
8
|
+
function pct(pass, total) {
|
|
9
|
+
return total === 0 ? "–" : `${Math.round((pass / total) * 100)}%`;
|
|
10
|
+
}
|
|
11
|
+
function table(header, rows) {
|
|
12
|
+
const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
|
|
13
|
+
const fmt = (r) => r.map((c, i) => (c ?? "").padEnd(widths[i])).join(" ").trimEnd();
|
|
14
|
+
return [fmt(header), widths.map((w) => "-".repeat(w)).join(" "), ...rows.map(fmt)].join("\n");
|
|
15
|
+
}
|
|
16
|
+
export function renderStats({ entries, results, queue, rating, project }) {
|
|
17
|
+
if (project) {
|
|
18
|
+
entries = entries.filter((e) => e.project === project);
|
|
19
|
+
results = results.filter((r) => r.project === project);
|
|
20
|
+
const ids = new Set(entries.map((e) => e.id));
|
|
21
|
+
queue = Object.fromEntries(Object.entries(queue).filter(([id]) => ids.has(id)));
|
|
22
|
+
}
|
|
23
|
+
if (entries.length === 0 && results.length === 0) {
|
|
24
|
+
return project ? `No selflore data for project "${project}" yet.` : "No selflore data yet. Work normally; entries appear as you go.";
|
|
25
|
+
}
|
|
26
|
+
const skills = [...new Set([...entries.map((e) => e.skill), ...results.map((r) => r.skill)])].filter(Boolean).sort();
|
|
27
|
+
const weeks = [...new Set([...entries.map((e) => weekOf(e.date)), ...results.map((r) => weekOf(r.ts))])].sort();
|
|
28
|
+
const rows = weeks.map((w) => {
|
|
29
|
+
const wr = results.filter((r) => weekOf(r.ts) === w);
|
|
30
|
+
const pass = (rs) => rs.filter((r) => r.grade === "got").length;
|
|
31
|
+
return [
|
|
32
|
+
w,
|
|
33
|
+
String(entries.filter((e) => weekOf(e.date) === w).length),
|
|
34
|
+
String(wr.length),
|
|
35
|
+
pct(pass(wr), wr.length),
|
|
36
|
+
...skills.map((s) => {
|
|
37
|
+
const sr = wr.filter((r) => r.skill === s);
|
|
38
|
+
return pct(pass(sr), sr.length);
|
|
39
|
+
}),
|
|
40
|
+
];
|
|
41
|
+
});
|
|
42
|
+
const passes = results.filter((r) => r.grade === "got").length;
|
|
43
|
+
const first = results.filter((r) => !r.is_retest);
|
|
44
|
+
const retest = results.filter((r) => r.is_retest);
|
|
45
|
+
const passCount = (rs) => rs.filter((r) => r.grade === "got").length;
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
const backlog = Object.values(queue);
|
|
48
|
+
const overdue = backlog.filter((q) => q.due[0] && new Date(q.due[0]).getTime() <= now).length;
|
|
49
|
+
const observed = results.length ? passes / results.length : null;
|
|
50
|
+
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);
|
|
53
|
+
const lines = [
|
|
54
|
+
`selflore stats${project ? ` — ${project}` : ""}`,
|
|
55
|
+
"",
|
|
56
|
+
table(["week of", "entries", "questions", "pass", ...skills.map((s) => `pass:${s}`)], rows),
|
|
57
|
+
"",
|
|
58
|
+
`overall pass rate ${pct(passes, results.length)} (${passes}/${results.length})`,
|
|
59
|
+
`detail pass ${pct(passCount(byLevel("detail")), byLevel("detail").length)}`,
|
|
60
|
+
`design pass ${pct(passCount(byLevel("design")), byLevel("design").length)}`,
|
|
61
|
+
`first-attempt pass ${pct(passCount(first), first.length)}`,
|
|
62
|
+
`retest pass ${pct(passCount(retest), retest.length)}`,
|
|
63
|
+
`retest backlog ${backlog.length} queued, ${overdue} due now`,
|
|
64
|
+
`self-rating ${rating}/10 (≈${rating * 10}%) vs observed ${observed === null ? "–" : `${Math.round(observed * 100)}%`}`,
|
|
65
|
+
];
|
|
66
|
+
if (observed !== null && results.length >= 10) {
|
|
67
|
+
const gap = Math.round(observed * 100) - rating * 10;
|
|
68
|
+
if (Math.abs(gap) >= 20)
|
|
69
|
+
lines.push(` tests ${gap > 0 ? "rate you higher" : "rate you lower"} than you do; re-rate with \`npx selflore init\` if it holds`);
|
|
70
|
+
}
|
|
71
|
+
return lines.join("\n");
|
|
72
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
/**
|
|
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
|
+
*/
|
|
8
|
+
export const MIN_LINES = { light: 80, normal: 30, thorough: 15 };
|
|
9
|
+
const DEP_FILES = new Set([
|
|
10
|
+
"package.json",
|
|
11
|
+
"requirements.txt",
|
|
12
|
+
"pyproject.toml",
|
|
13
|
+
"Pipfile",
|
|
14
|
+
"go.mod",
|
|
15
|
+
"Cargo.toml",
|
|
16
|
+
"Gemfile",
|
|
17
|
+
"composer.json",
|
|
18
|
+
"build.gradle",
|
|
19
|
+
"build.gradle.kts",
|
|
20
|
+
"pom.xml",
|
|
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"]);
|
|
24
|
+
const TEST_CMD = /\b(test|tests|jest|vitest|pytest|mocha|rspec|cargo test|go test|phpunit|tsc)\b/;
|
|
25
|
+
const FAIL_TEXT = /\b(FAIL|FAILED|failed|Error:|error TS\d+|Traceback|panic:)\b/;
|
|
26
|
+
function lineCount(s) {
|
|
27
|
+
return typeof s === "string" && s.length ? s.split("\n").length : 0;
|
|
28
|
+
}
|
|
29
|
+
function contentText(c) {
|
|
30
|
+
if (typeof c === "string")
|
|
31
|
+
return c;
|
|
32
|
+
if (Array.isArray(c))
|
|
33
|
+
return c.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("\n");
|
|
34
|
+
return "";
|
|
35
|
+
}
|
|
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();
|
|
50
|
+
const depChanges = new Set();
|
|
51
|
+
const testCmds = new Map(); // tool_use id -> is a test command
|
|
52
|
+
const seq = [];
|
|
53
|
+
for (const raw of jsonl.split("\n")) {
|
|
54
|
+
if (!raw.trim())
|
|
55
|
+
continue;
|
|
56
|
+
let line;
|
|
57
|
+
try {
|
|
58
|
+
line = JSON.parse(raw);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const content = line.message?.content;
|
|
64
|
+
if (!Array.isArray(content))
|
|
65
|
+
continue;
|
|
66
|
+
for (const block of content) {
|
|
67
|
+
if (block.type === "tool_use") {
|
|
68
|
+
const tu = block;
|
|
69
|
+
const input = tu.input ?? {};
|
|
70
|
+
const file = typeof input.file_path === "string" ? input.file_path : "";
|
|
71
|
+
if (["Write", "Edit", "MultiEdit"].includes(tu.name)) {
|
|
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);
|
|
83
|
+
if (DEP_FILES.has(path.basename(file)))
|
|
84
|
+
depChanges.add(file);
|
|
85
|
+
seq.push("edit");
|
|
86
|
+
}
|
|
87
|
+
else if (tu.name === "Bash" && typeof input.command === "string") {
|
|
88
|
+
testCmds.set(tu.id, TEST_CMD.test(input.command));
|
|
89
|
+
if (/\b(npm|pnpm|yarn|bun) (add|install|i) \S|\bpip install \S|\bcargo add\b|\bgo get\b/.test(input.command))
|
|
90
|
+
depChanges.add(input.command.slice(0, 80));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
else if (block.type === "tool_result") {
|
|
94
|
+
const id = String(block.tool_use_id ?? "");
|
|
95
|
+
if (!testCmds.get(id))
|
|
96
|
+
continue;
|
|
97
|
+
const failed = block.is_error === true || FAIL_TEXT.test(contentText(block.content));
|
|
98
|
+
seq.push(failed ? "fail" : "pass");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const largeWrites = [...added]
|
|
103
|
+
.filter(([file, n]) => n >= minLines && (opts.keepWrite?.({ file, editCount: edits.get(file) ?? 1 }) ?? true))
|
|
104
|
+
.map(([file]) => file);
|
|
105
|
+
// fail → (edit)+ → pass
|
|
106
|
+
let bugFixLoop = false;
|
|
107
|
+
let state = "idle";
|
|
108
|
+
for (const ev of seq) {
|
|
109
|
+
if (ev === "fail")
|
|
110
|
+
state = "failed";
|
|
111
|
+
else if (ev === "edit" && state !== "idle")
|
|
112
|
+
state = "edited";
|
|
113
|
+
else if (ev === "pass" && state === "edited") {
|
|
114
|
+
bugFixLoop = true;
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
else if (ev === "pass")
|
|
118
|
+
state = "idle";
|
|
119
|
+
}
|
|
120
|
+
return { largeWrites, depChanges: [...depChanges], bugFixLoop };
|
|
121
|
+
}
|
|
122
|
+
export function anyTrigger(t) {
|
|
123
|
+
return t.largeWrites.length > 0 || t.depChanges.length > 0 || t.bugFixLoop;
|
|
124
|
+
}
|
|
125
|
+
export function describeTriggers(t) {
|
|
126
|
+
const parts = [];
|
|
127
|
+
if (t.largeWrites.length)
|
|
128
|
+
parts.push(`changes to ${t.largeWrites.map((f) => path.basename(f)).join(", ")}`);
|
|
129
|
+
if (t.depChanges.length)
|
|
130
|
+
parts.push("new dependencies");
|
|
131
|
+
if (t.bugFixLoop)
|
|
132
|
+
parts.push("a fail → fix → pass loop");
|
|
133
|
+
return parts.join("; ");
|
|
134
|
+
}
|
|
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) {
|
|
140
|
+
if (!file)
|
|
141
|
+
return { text: "", start: from, end: from };
|
|
142
|
+
let size;
|
|
143
|
+
try {
|
|
144
|
+
size = fs.statSync(file).size;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
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
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const text = out.join("\n\n");
|
|
249
|
+
return text.length <= maxChars ? text : `… (earlier work omitted)\n\n${text.slice(text.length - maxChars)}`;
|
|
250
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Prompt } from "@clack/core";
|
|
2
|
+
import { S_BAR, S_BAR_END, symbol } from "@clack/prompts";
|
|
3
|
+
import { styleText } from "node:util";
|
|
4
|
+
const MIN = 1;
|
|
5
|
+
const MAX = 10;
|
|
6
|
+
/** Horizontal 1–10 scale: ←/→ to move, digits jump (0 = 10), enter to confirm. */
|
|
7
|
+
class RatingPrompt extends Prompt {
|
|
8
|
+
constructor(opts) {
|
|
9
|
+
super(opts, false);
|
|
10
|
+
this.value = opts.initialValue ?? 5;
|
|
11
|
+
this.on("cursor", (action) => {
|
|
12
|
+
const v = this.value ?? 5;
|
|
13
|
+
if (action === "left" || action === "down")
|
|
14
|
+
this.value = Math.max(MIN, v - 1);
|
|
15
|
+
if (action === "right" || action === "up")
|
|
16
|
+
this.value = Math.min(MAX, v + 1);
|
|
17
|
+
});
|
|
18
|
+
this.on("key", (ch) => {
|
|
19
|
+
if (ch && /^[0-9]$/.test(ch))
|
|
20
|
+
this.value = ch === "0" ? 10 : Number(ch);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function renderScale(value) {
|
|
25
|
+
return Array.from({ length: MAX - MIN + 1 }, (_, i) => i + MIN)
|
|
26
|
+
.map((n) => (n === value ? styleText(["green", "bold", "inverse"], ` ${n} `) : styleText("dim", ` ${n} `)))
|
|
27
|
+
.join(" ");
|
|
28
|
+
}
|
|
29
|
+
export async function ratingPrompt(message, initialValue = 5) {
|
|
30
|
+
return (await new RatingPrompt({
|
|
31
|
+
initialValue,
|
|
32
|
+
render() {
|
|
33
|
+
const title = `${styleText("gray", S_BAR)}\n${symbol(this.state)} ${message}\n`;
|
|
34
|
+
const value = this.value ?? initialValue;
|
|
35
|
+
switch (this.state) {
|
|
36
|
+
case "submit":
|
|
37
|
+
return `${title}${styleText("gray", S_BAR)} ${styleText("dim", `${value}/10`)}`;
|
|
38
|
+
case "cancel":
|
|
39
|
+
return `${title}${styleText("gray", S_BAR)} ${styleText(["strikethrough", "dim"], `${value}/10`)}\n${styleText("gray", S_BAR)}`;
|
|
40
|
+
default:
|
|
41
|
+
return [
|
|
42
|
+
`${title}${styleText("cyan", S_BAR)} ${renderScale(value)}`,
|
|
43
|
+
`${styleText("cyan", S_BAR)} ${styleText("dim", "← → to change · enter to confirm")}`,
|
|
44
|
+
`${styleText("cyan", S_BAR_END)}\n`,
|
|
45
|
+
].join("\n");
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
}).prompt());
|
|
49
|
+
}
|
package/dist/sl.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Data CLI the selflore skill calls for bookkeeping that must be exact.
|
|
3
|
+
import { readStdin } from "./hooks/io.js";
|
|
4
|
+
import { addEntry, finishTest, focusArgs, focusCmd, listCmd, notesCmd, quizInput, recordCmd, statsCmd, suppressCmd, } from "./lib/commands.js";
|
|
5
|
+
const USAGE = `usage: sl <command>
|
|
6
|
+
entry add --session <id> read entry markdown from stdin and store it (merges near-duplicates)
|
|
7
|
+
entry list [--session <id>]
|
|
8
|
+
quiz-input JSON of fresh entries + due retests
|
|
9
|
+
record --entry <id> --grade got|partial|missed --type <question-type>
|
|
10
|
+
suppress <id> flag an entry as unfair; never test it again
|
|
11
|
+
finish-test
|
|
12
|
+
stats [--project <name>]
|
|
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
|
+
function flag(args, name) {
|
|
16
|
+
const i = args.indexOf(`--${name}`);
|
|
17
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
18
|
+
}
|
|
19
|
+
async function main(argv) {
|
|
20
|
+
const [cmd, sub, ...rest] = argv;
|
|
21
|
+
const args = [sub, ...rest].filter((a) => a !== undefined);
|
|
22
|
+
switch (cmd) {
|
|
23
|
+
case "entry": {
|
|
24
|
+
const session = flag(args, "session");
|
|
25
|
+
if (sub === "list")
|
|
26
|
+
return listCmd(session);
|
|
27
|
+
if (sub !== "add")
|
|
28
|
+
break;
|
|
29
|
+
if (!session)
|
|
30
|
+
return { code: 1, out: "missing --session <id> (it is in the session context as selflore session_id=…)" };
|
|
31
|
+
return addEntry(await readStdin(), { session, cwd: process.cwd() });
|
|
32
|
+
}
|
|
33
|
+
case "quiz-input":
|
|
34
|
+
return quizInput();
|
|
35
|
+
case "record": {
|
|
36
|
+
const entry = flag(args, "entry");
|
|
37
|
+
const grade = flag(args, "grade");
|
|
38
|
+
const type = flag(args, "type");
|
|
39
|
+
if (!entry || !grade || !type)
|
|
40
|
+
break;
|
|
41
|
+
return recordCmd(entry, grade, type);
|
|
42
|
+
}
|
|
43
|
+
case "suppress":
|
|
44
|
+
if (!sub)
|
|
45
|
+
break;
|
|
46
|
+
return suppressCmd(sub);
|
|
47
|
+
case "finish-test":
|
|
48
|
+
return finishTest();
|
|
49
|
+
case "stats":
|
|
50
|
+
return statsCmd(flag(args, "project"));
|
|
51
|
+
case "focus":
|
|
52
|
+
return focusCmd(focusArgs(args));
|
|
53
|
+
case "notes":
|
|
54
|
+
return notesCmd({ all: args.includes("--all"), project: flag(args, "project"), text: args.includes("--text") });
|
|
55
|
+
}
|
|
56
|
+
return { code: 1, out: USAGE };
|
|
57
|
+
}
|
|
58
|
+
main(process.argv.slice(2)).then((r) => {
|
|
59
|
+
(r.code === 0 ? process.stdout : process.stderr).write(r.out + "\n");
|
|
60
|
+
process.exit(r.code);
|
|
61
|
+
}, (err) => {
|
|
62
|
+
process.stderr.write(`sl: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
63
|
+
process.exit(1);
|
|
64
|
+
});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "selflore",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
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",
|
|
7
7
|
"claude-skill",
|
|
@@ -10,17 +10,18 @@
|
|
|
10
10
|
],
|
|
11
11
|
"author": "lak7-manadon",
|
|
12
12
|
"license": "MIT",
|
|
13
|
-
"
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/lak7/selflore.git"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/lak7/selflore#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/lak7/selflore/issues"
|
|
21
20
|
},
|
|
21
|
+
"type": "module",
|
|
22
22
|
"files": [
|
|
23
23
|
"dist",
|
|
24
|
+
"skill",
|
|
24
25
|
"README.md"
|
|
25
26
|
],
|
|
26
27
|
"engines": {
|
|
@@ -28,9 +29,19 @@
|
|
|
28
29
|
},
|
|
29
30
|
"scripts": {
|
|
30
31
|
"build": "tsc",
|
|
32
|
+
"test": "vitest run",
|
|
31
33
|
"prepublishOnly": "npm run build"
|
|
32
34
|
},
|
|
33
35
|
"devDependencies": {
|
|
34
|
-
"
|
|
36
|
+
"@types/node": "^26.6.3",
|
|
37
|
+
"typescript": "^7.0.2",
|
|
38
|
+
"vitest": "^5.0.3"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@clack/core": "^1.5.1",
|
|
42
|
+
"@clack/prompts": "^1.8.1"
|
|
43
|
+
},
|
|
44
|
+
"bin": {
|
|
45
|
+
"selflore": "dist/cli.js"
|
|
35
46
|
}
|
|
36
47
|
}
|