@moberg_hr/work-tree 1.8.5 → 1.9.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/dist/wd-bin.js CHANGED
@@ -1462,6 +1462,9 @@ function latestJsonlMtimeMs(projectDir) {
1462
1462
  }
1463
1463
  return latest;
1464
1464
  }
1465
+ function claudeActiveWithin(activityMs, nowMs, windowMs) {
1466
+ return activityMs > 0 && nowMs - activityMs < windowMs;
1467
+ }
1465
1468
  function getClaudeActivityMs(launchPath) {
1466
1469
  const dir = path9.join(
1467
1470
  os4.homedir(),
@@ -7683,7 +7686,7 @@ function createCommentStore() {
7683
7686
  }
7684
7687
  const parent = findParent2(input2.parentId);
7685
7688
  const side = input2.side ?? parent?.side ?? "general";
7686
- if (side !== "left" && side !== "right" && side !== "general") {
7689
+ if (side !== "left" && side !== "right" && side !== "general" && side !== "file") {
7687
7690
  throw new Error("invalid side");
7688
7691
  }
7689
7692
  const c = {
@@ -7708,6 +7711,14 @@ function createCommentStore() {
7708
7711
  comments.splice(idx, 1);
7709
7712
  return true;
7710
7713
  },
7714
+ setResolved(id, resolved) {
7715
+ const c = comments.find((x) => x.id === id);
7716
+ if (!c) return null;
7717
+ const next = resolved || void 0;
7718
+ if (c.resolved === next) return null;
7719
+ c.resolved = next;
7720
+ return c;
7721
+ },
7711
7722
  submit(summary) {
7712
7723
  const drafts = comments.filter((c) => c.status === "draft").sort((a, b) => a.createdAt.localeCompare(b.createdAt));
7713
7724
  let summaryComment = null;
@@ -8096,7 +8107,7 @@ var commentInputSchema = z.object({
8096
8107
  repo: z.string().optional(),
8097
8108
  file: z.string().optional(),
8098
8109
  line: z.number().int().optional(),
8099
- side: z.enum(["left", "right", "general"]).optional(),
8110
+ side: z.enum(["left", "right", "general", "file"]).optional(),
8100
8111
  body: z.string().min(1),
8101
8112
  status: z.enum(["published", "draft"]).optional(),
8102
8113
  lineContent: z.string().optional(),
@@ -8106,6 +8117,9 @@ var commentInputSchema = z.object({
8106
8117
  var submitReviewSchema = z.object({
8107
8118
  summary: z.string().optional()
8108
8119
  });
8120
+ var resolveSchema = z.object({
8121
+ resolved: z.boolean()
8122
+ });
8109
8123
 
8110
8124
  // src/core/comment-server.ts
8111
8125
  async function startCommentServer(opts) {
@@ -8142,6 +8156,18 @@ async function startCommentServer(opts) {
8142
8156
  if (removed && opts.onCommentDeleted) opts.onCommentDeleted(id);
8143
8157
  return c.json({ comments: store.snapshot() });
8144
8158
  });
8159
+ routes.post(
8160
+ "/api/comments/:id/resolve",
8161
+ zValidator("json", resolveSchema),
8162
+ (c) => {
8163
+ const updated = store.setResolved(
8164
+ c.req.param("id"),
8165
+ c.req.valid("json").resolved
8166
+ );
8167
+ if (updated) api.broadcast("comments-changed", { id: updated.id });
8168
+ return c.json({ comments: store.snapshot() });
8169
+ }
8170
+ );
8145
8171
  routes.post(
8146
8172
  "/api/submit-review",
8147
8173
  zValidator("json", submitReviewSchema),
@@ -8196,7 +8222,7 @@ async function startCommentServer(opts) {
8196
8222
  }
8197
8223
  function formatSingleComment(c) {
8198
8224
  const bodyLines = c.body.split("\n").map((l) => `> ${l}`).join("\n");
8199
- const header = c.side === "general" ? `**General review comment**` : `**${c.repo}/${c.file}** : line ${c.line} (${c.side})`;
8225
+ const header = c.side === "general" ? `**General review comment**` : c.side === "file" ? `**${c.repo}/${c.file}** : whole file` : `**${c.repo}/${c.file}** : line ${c.line} (${c.side})`;
8200
8226
  const meta = [];
8201
8227
  if (c.author === "claude") meta.push("author: claude");
8202
8228
  if (c.parentId) meta.push(`reply-to: ${c.parentId}`);
@@ -8724,13 +8750,13 @@ var diffCommand = {
8724
8750
  // src/commands/web.ts
8725
8751
  import fs41 from "fs";
8726
8752
  import os13 from "os";
8727
- import path40 from "path";
8753
+ import path41 from "path";
8728
8754
  import chalk23 from "chalk";
8729
8755
 
8730
8756
  // src/core/web-server.ts
8731
8757
  import fs40 from "fs";
8732
8758
  import os12 from "os";
8733
- import path39 from "path";
8759
+ import path40 from "path";
8734
8760
  import chalk22 from "chalk";
8735
8761
  import { Hono as Hono3 } from "hono";
8736
8762
  import { streamSSE as streamSSE3 } from "hono/streaming";
@@ -8936,6 +8962,12 @@ function getCommentFileStore(sessionId) {
8936
8962
  return { value: r, persisted: r };
8937
8963
  });
8938
8964
  },
8965
+ setResolved(id, resolved) {
8966
+ return lockedMutate(() => {
8967
+ const c = inner.setResolved(id, resolved);
8968
+ return { value: c, persisted: c !== null };
8969
+ });
8970
+ },
8939
8971
  submit(summary) {
8940
8972
  return lockedMutate(() => {
8941
8973
  const result = inner.submit(summary);
@@ -8950,6 +8982,14 @@ function getCommentFileStore(sessionId) {
8950
8982
  },
8951
8983
  reload() {
8952
8984
  reloadInner();
8985
+ },
8986
+ clearAll() {
8987
+ return lockedMutate(() => {
8988
+ const list = inner.list();
8989
+ const n = list.length;
8990
+ list.length = 0;
8991
+ return { value: n, persisted: n > 0 };
8992
+ });
8953
8993
  }
8954
8994
  };
8955
8995
  cache.set(sessionId, store);
@@ -9169,6 +9209,21 @@ function mountSessionCommentRoutes(app, opts) {
9169
9209
  if (removed) opts.broadcast("comments-changed", { sessionId: id, deleted: cid });
9170
9210
  return c.json({ comments: store.snapshot() });
9171
9211
  });
9212
+ app.post(
9213
+ "/api/sessions/:id/comments/:cid/resolve",
9214
+ zValidator2("json", resolveSchema),
9215
+ (c) => {
9216
+ const id = c.req.param("id");
9217
+ if (!requireSession(id)) return c.json({ error: "unknown session" }, 404);
9218
+ const store = getCommentFileStore(id);
9219
+ const updated = store.setResolved(
9220
+ c.req.param("cid"),
9221
+ c.req.valid("json").resolved
9222
+ );
9223
+ if (updated) opts.broadcast("comments-changed", { sessionId: id, id: updated.id });
9224
+ return c.json({ comments: store.snapshot() });
9225
+ }
9226
+ );
9172
9227
  app.post(
9173
9228
  "/api/sessions/:id/submit-review",
9174
9229
  zValidator2("json", submitReviewSchema),
@@ -9480,8 +9535,8 @@ function mountWorktreeRoutes(app, opts) {
9480
9535
  import { zValidator as zValidator5 } from "@hono/zod-validator";
9481
9536
  import { z as z4 } from "zod";
9482
9537
  import { EventEmitter } from "events";
9483
- import path38 from "path";
9484
- import spawn13 from "cross-spawn";
9538
+ import path39 from "path";
9539
+ import spawn14 from "cross-spawn";
9485
9540
 
9486
9541
  // src/core/checkpoint.ts
9487
9542
  import fs39 from "fs";
@@ -9610,6 +9665,17 @@ async function takeCheckpoint(scopeHash, repos, opts = {}) {
9610
9665
  return entry;
9611
9666
  });
9612
9667
  }
9668
+ async function setCheckpointLabel(scopeHash, id, label2) {
9669
+ const file = manifestPath(scopeHash);
9670
+ ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));
9671
+ await withFileLock(file, () => {
9672
+ const manifest = loadManifest(scopeHash);
9673
+ const entry = manifest.entries.find((e) => e.id === id);
9674
+ if (!entry || entry.label === label2) return;
9675
+ entry.label = label2;
9676
+ atomicWriteFile(file, JSON.stringify(manifest, null, 2));
9677
+ });
9678
+ }
9613
9679
  function clearCheckpoints(scopeHash, repoRoots) {
9614
9680
  const manifest = loadManifest(scopeHash);
9615
9681
  for (const root of repoRoots) {
@@ -9631,8 +9697,130 @@ function clearCheckpoints(scopeHash, repoRoots) {
9631
9697
  }
9632
9698
  }
9633
9699
 
9634
- // src/core/scope-manager.ts
9700
+ // src/core/checkpoint-summary.ts
9701
+ import spawn13 from "cross-spawn";
9635
9702
  import path37 from "path";
9703
+ var MAX_DIFF_CHARS = 6e3;
9704
+ var MAX_LABEL_CHARS = 80;
9705
+ function buildDelta(scopeHash, repos, id) {
9706
+ const manifest = loadManifest(scopeHash);
9707
+ const entry = manifest.entries.find((e) => e.id === id);
9708
+ const prev = manifest.entries.find((e) => e.id === id - 1);
9709
+ const all = [];
9710
+ for (const repo of repos) {
9711
+ const toRef = entry?.repos[repo.name];
9712
+ if (!toRef) continue;
9713
+ const fromRef = prev?.repos[repo.name] ?? "HEAD";
9714
+ try {
9715
+ all.push(...computeRangeDiff({ root: repo.root, fromRef, toRef }));
9716
+ } catch {
9717
+ }
9718
+ }
9719
+ let added = 0;
9720
+ let deleted = 0;
9721
+ for (const f of all) {
9722
+ added += f.added;
9723
+ deleted += f.deleted;
9724
+ }
9725
+ const parts = [];
9726
+ let budget = MAX_DIFF_CHARS;
9727
+ for (const f of all) {
9728
+ const head = `### ${f.status} ${f.path} (+${f.added} -${f.deleted})
9729
+ `;
9730
+ if (budget - head.length < 0) break;
9731
+ parts.push(head);
9732
+ budget -= head.length;
9733
+ for (const h of f.hunks) {
9734
+ for (const ln of h.lines) {
9735
+ if (ln.kind !== "add" && ln.kind !== "delete") continue;
9736
+ const prefix = ln.kind === "add" ? "+" : "-";
9737
+ const line = `${prefix}${ln.content}
9738
+ `;
9739
+ if (budget - line.length < 0) {
9740
+ budget = -1;
9741
+ break;
9742
+ }
9743
+ parts.push(line);
9744
+ budget -= line.length;
9745
+ }
9746
+ if (budget < 0) break;
9747
+ }
9748
+ if (budget < 0) break;
9749
+ }
9750
+ return { files: all, added, deleted, text: parts.join("") };
9751
+ }
9752
+ function heuristicLabel(files, added, deleted) {
9753
+ if (files.length === 0) return "no changes";
9754
+ if (files.length === 1) {
9755
+ return `${path37.basename(files[0].path)} +${added} \u2212${deleted}`;
9756
+ }
9757
+ return `${files.length} files \xB7 +${added} \u2212${deleted}`;
9758
+ }
9759
+ function runClaude(prompt, timeoutMs = 25e3) {
9760
+ return new Promise((resolve) => {
9761
+ let settled = false;
9762
+ const finish = (v) => {
9763
+ if (settled) return;
9764
+ settled = true;
9765
+ resolve(v);
9766
+ };
9767
+ let out = "";
9768
+ let child;
9769
+ try {
9770
+ child = spawn13("claude", ["-p"], {
9771
+ stdio: ["pipe", "pipe", "ignore"],
9772
+ windowsHide: true
9773
+ });
9774
+ } catch {
9775
+ finish(null);
9776
+ return;
9777
+ }
9778
+ const timer = setTimeout(() => {
9779
+ try {
9780
+ child.kill();
9781
+ } catch {
9782
+ }
9783
+ finish(null);
9784
+ }, timeoutMs);
9785
+ child.stdout?.on("data", (d) => {
9786
+ out += d.toString();
9787
+ });
9788
+ child.on("error", () => {
9789
+ clearTimeout(timer);
9790
+ finish(null);
9791
+ });
9792
+ child.on("close", (code) => {
9793
+ clearTimeout(timer);
9794
+ finish(code === 0 && out.trim() ? out.trim() : null);
9795
+ });
9796
+ try {
9797
+ child.stdin?.write(prompt);
9798
+ child.stdin?.end();
9799
+ } catch {
9800
+ clearTimeout(timer);
9801
+ finish(null);
9802
+ }
9803
+ });
9804
+ }
9805
+ function cleanLabel(raw) {
9806
+ const firstLine = raw.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
9807
+ const cleaned = firstLine.replace(/^["'`]+|["'`]+$/g, "").replace(/\s+/g, " ").replace(/[.;]+$/, "").trim();
9808
+ return cleaned.slice(0, MAX_LABEL_CHARS);
9809
+ }
9810
+ async function summarizeCheckpoint(scopeHash, repos, id) {
9811
+ const { files, added, deleted, text } = buildDelta(scopeHash, repos, id);
9812
+ if (files.length === 0) return "no changes";
9813
+ const fallback = heuristicLabel(files, added, deleted);
9814
+ if (!text.trim()) return fallback;
9815
+ const prompt = "Summarise this code change in 8 words or fewer, imperative mood, no trailing punctuation. Output ONLY the summary line.\n\n" + text;
9816
+ const reply = await runClaude(prompt);
9817
+ if (!reply) return fallback;
9818
+ const label2 = cleanLabel(reply);
9819
+ return label2 || fallback;
9820
+ }
9821
+
9822
+ // src/core/scope-manager.ts
9823
+ import path38 from "path";
9636
9824
  import crypto5 from "crypto";
9637
9825
  var scopes = /* @__PURE__ */ new Map();
9638
9826
  function hashFor(paths) {
@@ -9649,7 +9837,7 @@ var ScopePathRejectedError = class extends Error {
9649
9837
  }
9650
9838
  };
9651
9839
  function normaliseForCompare(p) {
9652
- return path37.resolve(p).replace(/\\/g, "/").toLowerCase();
9840
+ return path38.resolve(p).replace(/\\/g, "/").toLowerCase();
9653
9841
  }
9654
9842
  function rejectedPaths(normalised) {
9655
9843
  const config = loadConfig();
@@ -9667,7 +9855,7 @@ function rejectedPaths(normalised) {
9667
9855
  });
9668
9856
  }
9669
9857
  function registerScope(paths, label2) {
9670
- const normalised = paths.map((p) => path37.resolve(p));
9858
+ const normalised = paths.map((p) => path38.resolve(p));
9671
9859
  const rejected = rejectedPaths(normalised);
9672
9860
  if (rejected.length > 0) throw new ScopePathRejectedError(rejected);
9673
9861
  const hash = hashFor(normalised);
@@ -9681,11 +9869,16 @@ function registerScope(paths, label2) {
9681
9869
  const scope = {
9682
9870
  hash,
9683
9871
  paths: normalised,
9684
- label: label2 ?? path37.basename(normalised[0]),
9872
+ label: label2 ?? path38.basename(normalised[0]),
9685
9873
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
9686
9874
  ended: false
9687
9875
  };
9688
- scopes.set(hash, { scope, watcher: null, subscribers: /* @__PURE__ */ new Set() });
9876
+ scopes.set(hash, {
9877
+ scope,
9878
+ watcher: null,
9879
+ subscribers: /* @__PURE__ */ new Set(),
9880
+ suppressWatchUntil: 0
9881
+ });
9689
9882
  return scope;
9690
9883
  }
9691
9884
  function markScopeEnded(hash) {
@@ -9695,9 +9888,29 @@ function markScopeEnded(hash) {
9695
9888
  entry.scope.ended = true;
9696
9889
  return true;
9697
9890
  }
9891
+ function reviveScope(hash) {
9892
+ const entry = scopes.get(hash);
9893
+ if (!entry || !entry.scope.ended) return false;
9894
+ entry.scope.ended = false;
9895
+ return true;
9896
+ }
9698
9897
  function getScope(hash) {
9699
9898
  return scopes.get(hash)?.scope ?? null;
9700
9899
  }
9900
+ function suppressScopeWatch(hash, ms) {
9901
+ const entry = scopes.get(hash);
9902
+ if (entry) entry.suppressWatchUntil = Date.now() + ms;
9903
+ }
9904
+ function scopeCoversCwd(paths, cwd) {
9905
+ const nc = normaliseForCompare(cwd);
9906
+ return paths.some((p) => {
9907
+ const np = normaliseForCompare(p);
9908
+ return np === nc || np.startsWith(nc + "/") || nc.startsWith(np + "/");
9909
+ });
9910
+ }
9911
+ function scopesForCwd(cwd) {
9912
+ return Array.from(scopes.values()).map((e) => e.scope).filter((s) => scopeCoversCwd(s.paths, cwd));
9913
+ }
9701
9914
  function listScopes() {
9702
9915
  return Array.from(scopes.values()).map((e) => e.scope);
9703
9916
  }
@@ -9718,6 +9931,7 @@ function subscribeScope(hash, cb) {
9718
9931
  roots: entry.scope.paths,
9719
9932
  debounceMs: 150,
9720
9933
  onChange: () => {
9934
+ if (Date.now() < entry.suppressWatchUntil) return;
9721
9935
  for (const sub of entry.subscribers) {
9722
9936
  try {
9723
9937
  sub();
@@ -9751,10 +9965,13 @@ import { streamSSE as streamSSE2 } from "hono/streaming";
9751
9965
  function mountScopeRoutes(app, opts) {
9752
9966
  const checkpointWatched = /* @__PURE__ */ new Set();
9753
9967
  const lastStatus = /* @__PURE__ */ new Map();
9968
+ const snapshotTimers = /* @__PURE__ */ new Map();
9969
+ const CHECKPOINT_SETTLE_MS = 4e3;
9970
+ const CLAUDE_SESSION_MS = 5 * 6e4;
9754
9971
  function workingTreeFingerprint(paths) {
9755
9972
  const parts = [];
9756
9973
  for (const p of paths) {
9757
- const r = spawn13.sync(
9974
+ const r = spawn14.sync(
9758
9975
  "git",
9759
9976
  ["status", "--porcelain", "--no-renames", "-z"],
9760
9977
  { cwd: p, encoding: "utf-8", windowsHide: true }
@@ -9765,6 +9982,10 @@ function mountScopeRoutes(app, opts) {
9765
9982
  }
9766
9983
  const scopeBus = new EventEmitter();
9767
9984
  scopeBus.setMaxListeners(0);
9985
+ function emitCommentsChanged(payload) {
9986
+ opts.broadcast("comments-changed", payload);
9987
+ scopeBus.emit("comments-changed", payload);
9988
+ }
9768
9989
  function scopeRepos(scopePaths) {
9769
9990
  return scopePaths.map((p) => ({ name: p, root: p }));
9770
9991
  }
@@ -9781,6 +10002,12 @@ function mountScopeRoutes(app, opts) {
9781
10002
  const { paths, label: label2 } = c.req.valid("json");
9782
10003
  try {
9783
10004
  const scope = registerScope(paths, label2);
10005
+ if (reviveScope(scope.hash)) {
10006
+ const cleared = commentStore(scope.hash).clearAll();
10007
+ if (cleared > 0) {
10008
+ emitCommentsChanged({ scopeHash: scope.hash });
10009
+ }
10010
+ }
9784
10011
  opts.broadcast("scopes-changed", { hash: scope.hash });
9785
10012
  const announceCheckpoint = (entry) => {
9786
10013
  const payload = { scopeHash: scope.hash, id: entry.id };
@@ -9796,18 +10023,32 @@ function mountScopeRoutes(app, opts) {
9796
10023
  }
9797
10024
  if (!checkpointWatched.has(scope.hash)) {
9798
10025
  checkpointWatched.add(scope.hash);
9799
- subscribeScope(scope.hash, () => {
10026
+ const hash = scope.hash;
10027
+ const runSnapshot = () => {
10028
+ snapshotTimers.delete(hash);
10029
+ const claudeMs = scope.paths.reduce(
10030
+ (m, p) => Math.max(m, getClaudeActivityMs(p)),
10031
+ 0
10032
+ );
10033
+ if (claudeActiveWithin(claudeMs, Date.now(), CLAUDE_SESSION_MS)) {
10034
+ return;
10035
+ }
9800
10036
  try {
9801
10037
  const fp = workingTreeFingerprint(scope.paths);
9802
- if (lastStatus.get(scope.hash) === fp) return;
9803
- lastStatus.set(scope.hash, fp);
10038
+ if (lastStatus.get(hash) === fp) return;
10039
+ lastStatus.set(hash, fp);
9804
10040
  } catch {
9805
10041
  }
9806
- takeCheckpoint(scope.hash, scopeRepos(scope.paths)).then((entry) => {
10042
+ takeCheckpoint(hash, scopeRepos(scope.paths)).then((entry) => {
9807
10043
  if (entry) announceCheckpoint(entry);
9808
10044
  }).catch((err) => {
9809
10045
  console.error("[checkpoint] auto-snapshot failed:", err);
9810
10046
  });
10047
+ };
10048
+ subscribeScope(hash, () => {
10049
+ const pending = snapshotTimers.get(hash);
10050
+ if (pending) clearTimeout(pending);
10051
+ snapshotTimers.set(hash, setTimeout(runSnapshot, CHECKPOINT_SETTLE_MS));
9811
10052
  });
9812
10053
  }
9813
10054
  return c.json({
@@ -9824,6 +10065,27 @@ function mountScopeRoutes(app, opts) {
9824
10065
  }
9825
10066
  );
9826
10067
  app.get("/api/scopes", (c) => c.json({ scopes: listScopes() }));
10068
+ app.post(
10069
+ "/api/checkpoint",
10070
+ zValidator5("json", z4.object({ cwd: z4.string().min(1) })),
10071
+ async (c) => {
10072
+ const { cwd } = c.req.valid("json");
10073
+ const matched = scopesForCwd(cwd);
10074
+ let snapshotted = 0;
10075
+ for (const s of matched) {
10076
+ const entry = await takeCheckpoint(s.hash, scopeRepos(s.paths)).catch(
10077
+ () => null
10078
+ );
10079
+ if (entry) {
10080
+ const payload = { scopeHash: s.hash, id: entry.id };
10081
+ opts.broadcast("checkpoints-changed", payload);
10082
+ scopeBus.emit("checkpoints-changed", payload);
10083
+ snapshotted++;
10084
+ }
10085
+ }
10086
+ return c.json({ ok: true, scopes: matched.length, snapshotted });
10087
+ }
10088
+ );
9827
10089
  app.delete("/api/scopes/:hash", (c) => {
9828
10090
  const hash = c.req.param("hash");
9829
10091
  const scope = getScope(hash);
@@ -9831,6 +10093,11 @@ function mountScopeRoutes(app, opts) {
9831
10093
  const ok = removeScope(hash);
9832
10094
  checkpointWatched.delete(hash);
9833
10095
  lastStatus.delete(hash);
10096
+ const pendingTimer = snapshotTimers.get(hash);
10097
+ if (pendingTimer) {
10098
+ clearTimeout(pendingTimer);
10099
+ snapshotTimers.delete(hash);
10100
+ }
9834
10101
  if (repoPaths.length > 0) clearCheckpoints(hash, repoPaths);
9835
10102
  if (ok) opts.broadcast("scopes-changed", { hash });
9836
10103
  return c.json({ ok });
@@ -9878,11 +10145,12 @@ function mountScopeRoutes(app, opts) {
9878
10145
  const fromSha = fromEntry.repos[p] ?? "HEAD";
9879
10146
  const toSha = toEntry === void 0 ? "working" : toEntry.repos[p] ?? "HEAD";
9880
10147
  return {
9881
- name: path38.basename(p),
10148
+ name: path39.basename(p),
9882
10149
  root: p,
9883
10150
  files: computeRangeDiff({ root: p, fromRef: fromSha, toRef: toSha })
9884
10151
  };
9885
10152
  });
10153
+ suppressScopeWatch(scope.hash, 800);
9886
10154
  return c.json({
9887
10155
  scopeHash: scope.hash,
9888
10156
  base: "uncommitted",
@@ -9896,7 +10164,7 @@ function mountScopeRoutes(app, opts) {
9896
10164
  (p) => resolveRepoDiff(p, base, sessionBaseForPath(p))
9897
10165
  );
9898
10166
  const repos = scope.paths.map((p, i) => ({
9899
- name: path38.basename(p),
10167
+ name: path39.basename(p),
9900
10168
  root: p,
9901
10169
  resolvedBase: resolved[i].resolvedBase,
9902
10170
  files: computeDiff({ root: p, diffArg: resolved[i].diffArg })
@@ -9904,6 +10172,7 @@ function mountScopeRoutes(app, opts) {
9904
10172
  const resolvedBase = resolved[0]?.resolvedBase ?? "HEAD";
9905
10173
  const head = git(["rev-parse", "--abbrev-ref", "HEAD"], scope.paths[0]);
9906
10174
  const headBranch = head.exitCode === 0 && head.stdout && head.stdout !== "HEAD" ? head.stdout : void 0;
10175
+ suppressScopeWatch(scope.hash, 800);
9907
10176
  return c.json({
9908
10177
  scopeHash: scope.hash,
9909
10178
  base,
@@ -9926,7 +10195,7 @@ function mountScopeRoutes(app, opts) {
9926
10195
  if (!relPath || !Number.isInteger(start) || !Number.isInteger(end)) {
9927
10196
  return c.json({ error: "bad path/start/end" }, 400);
9928
10197
  }
9929
- const root = scope.paths.length === 1 ? scope.paths[0] : scope.paths.find((p) => path38.basename(p) === repoName);
10198
+ const root = scope.paths.length === 1 ? scope.paths[0] : scope.paths.find((p) => path39.basename(p) === repoName);
9930
10199
  if (!root) return c.json({ error: "unknown repo" }, 404);
9931
10200
  const result = readContextLines({ root, relPath, start, end, ref });
9932
10201
  if (!result) return c.json({ error: "cannot read file" }, 400);
@@ -9941,6 +10210,22 @@ function mountScopeRoutes(app, opts) {
9941
10210
  entries: manifest.entries
9942
10211
  });
9943
10212
  });
10213
+ app.post("/api/scopes/:hash/checkpoints/:id/summary", async (c) => {
10214
+ const scope = getScope(c.req.param("hash"));
10215
+ if (!scope) return c.json({ error: "unknown scope" }, 404);
10216
+ const id = Number(c.req.param("id"));
10217
+ if (!Number.isInteger(id) || id < 0) {
10218
+ return c.json({ error: "bad checkpoint id" }, 400);
10219
+ }
10220
+ const entry = loadManifest(scope.hash).entries.find((e) => e.id === id);
10221
+ if (!entry) return c.json({ error: "unknown checkpoint" }, 404);
10222
+ if (entry.label && entry.label.trim()) return c.json({ label: entry.label });
10223
+ if (id === 0) return c.json({ label: "Initial" });
10224
+ const label2 = await summarizeCheckpoint(scope.hash, scopeRepos(scope.paths), id);
10225
+ await setCheckpointLabel(scope.hash, id, label2);
10226
+ opts.broadcast("checkpoints-changed", { scopeHash: scope.hash, id });
10227
+ return c.json({ label: label2 });
10228
+ });
9944
10229
  function commentStore(hash) {
9945
10230
  return getCommentFileStore(commentStoreIdForScope(hash));
9946
10231
  }
@@ -9961,7 +10246,7 @@ function mountScopeRoutes(app, opts) {
9961
10246
  const store = commentStore(scope.hash);
9962
10247
  try {
9963
10248
  const comment = store.post(c.req.valid("json"));
9964
- opts.broadcast("comments-changed", {
10249
+ emitCommentsChanged({
9965
10250
  scopeHash: scope.hash,
9966
10251
  id: comment.id
9967
10252
  });
@@ -9977,13 +10262,33 @@ function mountScopeRoutes(app, opts) {
9977
10262
  const store = commentStore(scope.hash);
9978
10263
  const removed = store.remove(c.req.param("cid"));
9979
10264
  if (removed) {
9980
- opts.broadcast("comments-changed", {
10265
+ emitCommentsChanged({
9981
10266
  scopeHash: scope.hash,
9982
10267
  deleted: c.req.param("cid")
9983
10268
  });
9984
10269
  }
9985
10270
  return c.json({ comments: store.snapshot() });
9986
10271
  });
10272
+ app.post(
10273
+ "/api/scopes/:hash/comments/:cid/resolve",
10274
+ zValidator5("json", resolveSchema),
10275
+ (c) => {
10276
+ const scope = getScope(c.req.param("hash"));
10277
+ if (!scope) return c.json({ error: "unknown scope" }, 404);
10278
+ const store = commentStore(scope.hash);
10279
+ const updated = store.setResolved(
10280
+ c.req.param("cid"),
10281
+ c.req.valid("json").resolved
10282
+ );
10283
+ if (updated) {
10284
+ emitCommentsChanged({
10285
+ scopeHash: scope.hash,
10286
+ id: updated.id
10287
+ });
10288
+ }
10289
+ return c.json({ comments: store.snapshot() });
10290
+ }
10291
+ );
9987
10292
  app.post(
9988
10293
  "/api/scopes/:hash/submit-review",
9989
10294
  zValidator5("json", submitReviewSchema),
@@ -9992,7 +10297,7 @@ function mountScopeRoutes(app, opts) {
9992
10297
  if (!scope) return c.json({ error: "unknown scope" }, 404);
9993
10298
  const store = commentStore(scope.hash);
9994
10299
  const result = store.submit(c.req.valid("json").summary);
9995
- opts.broadcast("comments-changed", {
10300
+ emitCommentsChanged({
9996
10301
  scopeHash: scope.hash,
9997
10302
  submittedCount: result.drafts.length
9998
10303
  });
@@ -10008,7 +10313,7 @@ function mountScopeRoutes(app, opts) {
10008
10313
  const store = commentStore(scope.hash);
10009
10314
  const discarded = store.discardDrafts();
10010
10315
  if (discarded > 0) {
10011
- opts.broadcast("comments-changed", { scopeHash: scope.hash });
10316
+ emitCommentsChanged({ scopeHash: scope.hash });
10012
10317
  }
10013
10318
  return c.json({ discarded, comments: store.snapshot() });
10014
10319
  });
@@ -10018,7 +10323,9 @@ function mountScopeRoutes(app, opts) {
10018
10323
  const store = commentStore(scope.hash);
10019
10324
  const count = store.list().length;
10020
10325
  markScopeEnded(scope.hash);
10021
- opts.broadcast("review-done", { scopeHash: scope.hash, count });
10326
+ const payload = { scopeHash: scope.hash, count };
10327
+ opts.broadcast("review-done", payload);
10328
+ scopeBus.emit("review-done", payload);
10022
10329
  return c.json({ ok: true, count });
10023
10330
  });
10024
10331
  app.get("/api/scopes/:hash/events", (c) => {
@@ -10041,11 +10348,31 @@ function mountScopeRoutes(app, opts) {
10041
10348
  });
10042
10349
  };
10043
10350
  scopeBus.on("checkpoints-changed", onCheckpoint);
10351
+ const onComments = (payload) => {
10352
+ if (payload.scopeHash !== scope.hash) return;
10353
+ stream.writeSSE({
10354
+ event: "comments-changed",
10355
+ data: JSON.stringify(payload)
10356
+ }).catch(() => {
10357
+ });
10358
+ };
10359
+ scopeBus.on("comments-changed", onComments);
10360
+ const onDone = (payload) => {
10361
+ if (payload.scopeHash !== scope.hash) return;
10362
+ stream.writeSSE({
10363
+ event: "review-done",
10364
+ data: JSON.stringify(payload)
10365
+ }).catch(() => {
10366
+ });
10367
+ };
10368
+ scopeBus.on("review-done", onDone);
10044
10369
  await stream.writeSSE({ event: "connected", data: "" });
10045
10370
  await new Promise((resolve) => {
10046
10371
  stream.onAbort(() => {
10047
10372
  unsubscribe?.();
10048
10373
  scopeBus.off("checkpoints-changed", onCheckpoint);
10374
+ scopeBus.off("comments-changed", onComments);
10375
+ scopeBus.off("review-done", onDone);
10049
10376
  resolve();
10050
10377
  });
10051
10378
  });
@@ -10164,7 +10491,7 @@ function computeSessionDiff(s, base) {
10164
10491
  (p) => resolveRepoDiff(p, base, s.baseBranches?.[p] ?? s.baseBranch)
10165
10492
  );
10166
10493
  const repos = s.paths.map((p, i) => ({
10167
- name: path39.basename(p),
10494
+ name: path40.basename(p),
10168
10495
  root: p,
10169
10496
  resolvedBase: resolved[i].resolvedBase,
10170
10497
  files: computeDiff({ root: p, diffArg: resolved[i].diffArg })
@@ -10184,10 +10511,10 @@ async function startWebServer(opts = {}) {
10184
10511
  for (const cb of sseListeners) cb({ event, data });
10185
10512
  };
10186
10513
  const home = os12.homedir();
10187
- const historyPath = path39.join(home, ".work", "history.json");
10514
+ const historyPath = path40.join(home, ".work", "history.json");
10188
10515
  const onHistoryChange = () => broadcast("sessions-changed", { ts: Date.now() });
10189
10516
  fs40.watchFile(historyPath, { interval: 1e3 }, onHistoryChange);
10190
- const tasksPath = path39.join(home, ".work", "tasks.json");
10517
+ const tasksPath = path40.join(home, ".work", "tasks.json");
10191
10518
  const onTasksChange = () => broadcast("tasks-changed", { ts: Date.now() });
10192
10519
  fs40.watchFile(tasksPath, { interval: 1e3 }, onTasksChange);
10193
10520
  const projectsRoot = claudeProjectsRoot();
@@ -10332,10 +10659,10 @@ function info2(message) {
10332
10659
  process.stderr.write(message + "\n");
10333
10660
  }
10334
10661
  function urlFilePath() {
10335
- return path40.join(os13.homedir(), ".work", "web.url");
10662
+ return path41.join(os13.homedir(), ".work", "web.url");
10336
10663
  }
10337
10664
  function pidFilePath() {
10338
- return path40.join(os13.homedir(), ".work", "web.pid");
10665
+ return path41.join(os13.homedir(), ".work", "web.pid");
10339
10666
  }
10340
10667
  function isPidAlive(pid) {
10341
10668
  try {
@@ -10460,7 +10787,7 @@ var webCommand = {
10460
10787
  const lean = !!argv.lean || process.env.WORK_WEB_LEAN === "1";
10461
10788
  const handle = await startWebServer({ lean });
10462
10789
  try {
10463
- fs41.mkdirSync(path40.dirname(urlFilePath()), { recursive: true });
10790
+ fs41.mkdirSync(path41.dirname(urlFilePath()), { recursive: true });
10464
10791
  fs41.writeFileSync(urlFilePath(), handle.url);
10465
10792
  fs41.writeFileSync(pidFilePath(), String(process.pid));
10466
10793
  } catch {
@@ -10489,6 +10816,13 @@ var webCommand = {
10489
10816
  ]).catch(() => {
10490
10817
  });
10491
10818
  }
10819
+ await installCommandHook({
10820
+ owner: "web-checkpoint",
10821
+ event: "Stop",
10822
+ command: "work hook checkpoint",
10823
+ timeoutSec: 5
10824
+ }).catch(() => {
10825
+ });
10492
10826
  const shutdown = () => {
10493
10827
  info2(chalk23.gray("\nStopping work web."));
10494
10828
  try {
@@ -10509,6 +10843,10 @@ var webCommand = {
10509
10843
  } catch {
10510
10844
  }
10511
10845
  }
10846
+ try {
10847
+ removeCommandHookSync("web-checkpoint", "Stop");
10848
+ } catch {
10849
+ }
10512
10850
  handle.stop();
10513
10851
  process.exit(0);
10514
10852
  };
@@ -10530,6 +10868,31 @@ var webCommand = {
10530
10868
  };
10531
10869
 
10532
10870
  // src/commands/hook.ts
10871
+ import fs42 from "fs";
10872
+ import os14 from "os";
10873
+ import path42 from "path";
10874
+ async function triggerCheckpoint(cwd) {
10875
+ let base;
10876
+ try {
10877
+ base = fs42.readFileSync(path42.join(os14.homedir(), ".work", "web.url"), "utf-8").trim();
10878
+ } catch {
10879
+ return;
10880
+ }
10881
+ if (!base) return;
10882
+ const controller = new AbortController();
10883
+ const timer = setTimeout(() => controller.abort(), 3e3);
10884
+ try {
10885
+ await fetch(`${base}api/checkpoint`, {
10886
+ method: "POST",
10887
+ headers: { "Content-Type": "application/json" },
10888
+ body: JSON.stringify({ cwd }),
10889
+ signal: controller.signal
10890
+ });
10891
+ } catch {
10892
+ } finally {
10893
+ clearTimeout(timer);
10894
+ }
10895
+ }
10533
10896
  function computeHookOutput(input2) {
10534
10897
  const session = findSessionForCwd(input2.cwd);
10535
10898
  if (!session) return null;
@@ -10579,13 +10942,17 @@ var hookCommand = {
10579
10942
  // hidden — humans don't call this directly
10580
10943
  builder: (y) => y.positional("event", {
10581
10944
  type: "string",
10582
- choices: ["prompt-submit", "stop"],
10945
+ choices: ["prompt-submit", "stop", "checkpoint"],
10583
10946
  describe: "Hook event name"
10584
10947
  }),
10585
10948
  handler: async (argv) => {
10586
10949
  const event = argv.event;
10587
10950
  const payload = await readStdinJson();
10588
10951
  const cwd = payload.cwd ?? process.cwd();
10952
+ if (event === "checkpoint") {
10953
+ await triggerCheckpoint(cwd);
10954
+ return;
10955
+ }
10589
10956
  const result = computeHookOutput({ event, cwd });
10590
10957
  if (!result || !result.sessionId) return;
10591
10958
  process.stdout.write(result.stdout);
@@ -10595,7 +10962,7 @@ var hookCommand = {
10595
10962
 
10596
10963
  // src/commands/run.ts
10597
10964
  import chalk24 from "chalk";
10598
- import spawn14 from "cross-spawn";
10965
+ import spawn15 from "cross-spawn";
10599
10966
 
10600
10967
  // src/core/fleet.ts
10601
10968
  function selectSessions(sessions, filter) {
@@ -10637,7 +11004,7 @@ function killAllChildren(signal = "SIGTERM") {
10637
11004
  function runInPath(unit, cmd, prefix) {
10638
11005
  const { bin, args } = shellInvocation(cmd);
10639
11006
  return new Promise((resolve) => {
10640
- const child = spawn14(bin, args, {
11007
+ const child = spawn15(bin, args, {
10641
11008
  cwd: unit.path,
10642
11009
  stdio: prefix ? ["ignore", "pipe", "pipe"] : "inherit",
10643
11010
  shell: false
@@ -10869,15 +11236,15 @@ var runCommand = {
10869
11236
  };
10870
11237
 
10871
11238
  // src/commands/broadcast.ts
10872
- import fs43 from "fs";
11239
+ import fs44 from "fs";
10873
11240
  import chalk25 from "chalk";
10874
11241
 
10875
11242
  // src/core/broadcast.ts
10876
11243
  import crypto6 from "crypto";
10877
- import fs42 from "fs";
11244
+ import fs43 from "fs";
10878
11245
  function readComments(file) {
10879
11246
  try {
10880
- const parsed = JSON.parse(fs42.readFileSync(file, "utf-8"));
11247
+ const parsed = JSON.parse(fs43.readFileSync(file, "utf-8"));
10881
11248
  return Array.isArray(parsed) ? parsed : [];
10882
11249
  } catch {
10883
11250
  return [];
@@ -10885,7 +11252,7 @@ function readComments(file) {
10885
11252
  }
10886
11253
  async function appendLocked(sessionId, body) {
10887
11254
  const file = commentsFileFor(sessionId);
10888
- fs42.mkdirSync(commentsDir(), { recursive: true });
11255
+ fs43.mkdirSync(commentsDir(), { recursive: true });
10889
11256
  ensureFile(file, "[]");
10890
11257
  const comment = {
10891
11258
  id: crypto6.randomBytes(8).toString("hex"),
@@ -10922,7 +11289,7 @@ async function broadcastPrompt(sessions, filter, prompt) {
10922
11289
  // src/commands/broadcast.ts
10923
11290
  function readStdin() {
10924
11291
  try {
10925
- return fs43.readFileSync(0, "utf-8");
11292
+ return fs44.readFileSync(0, "utf-8");
10926
11293
  } catch {
10927
11294
  return "";
10928
11295
  }
@@ -10997,8 +11364,8 @@ var broadcastCommand = {
10997
11364
  };
10998
11365
 
10999
11366
  // src/completions/index.ts
11000
- import fs44 from "fs";
11001
- import path41 from "path";
11367
+ import fs45 from "fs";
11368
+ import path43 from "path";
11002
11369
  function completionHandler(current, argv, done) {
11003
11370
  const rawArgs = argv._;
11004
11371
  const args = rawArgs.slice(1, -1);
@@ -11102,7 +11469,7 @@ function completeTreeRemoveList(command, args, current, config, done) {
11102
11469
  }
11103
11470
  function completeRepoBranches(alias, current, config, done) {
11104
11471
  const repoPath = config.repos[alias];
11105
- if (!repoPath || !fs44.existsSync(repoPath)) {
11472
+ if (!repoPath || !fs45.existsSync(repoPath)) {
11106
11473
  done([]);
11107
11474
  return;
11108
11475
  }
@@ -11111,19 +11478,19 @@ function completeRepoBranches(alias, current, config, done) {
11111
11478
  done(branches);
11112
11479
  }
11113
11480
  function completeGroupBranches(groupName, repoAliases, current, config, done) {
11114
- const groupDir = path41.join(config.worktreesRoot, groupName);
11115
- if (!fs44.existsSync(groupDir)) {
11481
+ const groupDir = path43.join(config.worktreesRoot, groupName);
11482
+ if (!fs45.existsSync(groupDir)) {
11116
11483
  done([]);
11117
11484
  return;
11118
11485
  }
11119
11486
  try {
11120
- const branchDirs = fs44.readdirSync(groupDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => {
11121
- const bdPath = path41.join(groupDir, d.name);
11487
+ const branchDirs = fs45.readdirSync(groupDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => {
11488
+ const bdPath = path43.join(groupDir, d.name);
11122
11489
  for (const alias of repoAliases) {
11123
11490
  const repoPath = config.repos[alias];
11124
11491
  if (!repoPath) continue;
11125
- const subPath = path41.join(bdPath, path41.basename(repoPath));
11126
- if (fs44.existsSync(subPath)) {
11492
+ const subPath = path43.join(bdPath, path43.basename(repoPath));
11493
+ if (fs45.existsSync(subPath)) {
11127
11494
  const branch = getCurrentBranch(subPath);
11128
11495
  if (branch) return branch;
11129
11496
  }
@@ -11137,7 +11504,7 @@ function completeGroupBranches(groupName, repoAliases, current, config, done) {
11137
11504
  }
11138
11505
 
11139
11506
  // src/version.ts
11140
- var VERSION = true ? "1.8.5" : "dev";
11507
+ var VERSION = true ? "1.9.1" : "dev";
11141
11508
 
11142
11509
  // src/cli.ts
11143
11510
  function showHelp() {