@lastweek-work/cli 0.3.0 → 0.3.2

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/dist/bursts.js CHANGED
@@ -1,8 +1,8 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
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
4
  import { appendSpool } from "./spool.js";
5
- import { stateDir } from "./state.js";
5
+ import { ensureStateDir, stateDir, writeAtomic } 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`);
@@ -19,6 +19,17 @@ export function openBursts() {
19
19
  return [];
20
20
  const out = [];
21
21
  for (const f of readdirSync(dir())) {
22
+ if (!f.endsWith(".json")) {
23
+ // Another process's temp file mid-write, or one a killed process left: the latter goes after 5 minutes.
24
+ try {
25
+ if (Date.now() - statSync(join(dir(), f)).mtimeMs > 5 * 60_000)
26
+ rmSync(join(dir(), f), { force: true });
27
+ }
28
+ catch {
29
+ // renamed or removed meanwhile
30
+ }
31
+ continue;
32
+ }
22
33
  try {
23
34
  out.push(JSON.parse(readFileSync(join(dir(), f), "utf8")));
24
35
  }
@@ -30,9 +41,10 @@ export function openBursts() {
30
41
  }
31
42
  /** Records one hook call; spools whatever bursts it finished (its own previous one, and idle ones of other sessions). */
32
43
  export function recordCall(call, now) {
44
+ ensureStateDir();
33
45
  mkdirSync(dir(), { recursive: true });
34
46
  const { burst, done } = applyCall(load(call.session), call, now);
35
- writeFileSync(file(call.session), JSON.stringify(burst));
47
+ writeAtomic(file(call.session), JSON.stringify(burst));
36
48
  const finished = done ? [done] : [];
37
49
  return { spooled: finished.length + spoolIdle(now, call.session, finished) };
38
50
  }
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";
@@ -14,7 +14,7 @@ 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]
@@ -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
  }
@@ -250,6 +256,7 @@ async function main() {
250
256
  }
251
257
  const r = await runScan(cfg, resolveSince(values.since ?? positionals[0]));
252
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})` : "") +
253
260
  (r.spoolSent ? `; spool sent ${r.spoolSent}` : ""));
254
261
  break;
255
262
  }
