@lastweek-work/cli 0.2.0 → 0.3.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 CHANGED
@@ -23,7 +23,7 @@ Config: `~/.config/lastweek/config.json` (override with `LASTWEEK_CONFIG`), vali
23
23
  "deviceToken": "<rwd_… from the web app, Devices page>",
24
24
  "repoRoots": ["~/Work"],
25
25
  "authorEmails": ["you@example.com", "you@client.de"],
26
- "agentEmails": ["noreply@anthropic.com", "cursoragent@cursor.com"] }
26
+ "agentEmails": ["noreply@anthropic.com", "cursoragent@cursor.com", "198982749+copilot@users.noreply.github.com"] }
27
27
  ```
28
28
  `ingestUrl`/`deviceToken` may be omitted for `--dry-run`. Emails match case-insensitively.
29
29
 
@@ -63,6 +63,18 @@ Add to `~/.claude/settings.json` (merge with existing hooks). Fires on every edi
63
63
  out with the next flush or scan. Errors land in `~/.local/state/lastweek/agent.log`.
64
64
  - **Same session as your commits:** events carry the repo root (not Claude's working subfolder).
65
65
 
66
+ ## GitHub Copilot (CLI and VS Code)
67
+
68
+ `lastweek agents` (or `lastweek connect`) sets Copilot up the same way as Claude Code, when Copilot CLI or the
69
+ VS Code Copilot extension is installed:
70
+
71
+ - a hook file of its own, `~/.copilot/hooks/lastweek.json` (`postToolUse` and `userPromptSubmitted` →
72
+ `lastweek log --agent copilot`): Copilot sessions become bursts like Claude Code's, labelled "GitHub Copilot";
73
+ - the MCP server in `~/.copilot/mcp-config.json` (other servers are kept, the file is backed up first).
74
+
75
+ Both files are read by Copilot CLI and by Copilot in VS Code; `$COPILOT_HOME` is respected. The same privacy rules
76
+ apply: session id, timestamps, tool names and file paths only.
77
+
66
78
  ## MCP server
67
79
 
68
80
  Optional, for outcome summaries in the agent's own words. Claude Code:
package/dist/agents.js CHANGED
@@ -1,4 +1,4 @@
1
- import { appendFileSync, copyFileSync, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
1
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  // Registers lastweek's stdio MCP server (`lastweek mcp`) with coding agents other than Claude Code (which has its
@@ -7,6 +7,10 @@ import { join } from "node:path";
7
7
  // Cursor ~/.cursor/mcp.json { "mcpServers": { name: { type: "stdio", command, args } } } cursor.com/docs/context/mcp
8
8
  // Codex CLI ~/.codex/config.toml [mcp_servers.<name>] command = "…" args = […] learn.chatgpt.com/docs/extend/mcp
9
9
  // Gemini CLI ~/.gemini/settings.json { "mcpServers": { name: { command, args } } } github.com/google-gemini/gemini-cli docs/tools/mcp-server.md
10
+ // Copilot ~/.copilot/mcp-config.json { "mcpServers": { name: { type: "local", command, args, tools } } }
11
+ // + ~/.copilot/hooks/lastweek.json (our own file). Both read by Copilot CLI and by Copilot in VS Code
12
+ // ($COPILOT_HOME if set). docs.github.com/copilot/reference/hooks-reference,
13
+ // code.visualstudio.com/docs/agents/reference/mcp-configuration (checked 2026-11-17)
10
14
  export const SERVER_NAME = "lastweek";
11
15
  /** The server's name before the rename; removed when it is clearly ours, so tools don't show up twice. */
12
16
  const LEGACY_NAME = "rewind";
@@ -134,20 +138,87 @@ export function registerCodex(home = homedir()) {
134
138
  appendFileSync(path, `${lead}${table}${nl}`);
135
139
  return result("registered");
136
140
  }
141
+ /** Copilot's config directory: $COPILOT_HOME, else ~/.copilot. */
142
+ export const copilotDir = (home = homedir(), env = process.env) => env.COPILOT_HOME?.trim() || join(home, ".copilot");
143
+ /** The GitHub Copilot extension in VS Code (stable or Insiders), for people who never ran Copilot CLI. */
144
+ function vscodeCopilot(home) {
145
+ for (const d of [".vscode", ".vscode-insiders"]) {
146
+ try {
147
+ if (readdirSync(join(home, d, "extensions")).some((e) => e.toLowerCase().startsWith("github.copilot")))
148
+ return true;
149
+ }
150
+ catch {
151
+ // no VS Code here
152
+ }
153
+ }
154
+ return false;
155
+ }
156
+ export const copilotInstalled = (home = homedir(), env = process.env) => isDir(copilotDir(home, env)) || vscodeCopilot(home);
157
+ /** The hook command; like Claude Code's it must never fail or block the agent. */
158
+ export const COPILOT_HOOK = "lastweek log --agent copilot";
159
+ const COPILOT_HOOKS = {
160
+ version: 1,
161
+ hooks: Object.fromEntries(
162
+ // After every tool call and on every prompt: the times a session was working, never its contents.
163
+ ["postToolUse", "userPromptSubmitted"].map((event) => [
164
+ event,
165
+ [{ type: "command", bash: `${COPILOT_HOOK} 2>/dev/null || true`, command: COPILOT_HOOK, timeoutSec: 10 }],
166
+ ])),
167
+ };
168
+ /**
169
+ * GitHub Copilot (CLI and VS Code): the MCP server in mcp-config.json (other servers kept) and a hook file of our
170
+ * own, hooks/lastweek.json, so Copilot's working time is recorded like Claude Code's, without the model having to
171
+ * call a tool. Only when Copilot is installed; the directory is created for VS Code users without the CLI.
172
+ */
173
+ export function registerCopilot(home = homedir(), env = process.env) {
174
+ const dir = copilotDir(home, env);
175
+ const label = "GitHub Copilot";
176
+ if (!copilotInstalled(home, env))
177
+ return { agent: "copilot", label, path: join(dir, "mcp-config.json"), status: "not-installed" };
178
+ mkdirSync(join(dir, "hooks"), { recursive: true });
179
+ const mcp = registerJson("copilot", label, dir, "mcp-config.json", {
180
+ type: "local",
181
+ command: SERVER_NAME,
182
+ args: ["mcp"],
183
+ tools: ["*"],
184
+ });
185
+ const hookPath = join(dir, "hooks", `${SERVER_NAME}.json`);
186
+ const want = `${JSON.stringify(COPILOT_HOOKS, null, 2)}\n`;
187
+ let hookChanged = false;
188
+ let current = null;
189
+ try {
190
+ current = readFileSync(hookPath, "utf8");
191
+ }
192
+ catch {
193
+ // not there yet
194
+ }
195
+ if (current !== want) {
196
+ backup(hookPath);
197
+ writeFileSync(hookPath, want);
198
+ hookChanged = true;
199
+ }
200
+ if (mcp.status === "unreadable")
201
+ return mcp;
202
+ return { ...mcp, status: mcp.status === "registered" || hookChanged ? "registered" : "already" };
203
+ }
137
204
  /** Every supported coding agent besides Claude Code, in a fixed order. */
138
- export const registerCodingAgents = (home = homedir()) => [
205
+ export const registerCodingAgents = (home = homedir(), env = process.env) => [
139
206
  registerCursor(home),
140
207
  registerCodex(home),
141
208
  registerGemini(home),
209
+ registerCopilot(home, env),
210
+ ];
211
+ /** Labels of the coding agents (besides Claude Code) that are installed. */
212
+ export const installedCodingAgents = (home = homedir(), env = process.env) => [
213
+ ...[
214
+ [".cursor", "Cursor"],
215
+ [".codex", "Codex CLI"],
216
+ [".gemini", "Gemini CLI"],
217
+ ]
218
+ .filter(([dir]) => isDir(join(home, dir)))
219
+ .map(([, label]) => label),
220
+ ...(copilotInstalled(home, env) ? ["GitHub Copilot"] : []),
142
221
  ];
143
- /** Labels of the coding agents (besides Claude Code) whose config directory exists. */
144
- export const installedCodingAgents = (home = homedir()) => [
145
- [".cursor", "Cursor"],
146
- [".codex", "Codex CLI"],
147
- [".gemini", "Gemini CLI"],
148
- ]
149
- .filter(([dir]) => isDir(join(home, dir)))
150
- .map(([, label]) => label);
151
222
  /**
152
223
  * The MCP client's self-reported name (initialize → clientInfo.name) as a short agent id, e.g. "cursor-vscode" →
153
224
  * "cursor", "codex-mcp-client" → "codex". Unknown clients keep their own name, cleaned up; no name → undefined.
@@ -164,6 +235,9 @@ export function agentFromClient(name) {
164
235
  return "codex";
165
236
  if (n.includes("gemini"))
166
237
  return "gemini-cli";
238
+ // Copilot CLI, and VS Code itself (its MCP client is Copilot's agent mode; Cursor, a fork, is caught above).
239
+ if (n.includes("copilot") || n === "visual studio code" || n.startsWith("vscode"))
240
+ return "copilot";
167
241
  return (n
168
242
  .replace(/[^a-z0-9._-]+/g, "-")
169
243
  .replace(/^-+|-+$/g, "")
package/dist/bursts.js CHANGED
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync
2
2
  import { join } from "node:path";
3
3
  import { applyCall, burstToEvent, isIdle } from "./hook.js";
4
4
  import { appendSpool } from "./spool.js";
5
- import { stateDir } from "./state.js";
5
+ import { ensureStateDir, stateDir } from "./state.js";
6
6
  /** One file per Claude Code session holding its open burst. Survives restarts; nothing is lost if the Mac dies. */
7
7
  const dir = () => join(stateDir(), "sessions");
8
8
  const file = (session) => join(dir(), `${session.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 100)}.json`);
@@ -30,6 +30,7 @@ export function openBursts() {
30
30
  }
31
31
  /** Records one hook call; spools whatever bursts it finished (its own previous one, and idle ones of other sessions). */
32
32
  export function recordCall(call, now) {
33
+ ensureStateDir();
33
34
  mkdirSync(dir(), { recursive: true });
34
35
  const { burst, done } = applyCall(load(call.session), call, now);
35
36
  writeFileSync(file(call.session), JSON.stringify(burst));
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
- import { appendFileSync, mkdirSync } from "node:fs";
3
+ import { appendFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { join, resolve } from "node:path";
6
6
  import { parseArgs } from "node:util";
@@ -9,18 +9,18 @@ import { openBursts, recordCall, spoolIdle } from "./bursts.js";
9
9
  import { configPath, loadConfig } from "./config.js";
10
10
  import { ask, claudeInstalled, connectClaude, detectAuthorEmails, detectRepoRoots, gitEmail, mergeConfig, pair, readJson, say, writeConfig, } from "./connect.js";
11
11
  import { authorWarning, findRepos, mainRepoPath, scanRepos } from "./git.js";
12
- import { callFromInput } from "./hook.js";
12
+ import { callFromInput, isHookAgent } from "./hook.js";
13
13
  import { ingest } from "./ingest.js";
14
14
  import { runMcp } from "./mcp.js";
15
15
  import { installedPlist, installSchedule, scheduleInstalled, uninstallSchedule } from "./schedule.js";
16
16
  import { flushSpool, spoolSize } from "./spool.js";
17
- import { readLastScan, stateDir, writeLastScan } from "./state.js";
17
+ import { ensureStateDir, readLastScan, stateDir, writeLastScan } from "./state.js";
18
18
  import { openTasks } from "./tasks.js";
19
19
  const USAGE = `usage:
