@lastweek-work/cli 0.3.2 → 0.3.5

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
@@ -43,12 +43,21 @@ lastweek scan --dry-run # print events as JSON, send nothing, don'
43
43
  - Sends in chunks of 500. Exits non-zero on any failure; `last_scan` (`~/.local/state/lastweek/last_scan`,
44
44
  override with `LASTWEEK_STATE_DIR`) only advances after everything was ingested. Reruns are safe (server dedupes).
45
45
 
46
+ ## Claude Code session logs (0.3.5)
47
+
48
+ `lastweek scan` also reads Claude Code's own logs in `~/.claude/projects` (the first scan the last 30 days, then
49
+ what changed since the last scan): timestamps, session id, working folder, tool names and edited file paths, folded
50
+ into the same bursts as the hook below. Prompt text, shell commands and tool output are never kept or sent. A burst
51
+ the hook already sent has the same key and is not sent twice.
52
+
46
53
  ## Claude Code hook
47
54
 
48
- Add to `~/.claude/settings.json` (merge with existing hooks). Fires on every edit and every prompt:
55
+ `lastweek agents` adds this to `~/.claude/settings.json` (merged with existing hooks). Fires on every tool call and every
56
+ prompt, so long runs of tests, builds or reading without an edit still count (0.3.4; edit-only installs from earlier
57
+ versions are widened by the next scan):
49
58
  ```json
50
59
  { "hooks": {
51
- "PostToolUse": [ { "matcher": "Edit|Write|MultiEdit|NotebookEdit",
60
+ "PostToolUse": [ { "matcher": "*",
52
61
  "hooks": [ { "type": "command", "command": "lastweek log 2>/dev/null || true" } ] } ],
53
62
  "UserPromptSubmit": [
54
63
  { "hooks": [ { "type": "command", "command": "lastweek log 2>/dev/null || true" } ] } ] } }
@@ -56,12 +65,18 @@ Add to `~/.claude/settings.json` (merge with existing hooks). Fires on every edi
56
65
  - **Coalesced:** calls of one session within 60 s extend one *burst*; a burst becomes one interval event
57
66
  (first call → last call, max 15 min) with counts per tool and up to 10 touched files (repo-relative).
58
67
  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.
68
+ - **Private:** only session id, timestamps, tool names and file paths are read. Prompt text, shell commands and tool
69
+ output are never stored or sent.
61
70
  - **Never blocks Claude:** no network in the hook, no config needed, always exits 0. Finished bursts go to
62
71
  `~/.local/state/lastweek/spool.jsonl`; a detached `lastweek flush` sends them. Offline? They wait in the spool and go
63
72
  out with the next flush or scan. Errors land in `~/.local/state/lastweek/agent.log`.
64
73
  - **Same session as your commits:** events carry the repo root (not Claude's working subfolder).
74
+ - **Home and temp folders are no repo** (0.3.3): a session started in your home folder itself or in a temp folder
75
+ (`/tmp`, `/var/folders`, anything below) is resolved while the folder still exists: a Claude Code scratchpad →
76
+ its project's repo; a clone in a temp folder → your local repo with the same `origin` (else the remote itself,
77
+ `git:github.com/org/name`, so a project pattern can claim it); else the repo holding most of the touched files.
78
+ The original folder stays in the event (`payload.cwd`). What can't be resolved is settled per session in the
79
+ web app's weekly roundup, never billed before.
65
80
 
66
81
  ## GitHub Copilot (CLI and VS Code)
67
82
 
package/dist/bursts.js CHANGED
@@ -1,11 +1,16 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { applyCall, burstToEvent, isIdle } from "./hook.js";
4
+ import { repoOfFiles } from "./resolve.js";
4
5
  import { appendSpool } from "./spool.js";
5
6
  import { ensureStateDir, stateDir, writeAtomic } from "./state.js";
6
7
  /** One file per Claude Code session holding its open burst. Survives restarts; nothing is lost if the Mac dies. */
7
8
  const dir = () => join(stateDir(), "sessions");
8
9
  const file = (session) => join(dir(), `${session.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 100)}.json`);
10
+ /** The session's open burst, if any (the hook reuses its repo resolution while the working folder stays the same). */
11
+ export function currentBurst(session) {
12
+ return load(session);
13
+ }
9
14
  function load(session) {
10
15
  try {
11
16
  return JSON.parse(readFileSync(file(session), "utf8"));
@@ -54,6 +59,24 @@ export function spoolIdle(now, except, alsoSpool = []) {
54
59
  for (const b of idle)
55
60
  rmSync(file(b.session), { force: true });
56
61
  const all = [...alsoSpool, ...idle];
57
- appendSpool(all.map((b) => burstToEvent(b)));
62
+ appendSpool(all.map((b) => burstToEvent(settle(b))));
58
63
  return idle.length;
59
64
  }
65
+ /**
66
+ * (c) A burst whose folder stayed unresolved (catch-all or not git) goes to the real repo holding most of its touched
67
+ * files; its files become relative to that repo. Otherwise it keeps the folder.
68
+ */
69
+ export function settle(b, deps = {}) {
70
+ if (!b.open || !b.repo)
71
+ return b;
72
+ const folder = b.repo;
73
+ const repo = repoOfFiles(folder, b.files, deps);
74
+ if (!repo)
75
+ return b;
76
+ const files = b.files.map((f) => {
77
+ const abs = f.startsWith("/") ? f : join(folder, f);
78
+ return abs.startsWith(`${repo}/`) ? abs.slice(repo.length + 1) : abs;
79
+ });
80
+ const { open: _open, ...rest } = b;
81
+ return { ...rest, repo, files, cwd: b.cwd ?? folder, via: "files" };
82
+ }
package/dist/cli.js CHANGED
@@ -1,21 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
- import { appendFileSync } from "node:fs";
3
+ import { appendFileSync, existsSync } 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";
7
7
  import { installedCodingAgents, registerCodingAgents } from "./agents.js";
8
- import { openBursts, recordCall, spoolIdle } from "./bursts.js";
8
+ import { currentBurst, openBursts, recordCall, spoolIdle } from "./bursts.js";
9
9
  import { configPath, loadConfig } from "./config.js";
10
- import { ask, claudeInstalled, connectClaude, detectAuthorEmails, detectRepoRoots, gitEmail, mergeConfig, pair, readJson, say, writeConfig, } from "./connect.js";
11
- import { authorWarning, findRepos, mainRepoPath, scanRepos } from "./git.js";
10
+ import { ask, claudeInstalled, connectClaude, detectAuthorEmails, detectRepoRoots, gitEmail, mergeConfig, pair, readJson, say, upgradeClaudeHooks, writeConfig, } from "./connect.js";
11
+ import { authorWarning, findRepos, scanRepos } from "./git.js";
12
12
  import { callFromInput, isHookAgent } from "./hook.js";
13
13
  import { ingest } from "./ingest.js";
14
14
  import { runMcp } from "./mcp.js";
15
+ import { knownRepos, resolveCwd } from "./resolve.js";
15
16
  import { installedPlist, installSchedule, scheduleInstalled, uninstallSchedule } from "./schedule.js";
16
17
  import { flushSpool, spoolSize } from "./spool.js";
17
- import { ensureStateDir, readLastScan, stateDir, writeLastScan } from "./state.js";
18
+ import { ensureStateDir, readLastScan, stateDir, writeAtomic, writeLastScan } from "./state.js";
18
19
  import { openTasks } from "./tasks.js";
20
+ import { scanTranscripts } from "./transcripts.js";
19
21
  const USAGE = `usage:
