@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/README.md
CHANGED
|
@@ -1,3 +1,88 @@
|
|
|
1
|
-
#
|
|
1
|
+
# lastweek
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The local agent for [lastweek](https://lastweek.work): your timesheet, reconstructed from what you actually did.
|
|
4
|
+
It runs on your machine and collects evidence of your work (git commits, coding-agent sessions); lastweek turns it
|
|
5
|
+
into a draft timesheet that you review and approve.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install -g @lastweek-work/cli
|
|
9
|
+
lastweek connect <CODE> --server https://lastweek.work # the code comes from the setup page in your account
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
**What leaves your machine:** commit subjects, timestamps and repo paths, plus short summaries of coding-agent
|
|
13
|
+
activity. **Never:** diffs, file contents or prompts. Only repos in the folders you chose are read. Requires
|
|
14
|
+
Node.js 22 or later; the background scan uses launchd on macOS.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
Details for developers and power users:
|
|
19
|
+
|
|
20
|
+
Config: `~/.config/lastweek/config.json` (override with `LASTWEEK_CONFIG`), validated on load:
|
|
21
|
+
```json
|
|
22
|
+
{ "ingestUrl": "https://<ref>.supabase.co/functions/v1/ingest",
|
|
23
|
+
"deviceToken": "<rwd_… from the web app, Devices page>",
|
|
24
|
+
"repoRoots": ["~/Work"],
|
|
25
|
+
"authorEmails": ["you@example.com", "you@client.de"],
|
|
26
|
+
"agentEmails": ["noreply@anthropic.com", "cursoragent@cursor.com"] }
|
|
27
|
+
```
|
|
28
|
+
`ingestUrl`/`deviceToken` may be omitted for `--dry-run`. Emails match case-insensitively.
|
|
29
|
+
|
|
30
|
+
Which commits count: yours as **author, committer or `Co-authored-by`** — and commits by a coding agent
|
|
31
|
+
(`agentEmails`; the defaults above apply when the key is omitted) **that were made or merged on this machine**
|
|
32
|
+
(local reflog). Agent work in temporary worktrees counts after you merge it, even once the worktree is gone; a
|
|
33
|
+
colleague's agent commits in a shared repo never do. Add other agents' commit addresses (e.g. ChatGPT/Codex) to
|
|
34
|
+
`agentEmails`.
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
lastweek scan # since the last successful scan (else 8 days)
|
|
38
|
+
lastweek scan 2026-10-27T00:00:00Z # explicit since (also --since)
|
|
39
|
+
lastweek scan --dry-run # print events as JSON, send nothing, don't move last_scan
|
|
40
|
+
```
|
|
41
|
+
- Walks `repoRoots` 3 levels deep, adds every worktree. Commits are keyed on the main repo, so a commit seen from
|
|
42
|
+
several worktrees is one event; each worktree's HEAD reflog is scanned separately.
|
|
43
|
+
- Sends in chunks of 500. Exits non-zero on any failure; `last_scan` (`~/.local/state/lastweek/last_scan`,
|
|
44
|
+
override with `LASTWEEK_STATE_DIR`) only advances after everything was ingested. Reruns are safe (server dedupes).
|
|
45
|
+
|
|
46
|
+
## Claude Code hook
|
|
47
|
+
|
|
48
|
+
Add to `~/.claude/settings.json` (merge with existing hooks). Fires on every edit and every prompt:
|
|
49
|
+
```json
|
|
50
|
+
{ "hooks": {
|
|
51
|
+
"PostToolUse": [ { "matcher": "Edit|Write|MultiEdit|NotebookEdit",
|
|
52
|
+
"hooks": [ { "type": "command", "command": "lastweek log 2>/dev/null || true" } ] } ],
|
|
53
|
+
"UserPromptSubmit": [
|
|
54
|
+
{ "hooks": [ { "type": "command", "command": "lastweek log 2>/dev/null || true" } ] } ] } }
|
|
55
|
+
```
|
|
56
|
+
- **Coalesced:** calls of one session within 60 s extend one *burst*; a burst becomes one interval event
|
|
57
|
+
(first call → last call, max 15 min) with counts per tool and up to 10 touched files (repo-relative).
|
|
58
|
+
An hour of agent work is a handful of events and one block in the review — not 300 rows.
|
|
59
|
+
- **Private:** only session id, timestamps, tool names and file paths are read. Prompt text and tool output are never
|
|
60
|
+
stored or sent.
|
|
61
|
+
- **Never blocks Claude:** no network in the hook, no config needed, always exits 0. Finished bursts go to
|
|
62
|
+
`~/.local/state/lastweek/spool.jsonl`; a detached `lastweek flush` sends them. Offline? They wait in the spool and go
|
|
63
|
+
out with the next flush or scan. Errors land in `~/.local/state/lastweek/agent.log`.
|
|
64
|
+
- **Same session as your commits:** events carry the repo root (not Claude's working subfolder).
|
|
65
|
+
|
|
66
|
+
## MCP server
|
|
67
|
+
|
|
68
|
+
Optional, for outcome summaries in the agent's own words. Claude Code:
|
|
69
|
+
```
|
|
70
|
+
claude mcp add lastweek --scope user --env LASTWEEK_AGENT_NAME=claude-code -- lastweek mcp
|
|
71
|
+
```
|
|
72
|
+
Cursor (`~/.cursor/mcp.json`):
|
|
73
|
+
```json
|
|
74
|
+
{ "mcpServers": { "lastweek": { "command": "lastweek", "args": ["mcp"], "env": { "LASTWEEK_AGENT_NAME": "cursor" } } } }
|
|
75
|
+
```
|
|
76
|
+
Tools: `log_activity(summary, repo?, started_at?, ended_at?)`, `start_task(summary, repo?)` →
|
|
77
|
+
`end_task(task_id?, summary?)` (the time in between becomes one block). Events are spooled first, like the hook's.
|
|
78
|
+
|
|
79
|
+
## Other commands
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
lastweek flush # send spooled hook/MCP events now
|
|
83
|
+
lastweek status # config, last scan, spool size, open bursts/tasks, schedule
|
|
84
|
+
lastweek schedule install --every 30 # macOS launchd: run `lastweek scan` every 30 min (also flushes the spool)
|
|
85
|
+
lastweek schedule uninstall
|
|
86
|
+
```
|
|
87
|
+
The schedule logs to `~/.local/state/lastweek/scan.log`. It uses the Node and PATH of the shell you install it from;
|
|
88
|
+
re-run `install` after switching Node versions.
|
package/dist/bursts.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { applyCall, burstToEvent, isIdle } from "./hook.js";
|
|
4
|
+
import { appendSpool } from "./spool.js";
|
|
5
|
+
import { stateDir } from "./state.js";
|
|
6
|
+
/** One file per Claude Code session holding its open burst. Survives restarts; nothing is lost if the Mac dies. */
|
|
7
|
+
const dir = () => join(stateDir(), "sessions");
|
|
8
|
+
const file = (session) => join(dir(), `${session.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 100)}.json`);
|
|
9
|
+
function load(session) {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(readFileSync(file(session), "utf8"));
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function openBursts() {
|
|
18
|
+
if (!existsSync(dir()))
|
|
19
|
+
return [];
|
|
20
|
+
const out = [];
|
|
21
|
+
for (const f of readdirSync(dir())) {
|
|
22
|
+
try {
|
|
23
|
+
out.push(JSON.parse(readFileSync(join(dir(), f), "utf8")));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
rmSync(join(dir(), f), { force: true }); // unreadable leftovers
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
/** Records one hook call; spools whatever bursts it finished (its own previous one, and idle ones of other sessions). */
|
|
32
|
+
export function recordCall(call, now) {
|
|
33
|
+
mkdirSync(dir(), { recursive: true });
|
|
34
|
+
const { burst, done } = applyCall(load(call.session), call, now);
|
|
35
|
+
writeFileSync(file(call.session), JSON.stringify(burst));
|
|
36
|
+
const finished = done ? [done] : [];
|
|
37
|
+
return { spooled: finished.length + spoolIdle(now, call.session, finished) };
|
|
38
|
+
}
|
|
39
|
+
/** Moves bursts nobody extended for longer than the gap into the spool. */
|
|
40
|
+
export function spoolIdle(now, except, alsoSpool = []) {
|
|
41
|
+
const idle = openBursts().filter((b) => b.session !== except && isIdle(b, now));
|
|
42
|
+
for (const b of idle)
|
|
43
|
+
rmSync(file(b.session), { force: true });
|
|
44
|
+
const all = [...alsoSpool, ...idle];
|
|
45
|
+
appendSpool(all.map((b) => burstToEvent(b)));
|
|
46
|
+
return idle.length;
|
|
47
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
import { openBursts, recordCall, spoolIdle } from "./bursts.js";
|
|
8
|
+
import { configPath, loadConfig } from "./config.js";
|
|
9
|
+
import { ask, claudeInstalled, connectClaude, detectAuthorEmails, detectRepoRoots, gitEmail, mergeConfig, pair, readJson, say, writeConfig, } from "./connect.js";
|
|
10
|
+
import { authorWarning, findRepos, mainRepoPath, scanRepos } from "./git.js";
|
|
11
|
+
import { callFromInput } from "./hook.js";
|
|
12
|
+
import { ingest } from "./ingest.js";
|
|
13
|
+
import { runMcp } from "./mcp.js";
|
|
14
|
+
import { installedPlist, installSchedule, scheduleInstalled, uninstallSchedule } from "./schedule.js";
|
|
15
|
+
import { flushSpool, spoolSize } from "./spool.js";
|
|
16
|
+
import { readLastScan, stateDir, writeLastScan } from "./state.js";
|
|
17
|
+
import { openTasks } from "./tasks.js";
|
|
18
|
+
const USAGE = `usage:
|
|
19
|
+
lastweek connect <CODE> --server <url> [--name <device>] [--yes] [--no-agents] [--no-schedule] [--no-scan]
|
|
20
|
+
set everything up with a code from the web app's setup tour
|
|
21
|
+
lastweek connect --repos <folder> | --agents later additions: another code folder / Claude Code
|
|
22
|
+
lastweek scan [since-iso] [--since <iso>] [--dry-run] collect git evidence (default since: last successful scan, else 8 days)
|
|
23
|
+
lastweek log Claude Code hook: reads hook JSON on stdin, never fails, returns fast
|
|
24
|
+
lastweek flush send spooled hook/MCP events now
|
|
25
|
+
lastweek status config, last scan, spool, open bursts/tasks, schedule
|
|
26
|
+
lastweek schedule install [--every <minutes>] macOS: run \`lastweek scan\` every N minutes (default 30)
|
|
27
|
+
lastweek schedule uninstall
|
|
28
|
+
lastweek mcp stdio MCP server (log_activity, start_task, end_task)`;
|
|
29
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
30
|
+
function resolveSince(explicit) {
|
|
31
|
+
const since = explicit ?? readLastScan() ?? new Date(Date.now() - 8 * 86400e3).toISOString();
|
|
32
|
+
const ms = Date.parse(since);
|
|
33
|
+
if (Number.isNaN(ms))
|
|
34
|
+
throw new Error(`since must be an ISO-8601 timestamp, got "${since}"`);
|
|
35
|
+
return new Date(ms).toISOString();
|
|
36
|
+
}
|
|
37
|
+
/** Errors from background paths (hook, detached flush) go to a local log instead of the terminal. */
|
|
38
|
+
function logError(where, e) {
|
|
39
|
+
try {
|
|
40
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
41
|
+
appendFileSync(join(stateDir(), "agent.log"), `${new Date().toISOString()} ${where}: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// nowhere left to report; the hook must still succeed
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Sends idle bursts and the spool. Shared by `flush`, `scan` and the MCP server. */
|
|
48
|
+
export async function flushNow() {
|
|
49
|
+
spoolIdle(Date.now());
|
|
50
|
+
const cfg = loadConfig();
|
|
51
|
+
return flushSpool((events) => ingest(cfg, events));
|
|
52
|
+
}
|
|
53
|
+
/** Fire-and-forget `lastweek flush` so the hook never waits on the network. */
|
|
54
|
+
function flushInBackground() {
|
|
55
|
+
const child = spawn(process.execPath, [...process.execArgv, process.argv[1], "flush", "--quiet"], {
|
|
56
|
+
detached: true,
|
|
57
|
+
stdio: "ignore",
|
|
58
|
+
env: process.env,
|
|
59
|
+
});
|
|
60
|
+
child.unref();
|
|
61
|
+
}
|
|
62
|
+
async function readStdin(timeoutMs = 2000) {
|
|
63
|
+
if (process.stdin.isTTY)
|
|
64
|
+
return "";
|
|
65
|
+
return new Promise((resolve) => {
|
|
66
|
+
let data = "";
|
|
67
|
+
const done = () => resolve(data);
|
|
68
|
+
const timer = setTimeout(done, timeoutMs);
|
|
69
|
+
process.stdin.on("data", (c) => {
|
|
70
|
+
data += c;
|
|
71
|
+
});
|
|
72
|
+
process.stdin.on("end", () => {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
done();
|
|
75
|
+
});
|
|
76
|
+
process.stdin.on("error", () => {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
done();
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/** Collect git evidence since `since`, send it with the spool, remember the scan. Shared by scan and connect. */
|
|
83
|
+
async function runScan(cfg, since) {
|
|
84
|
+
const startedAt = new Date().toISOString();
|
|
85
|
+
const repos = findRepos(cfg.repoRoots);
|
|
86
|
+
const stats = { commits: 0, matched: 0 };
|
|
87
|
+
const events = scanRepos(repos, cfg.authorEmails, since, stats, cfg.agentEmails);
|
|
88
|
+
const warning = authorWarning(stats);
|
|
89
|
+
if (warning)
|
|
90
|
+
console.error(warning);
|
|
91
|
+
// Hook/MCP events waiting in the spool go out with every scan (and with the scheduled one).
|
|
92
|
+
const spooled = await flushNow();
|
|
93
|
+
if (spooled.failed)
|
|
94
|
+
console.error(`spool: ${spooled.failed} events kept for later (${spooled.error})`);
|
|
95
|
+
const r = await ingest(cfg, events);
|
|
96
|
+
writeLastScan(startedAt);
|
|
97
|
+
return { repos: repos.length, events: events.length, since, ...r, spoolSent: spooled.sent };
|
|
98
|
+
}
|
|
99
|
+
/** The setup tour's one command. Every step explains itself; nothing secret is printed. */
|
|
100
|
+
async function connect(args) {
|
|
101
|
+
const { values, positionals } = parseArgs({
|
|
102
|
+
args,
|
|
103
|
+
allowPositionals: true,
|
|
104
|
+
options: {
|
|
105
|
+
server: { type: "string" },
|
|
106
|
+
name: { type: "string" },
|
|
107
|
+
repos: { type: "string", multiple: true },
|
|
108
|
+
yes: { type: "boolean", default: false },
|
|
109
|
+
agents: { type: "boolean", default: false },
|
|
110
|
+
"no-agents": { type: "boolean", default: false },
|
|
111
|
+
"no-schedule": { type: "boolean", default: false },
|
|
112
|
+
"no-scan": { type: "boolean", default: false },
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
const path = configPath();
|
|
116
|
+
const existing = readJson(path);
|
|
117
|
+
const code = positionals[0];
|
|
118
|
+
const update = {};
|
|
119
|
+
if (code) {
|
|
120
|
+
if (!values.server)
|
|
121
|
+
throw new Error(say.needCode);
|
|
122
|
+
console.log(say.pairing);
|
|
123
|
+
// Without --name the name chosen in the browser is used.
|
|
124
|
+
const r = await pair(values.server, code, values.name ?? "");
|
|
125
|
+
if (!r.ok) {
|
|
126
|
+
console.error(r.reason === "code" ? say.badCode : r.reason === "limited" ? say.limited : say.serverError(r.status));
|
|
127
|
+
process.exitCode = 1;
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
update.deviceToken = r.deviceToken;
|
|
131
|
+
update.ingestUrl = r.ingestUrl;
|
|
132
|
+
console.log(say.paired);
|
|
133
|
+
}
|
|
134
|
+
else if (!existing?.deviceToken && !values.agents) {
|
|
135
|
+
throw new Error(say.needCode);
|
|
136
|
+
}
|
|
137
|
+
// Folders and emails: detected on first connect, extended with --repos later.
|
|
138
|
+
if (code || values.repos) {
|
|
139
|
+
// --repos may be relative or start with ~; the background scan runs elsewhere, so store absolute/home paths.
|
|
140
|
+
const typed = (values.repos ?? []).map((r) => {
|
|
141
|
+
const abs = r.startsWith("~") ? r.replace(/^~/, homedir()) : resolve(r);
|
|
142
|
+
return abs.startsWith(`${homedir()}/`) ? `~${abs.slice(homedir().length)}` : abs;
|
|
143
|
+
});
|
|
144
|
+
const roots = typed.length ? typed : detectRepoRoots(homedir(), (r) => findRepos(r, 3, () => { }));
|
|
145
|
+
const repos = findRepos(roots.map((r) => r.replace(/^~/, homedir())), 3, () => { });
|
|
146
|
+
if (roots.length)
|
|
147
|
+
console.log(say.folders(roots, repos.length));
|
|
148
|
+
else
|
|
149
|
+
console.log(say.noFolders);
|
|
150
|
+
const emails = detectAuthorEmails(repos, gitEmail);
|
|
151
|
+
if (emails.length)
|
|
152
|
+
console.log(say.emails(emails));
|
|
153
|
+
else if (!existing?.authorEmails?.length)
|
|
154
|
+
console.log(say.noEmails);
|
|
155
|
+
update.repoRoots = roots;
|
|
156
|
+
update.authorEmails = emails;
|
|
157
|
+
}
|
|
158
|
+
// Always save once paired: the code is used up, and folders/emails can be added later with --repos.
|
|
159
|
+
if (code || values.repos) {
|
|
160
|
+
writeConfig(path, mergeConfig(existing, update));
|
|
161
|
+
console.log(say.saved(path));
|
|
162
|
+
}
|
|
163
|
+
// Background scan (macOS launchd); needs a stable install, not a temporary npx copy.
|
|
164
|
+
if (code && !values["no-schedule"]) {
|
|
165
|
+
if (process.platform !== "darwin")
|
|
166
|
+
console.log(say.scheduleMacOnly);
|
|
167
|
+
else if (/[\\/]_npx[\\/]/.test(process.argv[1] ?? ""))
|
|
168
|
+
console.log(say.scheduleTemp);
|
|
169
|
+
else {
|
|
170
|
+
try {
|
|
171
|
+
installSchedule(process.argv[1], 30);
|
|
172
|
+
console.log(say.schedule);
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
console.error(say.scheduleFailed(e instanceof Error ? e.message : String(e)));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Claude Code: hook + MCP, only after asking (or --yes / --agents).
|
|
180
|
+
// A temporary npx copy would leave hooks pointing at a `lastweek` that isn't installed.
|
|
181
|
+
const temporary = /[\\/]_npx[\\/]/.test(process.argv[1] ?? "");
|
|
182
|
+
if ((code || values.agents) && !values["no-agents"] && claudeInstalled()) {
|
|
183
|
+
if (temporary)
|
|
184
|
+
console.log(say.claudeTemp);
|
|
185
|
+
else if (values.yes || values.agents || (await ask(say.claudeAsk))) {
|
|
186
|
+
const r = connectClaude();
|
|
187
|
+
if (r.unreadable)
|
|
188
|
+
console.error(say.claudeUnreadable(r.unreadable));
|
|
189
|
+
else
|
|
190
|
+
console.log(r.changed || r.mcp ? say.claudeDone(r.mcp) : say.claudeAlready);
|
|
191
|
+
}
|
|
192
|
+
else
|
|
193
|
+
console.log(say.claudeSkipped);
|
|
194
|
+
}
|
|
195
|
+
// First scan right away, so the browser shows data while the user is still there.
|
|
196
|
+
if (code && !values["no-scan"]) {
|
|
197
|
+
try {
|
|
198
|
+
const cfg = loadConfig();
|
|
199
|
+
if (!cfg.repoRoots.length || !cfg.authorEmails.length)
|
|
200
|
+
throw new Error(say.noFolders);
|
|
201
|
+
console.log(say.scanning);
|
|
202
|
+
const r = await runScan(cfg, resolveSince(undefined));
|
|
203
|
+
console.log(say.scanned(r.events, r.repos));
|
|
204
|
+
}
|
|
205
|
+
catch (e) {
|
|
206
|
+
console.error(say.scanFailed(e instanceof Error ? e.message : String(e)));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (code)
|
|
210
|
+
console.log(`\n${say.done}`);
|
|
211
|
+
}
|
|
212
|
+
async function main() {
|
|
213
|
+
switch (cmd) {
|
|
214
|
+
case "scan": {
|
|
215
|
+
const { values, positionals } = parseArgs({
|
|
216
|
+
args: rest,
|
|
217
|
+
allowPositionals: true,
|
|
218
|
+
options: { since: { type: "string" }, "dry-run": { type: "boolean", default: false } },
|
|
219
|
+
});
|
|
220
|
+
const cfg = loadConfig();
|
|
221
|
+
if (values["dry-run"]) {
|
|
222
|
+
const since = resolveSince(values.since ?? positionals[0]);
|
|
223
|
+
const repos = findRepos(cfg.repoRoots);
|
|
224
|
+
const stats = { commits: 0, matched: 0 };
|
|
225
|
+
const events = scanRepos(repos, cfg.authorEmails, since, stats, cfg.agentEmails);
|
|
226
|
+
const warning = authorWarning(stats);
|
|
227
|
+
if (warning)
|
|
228
|
+
console.error(warning);
|
|
229
|
+
console.log(JSON.stringify(events, null, 2));
|
|
230
|
+
console.error(`dry run: ${repos.length} repos, ${events.length} events since ${since}`);
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
const r = await runScan(cfg, resolveSince(values.since ?? positionals[0]));
|
|
234
|
+
console.log(`${new Date().toISOString()} ${r.repos} repos, ${r.events} events since ${r.since}: inserted ${r.inserted}, duplicates ${r.duplicates}` +
|
|
235
|
+
(r.spoolSent ? `; spool sent ${r.spoolSent}` : ""));
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
case "connect": {
|
|
239
|
+
await connect(rest);
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
case "log": {
|
|
243
|
+
// Claude Code hook. Must never fail or block the agent: no config needed, no network, always exit 0.
|
|
244
|
+
try {
|
|
245
|
+
const raw = await readStdin();
|
|
246
|
+
const input = (raw.trim() ? JSON.parse(raw) : {});
|
|
247
|
+
const repo = typeof input.cwd === "string" && input.cwd ? mainRepoPath(input.cwd) : null;
|
|
248
|
+
recordCall(callFromInput(input, repo), Date.now());
|
|
249
|
+
if (spoolSize() > 0)
|
|
250
|
+
flushInBackground();
|
|
251
|
+
}
|
|
252
|
+
catch (e) {
|
|
253
|
+
logError("log", e);
|
|
254
|
+
}
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
case "flush": {
|
|
258
|
+
const quiet = rest.includes("--quiet");
|
|
259
|
+
try {
|
|
260
|
+
const r = await flushNow();
|
|
261
|
+
if (!quiet)
|
|
262
|
+
console.log(`sent ${r.sent} (inserted ${r.inserted}, duplicates ${r.duplicates}), kept ${r.failed}`);
|
|
263
|
+
if (r.failed) {
|
|
264
|
+
logError("flush", r.error);
|
|
265
|
+
if (!quiet)
|
|
266
|
+
process.exitCode = 1;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
catch (e) {
|
|
270
|
+
logError("flush", e);
|
|
271
|
+
if (!quiet)
|
|
272
|
+
throw e;
|
|
273
|
+
}
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
case "status": {
|
|
277
|
+
let config = "ok";
|
|
278
|
+
try {
|
|
279
|
+
const cfg = loadConfig();
|
|
280
|
+
if (!cfg.ingestUrl || !cfg.deviceToken)
|
|
281
|
+
config = "ok (no ingestUrl/deviceToken: dry-run only)";
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
config = e instanceof Error ? e.message : String(e);
|
|
285
|
+
}
|
|
286
|
+
const bursts = openBursts();
|
|
287
|
+
console.log([
|
|
288
|
+
`config: ${config}`,
|
|
289
|
+
`last scan: ${readLastScan() ?? "never"}`,
|
|
290
|
+
`spool: ${spoolSize()} events waiting`,
|
|
291
|
+
`bursts: ${bursts.length} open${bursts.length ? ` (oldest ${new Date(Math.min(...bursts.map((b) => b.start))).toISOString()})` : ""}`,
|
|
292
|
+
`tasks: ${openTasks().length} open`,
|
|
293
|
+
`schedule: ${scheduleInstalled() ? `installed (${installedPlist()})` : "not installed"}`,
|
|
294
|
+
`state dir: ${stateDir()}`,
|
|
295
|
+
].join("\n"));
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
case "schedule": {
|
|
299
|
+
const [sub, ...args] = rest;
|
|
300
|
+
if (sub === "install") {
|
|
301
|
+
const { values } = parseArgs({ args, options: { every: { type: "string", default: "30" } } });
|
|
302
|
+
const every = Number(values.every);
|
|
303
|
+
if (!Number.isInteger(every) || every < 5 || every > 1440)
|
|
304
|
+
throw new Error("--every must be 5…1440 minutes");
|
|
305
|
+
const path = installSchedule(process.argv[1], every);
|
|
306
|
+
console.log(`installed: lastweek scan every ${every} min (${path}); log: ${join(stateDir(), "scan.log")}`);
|
|
307
|
+
}
|
|
308
|
+
else if (sub === "uninstall") {
|
|
309
|
+
console.log(uninstallSchedule() ? "schedule removed" : "no schedule installed");
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
console.log(USAGE);
|
|
313
|
+
process.exitCode = 2;
|
|
314
|
+
}
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
case "mcp":
|
|
318
|
+
await runMcp();
|
|
319
|
+
break;
|
|
320
|
+
default:
|
|
321
|
+
console.log(USAGE);
|
|
322
|
+
if (cmd)
|
|
323
|
+
process.exitCode = 2;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
main().catch((e) => {
|
|
327
|
+
console.error(e instanceof Error ? e.message : e);
|
|
328
|
+
process.exit(1);
|
|
329
|
+
});
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { DEFAULT_AGENT_EMAILS } from "./git.js";
|
|
6
|
+
import { preferLegacy } from "./paths.js";
|
|
7
|
+
// ingestUrl/deviceToken are optional so `scan --dry-run` works before a device exists; ingest() requires them.
|
|
8
|
+
const ConfigSchema = z.object({
|
|
9
|
+
ingestUrl: z.string().url().optional(), // https://<project>.supabase.co/functions/v1/ingest
|
|
10
|
+
deviceToken: z
|
|
11
|
+
.string()
|
|
12
|
+
.regex(/^rwd_[0-9a-f]{64}$/, "must be a device token from the web app (rwd_…)")
|
|
13
|
+
.optional(), // only its hash is stored server-side
|
|
14
|
+
// May be empty right after pairing (no folders/email found yet); `rewind connect --repos` fills them in.
|
|
15
|
+
repoRoots: z.array(z.string().min(1)), // e.g. ["~/Work"]
|
|
16
|
+
authorEmails: z.array(z.string().email()), // commits by these authors count as evidence
|
|
17
|
+
// Coding agents whose commits count when made or merged on this machine. Defaults: Claude Code, Cursor.
|
|
18
|
+
agentEmails: z.array(z.string().email()).optional(),
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* ~/.config/lastweek/config.json. A config from before the rename (~/.config/rewind) keeps being used where it is,
|
|
22
|
+
* so an existing pairing survives the update. LASTWEEK_CONFIG (or the old REWIND_CONFIG) overrides.
|
|
23
|
+
*/
|
|
24
|
+
export function configPath() {
|
|
25
|
+
const env = process.env.LASTWEEK_CONFIG ?? process.env.REWIND_CONFIG;
|
|
26
|
+
if (env)
|
|
27
|
+
return env;
|
|
28
|
+
return preferLegacy(join(homedir(), ".config", "lastweek", "config.json"), join(homedir(), ".config", "rewind", "config.json"));
|
|
29
|
+
}
|
|
30
|
+
export function loadConfig(path = configPath()) {
|
|
31
|
+
const parsed = ConfigSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
|
|
32
|
+
if (!parsed.success) {
|
|
33
|
+
// Issue paths and messages only; zod does not include input values, so the token never reaches the terminal.
|
|
34
|
+
const issues = parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
|
|
35
|
+
const hint = parsed.error.issues.some((i) => i.path[0] === "authorEmails")
|
|
36
|
+
? "\nauthorEmails must list the email(s) your commits use — see `git config user.email` (per repo it may differ)."
|
|
37
|
+
: "";
|
|
38
|
+
throw new Error(`invalid config ${path}: ${issues}${hint}`);
|
|
39
|
+
}
|
|
40
|
+
const cfg = parsed.data;
|
|
41
|
+
cfg.repoRoots = cfg.repoRoots.map((r) => r.replace(/^~/, homedir()));
|
|
42
|
+
cfg.authorEmails = cfg.authorEmails.map((e) => e.toLowerCase());
|
|
43
|
+
cfg.agentEmails = (cfg.agentEmails ?? DEFAULT_AGENT_EMAILS).map((e) => e.toLowerCase());
|
|
44
|
+
return cfg;
|
|
45
|
+
}
|