@litfamily/litclaude 1.0.57 → 1.0.59
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/CHANGELOG.md +42 -0
- package/README.md +8 -8
- package/README_ko-KR.md +8 -8
- package/bin/litclaude-ai.js +31 -3
- package/docs/assets/readme/badge-version.svg +1 -1
- package/package.json +1 -1
- package/plugins/litclaude/.claude-plugin/plugin.json +1 -1
- package/plugins/litclaude/bin/litclaude-ai +2 -0
- package/plugins/litclaude/bin/litclaude-hook.js +87 -654
- package/plugins/litclaude/bin/litclaude-mcp.js +1 -1
- package/plugins/litclaude/hooks/lit-mod.mjs +20 -8
- package/plugins/litclaude/lib/goal-files.mjs +104 -0
- package/plugins/litclaude/lib/interface-probe-gate.mjs +20 -11
- package/plugins/litclaude/lib/lit-plan-persistence.mjs +23 -13
- package/plugins/litclaude/lib/litgoal/state.mjs +36 -16
- package/plugins/litclaude/lib/mod/goal.mjs +4 -0
- package/plugins/litclaude/lib/receipt-gate.mjs +101 -0
- package/plugins/litclaude/lib/receipts.mjs +379 -0
- package/plugins/litclaude/lib/rewind/suggest.mjs +20 -9
- package/plugins/litclaude/lib/route-match.mjs +729 -0
- package/plugins/litclaude/lib/route-why-cli.mjs +33 -0
- package/plugins/litclaude/lib/session-state.mjs +180 -0
- package/plugins/litclaude/lib/workflow-stage.mjs +8 -1
- package/plugins/litclaude/scripts/goal-propose.mjs +29 -18
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// The session's receipt ledger: which checks ran and when code last changed, written from what the
|
|
2
|
+
// PostToolUse hooks already see. Claude Code 2.1.330 gives a Bash call no exit field: a call that
|
|
3
|
+
// exits 0 reaches PostToolUse, a non-zero exit reaches PostToolUseFailure, whose `error` starts with
|
|
4
|
+
// the host's own `Exit code <n>` line. The event is the pass/fail signal; the number comes from that
|
|
5
|
+
// anchored host line only, never from the command's output. A receipt keeps the check's name (the
|
|
6
|
+
// command and its script, no arguments), the exit, and hashes; never a prompt, argument or output.
|
|
7
|
+
// sessions/<sid>/receipts.jsonl {at, check, exit, outputSha256, treeSha, codeSha}, one line per check run
|
|
8
|
+
// sessions/<sid>/edits.json {lastCodeEditAt, baselineCodeSha}
|
|
9
|
+
// sessions/<sid>/check-rc one integer, written by a rewritten piped check and removed on read
|
|
10
|
+
// lastCodeEditAt comes from Write, Edit, MultiEdit, NotebookEdit. baselineCodeSha is the code
|
|
11
|
+
// fingerprint taken the first time lit-loop, litwork or start-work activates. codeSha is that same
|
|
12
|
+
// fingerprint at the check. A piped or `;`-chained check records the integer in check-rc, not the
|
|
13
|
+
// pipeline's status and not anything parsed from the command's output. A check that ends a leading
|
|
14
|
+
// `&&` chain is wrapped alone; if an earlier part of that chain fails, the check never runs.
|
|
15
|
+
import { execFileSync } from "node:child_process";
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
import { closeSync, constants, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
18
|
+
import { join, relative, resolve } from "node:path";
|
|
19
|
+
|
|
20
|
+
import { resolveProjectStateRoot, STATE_APPEND_FLAG, STATE_WRITE_FLAG } from "./project-state-root.mjs";
|
|
21
|
+
import { sessionStateDir, sessionStatePath } from "./session-state.mjs";
|
|
22
|
+
import { readStack } from "./workflow-stack.mjs";
|
|
23
|
+
|
|
24
|
+
export const RECEIPTS_FILE = "receipts.jsonl";
|
|
25
|
+
export const EDITS_FILE = "edits.json";
|
|
26
|
+
const MAX_COMMAND = 4096;
|
|
27
|
+
const GIT_TIMEOUT_MS = 4000;
|
|
28
|
+
const CODE_FILE_CAP = 20000;
|
|
29
|
+
const EDIT_TOOLS = new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
|
|
30
|
+
const GATED_SKILLS = new Set(["lit-loop", "litwork", "start-work"]);
|
|
31
|
+
export const CHECK_RC_FILE = "check-rc";
|
|
32
|
+
const WRAP_MARK = "; __lit_rc=$?; printf '%s\\n' \"$__lit_rc\" > ";
|
|
33
|
+
const HOST_EXIT_LINE = /^Exit code (\d{1,3})(?:\n|$)/u;
|
|
34
|
+
const ENV_PREFIX = /^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*/u;
|
|
35
|
+
// Redirections never change a command's exit status, so they are dropped before matching.
|
|
36
|
+
const REDIRECTION = /\s*(?:\d|&)?>>?(?:&\d+|\s*[^\s|;&<>]+)/gu;
|
|
37
|
+
const UNSAFE_SHELL = /[|;`&()<>\n\r]|\$\(/u;
|
|
38
|
+
const CHECKS = [
|
|
39
|
+
[/^npm\s+test(?=\s|$)/u, () => "npm test"],
|
|
40
|
+
[/^npm\s+run\s+(test[A-Za-z0-9:._-]*)(?=\s|$)/u, (match) => `npm run ${match[1]}`],
|
|
41
|
+
[/^node\s+--test(?=\s|$)/u, () => "node --test"],
|
|
42
|
+
[/^pytest(?=\s|$)/u, () => "pytest"],
|
|
43
|
+
[/^cargo\s+test(?=\s|$)/u, () => "cargo test"],
|
|
44
|
+
[/^go\s+test(?=\s|$)/u, () => "go test"],
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The check a Bash command runs, as `npm test`, `npm run test:unit`, `node --test`, `pytest`,
|
|
49
|
+
* `cargo test` or `go test`; null for anything else. Only `a && b && check` chains count, because a
|
|
50
|
+
* pipe, `;`, `||`, a background `&` or a subshell can report a status that is not the check's.
|
|
51
|
+
*/
|
|
52
|
+
export const normalizeCheck = (command) => {
|
|
53
|
+
if (typeof command !== "string" || command.length > MAX_COMMAND) return null;
|
|
54
|
+
const segments = command.replace(REDIRECTION, " ").split("&&").map((segment) => segment.trim());
|
|
55
|
+
if (segments.some((segment) => !segment || UNSAFE_SHELL.test(segment))) return null;
|
|
56
|
+
const last = segments.at(-1).replace(ENV_PREFIX, "");
|
|
57
|
+
for (const [pattern, name] of CHECKS) {
|
|
58
|
+
const match = pattern.exec(last);
|
|
59
|
+
if (match) return name(match);
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
65
|
+
|
|
66
|
+
const gitBytes = (cwd, args, input) => execFileSync("git", args, {
|
|
67
|
+
cwd,
|
|
68
|
+
input,
|
|
69
|
+
timeout: GIT_TIMEOUT_MS,
|
|
70
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
71
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const isDocRel = (rel) => {
|
|
75
|
+
const path = String(rel).replaceAll("\\", "/");
|
|
76
|
+
return /\.(?:md|txt)$/iu.test(path) || path.startsWith("docs/");
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* sha256 of working-tree contents for tracked and untracked code files, ordered by path.
|
|
81
|
+
* Null when this is not a git checkout, the listing is over CODE_FILE_CAP, or git fails.
|
|
82
|
+
* Staging and committing do not change it: the hash is of file bytes, not of HEAD or the index.
|
|
83
|
+
*/
|
|
84
|
+
export const codeShaOf = (cwd) => {
|
|
85
|
+
try {
|
|
86
|
+
const inside = gitBytes(cwd, ["rev-parse", "--is-inside-work-tree"]).toString("utf8").trim();
|
|
87
|
+
if (inside !== "true") return null;
|
|
88
|
+
const listed = gitBytes(cwd, ["ls-files", "-co", "--exclude-standard", "-z"])
|
|
89
|
+
.toString("utf8").split("\0").filter(Boolean);
|
|
90
|
+
if (listed.length > CODE_FILE_CAP) return null;
|
|
91
|
+
const paths = listed.filter((path) => !isDocRel(path) && !path.includes("\n")).filter((path) => {
|
|
92
|
+
const stats = lstatSync(join(cwd, path), { throwIfNoEntry: false });
|
|
93
|
+
return Boolean(stats && (stats.isFile() || stats.isSymbolicLink()));
|
|
94
|
+
}).sort();
|
|
95
|
+
if (paths.length > CODE_FILE_CAP) return null;
|
|
96
|
+
const hash = createHash("sha256");
|
|
97
|
+
if (paths.length > 0) {
|
|
98
|
+
const blobs = gitBytes(cwd, ["hash-object", "--stdin-paths"], Buffer.from(`${paths.join("\n")}\n`))
|
|
99
|
+
.toString("utf8").trim().split("\n");
|
|
100
|
+
if (blobs.length !== paths.length || blobs.some((blob) => !/^[0-9a-f]{40}$/u.test(blob))) return null;
|
|
101
|
+
for (let i = 0; i < paths.length; i += 1) hash.update(`${paths[i]}\0${blobs[i]}\n`);
|
|
102
|
+
}
|
|
103
|
+
return hash.digest("hex");
|
|
104
|
+
} catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const shellQuote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
110
|
+
|
|
111
|
+
// Index of the first unquoted `|` (not `||`) or `;`. `orOr` is an unquoted `||` before that split.
|
|
112
|
+
// `lastAndEnd` is the index just after the last unquoted `&&` before it, or -1. A bare `&` marks
|
|
113
|
+
// a background command. Quotes hide all three.
|
|
114
|
+
const findPipeOrSemi = (command) => {
|
|
115
|
+
let quote = null;
|
|
116
|
+
let escape = false;
|
|
117
|
+
let background = false;
|
|
118
|
+
let index = -1;
|
|
119
|
+
let orOr = false;
|
|
120
|
+
let lastAndEnd = -1;
|
|
121
|
+
for (let i = 0; i < command.length; i += 1) {
|
|
122
|
+
const ch = command[i];
|
|
123
|
+
if (escape) { escape = false; continue; }
|
|
124
|
+
if (quote === "'") { if (ch === "'") quote = null; continue; }
|
|
125
|
+
if (quote === '"') {
|
|
126
|
+
if (ch === "\\") { escape = true; continue; }
|
|
127
|
+
if (ch === '"') quote = null;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (ch === "\\") { escape = true; continue; }
|
|
131
|
+
if (ch === "'" || ch === '"') { quote = ch; continue; }
|
|
132
|
+
if (ch === "|" && command[i + 1] === "|") {
|
|
133
|
+
if (index < 0) orOr = true;
|
|
134
|
+
i += 1;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if ((ch === "|" || ch === ";") && index < 0) index = i;
|
|
138
|
+
if (ch === "&" && command[i + 1] === "&") {
|
|
139
|
+
if (index < 0) lastAndEnd = i + 2;
|
|
140
|
+
i += 1;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (ch === "&" && command[i - 1] !== ">" && command[i - 1] !== "<" && command[i - 1] !== "|") background = true;
|
|
144
|
+
}
|
|
145
|
+
return { index, background, orOr, lastAndEnd };
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const sessionGated = (cwd, sessionId) => {
|
|
149
|
+
const { frames, history } = readStack(cwd, sessionId);
|
|
150
|
+
return [...frames, ...history].some((entry) => GATED_SKILLS.has(entry?.skill));
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const shellWhitespace = (ch) => ch === " " || ch === "\t";
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The command with its check wrapped so the check's exit is written to `check-rc` and the group's
|
|
157
|
+
* exit stays the check's. A check that is the whole prefix is wrapped as before. A check that is the
|
|
158
|
+
* last part of a leading `&&` chain is wrapped alone; the earlier parts stay byte-identical. Null
|
|
159
|
+
* when nothing should change.
|
|
160
|
+
*/
|
|
161
|
+
export const planCheckRewrite = ({ cwd, sessionId, command, runInBackground = false }) => {
|
|
162
|
+
try {
|
|
163
|
+
if (runInBackground === true) return null;
|
|
164
|
+
if (typeof command !== "string" || command.length === 0 || command.length > MAX_COMMAND) return null;
|
|
165
|
+
if (command.includes("pipefail")) return null;
|
|
166
|
+
const split = findPipeOrSemi(command);
|
|
167
|
+
if (split.index < 0 || split.background || split.orOr) return null;
|
|
168
|
+
const prefix = command.slice(0, split.index);
|
|
169
|
+
let head = "";
|
|
170
|
+
let trailing = "";
|
|
171
|
+
let checkSegment = prefix;
|
|
172
|
+
if (split.lastAndEnd >= 0) {
|
|
173
|
+
let start = split.lastAndEnd;
|
|
174
|
+
while (start < split.index && shellWhitespace(command[start])) start += 1;
|
|
175
|
+
let end = split.index;
|
|
176
|
+
while (end > start && shellWhitespace(command[end - 1])) end -= 1;
|
|
177
|
+
// An opening `&&` with nothing before it, or a blank last element, is not a chain to wrap.
|
|
178
|
+
if (!/\S/u.test(command.slice(0, split.lastAndEnd - 2)) || start >= end) return null;
|
|
179
|
+
head = command.slice(0, start);
|
|
180
|
+
trailing = command.slice(end, split.index);
|
|
181
|
+
checkSegment = command.slice(start, end);
|
|
182
|
+
}
|
|
183
|
+
if (normalizeCheck(checkSegment) === null) return null;
|
|
184
|
+
if (!sessionGated(cwd, sessionId)) return null;
|
|
185
|
+
const dir = sessionStateDir(cwd, sessionId);
|
|
186
|
+
if (dir === null) return null;
|
|
187
|
+
const rcPath = join(dir, CHECK_RC_FILE);
|
|
188
|
+
if (lstatSync(rcPath, { throwIfNoEntry: false })?.isSymbolicLink()) return null;
|
|
189
|
+
// A short-circuited chain never writes a new exit. Drop a leftover file so it cannot be recorded.
|
|
190
|
+
try {
|
|
191
|
+
unlinkSync(rcPath);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (error?.code !== "ENOENT") throw error;
|
|
194
|
+
}
|
|
195
|
+
const wrapped = `{ ${checkSegment}; __lit_rc=$?; printf '%s\\n' "$__lit_rc" > ${shellQuote(rcPath)}; (exit $__lit_rc); }`;
|
|
196
|
+
return `${head}${wrapped}${trailing}${command.slice(split.index)}`;
|
|
197
|
+
} catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const checkFromWrapped = (command) => {
|
|
203
|
+
if (typeof command !== "string") return null;
|
|
204
|
+
const at = command.indexOf(WRAP_MARK);
|
|
205
|
+
if (at < 2) return null;
|
|
206
|
+
if (command.startsWith("{ ")) return normalizeCheck(command.slice(2, at));
|
|
207
|
+
const marker = command.lastIndexOf("&&", at);
|
|
208
|
+
if (marker < 0) return null;
|
|
209
|
+
const braced = /^\s*\{ ([\s\S]*)$/u.exec(command.slice(marker + 2, at));
|
|
210
|
+
return braced ? normalizeCheck(braced[1]) : null;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
// Reads and removes check-rc. A symlink is left in place and counts as no exit.
|
|
214
|
+
const takeCheckRc = (dir) => {
|
|
215
|
+
const path = join(dir, CHECK_RC_FILE);
|
|
216
|
+
let fd;
|
|
217
|
+
try {
|
|
218
|
+
const stats = lstatSync(path, { throwIfNoEntry: false });
|
|
219
|
+
if (!stats || stats.isSymbolicLink() || !stats.isFile()) return null;
|
|
220
|
+
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
221
|
+
const text = readFileSync(fd, "utf8");
|
|
222
|
+
closeSync(fd);
|
|
223
|
+
fd = undefined;
|
|
224
|
+
unlinkSync(path);
|
|
225
|
+
const match = /^([0-9]{1,3})\n?$/u.exec(text);
|
|
226
|
+
return match ? Number(match[1]) : null;
|
|
227
|
+
} catch {
|
|
228
|
+
if (fd !== undefined) closeSync(fd);
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
/** sha256 of `git diff HEAD --binary` plus the untracked file list; null outside a git work tree. */
|
|
234
|
+
export const treeShaOf = (cwd) => {
|
|
235
|
+
try {
|
|
236
|
+
const git = (args) => execFileSync("git", args, { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
|
|
237
|
+
const diff = git(["diff", "HEAD", "--binary"]);
|
|
238
|
+
const untracked = git(["ls-files", "--others", "--exclude-standard", "-z", "--", ":/"]);
|
|
239
|
+
return createHash("sha256").update(diff).update("\0").update(untracked).digest("hex");
|
|
240
|
+
} catch {
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const appendLine = (path, record) => {
|
|
246
|
+
const fd = openSync(path, STATE_APPEND_FLAG, 0o600);
|
|
247
|
+
try {
|
|
248
|
+
writeSync(fd, `${JSON.stringify(record)}\n`);
|
|
249
|
+
} finally {
|
|
250
|
+
closeSync(fd);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Appends one receipt for a check run seen by PostToolUse (`failed: false`) or PostToolUseFailure
|
|
256
|
+
* (`failed: true`). A background or interrupted run, a non-check command or an unsafe session id writes
|
|
257
|
+
* nothing.
|
|
258
|
+
*/
|
|
259
|
+
export const recordCheckRun = ({ cwd, sessionId, input, failed = false, now = new Date() }) => {
|
|
260
|
+
if (input?.tool_name !== "Bash") return null;
|
|
261
|
+
// A background run reaches PostToolUse when it starts, before any result exists.
|
|
262
|
+
if (input.tool_input?.run_in_background === true || input.tool_response?.backgroundTaskId) return null;
|
|
263
|
+
const command = input.tool_input?.command;
|
|
264
|
+
const bare = normalizeCheck(command);
|
|
265
|
+
const wrapped = bare === null ? checkFromWrapped(command) : null;
|
|
266
|
+
const check = bare ?? wrapped;
|
|
267
|
+
if (check === null) return null;
|
|
268
|
+
const dir = sessionStateDir(cwd, sessionId);
|
|
269
|
+
if (dir === null) return null;
|
|
270
|
+
const rcExit = takeCheckRc(dir);
|
|
271
|
+
// A wrapped check has no receipt until its own exit is on disk. The event status is the
|
|
272
|
+
// pipeline's or the later command's, so it is not a substitute.
|
|
273
|
+
if (wrapped !== null && rcExit === null) return null;
|
|
274
|
+
let exit;
|
|
275
|
+
let output;
|
|
276
|
+
if (wrapped !== null) {
|
|
277
|
+
exit = rcExit;
|
|
278
|
+
if (failed) {
|
|
279
|
+
if (input.is_interrupt === true) return null;
|
|
280
|
+
output = typeof input.error === "string" ? input.error : "";
|
|
281
|
+
} else {
|
|
282
|
+
const response = input.tool_response ?? {};
|
|
283
|
+
if (response.interrupted === true) return null;
|
|
284
|
+
output = `${response.stdout ?? ""}\0${response.stderr ?? ""}`;
|
|
285
|
+
}
|
|
286
|
+
} else if (failed) {
|
|
287
|
+
if (input.is_interrupt === true) return null;
|
|
288
|
+
output = typeof input.error === "string" ? input.error : "";
|
|
289
|
+
const hostLine = HOST_EXIT_LINE.exec(output);
|
|
290
|
+
exit = hostLine ? Number(hostLine[1]) : null;
|
|
291
|
+
} else {
|
|
292
|
+
const response = input.tool_response ?? {};
|
|
293
|
+
if (response.interrupted === true) return null;
|
|
294
|
+
exit = 0;
|
|
295
|
+
output = `${response.stdout ?? ""}\0${response.stderr ?? ""}`;
|
|
296
|
+
}
|
|
297
|
+
const receipt = { at: now.toISOString(), check, exit, outputSha256: sha256(String(output)), treeSha: treeShaOf(cwd), codeSha: codeShaOf(cwd) };
|
|
298
|
+
appendLine(join(dir, RECEIPTS_FILE), receipt);
|
|
299
|
+
return receipt;
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
const isDocPath = (root, path) => {
|
|
303
|
+
const rel = relative(root, resolve(root, path)).replaceAll("\\", "/");
|
|
304
|
+
return /\.(?:md|txt)$/iu.test(rel) || rel.startsWith("docs/");
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
/** Records `lastCodeEditAt` when an edit tool changed a path that is not `*.md`, `*.txt` or `docs/**`. */
|
|
308
|
+
export const recordCodeEdit = ({ cwd, sessionId, input, filePaths = [], now = new Date() }) => {
|
|
309
|
+
if (!EDIT_TOOLS.has(input?.tool_name)) return false;
|
|
310
|
+
const notebook = input.tool_input?.notebook_path;
|
|
311
|
+
const paths = typeof notebook === "string" ? [...filePaths, notebook] : filePaths;
|
|
312
|
+
const root = resolveProjectStateRoot(cwd);
|
|
313
|
+
if (!paths.some((path) => typeof path === "string" && !isDocPath(root, path))) return false;
|
|
314
|
+
const dir = sessionStateDir(cwd, sessionId);
|
|
315
|
+
if (dir === null) return false;
|
|
316
|
+
const existing = readEditsObject(dir);
|
|
317
|
+
const next = { ...existing, lastCodeEditAt: now.toISOString() };
|
|
318
|
+
writeEdits(dir, next);
|
|
319
|
+
return true;
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const readEditsObject = (dir) => {
|
|
323
|
+
try {
|
|
324
|
+
const parsed = JSON.parse(readFileSync(join(dir, EDITS_FILE), "utf8"));
|
|
325
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
326
|
+
} catch (error) {
|
|
327
|
+
if (error?.code === "ENOENT") return {};
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const writeEdits = (dir, record) => {
|
|
333
|
+
const path = join(dir, EDITS_FILE);
|
|
334
|
+
const staging = `${path}.${process.pid}.tmp`;
|
|
335
|
+
writeFileSync(staging, `${JSON.stringify(record)}\n`, { flag: STATE_WRITE_FLAG, mode: 0o600 });
|
|
336
|
+
renameSync(staging, path);
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
/** Stores baselineCodeSha the first time a gated discipline activates, when the fingerprint exists. */
|
|
340
|
+
export const recordBaselineCodeSha = ({ cwd, sessionId, skill }) => {
|
|
341
|
+
if (!GATED_SKILLS.has(skill)) return false;
|
|
342
|
+
const dir = sessionStateDir(cwd, sessionId);
|
|
343
|
+
if (dir === null) return false;
|
|
344
|
+
const existing = readEditsObject(dir);
|
|
345
|
+
if (typeof existing.baselineCodeSha === "string") return false;
|
|
346
|
+
const codeSha = codeShaOf(cwd);
|
|
347
|
+
if (typeof codeSha !== "string") return false;
|
|
348
|
+
writeEdits(dir, { ...existing, baselineCodeSha: codeSha });
|
|
349
|
+
return true;
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
/** The session's receipts (unparseable lines skipped) and its last code edit time (NaN when none). */
|
|
353
|
+
export const readReceiptState = (cwd, sessionId) => {
|
|
354
|
+
const dir = sessionStatePath(cwd, sessionId);
|
|
355
|
+
if (dir === null) return { receipts: [], lastCodeEditAt: Number.NaN, baselineCodeSha: null };
|
|
356
|
+
const read = (name) => {
|
|
357
|
+
try {
|
|
358
|
+
return readFileSync(join(dir, name), "utf8");
|
|
359
|
+
} catch (error) {
|
|
360
|
+
if (error?.code === "ENOENT") return "";
|
|
361
|
+
throw error;
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
const receipts = read(RECEIPTS_FILE).split("\n").flatMap((line) => {
|
|
365
|
+
try {
|
|
366
|
+
const record = JSON.parse(line);
|
|
367
|
+
return record && typeof record === "object" ? [record] : [];
|
|
368
|
+
} catch {
|
|
369
|
+
return [];
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
const edits = read(EDITS_FILE);
|
|
373
|
+
const parsed = edits ? JSON.parse(edits) : null;
|
|
374
|
+
return {
|
|
375
|
+
receipts,
|
|
376
|
+
lastCodeEditAt: parsed ? Date.parse(parsed.lastCodeEditAt) : Number.NaN,
|
|
377
|
+
baselineCodeSha: typeof parsed?.baselineCodeSha === "string" ? parsed.baselineCodeSha : null,
|
|
378
|
+
};
|
|
379
|
+
};
|
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
// The SessionStart nudge toward lit-adhd: when this folder has other Claude Code sessions from the
|
|
2
2
|
// last three days, say once a day that `lit adhd` briefs them all on one screen. It looks only at
|
|
3
3
|
// this folder's own transcript folder (no scan of other projects) and stats file times, never
|
|
4
|
-
// contents, so it stays cheap on every session start. A marker
|
|
5
|
-
//
|
|
4
|
+
// contents, so it stays cheap on every session start. A marker in the session's own folder
|
|
5
|
+
// (`.litclaude/sessions/<id>/adhd-suggested.json`; the shared `.litclaude/adhd/suggested.json` is still
|
|
6
|
+
// read) keeps it to one nudge per calendar day, and the shown-ledger keeps the same words from coming
|
|
6
7
|
// back within a week. A symlinked `.litclaude`, folder or marker (a cloned
|
|
7
8
|
// repository can carry one) is never followed: the nudge is then skipped, not written elsewhere.
|
|
8
9
|
import { lstatSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
|
|
9
10
|
import { join } from "node:path";
|
|
10
11
|
|
|
11
12
|
import { prepareStateDir, STATE_WRITE_FLAG } from "../project-state-root.mjs";
|
|
13
|
+
import { sessionStateDir } from "../session-state.mjs";
|
|
12
14
|
import { recordShown, wasShown } from "../shown-ledger.mjs";
|
|
13
15
|
import { projectSlug } from "./transcripts.mjs";
|
|
14
16
|
|
|
@@ -38,19 +40,28 @@ const recentOthers = (folder, sessionId, now) => {
|
|
|
38
40
|
|
|
39
41
|
/**
|
|
40
42
|
* The one-line suggestion, or null when there is nothing to suggest or it was already made today.
|
|
41
|
-
* Making it records today's date in
|
|
43
|
+
* Making it records today's date in the session's `adhd-suggested.json` (legacy: `.litclaude/adhd/suggested.json`).
|
|
42
44
|
*/
|
|
43
45
|
export const adhdSuggestion = ({ cwd, sessionId, configDir, stateRoot, now = Date.now() }) => {
|
|
44
46
|
const count = recentOthers(join(configDir, "projects", projectSlug(cwd)), sessionId, now);
|
|
45
47
|
if (count === 0) return null;
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
-
|
|
48
|
+
const legacyDir = join(stateRoot, ".litclaude", "adhd");
|
|
49
|
+
const legacyMarker = join(legacyDir, "suggested.json");
|
|
50
|
+
let sessionDir;
|
|
49
51
|
try {
|
|
50
|
-
|
|
51
|
-
if (JSON.parse(readFileSync(marker, "utf8")).day === dayOf(now)) return null;
|
|
52
|
+
sessionDir = sessionStateDir(stateRoot, sessionId);
|
|
52
53
|
} catch {
|
|
53
|
-
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (sessionDir === null && !prepareStateDir(legacyDir)) return null;
|
|
57
|
+
const marker = sessionDir === null ? legacyMarker : join(sessionDir, "adhd-suggested.json");
|
|
58
|
+
for (const path of new Set([marker, legacyMarker])) {
|
|
59
|
+
try {
|
|
60
|
+
if (lstatSync(path).isSymbolicLink()) return null;
|
|
61
|
+
if (JSON.parse(readFileSync(path, "utf8")).day === dayOf(now)) return null;
|
|
62
|
+
} catch {
|
|
63
|
+
// No marker yet, or an unreadable one: suggest and rewrite it.
|
|
64
|
+
}
|
|
54
65
|
}
|
|
55
66
|
const text = `${count} other recent ${count === 1 ? "session" : "sessions"} here · type \`lit adhd\` for a one-screen brief of where each stands`;
|
|
56
67
|
// The same words were already shown here within the week: a new day alone is no reason to repeat them.
|