20
22
  lastweek connect <CODE> --server <url> [--name <device>] [--yes] [--no-agents] [--no-schedule] [--no-scan]
21
23
  set everything up with a code from the web app's setup tour
@@ -84,18 +86,33 @@ async function readStdin(timeoutMs = 2000) {
84
86
  /** Collect git evidence since `since`, send it with the spool, remember the scan. Shared by scan and connect. */
85
87
  async function runScan(cfg, since) {
86
88
  const startedAt = new Date().toISOString();
89
+ // Installed hooks follow the CLI version without the user re-running `lastweek agents` (never installs them).
90
+ try {
91
+ if (upgradeClaudeHooks())
92
+ console.error("Claude Code hooks updated: every tool call now counts.");
93
+ }
94
+ catch {
95
+ // a settings file we can't write: the old hooks keep working
96
+ }
87
97
  const repos = findRepos(cfg.repoRoots);
88
98
  const stats = { commits: 0, matched: 0 };
89
99
  const events = scanRepos(repos, cfg.authorEmails, since, stats, cfg.agentEmails);
90
100
  const warning = authorWarning(stats);
91
101
  if (warning)
92
102
  console.error(warning);
103
+ // Claude Code's session logs (Phase 32a); the first time, the last 30 days (what Claude Code keeps by default).
104
+ const marker = join(stateDir(), "transcripts_backfilled");
105
+ const backfilled = existsSync(marker);
106
+ const sessions = scanTranscripts(backfilled ? since : new Date(Date.now() - 30 * 86400e3).toISOString(), Date.now(), homedir(), { knownRepos });
107
+ events.push(...sessions);
93
108
  // Hook/MCP events waiting in the spool go out with every scan (and with the scheduled one).
94
109
  const spooled = await flushNow();
95
110
  if (spooled.failed)
96
111
  console.error(`spool: ${spooled.failed} events kept for later (${spooled.error})`);
97
112
  const r = await ingest(cfg, events);
98
113
  writeLastScan(startedAt);
114
+ if (!backfilled)
115
+ writeAtomic(marker, `${startedAt}\n`);
99
116
  return { repos: repos.length, events: events.length, since, ...r, spoolSent: spooled.sent };
100
117
  }
101
118
  /** The setup tour's one command. Every step explains itself; nothing secret is printed. */
@@ -273,8 +290,20 @@ async function main() {
273
290
  const agent = isHookAgent(named) ? named : "claude-code";
274
291
  const raw = await readStdin();
275
292
  const input = (raw.trim() ? JSON.parse(raw) : {});
276
- const repo = typeof input.cwd === "string" && input.cwd ? mainRepoPath(input.cwd) : null;
277
- recordCall(callFromInput(input, repo, agent), Date.now());
293
+ const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : null;
294
+ // Resolved once per working folder: later calls of the session's burst reuse it (no git calls per tool use).
295
+ const prev = cwd ? currentBurst(callFromInput(input, null, agent).session) : null;
296
+ const r = !cwd
297
+ ? null
298
+ : prev?.cwd === cwd && prev.repo
299
+ ? { repo: prev.repo, via: prev.via, open: prev.open }
300
+ : resolveCwd(cwd, { knownRepos });
301
+ recordCall({
302
+ ...callFromInput(input, r?.repo ?? null, agent),
303
+ ...(cwd ? { cwd } : {}),
304
+ ...(r?.via ? { via: r.via } : {}),
305
+ ...(r?.open ? { open: true } : {}),
306
+ }, Date.now());
278
307
  if (spoolSize() > 0)
279
308
  flushInBackground();
280
309
  }
package/dist/connect.js CHANGED
@@ -66,7 +66,10 @@ export function detectAuthorEmails(repos, gitEmail) {
66
66
  export const HOOK_COMMAND = "lastweek log 2>/dev/null || true";
67
67
  /** Exactly the hook command earlier versions wrote. */
68
68
  const LEGACY_HOOK = /^\s*rewind log(\s+2>\/dev\/null)?(\s*\|\|\s*true)?\s*$/;
69
- const EDIT_MATCHER = "Edit|Write|MultiEdit|NotebookEdit";
69
+ /** Every tool call counts as agent activity (Bash, Read, test runs), not only edits: long runs without an edit no
70
+ * longer look like a pause. Installs from before 0.x matched edits only and are upgraded in place. */
71
+ const ALL_TOOLS = "*";
72
+ const LEGACY_MATCHER = "Edit|Write|MultiEdit|NotebookEdit";
70
73
  /** Adds lastweek's hooks to Claude Code settings without touching anything else; idempotent. */
71
74
  export function mergeClaudeHooks(settings) {
72
75
  const next = structuredClone(settings);
@@ -100,6 +103,13 @@ export function mergeClaudeHooks(settings) {
100
103
  .filter((e) => e !== null);
101
104
  hooks[event] = next;
102
105
  }
106
+ // Our PostToolUse hook from before every tool counted: widen it (a matcher the user changed is left alone).
107
+ for (const e of hooks.PostToolUse ?? []) {
108
+ if (e.matcher === LEGACY_MATCHER && (e.hooks ?? []).some((h) => h.command === HOOK_COMMAND)) {
109
+ e.matcher = ALL_TOOLS;
110
+ changed = true;
111
+ }
112
+ }
103
113
  const has = (event) => (hooks[event] ?? []).some((e) => (e.hooks ?? []).some((h) => /\b(lastweek|rewind) log\b/.test(h.command ?? "")));
104
114
  const add = (event, entry) => {
105
115
  if (has(event))
@@ -107,7 +117,7 @@ export function mergeClaudeHooks(settings) {
107
117
  hooks[event] = [...(hooks[event] ?? []), entry];
108
118
  changed = true;
109
119
  };
110
- add("PostToolUse", { matcher: EDIT_MATCHER, hooks: [{ type: "command", command: HOOK_COMMAND }] });
120
+ add("PostToolUse", { matcher: ALL_TOOLS, hooks: [{ type: "command", command: HOOK_COMMAND }] });
111
121
  add("UserPromptSubmit", { hooks: [{ type: "command", command: HOOK_COMMAND }] });
112
122
  return { settings: next, changed };
113
123
  }
@@ -269,6 +279,23 @@ export function readJson(path) {
269
279
  return null;
270
280
  }
271
281
  }
282
+ /** Background upgrade (scan): rewrites lastweek's Claude Code hooks to the current form, only where they are
283
+ * already installed (never installs them). Backup and unreadable-file rules as in connectClaude. */
284
+ export function upgradeClaudeHooks(home = homedir()) {
285
+ const path = join(home, ".claude", "settings.json");
286
+ const current = existsSync(path) ? readJson(path) : null;
287
+ if (!current || typeof current !== "object" || Array.isArray(current))
288
+ return false;
289
+ const ours = (current.hooks?.PostToolUse ?? []).some((e) => (e.hooks ?? []).some((h) => h.command === HOOK_COMMAND));
290
+ if (!ours)
291
+ return false;
292
+ const { settings, changed } = mergeClaudeHooks(current);
293
+ if (!changed)
294
+ return false;
295
+ backup(path);
296
+ writeFileSync(path, `${JSON.stringify(settings, null, 2)}\n`);
297
+ return true;
298
+ }
272
299
  /**
273
300
  * Claude Code: hooks in ~/.claude/settings.json and the MCP server via the `claude` CLI. A settings file that exists
274
301
  * but can't be parsed is never touched; the first backup (.bak-lastweek) is never overwritten, later ones get a stamp.
package/dist/git.js CHANGED
@@ -9,14 +9,18 @@ function git(repo, args) {
9
9
  return "";
10
10
  }
11
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();
12
+ /** Main worktree path for any worktree of the repo `path` lies in, or null outside git. */
13
+ export function gitMainRoot(path) {
14
+ const common = git(path, ["rev-parse", "--path-format=absolute", "--git-common-dir"]).trim();
15
15
  if (common && basename(common) === ".git")
16
16
  return dirname(common);
17
17
  // Submodules and unusual layouts keep their git dir elsewhere; use the checkout itself.
18
- return git(repo, ["rev-parse", "--show-toplevel"]).trim() || repo;
18
+ return git(path, ["rev-parse", "--show-toplevel"]).trim() || null;
19
19
  }
20
+ /** Main worktree path for any worktree of a repo (worktrees share one common .git dir); outside git the path itself. */
21
+ export const mainRepoPath = (repo) => gitMainRoot(repo) ?? repo;
22
+ /** The URL of a repo's `origin` remote, or null. */
23
+ export const originUrl = (repo) => git(repo, ["remote", "get-url", "origin"]).trim() || null;
20
24
  /** Find git repos up to `depth` below each root. Worktrees are discovered via `git worktree list`. */
21
25
  export function findRepos(roots, depth = 3, warn = console.warn) {
22
26
  const out = new Set();
package/dist/hook.js CHANGED
@@ -35,6 +35,7 @@ export function callFromInput(input, repo, agent = "claude-code") {
35
35
  export function applyCall(current, call, now) {
36
36
  const continues = current !== null &&
37
37
  current.repo === call.repo &&
38
+ current.cwd === call.cwd &&
38
39
  now - current.last <= GAP_MS &&
39
40
  now - current.start < MAX_BURST_MS &&
40
41
  now >= current.last;
@@ -44,6 +45,9 @@ export function applyCall(current, call, now) {
44
45
  session: call.session,
45
46
  ...(call.agent ? { agent: call.agent } : {}),
46
47
  repo: call.repo,
48
+ ...(call.cwd ? { cwd: call.cwd } : {}),
49
+ ...(call.via ? { via: call.via } : {}),
50
+ ...(call.open ? { open: true } : {}),
47
51
  start: now,
48
52
  last: now,
49
53
  count: 0,
@@ -76,7 +80,16 @@ export function burstToEvent(b) {
76
80
  ended_at: b.last > b.start ? new Date(b.last).toISOString() : undefined,
77
81
  repo: b.repo ?? undefined,
78
82
  summary: `${HOOK_AGENTS[agent]}: ${b.count} ${b.count === 1 ? "Aktion" : "Aktionen"} (${tools})${b.files.length ? ` · ${b.files.length} ${b.files.length === 1 ? "Datei" : "Dateien"}` : ""}`,
79
- payload: { kind: "hook", agent, session: b.session, count: b.count, tools: b.tools, files: b.files },
83
+ payload: {
84
+ kind: "hook",
85
+ agent,
86
+ session: b.session,
87
+ count: b.count,
88
+ tools: b.tools,
89
+ files: b.files,
90
+ // Traceability: the folder the agent actually ran in, when the repo was resolved from it.
91
+ ...(b.via && b.cwd ? { cwd: b.cwd, resolved_by: b.via } : {}),
92
+ },
80
93
  dedupe_key: `hook:${b.session}:${start}`,
81
94
  };
82
95
  }
package/dist/mcp.js CHANGED
@@ -4,8 +4,8 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
4
4
  import { z } from "zod";
5
5
  import { agentFromClient } from "./agents.js";
6
6
  import { loadConfig } from "./config.js";
7
- import { mainRepoPath } from "./git.js";
8
7
  import { ingest } from "./ingest.js";
8
+ import { knownRepos, resolveCwd } from "./resolve.js";
9
9
  import { appendSpool, flushSpool } from "./spool.js";
10
10
  import { endTask, intervalProblem, startTask } from "./tasks.js";
11
11
  /** The published version (src/ and dist/ both sit next to package.json). */
@@ -20,7 +20,13 @@ export async function runMcp() {
20
20
  const server = new McpServer({ name: "lastweek", version: VERSION });
21
21
  // An explicit env name wins; otherwise the client's own name from the initialize request (clientInfo.name).
22
22
  const agentName = () => configured ?? agentFromClient(server.server.getClientVersion()?.name) ?? "unknown";
23
- const repoOf = (repo) => (repo ? mainRepoPath(repo) : undefined);
23
+ // The folder a model names may be a catch-all one (home, temp): resolved like the hook's working folder.
24
+ const resolve = (repo) => {
25
+ if (!repo)
26
+ return { repo: undefined, trace: {} };
27
+ const r = resolveCwd(repo, { knownRepos });
28
+ return { repo: r.repo, trace: r.via ? { cwd: repo, resolved_by: r.via } : {} };
29
+ };
24
30
  const flush = async () => {
25
31
  const r = await flushSpool((events) => ingest(cfg, events));
26
32
  if (r.rejected)
@@ -37,7 +43,7 @@ export async function runMcp() {
37
43
  const problem = intervalProblem(started_at ?? at, at, new Date());
38
44
  if (problem)
39
45
  return { content: [{ type: "text", text: `not logged: ${problem}` }], isError: true };
40
- const r = repoOf(repo);
46
+ const { repo: r, trace } = resolve(repo);
41
47
  appendSpool([
42
48
  {
43
49
  source: "mcp",
@@ -45,7 +51,7 @@ export async function runMcp() {
45
51
  ended_at: started_at && started_at !== at ? at : undefined,
46
52
  repo: r,
47
53
  summary,
48
- payload: { kind: "activity", agent: agentName() },
54
+ payload: { kind: "activity", agent: agentName(), ...trace },
49
55
  dedupe_key: `mcp:${r ?? "-"}:${at}:${summary.slice(0, 40)}`,
50
56
  },
51
57
  ]);
@@ -55,7 +61,7 @@ export async function runMcp() {
55
61
  summary: z.string().describe("What you are about to do, one line, in the user's language."),
56
62
  repo: z.string().optional().describe("Absolute repo path if known"),
57
63
  }, async ({ summary, repo }) => {
58
- const t = startTask(summary, repoOf(repo), new Date(), agentName());
64
+ const t = startTask(summary, resolve(repo).repo, new Date(), agentName());
59
65
  return { content: [{ type: "text", text: `task ${t.id} started` }] };
60
66
  });
61
67
  server.tool("end_task", "Mark the end of a task started with start_task (the most recent one if no id is given).", {
@@ -0,0 +1,152 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join } from "node:path";
4
+ import { loadConfig } from "./config.js";
5
+ import { findRepos, gitMainRoot, originUrl } from "./git.js";
6
+ /**
7
+ * Catch-all folders (2026-12-01): a coding agent started in the home folder itself or in a temp folder (/tmp, macOS's
8
+ * /var/folders, and everything below them) says nothing about the client. The server treats them as "no repo"
9
+ * (packages/engine/src/catchall.ts holds the same list). Temp folders are often gone later, so the real repo is
10
+ * resolved here, at capture time: a Claude Code scratchpad's project, a temp clone's remote, or the touched files.
11
+ */
12
+ const TEMP = /^(?:\/private)?\/(?:tmp|var\/folders)(?:\/|$)/i;
13
+ export const isCatchAllPath = (path, home = homedir()) => {
14
+ const p = path.replace(/\/+$/, "") || "/";
15
+ return p === home.replace(/\/+$/, "") || TEMP.test(p);
16
+ };
17
+ /** Repos under the configured roots, for matching a temp clone's remote; none without a readable config. */
18
+ export function knownRepos() {
19
+ try {
20
+ return findRepos(loadConfig().repoRoots, 3, () => { });
21
+ }
22
+ catch {
23
+ return [];
24
+ }
25
+ }
26
+ const catchAllOf = (deps) => deps.isCatchAll ?? ((p) => isCatchAllPath(p, deps.home));
27
+ /**
28
+ * A git remote URL as a stable key: host and path, lower case, without user, password, port or ".git"
29
+ * (`git@github.com:Org/Name.git` and `https://token@github.com/org/name` are both `github.com/org/name`).
30
+ */
31
+ export function remoteKey(url) {
32
+ const u = url.trim();
33
+ let host = "";
34
+ let path = "";
35
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(u)) {
36
+ try {
37
+ const parsed = new URL(u);
38
+ host = parsed.hostname;
39
+ path = parsed.pathname;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ else {
46
+ const scp = u.match(/^(?:[^@/]+@)?([^:/]+):(?!\/)(.+)$/); // git@host:org/name
47
+ if (!scp)
48
+ return null;
49
+ [, host, path] = scp;
50
+ }
51
+ path = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
52
+ return host && path ? `${host}/${path}`.toLowerCase() : null;
53
+ }
54
+ const encode = (name) => `-${name.replace(/[^A-Za-z0-9]/g, "-")}`;
55
+ /**
56
+ * Claude Code keeps a session's scratchpad in /tmp/claude-<uid>/<project>/<session>/scratchpad, where <project> is
57
+ * the project folder with every non-alphanumeric character turned into "-". That is ambiguous ("new-kars" or
58
+ * "new/kars"), so it is decoded against the folders that exist: longest name first.
59
+ */
60
+ export function scratchpadProject(cwd, root = "/") {
61
+ const m = cwd.match(/\/claude-\d+\/(-[^/]+)(?:\/|$)/);
62
+ if (!m)
63
+ return null;
64
+ const walk = (dir, rest, depth) => {
65
+ if (depth > 40)
66
+ return null;
67
+ let names;
68
+ try {
69
+ names = readdirSync(dir);
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ const fits = names
75
+ .map((n) => [n, encode(n)])
76
+ .filter(([, e]) => rest === e || rest.startsWith(`${e}-`))
77
+ .sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
78
+ for (const [name, e] of fits) {
79
+ const p = join(dir, name);
80
+ try {
81
+ if (!statSync(p).isDirectory())
82
+ continue;
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ const found = rest === e ? p : walk(p, rest.slice(e.length), depth + 1);
88
+ if (found)
89
+ return found;
90
+ }
91
+ return null;
92
+ };
93
+ return walk(root, m[1], 0);
94
+ }
95
+ /**
96
+ * The repo an agent's working folder stands for. A real repo resolves to its main worktree as before. A catch-all or
97
+ * non-git folder, in this order: (a) a Claude Code scratchpad → its project's repo; (b) a git clone in a temp folder →
98
+ * the known local repo with the same origin, else the remote itself (`git:github.com/org/name`); else the folder
99
+ * stays, marked open so the touched files can decide later (`repoOfFiles`).
100
+ */
101
+ export function resolveCwd(cwd, deps = {}) {
102
+ const catchAll = catchAllOf(deps);
103
+ const root = gitMainRoot(cwd);
104
+ if (root && !catchAll(root))
105
+ return { repo: root };
106
+ const project = scratchpadProject(cwd);
107
+ if (project) {
108
+ const repo = gitMainRoot(project) ?? project;
109
+ if (!catchAll(repo))
110
+ return { repo, via: "scratchpad" };
111
+ }
112
+ // A repo in the home folder itself (dotfiles) is not a clone of a client's repo: only temp clones count.
113
+ const home = (deps.home ?? homedir()).replace(/\/+$/, "");
114
+ const url = root && root !== home ? originUrl(root) : null;
115
+ if (url) {
116
+ // Cloned from a local path: that repo, if it is a real one.
117
+ const local = isAbsolute(url) && existsSync(url) ? gitMainRoot(url) : null;
118
+ if (local && !catchAll(local))
119
+ return { repo: local, via: "remote" };
120
+ const key = remoteKey(url);
121
+ if (key) {
122
+ const known = (deps.knownRepos?.() ?? []).find((r) => {
123
+ if (catchAll(r))
124
+ return false;
125
+ const u = originUrl(r);
126
+ return u !== null && remoteKey(u) === key;
127
+ });
128
+ return { repo: known ? (gitMainRoot(known) ?? known) : `git:${key}`, via: "remote" };
129
+ }
130
+ }
131
+ return { repo: root ?? cwd, open: true };
132
+ }
133
+ /**
134
+ * (c) The real repo most touched files lie in, when it holds more than half of them; else null. Relative files are
135
+ * relative to `folder` (the open working folder).
136
+ */
137
+ export function repoOfFiles(folder, files, deps = {}) {
138
+ if (files.length === 0)
139
+ return null;
140
+ const catchAll = catchAllOf(deps);
141
+ const counts = new Map();
142
+ for (const f of files) {
143
+ let dir = dirname(isAbsolute(f) ? f : join(folder, f));
144
+ while (!existsSync(dir) && dir !== dirname(dir))
145
+ dir = dirname(dir); // the file (or its folder) may be gone
146
+ const repo = gitMainRoot(dir);
147
+ if (repo && !catchAll(repo))
148
+ counts.set(repo, (counts.get(repo) ?? 0) + 1);
149
+ }
150
+ const top = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
151
+ return top && top[1] * 2 > files.length ? top[0] : null;
152
+ }
@@ -0,0 +1,108 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { settle } from "./bursts.js";
5
+ import { applyCall, burstToEvent, callFromInput } from "./hook.js";
6
+ import { resolveCwd } from "./resolve.js";
7
+ // Phase 32a: Claude Code's own session logs as evidence. Covers sessions before the hook was installed (or while it
8
+ // only saw edits), subagents and worktrees. Read per line: timestamp, session, cwd, tool names and the file path of a
9
+ // tool call, whether a line is a prompt. Prompt text, commands and tool output are never kept or sent.
10
+ // The same burst logic and dedupe keys as the hook, so a burst the hook already sent is not sent twice.
11
+ /** Newer calls are left to the live hook (its burst may still be growing). */
12
+ export const SETTLE_MS = 20 * 60_000;
13
+ /** The calls in one log file's text (pure). */
14
+ export function callsOf(text, fromMs, toMs) {
15
+ const out = [];
16
+ for (const raw of text.split("\n")) {
17
+ if (!raw.includes('"timestamp"'))
18
+ continue;
19
+ let l;
20
+ try {
21
+ l = JSON.parse(raw);
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ const at = Date.parse(l.timestamp ?? "");
27
+ if (!(at >= fromMs && at < toMs) || !l.sessionId || !l.cwd || l.isMeta)
28
+ continue;
29
+ // Subagents run beside the main thread (often in their own worktree): their own burst stream.
30
+ const key = `${l.sessionId}:${l.agentId ?? "main"}`;
31
+ const base = { session_id: l.sessionId, cwd: l.cwd };
32
+ const content = l.message?.content;
33
+ if (l.type === "assistant" && Array.isArray(content)) {
34
+ for (const c of content)
35
+ if (c?.type === "tool_use" && c.name)
36
+ out.push({ at, key, input: { ...base, tool_name: c.name, tool_input: c.input } });
37
+ }
38
+ else if (l.type === "user" && l.message?.role === "user") {
39
+ // A typed prompt: plain text, not a tool result handed back to the model.
40
+ const toolResult = Array.isArray(content) && content.some((c) => c?.type === "tool_result");
41
+ if (!toolResult)
42
+ out.push({ at, key, input: { ...base, tool_name: "UserPromptSubmit" } });
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+ /** Calls → finished bursts → events (pure apart from `resolve`). */
48
+ export function eventsOf(calls, resolve) {
49
+ const byKey = new Map();
50
+ for (const c of calls)
51
+ byKey.set(c.key, [...(byKey.get(c.key) ?? []), c]);
52
+ const cache = new Map();
53
+ const repoOf = (cwd) => cache.get(cwd) ?? cache.set(cwd, resolve(cwd)).get(cwd);
54
+ const events = [];
55
+ for (const list of byKey.values()) {
56
+ list.sort((a, b) => a.at - b.at);
57
+ let current = null;
58
+ const finish = (b) => {
59
+ if (b)
60
+ events.push(burstToEvent(settle(b)));
61
+ };
62
+ for (const c of list) {
63
+ const r = repoOf(c.input.cwd);
64
+ const call = {
65
+ ...callFromInput(c.input, r.repo),
66
+ cwd: c.input.cwd,
67
+ ...(r.via ? { via: r.via } : {}),
68
+ ...(r.open ? { open: true } : {}),
69
+ };
70
+ const { burst, done } = applyCall(current, call, c.at);
71
+ finish(done);
72
+ current = burst;
73
+ }
74
+ finish(current);
75
+ }
76
+ return events;
77
+ }
78
+ /** Claude Code session logs changed since `since`, as evidence events. Never throws: no logs means no events. */
79
+ export function scanTranscripts(since, now = Date.now(), home = homedir(), deps = {}) {
80
+ const root = join(home, ".claude", "projects");
81
+ if (!existsSync(root))
82
+ return [];
83
+ // shortcut: a burst crossing the window's start is cut there (an extra, overlapping event; the engine merges
84
+ // overlaps, hours don't change). Exact would need the previous scan's open bursts.
85
+ // From SETTLE_MS before `since`: what the previous scan left to the hook is read now (dedupe keeps it single).
86
+ const fromMs = Date.parse(since) - SETTLE_MS;
87
+ const toMs = now - SETTLE_MS;
88
+ const calls = [];
89
+ try {
90
+ for (const rel of readdirSync(root, { recursive: true, encoding: "utf8" })) {
91
+ if (!rel.endsWith(".jsonl"))
92
+ continue;
93
+ const path = join(root, rel);
94
+ try {
95
+ if (statSync(path).mtimeMs < fromMs)
96
+ continue; // untouched since the last scan
97
+ calls.push(...callsOf(readFileSync(path, "utf8"), fromMs, toMs));
98
+ }
99
+ catch {
100
+ // a log being rotated or unreadable: skip it
101
+ }
102
+ }
103
+ }
104
+ catch {
105
+ return [];
106
+ }
107
+ return eventsOf(calls, (cwd) => resolveCwd(cwd, deps));
108
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lastweek-work/cli",
3
- "version": "0.3.2",
3
+ "version": "0.3.5",
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",