@lastweek-work/cli 0.0.0-stage → 0.1.1
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 +87 -2
- package/dist/bursts.js +47 -0
- package/dist/cli.js +329 -0
- package/dist/config.js +45 -0
- package/dist/connect.js +285 -0
- package/dist/git.js +184 -0
- package/dist/hook.js +59 -0
- package/dist/ingest.js +22 -0
- package/dist/mcp.js +61 -0
- package/dist/paths.js +6 -0
- package/dist/schedule.js +79 -0
- package/dist/spool.js +88 -0
- package/dist/state.js +27 -0
- package/dist/tasks.js +39 -0
- package/package.json +50 -4
package/dist/connect.js
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
// `lastweek connect <CODE>`: everything a non-technical user would otherwise do by hand, in one command.
|
|
7
|
+
// Pair with the web app, find project folders and commit emails, write the config, start the background scan,
|
|
8
|
+
// connect Claude Code (asks first, backs up its settings), run the first scan. Pure helpers are exported for tests.
|
|
9
|
+
/** Folders people usually keep code in, relative to the home directory. */
|
|
10
|
+
export const REPO_FOLDER_CANDIDATES = [
|
|
11
|
+
"Work",
|
|
12
|
+
"work",
|
|
13
|
+
"Projects",
|
|
14
|
+
"projects",
|
|
15
|
+
"Code",
|
|
16
|
+
"code",
|
|
17
|
+
"Developer",
|
|
18
|
+
"dev",
|
|
19
|
+
"src",
|
|
20
|
+
"repos",
|
|
21
|
+
"git",
|
|
22
|
+
"GitHub",
|
|
23
|
+
"Sites",
|
|
24
|
+
"Documents/GitHub",
|
|
25
|
+
"Documents/Projects",
|
|
26
|
+
"Documents/Code",
|
|
27
|
+
];
|
|
28
|
+
const isDir = (p) => {
|
|
29
|
+
try {
|
|
30
|
+
return statSync(p).isDirectory();
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/** Candidate folders that exist and contain at least one Git repository, as "~/…" paths. */
|
|
37
|
+
export function detectRepoRoots(home, findRepos) {
|
|
38
|
+
const roots = [];
|
|
39
|
+
for (const rel of REPO_FOLDER_CANDIDATES) {
|
|
40
|
+
const abs = join(home, rel);
|
|
41
|
+
if (!isDir(abs))
|
|
42
|
+
continue;
|
|
43
|
+
// Case-insensitive file systems list "Work" and "work" as the same folder.
|
|
44
|
+
if (roots.some((r) => r.toLowerCase() === `~/${rel}`.toLowerCase()))
|
|
45
|
+
continue;
|
|
46
|
+
if (findRepos([abs]).length > 0)
|
|
47
|
+
roots.push(`~/${rel}`);
|
|
48
|
+
}
|
|
49
|
+
return roots;
|
|
50
|
+
}
|
|
51
|
+
/** The global Git email plus every repo-local one, lower-cased and de-duplicated. */
|
|
52
|
+
export function detectAuthorEmails(repos, gitEmail) {
|
|
53
|
+
const out = new Set();
|
|
54
|
+
const add = (e) => {
|
|
55
|
+
const v = e?.trim().toLowerCase();
|
|
56
|
+
if (v && /^[^\s@]+@[^\s@]+$/.test(v))
|
|
57
|
+
out.add(v);
|
|
58
|
+
};
|
|
59
|
+
add(gitEmail());
|
|
60
|
+
for (const r of repos)
|
|
61
|
+
add(gitEmail(r));
|
|
62
|
+
return [...out];
|
|
63
|
+
}
|
|
64
|
+
export const HOOK_COMMAND = "lastweek log 2>/dev/null || true";
|
|
65
|
+
/** Exactly the hook command earlier versions wrote. */
|
|
66
|
+
const LEGACY_HOOK = /^\s*rewind log(\s+2>\/dev\/null)?(\s*\|\|\s*true)?\s*$/;
|
|
67
|
+
const EDIT_MATCHER = "Edit|Write|MultiEdit|NotebookEdit";
|
|
68
|
+
/** Adds lastweek's hooks to Claude Code settings without touching anything else; idempotent. */
|
|
69
|
+
export function mergeClaudeHooks(settings) {
|
|
70
|
+
const next = structuredClone(settings);
|
|
71
|
+
const hooks = next.hooks ?? {};
|
|
72
|
+
next.hooks = hooks;
|
|
73
|
+
let changed = false;
|
|
74
|
+
// Our own hooks from before the rename are rewritten to the new command; a hook the user wrote around
|
|
75
|
+
// `rewind log` is left alone (the `rewind` alias keeps it working). Afterwards each event logs at most once.
|
|
76
|
+
for (const [event, entries] of Object.entries(hooks)) {
|
|
77
|
+
if (!entries)
|
|
78
|
+
continue;
|
|
79
|
+
let kept = false;
|
|
80
|
+
const next = entries
|
|
81
|
+
.map((e) => {
|
|
82
|
+
const before = e.hooks ?? [];
|
|
83
|
+
const after = before
|
|
84
|
+
.map((h) => (h.command && LEGACY_HOOK.test(h.command) ? { ...h, command: HOOK_COMMAND } : h))
|
|
85
|
+
.filter((h) => {
|
|
86
|
+
if (h.command !== HOOK_COMMAND)
|
|
87
|
+
return true;
|
|
88
|
+
if (kept)
|
|
89
|
+
return false;
|
|
90
|
+
kept = true;
|
|
91
|
+
return true;
|
|
92
|
+
});
|
|
93
|
+
if (JSON.stringify(after) === JSON.stringify(before))
|
|
94
|
+
return e;
|
|
95
|
+
changed = true;
|
|
96
|
+
return after.length ? { ...e, hooks: after } : null;
|
|
97
|
+
})
|
|
98
|
+
.filter((e) => e !== null);
|
|
99
|
+
hooks[event] = next;
|
|
100
|
+
}
|
|
101
|
+
const has = (event) => (hooks[event] ?? []).some((e) => (e.hooks ?? []).some((h) => /\b(lastweek|rewind) log\b/.test(h.command ?? "")));
|
|
102
|
+
const add = (event, entry) => {
|
|
103
|
+
if (has(event))
|
|
104
|
+
return;
|
|
105
|
+
hooks[event] = [...(hooks[event] ?? []), entry];
|
|
106
|
+
changed = true;
|
|
107
|
+
};
|
|
108
|
+
add("PostToolUse", { matcher: EDIT_MATCHER, hooks: [{ type: "command", command: HOOK_COMMAND }] });
|
|
109
|
+
add("UserPromptSubmit", { hooks: [{ type: "command", command: HOOK_COMMAND }] });
|
|
110
|
+
return { settings: next, changed };
|
|
111
|
+
}
|
|
112
|
+
/** New pairing replaces the token; folders and emails the user already has are kept and extended. */
|
|
113
|
+
export function mergeConfig(existing, update) {
|
|
114
|
+
const union = (a = [], b = []) => [...new Set([...a, ...b])];
|
|
115
|
+
return {
|
|
116
|
+
...existing,
|
|
117
|
+
...(update.ingestUrl ? { ingestUrl: update.ingestUrl } : {}),
|
|
118
|
+
...(update.deviceToken ? { deviceToken: update.deviceToken } : {}),
|
|
119
|
+
repoRoots: union(existing?.repoRoots, update.repoRoots),
|
|
120
|
+
authorEmails: union(existing?.authorEmails, update.authorEmails),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/** A pairing code as typed by people: any case, with or without the dash. */
|
|
124
|
+
export const normalizeCode = (code) => code.toUpperCase().replace(/[^A-Z0-9]/g, "");
|
|
125
|
+
export async function pair(server, code, name, fetchImpl = fetch) {
|
|
126
|
+
const res = await fetchImpl(`${server.replace(/\/$/, "")}/functions/v1/pair`, {
|
|
127
|
+
method: "POST",
|
|
128
|
+
headers: { "content-type": "application/json" },
|
|
129
|
+
body: JSON.stringify({ code: normalizeCode(code), name }),
|
|
130
|
+
});
|
|
131
|
+
const marker = res.ok ? null : ((await res.json().catch(() => ({}))).code ?? null);
|
|
132
|
+
if (marker === "invalid_code")
|
|
133
|
+
return { ok: false, reason: "code" };
|
|
134
|
+
if (marker === "rate_limited")
|
|
135
|
+
return { ok: false, reason: "limited" };
|
|
136
|
+
// Anything else (also a bare 404 from a wrong address) is a server/address problem, not a bad code.
|
|
137
|
+
if (!res.ok)
|
|
138
|
+
return { ok: false, reason: "server", status: res.status };
|
|
139
|
+
const body = (await res.json());
|
|
140
|
+
// The ingest address comes from the server address the user was given (the function's own view of its URL can
|
|
141
|
+
// be an internal hostname, e.g. in the local stack).
|
|
142
|
+
return {
|
|
143
|
+
ok: true,
|
|
144
|
+
deviceToken: body.deviceToken,
|
|
145
|
+
ingestUrl: `${server.replace(/\/$/, "")}/functions/v1/ingest`,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// ---------- messages (German if the system speaks German) ----------
|
|
149
|
+
const de = (process.env.LANG ?? Intl.DateTimeFormat().resolvedOptions().locale).toLowerCase().startsWith("de");
|
|
150
|
+
export const say = {
|
|
151
|
+
pairing: de ? "Verbinde mit lastweek …" : "Connecting to lastweek …",
|
|
152
|
+
paired: de ? "✓ Gerät verbunden" : "✓ Device connected",
|
|
153
|
+
badCode: de
|
|
154
|
+
? "✗ Der Code ist unbekannt, schon benutzt oder abgelaufen. Erzeuge im Browser einen neuen und versuch es noch einmal."
|
|
155
|
+
: "✗ The code is unknown, already used or expired. Create a new one in the browser and try again.",
|
|
156
|
+
limited: de
|
|
157
|
+
? "✗ Zu viele falsche Codes in kurzer Zeit. Bitte warte zehn Minuten und erzeuge dann einen neuen Code."
|
|
158
|
+
: "✗ Too many wrong codes in a short time. Please wait ten minutes, then create a new code.",
|
|
159
|
+
serverError: (s) => de
|
|
160
|
+
? `✗ Der Server antwortet nicht wie erwartet (${s ?? "?"}). Stimmt die Adresse hinter --server? Sonst gleich noch einmal versuchen.`
|
|
161
|
+
: `✗ The server didn't answer as expected (${s ?? "?"}). Is the address after --server right? Otherwise try again shortly.`,
|
|
162
|
+
needCode: de
|
|
163
|
+
? "Bitte den Befehl aus dem Browser verwenden: lastweek connect <CODE> --server <adresse>"
|
|
164
|
+
: "Please use the command from the browser: lastweek connect <CODE> --server <address>",
|
|
165
|
+
folders: (list, n) => de
|
|
166
|
+
? `✓ Projektordner: ${list.join(", ")} (${n} ${n === 1 ? "Repository" : "Repositories"})`
|
|
167
|
+
: `✓ Project folders: ${list.join(", ")} (${n} ${n === 1 ? "repository" : "repositories"})`,
|
|
168
|
+
noFolders: de
|
|
169
|
+
? "⚠ Keine Git-Projekte gefunden. Ordner ergänzen mit: lastweek connect --repos <Ordner>"
|
|
170
|
+
: "⚠ No Git projects found. Add a folder with: lastweek connect --repos <folder>",
|
|
171
|
+
emails: (list) => (de ? `✓ Commit-E-Mail: ${list.join(", ")}` : `✓ Commit email: ${list.join(", ")}`),
|
|
172
|
+
noEmails: de
|
|
173
|
+
? "⚠ Keine Git-E-Mail gefunden. Einrichten mit: git config --global user.email du@beispiel.de"
|
|
174
|
+
: "⚠ No Git email found. Set one with: git config --global user.email you@example.com",
|
|
175
|
+
saved: (p) => (de ? `✓ Einstellungen gespeichert (${p})` : `✓ Settings saved (${p})`),
|
|
176
|
+
schedule: de
|
|
177
|
+
? "✓ Läuft ab jetzt im Hintergrund, alle 30 Minuten"
|
|
178
|
+
: "✓ Runs in the background from now on, every 30 minutes",
|
|
179
|
+
scheduleMacOnly: de
|
|
180
|
+
? "ℹ Der Hintergrund-Scan gibt es bisher nur auf macOS. Hier bei Bedarf: lastweek scan"
|
|
181
|
+
: "ℹ The background scan is macOS-only for now. Run it here when needed: lastweek scan",
|
|
182
|
+
scheduleTemp: de
|
|
183
|
+
? "ℹ Hintergrund-Scan übersprungen: lastweek läuft nur temporär (npx). Dauerhaft: npm install -g @lastweek-work/cli"
|
|
184
|
+
: "ℹ Background scan skipped: lastweek runs temporarily (npx). Install it for good: npm install -g @lastweek-work/cli",
|
|
185
|
+
scheduleFailed: (reason) => de
|
|
186
|
+
? `⚠ Hintergrund-Scan konnte nicht eingerichtet werden (${reason}). Später: lastweek schedule install`
|
|
187
|
+
: `⚠ Couldn't set up the background scan (${reason}). Later: lastweek schedule install`,
|
|
188
|
+
claudeUnreadable: (p) => de
|
|
189
|
+
? `⚠ ${p} ließ sich nicht lesen; nichts geändert. Nach dem Prüfen der Datei: lastweek connect --agents`
|
|
190
|
+
: `⚠ Couldn't read ${p}; nothing changed. After checking the file: lastweek connect --agents`,
|
|
191
|
+
claudeTemp: de
|
|
192
|
+
? "ℹ Claude Code übersprungen: lastweek läuft nur temporär (npx). Dauerhaft installieren: npm install -g @lastweek-work/cli"
|
|
193
|
+
: "ℹ Claude Code skipped: lastweek runs temporarily (npx). Install it for good: npm install -g @lastweek-work/cli",
|
|
194
|
+
claudeAsk: de
|
|
195
|
+
? "Claude Code gefunden. Soll lastweek die Arbeit deiner Agenten mitzählen? (Hook + MCP, Sicherung wird angelegt) [J/n] "
|
|
196
|
+
: "Claude Code found. Should lastweek count your agents' work? (hook + MCP, a backup is made) [Y/n] ",
|
|
197
|
+
claudeDone: (mcp) => de
|
|
198
|
+
? `✓ Claude Code verbunden (Hook${mcp ? " + MCP" : ""})`
|
|
199
|
+
: `✓ Claude Code connected (hook${mcp ? " + MCP" : ""})`,
|
|
200
|
+
claudeAlready: de ? "✓ Claude Code war schon verbunden" : "✓ Claude Code was already connected",
|
|
201
|
+
claudeSkipped: de
|
|
202
|
+
? "– Claude Code übersprungen. Später: lastweek connect --agents"
|
|
203
|
+
: "– Claude Code skipped. Later: lastweek connect --agents",
|
|
204
|
+
scanning: de ? "Erster Scan der letzten 8 Tage …" : "First scan of the last 8 days …",
|
|
205
|
+
scanFailed: (reason) => de
|
|
206
|
+
? `⚠ Der erste Scan hat nicht geklappt (${reason}). Er läuft automatisch erneut; sofort geht es mit: lastweek scan`
|
|
207
|
+
: `⚠ The first scan didn't work (${reason}). It runs again automatically; to retry now: lastweek scan`,
|
|
208
|
+
scanned: (events, repos) => de
|
|
209
|
+
? `✓ ${events} Ereignisse aus ${repos} ${repos === 1 ? "Repository" : "Repositories"} übertragen`
|
|
210
|
+
: `✓ ${events} events from ${repos} ${repos === 1 ? "repository" : "repositories"} sent`,
|
|
211
|
+
done: de ? "Fertig! Zurück zum Browser, dort geht es weiter." : "Done! Back to the browser to continue.",
|
|
212
|
+
};
|
|
213
|
+
// ---------- side effects ----------
|
|
214
|
+
export function gitEmail(cwd) {
|
|
215
|
+
try {
|
|
216
|
+
const args = cwd ? ["-C", cwd, "config", "user.email"] : ["config", "--global", "user.email"];
|
|
217
|
+
return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
export function writeConfig(path, cfg) {
|
|
224
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
225
|
+
writeFileSync(path, `${JSON.stringify(cfg, null, 2)}\n`, { mode: 0o600 });
|
|
226
|
+
chmodSync(path, 0o600); // the file holds the device token
|
|
227
|
+
}
|
|
228
|
+
export function readJson(path) {
|
|
229
|
+
try {
|
|
230
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Claude Code: hooks in ~/.claude/settings.json and the MCP server via the `claude` CLI. A settings file that exists
|
|
238
|
+
* but can't be parsed is never touched; the first backup (.bak-lastweek) is never overwritten, later ones get a stamp.
|
|
239
|
+
*/
|
|
240
|
+
export function connectClaude(home = homedir()) {
|
|
241
|
+
const path = join(home, ".claude", "settings.json");
|
|
242
|
+
const current = existsSync(path) ? readJson(path) : {};
|
|
243
|
+
if (current === null || typeof current !== "object" || Array.isArray(current)) {
|
|
244
|
+
return { changed: false, mcp: false, unreadable: path };
|
|
245
|
+
}
|
|
246
|
+
const { settings, changed } = mergeClaudeHooks(current);
|
|
247
|
+
if (changed) {
|
|
248
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
249
|
+
if (existsSync(path)) {
|
|
250
|
+
const backup = existsSync(`${path}.bak-lastweek`) ? `${path}.bak-lastweek-${Date.now()}` : `${path}.bak-lastweek`;
|
|
251
|
+
copyFileSync(path, backup);
|
|
252
|
+
}
|
|
253
|
+
writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`);
|
|
254
|
+
}
|
|
255
|
+
let mcp = false;
|
|
256
|
+
try {
|
|
257
|
+
// The server's name before the rename; two registrations would give every session duplicate tools.
|
|
258
|
+
execFileSync("claude", ["mcp", "remove", "--scope", "user", "rewind"], { stdio: "pipe" });
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
// not registered, or no `claude` CLI
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
execFileSync("claude", ["mcp", "add", "--scope", "user", "lastweek", "--", "lastweek", "mcp"], { stdio: "pipe" });
|
|
265
|
+
mcp = true;
|
|
266
|
+
}
|
|
267
|
+
catch (e) {
|
|
268
|
+
// Already registered counts as done; no `claude` CLI means hooks only.
|
|
269
|
+
mcp = /already exists/i.test(String(e.stderr ?? ""));
|
|
270
|
+
}
|
|
271
|
+
return { changed, mcp };
|
|
272
|
+
}
|
|
273
|
+
export const claudeInstalled = (home = homedir()) => isDir(join(home, ".claude"));
|
|
274
|
+
export async function ask(question) {
|
|
275
|
+
if (!process.stdin.isTTY)
|
|
276
|
+
return false;
|
|
277
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
278
|
+
try {
|
|
279
|
+
const a = (await rl.question(question)).trim().toLowerCase();
|
|
280
|
+
return a === "" || a.startsWith("j") || a.startsWith("y");
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
rl.close();
|
|
284
|
+
}
|
|
285
|
+
}
|
package/dist/git.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
|
+
function git(repo, args) {
|
|
5
|
+
try {
|
|
6
|
+
return execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return "";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Main worktree path for any worktree of a repo (worktrees share one common .git dir). */
|
|
13
|
+
export function mainRepoPath(repo) {
|
|
14
|
+
const common = git(repo, ["rev-parse", "--path-format=absolute", "--git-common-dir"]).trim();
|
|
15
|
+
if (common && basename(common) === ".git")
|
|
16
|
+
return dirname(common);
|
|
17
|
+
// Submodules and unusual layouts keep their git dir elsewhere; use the checkout itself.
|
|
18
|
+
return git(repo, ["rev-parse", "--show-toplevel"]).trim() || repo;
|
|
19
|
+
}
|
|
20
|
+
/** Find git repos up to `depth` below each root. Worktrees are discovered via `git worktree list`. */
|
|
21
|
+
export function findRepos(roots, depth = 3, warn = console.warn) {
|
|
22
|
+
const out = new Set();
|
|
23
|
+
// Real paths, so a repo reached via a symlink (e.g. /tmp → /private/tmp, a linked folder) or listed again as a
|
|
24
|
+
// worktree is scanned once.
|
|
25
|
+
const real = (p) => {
|
|
26
|
+
try {
|
|
27
|
+
return realpathSync(p);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return p;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const walk = (dir, d) => {
|
|
34
|
+
if (existsSync(join(dir, ".git"))) {
|
|
35
|
+
out.add(real(dir));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (d === 0)
|
|
39
|
+
return;
|
|
40
|
+
let names;
|
|
41
|
+
try {
|
|
42
|
+
names = readdirSync(dir);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
for (const name of names) {
|
|
48
|
+
if (name === "node_modules" || name.startsWith("."))
|
|
49
|
+
continue;
|
|
50
|
+
const p = join(dir, name);
|
|
51
|
+
try {
|
|
52
|
+
if (statSync(p).isDirectory())
|
|
53
|
+
walk(p, d - 1);
|
|
54
|
+
}
|
|
55
|
+
catch { }
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
for (const r of roots) {
|
|
59
|
+
if (existsSync(r))
|
|
60
|
+
walk(r, depth);
|
|
61
|
+
else
|
|
62
|
+
warn(`repo root not found, skipped: ${r}`);
|
|
63
|
+
}
|
|
64
|
+
for (const repo of [...out]) {
|
|
65
|
+
for (const l of git(repo, ["worktree", "list", "--porcelain"]).split("\n")) {
|
|
66
|
+
if (l.startsWith("worktree "))
|
|
67
|
+
out.add(real(l.slice(9).trim()));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return [...out];
|
|
71
|
+
}
|
|
72
|
+
/** Commit addresses of coding agents. Their commits count only when made or merged on this machine (see below). */
|
|
73
|
+
export const DEFAULT_AGENT_EMAILS = ["noreply@anthropic.com", "cursoragent@cursor.com"];
|
|
74
|
+
/**
|
|
75
|
+
* Commits that entered this worktree through its own reflog: created here (`commit…` entries) or brought in by a
|
|
76
|
+
* local merge (`merge <branch>: …` → everything between the previous HEAD and the merge). This is how agent commits
|
|
77
|
+
* made in temporary worktrees reach the main checkout, and it is proof they happened on this machine.
|
|
78
|
+
*/
|
|
79
|
+
function localCommits(worktree, reflog, sinceMs) {
|
|
80
|
+
const out = new Set();
|
|
81
|
+
for (let i = 0; i < reflog.length; i++) {
|
|
82
|
+
const { sha, selector, subject } = reflog[i];
|
|
83
|
+
const at = Date.parse(selector.match(/\{(.+)\}/)?.[1] ?? "");
|
|
84
|
+
if (Number.isNaN(at) || at < sinceMs)
|
|
85
|
+
continue;
|
|
86
|
+
if (subject.startsWith("commit"))
|
|
87
|
+
out.add(sha);
|
|
88
|
+
const prev = reflog[i + 1]?.sha; // reflog is newest first
|
|
89
|
+
if (subject.startsWith("merge ") && prev && prev !== sha) {
|
|
90
|
+
for (const c of git(worktree, ["rev-list", `${prev}..${sha}`]).split("\n"))
|
|
91
|
+
if (c)
|
|
92
|
+
out.add(c);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
const emailsIn = (trailers) => [...trailers.matchAll(/<([^>]+)>/g)].map((m) => m[1].toLowerCase());
|
|
98
|
+
/**
|
|
99
|
+
* Commits that are the user's evidence since `since`, plus this worktree's HEAD reflog (catches amends, rebases,
|
|
100
|
+
* checkouts). A commit counts when the user is its author, committer or a `Co-authored-by`, or when a coding agent
|
|
101
|
+
* (agentEmails) authored it and it was made or merged on this machine — so a colleague's agent commits in a shared
|
|
102
|
+
* repo never count. `repo` on every event is the main worktree path so all worktrees of a repo map to one project;
|
|
103
|
+
* commit keys use it too, so a commit seen from several worktrees dedupes to one event.
|
|
104
|
+
*/
|
|
105
|
+
export function scanRepo(worktree, authorEmails, since, stats = { commits: 0, matched: 0 }, agentEmails = DEFAULT_AGENT_EMAILS) {
|
|
106
|
+
const repo = mainRepoPath(worktree);
|
|
107
|
+
const sinceMs = Date.parse(since);
|
|
108
|
+
const authors = new Set(authorEmails.map((e) => e.toLowerCase()));
|
|
109
|
+
const agents = new Set(agentEmails.map((e) => e.toLowerCase()));
|
|
110
|
+
const events = [];
|
|
111
|
+
const reflog = git(worktree, ["reflog", "--date=iso-strict", "--format=%H%x1f%gd%x1f%gs"])
|
|
112
|
+
.split("\n")
|
|
113
|
+
.filter(Boolean)
|
|
114
|
+
.map((l) => {
|
|
115
|
+
const [sha, selector, subject] = l.split("\x1f");
|
|
116
|
+
return { sha, selector, subject: subject ?? "" };
|
|
117
|
+
});
|
|
118
|
+
let local = null; // computed lazily: only needed when an agent commit shows up
|
|
119
|
+
const fmt = "%H%x1f%aI%x1f%ae%x1f%ce%x1f%(trailers:key=Co-authored-by,valueonly,separator=%x1e)%x1f%s";
|
|
120
|
+
for (const line of git(worktree, ["log", "--all", `--since=${since}`, `--format=${fmt}`]).split("\n")) {
|
|
121
|
+
if (!line)
|
|
122
|
+
continue;
|
|
123
|
+
const [sha, date, rawAuthor, rawCommitter, trailers, subject] = line.split("\x1f");
|
|
124
|
+
const author = rawAuthor.toLowerCase();
|
|
125
|
+
stats.commits++;
|
|
126
|
+
let via = null;
|
|
127
|
+
if (authors.has(author))
|
|
128
|
+
via = "author";
|
|
129
|
+
else if (authors.has(rawCommitter.toLowerCase()))
|
|
130
|
+
via = "committer";
|
|
131
|
+
else if (emailsIn(trailers ?? "").some((e) => authors.has(e)))
|
|
132
|
+
via = "co-author";
|
|
133
|
+
else if (agents.has(author)) {
|
|
134
|
+
local ??= localCommits(worktree, reflog, sinceMs);
|
|
135
|
+
if (local.has(sha))
|
|
136
|
+
via = "agent-local";
|
|
137
|
+
}
|
|
138
|
+
if (!via)
|
|
139
|
+
continue;
|
|
140
|
+
stats.matched++;
|
|
141
|
+
events.push({
|
|
142
|
+
source: "git",
|
|
143
|
+
occurred_at: date,
|
|
144
|
+
repo,
|
|
145
|
+
ref: sha,
|
|
146
|
+
summary: subject,
|
|
147
|
+
payload: { kind: via === "agent-local" ? "agent-commit" : "commit", email: rawAuthor, via },
|
|
148
|
+
dedupe_key: `git:${repo}:${sha}`,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
// reflog: HEAD movements are timestamped locally and survive history rewrites. Per worktree.
|
|
152
|
+
for (const { sha, selector, subject } of reflog) {
|
|
153
|
+
const at = selector.match(/\{(.+)\}/)?.[1];
|
|
154
|
+
if (!at || Date.parse(at) < sinceMs)
|
|
155
|
+
continue;
|
|
156
|
+
events.push({
|
|
157
|
+
source: "git",
|
|
158
|
+
occurred_at: at,
|
|
159
|
+
repo,
|
|
160
|
+
ref: sha,
|
|
161
|
+
summary: subject,
|
|
162
|
+
payload: { kind: "reflog", worktree },
|
|
163
|
+
dedupe_key: `reflog:${worktree}:${selector}`,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return events;
|
|
167
|
+
}
|
|
168
|
+
/** Scan many repos/worktrees; events are unique by dedupe_key. Pass `stats` to learn how many commits matched. */
|
|
169
|
+
export function scanRepos(worktrees, authorEmails, since, stats = { commits: 0, matched: 0 }, agentEmails = DEFAULT_AGENT_EMAILS) {
|
|
170
|
+
const byKey = new Map();
|
|
171
|
+
for (const wt of worktrees) {
|
|
172
|
+
for (const e of scanRepo(wt, authorEmails, since, stats, agentEmails)) {
|
|
173
|
+
if (!byKey.has(e.dedupe_key))
|
|
174
|
+
byKey.set(e.dedupe_key, e);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return [...byKey.values()];
|
|
178
|
+
}
|
|
179
|
+
/** A config that matches none of the commits it sees is almost always a wrong authorEmails. */
|
|
180
|
+
export function authorWarning(stats) {
|
|
181
|
+
if (stats.commits === 0 || stats.matched > 0)
|
|
182
|
+
return null;
|
|
183
|
+
return `warning: ${stats.commits} commits in range, none by your authorEmails — check them against \`git log --format=%ae\`.`;
|
|
184
|
+
}
|
package/dist/hook.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coalescing of Claude Code hook calls. Calls of one session that arrive within GAP of each other extend one burst;
|
|
3
|
+
* a burst becomes a single interval event [first call, last call]. Pure: time and state are passed in.
|
|
4
|
+
*/
|
|
5
|
+
export const GAP_MS = 60_000;
|
|
6
|
+
/** Long continuous bursts are cut so events reach the server regularly. */
|
|
7
|
+
export const MAX_BURST_MS = 15 * 60_000;
|
|
8
|
+
const MAX_FILES = 10;
|
|
9
|
+
export function callFromInput(input, repo) {
|
|
10
|
+
const raw = input.tool_input?.file_path ?? input.tool_input?.notebook_path ?? input.tool_input?.path;
|
|
11
|
+
let file = typeof raw === "string" ? raw : null;
|
|
12
|
+
if (file && repo && file.startsWith(`${repo}/`))
|
|
13
|
+
file = file.slice(repo.length + 1);
|
|
14
|
+
return {
|
|
15
|
+
session: typeof input.session_id === "string" && input.session_id ? input.session_id : "unknown",
|
|
16
|
+
repo,
|
|
17
|
+
label: input.tool_name ?? input.hook_event_name ?? "unknown",
|
|
18
|
+
file,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** Folds one call into the session's burst. Returns the burst to keep and any finished burst to emit. */
|
|
22
|
+
export function applyCall(current, call, now) {
|
|
23
|
+
const continues = current !== null &&
|
|
24
|
+
current.repo === call.repo &&
|
|
25
|
+
now - current.last <= GAP_MS &&
|
|
26
|
+
now - current.start < MAX_BURST_MS &&
|
|
27
|
+
now >= current.last;
|
|
28
|
+
const base = continues
|
|
29
|
+
? current
|
|
30
|
+
: { session: call.session, repo: call.repo, start: now, last: now, count: 0, tools: {}, files: [] };
|
|
31
|
+
const burst = {
|
|
32
|
+
...base,
|
|
33
|
+
last: now,
|
|
34
|
+
count: base.count + 1,
|
|
35
|
+
tools: { ...base.tools, [call.label]: (base.tools[call.label] ?? 0) + 1 },
|
|
36
|
+
files: call.file && !base.files.includes(call.file) && base.files.length < MAX_FILES
|
|
37
|
+
? [...base.files, call.file]
|
|
38
|
+
: base.files,
|
|
39
|
+
};
|
|
40
|
+
return { burst, done: continues ? null : current };
|
|
41
|
+
}
|
|
42
|
+
/** A burst nobody has extended for longer than GAP is finished. */
|
|
43
|
+
export const isIdle = (b, now) => now - b.last > GAP_MS;
|
|
44
|
+
export function burstToEvent(b, agent = "claude-code") {
|
|
45
|
+
const start = new Date(b.start).toISOString();
|
|
46
|
+
const tools = Object.entries(b.tools)
|
|
47
|
+
.sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]))
|
|
48
|
+
.map(([t, n]) => `${t} ${n}`)
|
|
49
|
+
.join(", ");
|
|
50
|
+
return {
|
|
51
|
+
source: "mcp",
|
|
52
|
+
occurred_at: start,
|
|
53
|
+
ended_at: b.last > b.start ? new Date(b.last).toISOString() : undefined,
|
|
54
|
+
repo: b.repo ?? undefined,
|
|
55
|
+
summary: `Claude Code: ${b.count} ${b.count === 1 ? "Aktion" : "Aktionen"} (${tools})${b.files.length ? ` · ${b.files.length} ${b.files.length === 1 ? "Datei" : "Dateien"}` : ""}`,
|
|
56
|
+
payload: { kind: "hook", agent, session: b.session, count: b.count, tools: b.tools, files: b.files },
|
|
57
|
+
dedupe_key: `hook:${b.session}:${start}`,
|
|
58
|
+
};
|
|
59
|
+
}
|
package/dist/ingest.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const CHUNK_SIZE = 500; // matches the ingest function's per-request limit
|
|
2
|
+
/** Posts events in chunks. Throws on the first failed chunk; earlier chunks stay ingested (dedupe makes retries safe). */
|
|
3
|
+
export async function ingest(cfg, events) {
|
|
4
|
+
const total = { inserted: 0, duplicates: 0 };
|
|
5
|
+
if (events.length === 0)
|
|
6
|
+
return total;
|
|
7
|
+
if (!cfg.ingestUrl || !cfg.deviceToken)
|
|
8
|
+
throw new Error("config needs ingestUrl and deviceToken to send events");
|
|
9
|
+
for (let i = 0; i < events.length; i += CHUNK_SIZE) {
|
|
10
|
+
const res = await fetch(cfg.ingestUrl, {
|
|
11
|
+
method: "POST",
|
|
12
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${cfg.deviceToken}` },
|
|
13
|
+
body: JSON.stringify({ events: events.slice(i, i + CHUNK_SIZE) }),
|
|
14
|
+
});
|
|
15
|
+
if (!res.ok)
|
|
16
|
+
throw new Error(`ingest failed: ${res.status} ${await res.text()}`);
|
|
17
|
+
const r = (await res.json());
|
|
18
|
+
total.inserted += r.inserted;
|
|
19
|
+
total.duplicates += r.duplicates;
|
|
20
|
+
}
|
|
21
|
+
return total;
|
|
22
|
+
}
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { loadConfig } from "./config.js";
|
|
5
|
+
import { mainRepoPath } from "./git.js";
|
|
6
|
+
import { ingest } from "./ingest.js";
|
|
7
|
+
import { appendSpool, flushSpool } from "./spool.js";
|
|
8
|
+
import { endTask, startTask } from "./tasks.js";
|
|
9
|
+
/**
|
|
10
|
+
* `lastweek mcp` — stdio MCP server. Every event is spooled first, then flushed; a failed flush keeps it for the next
|
|
11
|
+
* scan or hook. Tools only record time and a one-line outcome; they never compute hours.
|
|
12
|
+
*/
|
|
13
|
+
export async function runMcp() {
|
|
14
|
+
const cfg = loadConfig();
|
|
15
|
+
const agent = process.env.LASTWEEK_AGENT_NAME ?? process.env.REWIND_AGENT_NAME ?? "unknown";
|
|
16
|
+
const server = new McpServer({ name: "lastweek", version: "0.1.0" });
|
|
17
|
+
const repoOf = (repo) => (repo ? mainRepoPath(repo) : undefined);
|
|
18
|
+
const flush = async () => {
|
|
19
|
+
const r = await flushSpool((events) => ingest(cfg, events));
|
|
20
|
+
return r.failed ? " (offline — kept locally, sent later)" : "";
|
|
21
|
+
};
|
|
22
|
+
server.tool("log_activity", "Record what was just done, with a timestamp. Call after completing a meaningful unit of work.", {
|
|
23
|
+
summary: z.string().describe("One line, outcome not implementation. The user's language."),
|
|
24
|
+
repo: z.string().optional().describe("Absolute repo path if known"),
|
|
25
|
+
started_at: z.string().datetime({ offset: true }).optional(),
|
|
26
|
+
ended_at: z.string().datetime({ offset: true }).optional(),
|
|
27
|
+
}, async ({ summary, repo, started_at, ended_at }) => {
|
|
28
|
+
const at = ended_at ?? new Date().toISOString();
|
|
29
|
+
const r = repoOf(repo);
|
|
30
|
+
appendSpool([
|
|
31
|
+
{
|
|
32
|
+
source: "mcp",
|
|
33
|
+
occurred_at: started_at ?? at,
|
|
34
|
+
ended_at: started_at && started_at !== at ? at : undefined,
|
|
35
|
+
repo: r,
|
|
36
|
+
summary,
|
|
37
|
+
payload: { kind: "activity", agent },
|
|
38
|
+
dedupe_key: `mcp:${r ?? "-"}:${at}:${summary.slice(0, 40)}`,
|
|
39
|
+
},
|
|
40
|
+
]);
|
|
41
|
+
return { content: [{ type: "text", text: `logged${await flush()}` }] };
|
|
42
|
+
});
|
|
43
|
+
server.tool("start_task", "Mark the start of a unit of work. Call end_task when it is done; the time in between becomes one block.", {
|
|
44
|
+
summary: z.string().describe("What you are about to do, one line, in the user's language."),
|
|
45
|
+
repo: z.string().optional().describe("Absolute repo path if known"),
|
|
46
|
+
}, async ({ summary, repo }) => {
|
|
47
|
+
const t = startTask(summary, repoOf(repo), new Date(), agent);
|
|
48
|
+
return { content: [{ type: "text", text: `task ${t.id} started` }] };
|
|
49
|
+
});
|
|
50
|
+
server.tool("end_task", "Mark the end of a task started with start_task (the most recent one if no id is given).", {
|
|
51
|
+
task_id: z.string().optional(),
|
|
52
|
+
summary: z.string().optional().describe("The outcome, one line. Replaces the start summary."),
|
|
53
|
+
}, async ({ task_id, summary }) => {
|
|
54
|
+
const e = endTask(task_id, summary, new Date());
|
|
55
|
+
if (!e)
|
|
56
|
+
return { content: [{ type: "text", text: "no open task" }], isError: true };
|
|
57
|
+
appendSpool([e]);
|
|
58
|
+
return { content: [{ type: "text", text: `task ended${await flush()}` }] };
|
|
59
|
+
});
|
|
60
|
+
await server.connect(new StdioServerTransport());
|
|
61
|
+
}
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* Where a file or folder lives after the rename from rewind to lastweek: the new location, unless only the old one
|
|
4
|
+
* exists, in which case it keeps being used in place (an existing pairing, last scan and spool survive the update).
|
|
5
|
+
*/
|
|
6
|
+
export const preferLegacy = (current, legacy) => !existsSync(current) && existsSync(legacy) ? legacy : current;
|