20
20
  lastweek connect <CODE> --server <url> [--name <device>] [--yes] [--no-agents] [--no-schedule] [--no-scan]
21
21
  set everything up with a code from the web app's setup tour
22
22
  lastweek connect --repos <folder> | --agents later additions: another code folder / coding agents
23
- lastweek agents register the MCP server with Cursor, Codex CLI, Gemini CLI
23
+ lastweek agents register with Cursor, Codex CLI, Gemini CLI, GitHub Copilot
24
24
  lastweek scan [since-iso] [--since <iso>] [--dry-run] collect git evidence (default since: last successful scan, else 8 days)
25
25
  lastweek log Claude Code hook: reads hook JSON on stdin, never fails, returns fast
26
26
  lastweek flush send spooled hook/MCP events now
@@ -39,7 +39,7 @@ function resolveSince(explicit) {
39
39
  /** Errors from background paths (hook, detached flush) go to a local log instead of the terminal. */
40
40
  function logError(where, e) {
41
41
  try {
42
- mkdirSync(stateDir(), { recursive: true });
42
+ ensureStateDir();
43
43
  appendFileSync(join(stateDir(), "agent.log"), `${new Date().toISOString()} ${where}: ${e instanceof Error ? e.message : String(e)}\n`);
44
44
  }
45
45
  catch {
@@ -125,7 +125,13 @@ async function connect(args) {
125
125
  // Without --name the name chosen in the browser is used.
126
126
  const r = await pair(values.server, code, values.name ?? "");
127
127
  if (!r.ok) {
128
- console.error(r.reason === "code" ? say.badCode : r.reason === "limited" ? say.limited : say.serverError(r.status));
128
+ console.error(r.reason === "code"
129
+ ? say.badCode
130
+ : r.reason === "limited"
131
+ ? say.limited
132
+ : r.reason === "insecure"
133
+ ? say.insecure
134
+ : say.serverError(r.status));
129
135
  process.exitCode = 1;
130
136
  return;
131
137
  }
@@ -178,7 +184,7 @@ async function connect(args) {
178
184
  }
179
185
  }
180
186
  }
181
- // Coding agents: Claude Code (hook + MCP) and Cursor / Codex CLI / Gemini CLI (MCP), only after asking (or --yes /
187
+ // Coding agents: Claude Code and GitHub Copilot (hook + MCP), Cursor / Codex CLI / Gemini CLI (MCP), only after asking (or --yes /
182
188
  // --agents). A temporary npx copy would leave hooks and MCP entries pointing at a `lastweek` that isn't installed.
183
189
  const temporary = /[\\/]_npx[\\/]/.test(process.argv[1] ?? "");
184
190
  const claude = claudeInstalled();
@@ -211,8 +217,11 @@ async function connect(args) {
211
217
  if (code && !values["no-scan"]) {
212
218
  try {
213
219
  const cfg = loadConfig();
214
- if (!cfg.repoRoots.length || !cfg.authorEmails.length)
220
+ // Name the real gap: no folder, or no commit email (then every commit would be skipped as someone else's).
221
+ if (!cfg.repoRoots.length)
215
222
  throw new Error(say.noFolders);
223
+ if (!cfg.authorEmails.length)
224
+ throw new Error(say.noEmails);
216
225
  console.log(say.scanning);
217
226
  const r = await runScan(cfg, resolveSince(undefined));
218
227
  console.log(say.scanned(r.events, r.repos));
@@ -247,6 +256,7 @@ async function main() {
247
256
  }
248
257
  const r = await runScan(cfg, resolveSince(values.since ?? positionals[0]));
249
258
  console.log(`${new Date().toISOString()} ${r.repos} repos, ${r.events} events since ${r.since}: inserted ${r.inserted}, duplicates ${r.duplicates}` +
259
+ (r.rejected ? `, refused ${r.rejected} (${r.reason})` : "") +
250
260
  (r.spoolSent ? `; spool sent ${r.spoolSent}` : ""));
251
261
  break;
252
262
  }
@@ -255,12 +265,16 @@ async function main() {
255
265
  break;
256
266
  }
257
267
  case "log": {
258
- // Claude Code hook. Must never fail or block the agent: no config needed, no network, always exit 0.
268
+ // Claude Code / GitHub Copilot hook (`--agent copilot`). Must never fail or block the agent: no config needed,
269
+ // no network, always exit 0.
259
270
  try {
271
+ const i = rest.indexOf("--agent");
272
+ const named = i >= 0 ? rest[i + 1] : undefined;
273
+ const agent = isHookAgent(named) ? named : "claude-code";
260
274
  const raw = await readStdin();
261
275
  const input = (raw.trim() ? JSON.parse(raw) : {});
262
276
  const repo = typeof input.cwd === "string" && input.cwd ? mainRepoPath(input.cwd) : null;
263
- recordCall(callFromInput(input, repo), Date.now());
277
+ recordCall(callFromInput(input, repo, agent), Date.now());
264
278
  if (spoolSize() > 0)
265
279
  flushInBackground();
266
280
  }
@@ -274,7 +288,7 @@ async function main() {
274
288
  try {
275
289
  const r = await flushNow();
276
290
  if (!quiet)
277
- console.log(`sent ${r.sent} (inserted ${r.inserted}, duplicates ${r.duplicates}), kept ${r.failed}`);
291
+ console.log(`sent ${r.sent} (inserted ${r.inserted}, duplicates ${r.duplicates}${r.rejected ? `, refused ${r.rejected}: ${r.reason}` : ""}), kept ${r.failed}`);
278
292
  if (r.failed) {
279
293
  logError("flush", r.error);
280
294
  if (!quiet)
@@ -330,7 +344,7 @@ async function main() {
330
344
  break;
331
345
  }
332
346
  case "agents": {
333
- // Only the MCP registration for Cursor / Codex CLI / Gemini CLI; Claude Code stays with `connect --agents`.
347
+ // Cursor / Codex CLI / Gemini CLI (MCP) and GitHub Copilot (MCP + hook); Claude Code stays with `connect --agents`.
334
348
  if (/[\\/]_npx[\\/]/.test(process.argv[1] ?? "")) {
335
349
  console.log(say.agentsTemp);
336
350
  break;
package/dist/config.js CHANGED
@@ -4,9 +4,25 @@ import { join } from "node:path";
4
4
  import { z } from "zod";
5
5
  import { DEFAULT_AGENT_EMAILS } from "./git.js";
6
6
  import { preferLegacy } from "./paths.js";
7
+ /** https, or plain http only to this machine (the local stack): evidence and the device token never go out in clear. */
8
+ export function isSafeServerUrl(u) {
9
+ try {
10
+ const url = new URL(u);
11
+ if (url.protocol === "https:")
12
+ return true;
13
+ return url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
7
19
  // ingestUrl/deviceToken are optional so `scan --dry-run` works before a device exists; ingest() requires them.
8
20
  const ConfigSchema = z.object({
9
- ingestUrl: z.string().url().optional(), // https://<project>.supabase.co/functions/v1/ingest
21
+ ingestUrl: z
22
+ .string()
23
+ .url()
24
+ .refine(isSafeServerUrl, "must be https (http only to this machine); run lastweek connect again")
25
+ .optional(), // https://<project>.supabase.co/functions/v1/ingest
10
26
  deviceToken: z
11
27
  .string()
12
28
  .regex(/^rwd_[0-9a-f]{64}$/, "must be a device token from the web app (rwd_…)")
package/dist/connect.js CHANGED
@@ -4,6 +4,7 @@ import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { backup } from "./agents.js";
7
+ import { isSafeServerUrl } from "./config.js";
7
8
  // `lastweek connect <CODE>`: everything a non-technical user would otherwise do by hand, in one command.
8
9
  // Pair with the web app, find project folders and commit emails, write the config, start the background scan,
9
10
  // connect Claude Code (asks first, backs up its settings), run the first scan. Pure helpers are exported for tests.
@@ -124,11 +125,22 @@ export function mergeConfig(existing, update) {
124
125
  /** A pairing code as typed by people: any case, with or without the dash. */
125
126
  export const normalizeCode = (code) => code.toUpperCase().replace(/[^A-Z0-9]/g, "");
126
127
  export async function pair(server, code, name, fetchImpl = fetch) {
127
- const res = await fetchImpl(`${server.replace(/\/$/, "")}/functions/v1/pair`, {
128
- method: "POST",
129
- headers: { "content-type": "application/json" },
130
- body: JSON.stringify({ code: normalizeCode(code), name }),
131
- });
128
+ if (!isSafeServerUrl(server))
129
+ return { ok: false, reason: "insecure" };
130
+ let res;
131
+ try {
132
+ res = await fetchImpl(`${server.replace(/\/$/, "")}/functions/v1/pair`, {
133
+ method: "POST",
134
+ headers: { "content-type": "application/json" },
135
+ redirect: "error", // the code and the device token go to this address only
136
+ signal: AbortSignal.timeout(30_000),
137
+ body: JSON.stringify({ code: normalizeCode(code), name }),
138
+ });
139
+ }
140
+ catch {
141
+ // Unreachable, timed out or redirected: an address problem, not a bad code.
142
+ return { ok: false, reason: "server", status: undefined };
143
+ }
132
144
  const marker = res.ok ? null : ((await res.json().catch(() => ({}))).code ?? null);
133
145
  if (marker === "invalid_code")
134
146
  return { ok: false, reason: "code" };
@@ -157,6 +169,9 @@ export const say = {
157
169
  limited: de
158
170
  ? "✗ Zu viele falsche Codes in kurzer Zeit. Bitte warte zehn Minuten und erzeuge dann einen neuen Code."
159
171
  : "✗ Too many wrong codes in a short time. Please wait ten minutes, then create a new code.",
172
+ insecure: de
173
+ ? "✗ Die Adresse hinter --server muss mit https:// beginnen (http nur zu diesem Rechner)."
174
+ : "✗ The address after --server must start with https:// (http only to this machine).",
160
175
  serverError: (s) => de
161
176
  ? `✗ Der Server antwortet nicht wie erwartet (${s ?? "?"}). Stimmt die Adresse hinter --server? Sonst gleich noch einmal versuchen.`
162
177
  : `✗ The server didn't answer as expected (${s ?? "?"}). Is the address after --server right? Otherwise try again shortly.`,
package/dist/git.js CHANGED
@@ -70,7 +70,12 @@ export function findRepos(roots, depth = 3, warn = console.warn) {
70
70
  return [...out];
71
71
  }
72
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"];
73
+ export const DEFAULT_AGENT_EMAILS = [
74
+ "noreply@anthropic.com",
75
+ "cursoragent@cursor.com",
76
+ // GitHub Copilot's cloud agent (commits authored by "Copilot"); counts only when merged on this machine.
77
+ "198982749+copilot@users.noreply.github.com",
78
+ ];
74
79
  /**
75
80
  * Commits that entered this worktree through its own reflog: created here (`commit…` entries) or brought in by a
76
81
  * local merge (`merge <branch>: …` → everything between the previous HEAD and the merge). This is how agent commits
package/dist/hook.js CHANGED
@@ -1,21 +1,34 @@
1
1
  /**
2
- * Coalescing of Claude Code hook calls. Calls of one session that arrive within GAP of each other extend one burst;
2
+ * Coalescing of coding-agent hook calls (Claude Code; GitHub Copilot since Phase 27b). Calls of one session that arrive within GAP of each other extend one burst;
3
3
  * a burst becomes a single interval event [first call, last call]. Pure: time and state are passed in.
4
4
  */
5
5
  export const GAP_MS = 60_000;
6
6
  /** Long continuous bursts are cut so events reach the server regularly. */
7
7
  export const MAX_BURST_MS = 15 * 60_000;
8
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;
9
+ /** Agents that report through `lastweek log`; anything else is recorded as Claude Code, the original hook. */
10
+ export const HOOK_AGENTS = { "claude-code": "Claude Code", copilot: "GitHub Copilot" };
11
+ export const isHookAgent = (v) => typeof v === "string" && v in HOOK_AGENTS;
12
+ const str = (v) => (typeof v === "string" && v ? v : undefined);
13
+ export function callFromInput(input, repo, agent = "claude-code") {
14
+ const args = (input.tool_input ??
15
+ (input.toolArgs && typeof input.toolArgs === "object" ? input.toolArgs : {}));
16
+ const raw = args.file_path ?? args.filePath ?? args.notebook_path ?? args.path;
11
17
  let file = typeof raw === "string" ? raw : null;
12
18
  if (file && repo && file.startsWith(`${repo}/`))
13
19
  file = file.slice(repo.length + 1);
20
+ const session = str(input.session_id) ?? str(input.sessionId) ?? "unknown";
14
21
  return {
15
- session: typeof input.session_id === "string" && input.session_id ? input.session_id : "unknown",
22
+ // Prefixed for Copilot so its session files can never collide with Claude Code's.
23
+ session: agent === "claude-code" ? session : `${agent}-${session}`,
16
24
  repo,
17
- label: input.tool_name ?? input.hook_event_name ?? "unknown",
25
+ // Copilot's prompt hook carries no event name: no tool means a prompt.
26
+ label: str(input.tool_name) ??
27
+ str(input.toolName) ??
28
+ str(input.hook_event_name) ??
29
+ (agent === "copilot" ? "prompt" : "unknown"),
18
30
  file,
31
+ ...(agent === "claude-code" ? {} : { agent }),
19
32
  };
20
33
  }
21
34
  /** Folds one call into the session's burst. Returns the burst to keep and any finished burst to emit. */
@@ -27,7 +40,16 @@ export function applyCall(current, call, now) {
27
40
  now >= current.last;
28
41
  const base = continues
29
42
  ? current
30
- : { session: call.session, repo: call.repo, start: now, last: now, count: 0, tools: {}, files: [] };
43
+ : {
44
+ session: call.session,
45
+ ...(call.agent ? { agent: call.agent } : {}),
46
+ repo: call.repo,
47
+ start: now,
48
+ last: now,
49
+ count: 0,
50
+ tools: {},
51
+ files: [],
52
+ };
31
53
  const burst = {
32
54
  ...base,
33
55
  last: now,
@@ -41,7 +63,8 @@ export function applyCall(current, call, now) {
41
63
  }
42
64
  /** A burst nobody has extended for longer than GAP is finished. */
43
65
  export const isIdle = (b, now) => now - b.last > GAP_MS;
44
- export function burstToEvent(b, agent = "claude-code") {
66
+ export function burstToEvent(b) {
67
+ const agent = b.agent ?? "claude-code";
45
68
  const start = new Date(b.start).toISOString();
46
69
  const tools = Object.entries(b.tools)
47
70
  .sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]))
@@ -52,7 +75,7 @@ export function burstToEvent(b, agent = "claude-code") {
52
75
  occurred_at: start,
53
76
  ended_at: b.last > b.start ? new Date(b.last).toISOString() : undefined,
54
77
  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"}` : ""}`,
78
+ summary: `${HOOK_AGENTS[agent]}: ${b.count} ${b.count === 1 ? "Aktion" : "Aktionen"} (${tools})${b.files.length ? ` · ${b.files.length} ${b.files.length === 1 ? "Datei" : "Dateien"}` : ""}`,
56
79
  payload: { kind: "hook", agent, session: b.session, count: b.count, tools: b.tools, files: b.files },
57
80
  dedupe_key: `hook:${b.session}:${start}`,
58
81
  };
package/dist/ingest.js CHANGED
@@ -1,7 +1,15 @@
1
+ /** The server's text limits (ingest EventSchema): a long commit subject is cut here instead of refused there. */
2
+ export function clip(e) {
3
+ return {
4
+ ...e,
5
+ ...(e.summary && e.summary.length > 1000 ? { summary: e.summary.slice(0, 1000) } : {}),
6
+ ...(e.ref && e.ref.length > 256 ? { ref: e.ref.slice(0, 256) } : {}),
7
+ };
8
+ }
1
9
  export const CHUNK_SIZE = 500; // matches the ingest function's per-request limit
2
10
  /** Posts events in chunks. Throws on the first failed chunk; earlier chunks stay ingested (dedupe makes retries safe). */
3
11
  export async function ingest(cfg, events) {
4
- const total = { inserted: 0, duplicates: 0 };
12
+ const total = { inserted: 0, duplicates: 0, rejected: 0 };
5
13
  if (events.length === 0)
6
14
  return total;
7
15
  if (!cfg.ingestUrl || !cfg.deviceToken)
@@ -10,13 +18,21 @@ export async function ingest(cfg, events) {
10
18
  const res = await fetch(cfg.ingestUrl, {
11
19
  method: "POST",
12
20
  headers: { "content-type": "application/json", authorization: `Bearer ${cfg.deviceToken}` },
13
- body: JSON.stringify({ events: events.slice(i, i + CHUNK_SIZE) }),
21
+ // Only the ingest URL itself: a redirect could carry the evidence elsewhere. A hung server mustn't hang hooks.
22
+ redirect: "error",
23
+ signal: AbortSignal.timeout(30_000),
24
+ body: JSON.stringify({ events: events.slice(i, i + CHUNK_SIZE).map(clip) }),
14
25
  });
15
26
  if (!res.ok)
16
27
  throw new Error(`ingest failed: ${res.status} ${await res.text()}`);
17
28
  const r = (await res.json());
18
29
  total.inserted += r.inserted;
19
30
  total.duplicates += r.duplicates;
31
+ if (r.rejected) {
32
+ total.rejected = (total.rejected ?? 0) + r.rejected;
33
+ const i = r.issues?.[0];
34
+ total.reason ??= i ? `${i.path || "event"}: ${i.message}` : "refused";
35
+ }
20
36
  }
21
37
  return total;
22
38
  }
package/dist/mcp.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createRequire } from "node:module";
1
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
4
  import { z } from "zod";
@@ -6,7 +7,9 @@ import { loadConfig } from "./config.js";
6
7
  import { mainRepoPath } from "./git.js";
7
8
  import { ingest } from "./ingest.js";
8
9
  import { appendSpool, flushSpool } from "./spool.js";
9
- import { endTask, startTask } from "./tasks.js";
10
+ import { endTask, intervalProblem, startTask } from "./tasks.js";
11
+ /** The published version (src/ and dist/ both sit next to package.json). */
12
+ const VERSION = createRequire(import.meta.url)("../package.json").version;
10
13
  /**
11
14
  * `lastweek mcp` — stdio MCP server. Every event is spooled first, then flushed; a failed flush keeps it for the next
12
15
  * scan or hook. Tools only record time and a one-line outcome; they never compute hours.
@@ -14,12 +17,14 @@ import { endTask, startTask } from "./tasks.js";
14
17
  export async function runMcp() {
15
18
  const cfg = loadConfig();
16
19
  const configured = process.env.LASTWEEK_AGENT_NAME || process.env.REWIND_AGENT_NAME || undefined;
17
- const server = new McpServer({ name: "lastweek", version: "0.1.0" });
20
+ const server = new McpServer({ name: "lastweek", version: VERSION });
18
21
  // An explicit env name wins; otherwise the client's own name from the initialize request (clientInfo.name).
19
22
  const agentName = () => configured ?? agentFromClient(server.server.getClientVersion()?.name) ?? "unknown";
20
23
  const repoOf = (repo) => (repo ? mainRepoPath(repo) : undefined);
21
24
  const flush = async () => {
22
25
  const r = await flushSpool((events) => ingest(cfg, events));
26
+ if (r.rejected)
27
+ return ` (${r.rejected} refused by the server: ${r.reason})`;
23
28
  return r.failed ? " (offline — kept locally, sent later)" : "";
24
29
  };
25
30
  server.tool("log_activity", "Record what was just done, with a timestamp. Call after completing a meaningful unit of work.", {
@@ -29,6 +34,9 @@ export async function runMcp() {
29
34
  ended_at: z.string().datetime({ offset: true }).optional(),
30
35
  }, async ({ summary, repo, started_at, ended_at }) => {
31
36
  const at = ended_at ?? new Date().toISOString();
37
+ const problem = intervalProblem(started_at ?? at, at, new Date());
38
+ if (problem)
39
+ return { content: [{ type: "text", text: `not logged: ${problem}` }], isError: true };
32
40
  const r = repoOf(repo);
33
41
  appendSpool([
34
42
  {
@@ -57,6 +65,9 @@ export async function runMcp() {
57
65
  const e = endTask(task_id, summary, new Date());
58
66
  if (!e)
59
67
  return { content: [{ type: "text", text: "no open task" }], isError: true };
68
+ const problem = intervalProblem(e.occurred_at, e.ended_at, new Date());
69
+ if (problem)
70
+ return { content: [{ type: "text", text: `task dropped: ${problem}` }], isError: true };
60
71
  appendSpool([e]);
61
72
  return { content: [{ type: "text", text: `task ended${await flush()}` }] };
62
73
  });
package/dist/schedule.js CHANGED
@@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { stateDir } from "./state.js";
5
+ import { ensureStateDir, stateDir } from "./state.js";
6
6
  /** macOS launchd job that runs `lastweek scan` regularly, so nobody has to remember it. */
7
7
  export const LABEL = "work.lastweek.scan";
8
8
  /** The job's name before the rename; installing or uninstalling removes it too, so it never runs twice. */
@@ -44,7 +44,7 @@ export function installSchedule(cli, everyMinutes) {
44
44
  if (process.platform !== "darwin")
45
45
  throw new Error("lastweek schedule uses launchd and only works on macOS");
46
46
  mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
47
- mkdirSync(stateDir(), { recursive: true });
47
+ ensureStateDir();
48
48
  uninstallSchedule(); // replace any previous version
49
49
  writeFileSync(plistPath(),
50
50
  // launchd starts jobs with a minimal PATH; git must be findable.
package/dist/spool.js CHANGED
@@ -1,6 +1,6 @@
1
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, } from "node:fs";
1
+ import { appendFileSync, existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { stateDir } from "./state.js";
3
+ import { ensureStateDir, stateDir } from "./state.js";
4
4
  /**
5
5
  * Local outbox. Events are appended to spool.jsonl before any network call, so being offline or getting a 5xx never
6
6
  * loses evidence. Flushing is lock-free: the spool is atomically renamed to a per-process batch file, sent, and only
@@ -12,7 +12,7 @@ const spoolPath = () => join(stateDir(), SPOOL);
12
12
  export function appendSpool(events) {
13
13
  if (events.length === 0)
14
14
  return;
15
- mkdirSync(stateDir(), { recursive: true });
15
+ ensureStateDir();
16
16
  // One write per call; O_APPEND keeps concurrent writers' lines intact.
17
17
  appendFileSync(spoolPath(), events.map((e) => `${JSON.stringify(e)}\n`).join(""));
18
18
  }
@@ -50,7 +50,7 @@ function spoolFiles(minAgeMs) {
50
50
  }
51
51
  /** Sends everything spooled. On failure the events go back into the spool for the next attempt. */
52
52
  export async function flushSpool(send) {
53
- const result = { sent: 0, inserted: 0, duplicates: 0, failed: 0 };
53
+ const result = { sent: 0, inserted: 0, duplicates: 0, failed: 0, rejected: 0 };
54
54
  const batches = spoolFiles(STALE_BATCH_MS);
55
55
  if (existsSync(spoolPath())) {
56
56
  const mine = join(stateDir(), `spool.${process.pid}.${Date.now()}.sending`);
@@ -75,6 +75,10 @@ export async function flushSpool(send) {
75
75
  result.sent += events.length;
76
76
  result.inserted += r.inserted;
77
77
  result.duplicates += r.duplicates;
78
+ if (r.rejected) {
79
+ result.rejected += r.rejected;
80
+ result.reason ??= r.reason;
81
+ }
78
82
  rmSync(batch, { force: true });
79
83
  }
80
84
  catch (e) {
package/dist/state.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { preferLegacy } from "./paths.js";
@@ -13,6 +13,21 @@ export function stateDir() {
13
13
  const base = process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
14
14
  return preferLegacy(join(base, "lastweek"), join(base, "rewind"));
15
15
  }
16
+ /**
17
+ * Creates the state folder readable by the owner only (0700): the spool, tasks and logs hold commit subjects, repo
18
+ * paths and summaries. Also tightens a folder an older version created with the default mode.
19
+ */
20
+ export function ensureStateDir() {
21
+ const dir = stateDir();
22
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
23
+ try {
24
+ chmodSync(dir, 0o700);
25
+ }
26
+ catch {
27
+ // not ours to change (e.g. a shared test folder): the files still work
28
+ }
29
+ return dir;
30
+ }
16
31
  /** ISO timestamp of the start of the last scan whose events were all ingested, or null. */
17
32
  export function readLastScan() {
18
33
  const p = join(stateDir(), "last_scan");
@@ -22,6 +37,5 @@ export function readLastScan() {
22
37
  return Number.isNaN(Date.parse(v)) ? null : v;
23
38
  }
24
39
  export function writeLastScan(iso) {
25
- mkdirSync(stateDir(), { recursive: true });
26
- writeFileSync(join(stateDir(), "last_scan"), `${iso}\n`);
40
+ writeFileSync(join(ensureStateDir(), "last_scan"), `${iso}\n`);
27
41
  }
package/dist/tasks.js CHANGED
@@ -1,11 +1,26 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { stateDir } from "./state.js";
4
+ import { ensureStateDir, stateDir } from "./state.js";
5
+ /** The server refuses longer intervals (ingest MAX_SPAN_MS); checked here too so the model is told at once. */
6
+ export const MAX_SPAN_MS = 8 * 3_600_000;
7
+ const MAX_SKEW_MS = 5 * 60_000;
8
+ /** Why an interval reported by a coding agent can't be evidence, or null when it can. */
9
+ export function intervalProblem(startIso, endIso, now) {
10
+ const start = Date.parse(startIso);
11
+ const end = endIso ? Date.parse(endIso) : start;
12
+ if (end < start)
13
+ return "ended_at is before started_at";
14
+ if (end > now.getTime() + MAX_SKEW_MS)
15
+ return "the time is in the future";
16
+ if (end - start > MAX_SPAN_MS)
17
+ return "longer than 8 hours; log the parts you actually worked instead";
18
+ return null;
19
+ }
5
20
  const path = () => join(stateDir(), "tasks.json");
6
21
  const read = () => (existsSync(path()) ? JSON.parse(readFileSync(path(), "utf8")) : []);
7
22
  const write = (tasks) => {
8
- mkdirSync(stateDir(), { recursive: true });
23
+ ensureStateDir();
9
24
  writeFileSync(path(), JSON.stringify(tasks, null, 2));
10
25
  };
11
26
  export function startTask(summary, repo, now, agent) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lastweek-work/cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "The lastweek agent: collects git and coding-agent evidence on your machine and sends it to your lastweek account.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://lastweek.work",