@@ -281,7 +288,7 @@ async function main() {
281
288
  try {
282
289
  const r = await flushNow();
283
290
  if (!quiet)
284
- 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}`);
285
292
  if (r.failed) {
286
293
  logError("flush", r.error);
287
294
  if (!quiet)
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/ingest.js CHANGED
@@ -1,7 +1,19 @@
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
+ // Reflog subjects can carry a remote URL with credentials ("pull https://user:TOKEN@host/repo",
4
+ // "https://TOKEN@host"): never send those.
5
+ const summary = e.summary?.replace(/\/\/[^\s/@]+@/g, "//"); // also token-only: https://ghp_x@github.com
6
+ return {
7
+ ...e,
8
+ ...(summary !== e.summary ? { summary } : {}),
9
+ ...(summary && summary.length > 1000 ? { summary: summary.slice(0, 1000) } : {}),
10
+ ...(e.ref && e.ref.length > 256 ? { ref: e.ref.slice(0, 256) } : {}),
11
+ };
12
+ }
1
13
  export const CHUNK_SIZE = 500; // matches the ingest function's per-request limit
2
14
  /** Posts events in chunks. Throws on the first failed chunk; earlier chunks stay ingested (dedupe makes retries safe). */
3
15
  export async function ingest(cfg, events) {
4
- const total = { inserted: 0, duplicates: 0 };
16
+ const total = { inserted: 0, duplicates: 0, rejected: 0 };
5
17
  if (events.length === 0)
6
18
  return total;
7
19
  if (!cfg.ingestUrl || !cfg.deviceToken)
@@ -10,13 +22,21 @@ export async function ingest(cfg, events) {
10
22
  const res = await fetch(cfg.ingestUrl, {
11
23
  method: "POST",
12
24
  headers: { "content-type": "application/json", authorization: `Bearer ${cfg.deviceToken}` },
13
- body: JSON.stringify({ events: events.slice(i, i + CHUNK_SIZE) }),
25
+ // Only the ingest URL itself: a redirect could carry the evidence elsewhere. A hung server mustn't hang hooks.
26
+ redirect: "error",
27
+ signal: AbortSignal.timeout(30_000),
28
+ body: JSON.stringify({ events: events.slice(i, i + CHUNK_SIZE).map(clip) }),
14
29
  });
15
30
  if (!res.ok)
16
31
  throw new Error(`ingest failed: ${res.status} ${await res.text()}`);
17
32
  const r = (await res.json());
18
33
  total.inserted += r.inserted;
19
34
  total.duplicates += r.duplicates;
35
+ if (r.rejected) {
36
+ total.rejected = (total.rejected ?? 0) + r.rejected;
37
+ const i = r.issues?.[0];
38
+ total.reason ??= i ? `${i.path || "event"}: ${i.message}` : "refused";
39
+ }
20
40
  }
21
41
  return total;
22
42
  }
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, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, 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,52 @@ 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
+ writeAtomic(join(ensureStateDir(), "last_scan"), `${iso}\n`);
41
+ }
42
+ /**
43
+ * Replaces a file in one step (write a temp file, then rename): a reader in another hook or MCP process sees the old
44
+ * content or the new one, never half a file. Temp names end in ".tmp" so folder listings can skip them.
45
+ */
46
+ export function writeAtomic(path, content) {
47
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
48
+ try {
49
+ writeFileSync(tmp, content);
50
+ renameSync(tmp, path);
51
+ }
52
+ catch (e) {
53
+ rmSync(tmp, { force: true }); // a full disk mustn't leave summaries lying around
54
+ throw e;
55
+ }
56
+ }
57
+ /**
58
+ * Runs `fn` while holding `<path>.lock` (exclusive create), so read-change-write of one file by several processes
59
+ * (one MCP server per coding session) loses nobody's change. A lock older than 10 s belongs to a process that died.
60
+ */
61
+ export function withFileLock(path, fn) {
62
+ const lock = `${path}.lock`;
63
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
64
+ for (let tries = 0;; tries++) {
65
+ try {
66
+ closeSync(openSync(lock, "wx"));
67
+ break;
68
+ }
69
+ catch {
70
+ try {
71
+ if (Date.now() - statSync(lock).mtimeMs > 10_000)
72
+ rmSync(lock, { force: true });
73
+ }
74
+ catch {
75
+ // gone meanwhile: try again
76
+ }
77
+ if (tries > 200)
78
+ throw new Error("state file busy");
79
+ sleep(10);
80
+ }
81
+ }
82
+ try {
83
+ return fn();
84
+ }
85
+ finally {
86
+ rmSync(lock, { force: true });
87
+ }
27
88
  }
package/dist/tasks.js CHANGED
@@ -1,16 +1,32 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { stateDir } from "./state.js";
4
+ import { ensureStateDir, stateDir, withFileLock, writeAtomic } 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 });
9
- writeFileSync(path(), JSON.stringify(tasks, null, 2));
23
+ ensureStateDir();
24
+ writeAtomic(path(), JSON.stringify(tasks, null, 2));
10
25
  };
11
26
  export function startTask(summary, repo, now, agent) {
12
27
  const task = { id: randomUUID().slice(0, 8), summary, repo, started_at: now.toISOString(), agent };
13
- write([...read(), task]);
28
+ ensureStateDir();
29
+ withFileLock(path(), () => write([...read(), task])); // two sessions starting at once both keep their task
14
30
  return task;
15
31
  }
16
32
  export function openTasks() {
@@ -21,11 +37,16 @@ export function openTasks() {
21
37
  * The summary given at the end, if any, replaces the one from the start ("outcome, not intent").
22
38
  */
23
39
  export function endTask(id, summary, now) {
24
- const tasks = read();
25
- const task = id ? tasks.find((t) => t.id === id) : tasks.at(-1);
40
+ ensureStateDir();
41
+ const task = withFileLock(path(), () => {
42
+ const tasks = read();
43
+ const t = id ? tasks.find((x) => x.id === id) : tasks.at(-1);
44
+ if (t)
45
+ write(tasks.filter((x) => x !== t));
46
+ return t;
47
+ });
26
48
  if (!task)
27
49
  return null;
28
- write(tasks.filter((t) => t !== task));
29
50
  const end = now.toISOString();
30
51
  return {
31
52
  source: "mcp",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lastweek-work/cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
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",