@moberg_hr/work-tree 1.9.1 → 1.11.0

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
@@ -443,6 +443,17 @@ import fs3 from "fs";
443
443
  import path4 from "path";
444
444
  import spawn2 from "cross-spawn";
445
445
  import chalk from "chalk";
446
+
447
+ // src/core/internal-claude.ts
448
+ var INTERNAL_CLAUDE_ENV = "WORK_INTERNAL_CLAUDE";
449
+ function internalClaudeEnv() {
450
+ return { [INTERNAL_CLAUDE_ENV]: "1" };
451
+ }
452
+ function isInternalClaude() {
453
+ return process.env[INTERNAL_CLAUDE_ENV] === "1";
454
+ }
455
+
456
+ // src/core/claude-md.ts
446
457
  function generateGroupClaudeMd(groupName, repoAliases, config) {
447
458
  const outputPath = path4.join(getConfigDir(), `${groupName}.claude.md`);
448
459
  const promptParts = [];
@@ -499,7 +510,9 @@ function generateGroupClaudeMd(groupName, repoAliases, config) {
499
510
  input: prompt,
500
511
  encoding: "utf-8",
501
512
  stdio: ["pipe", "pipe", "pipe"],
502
- windowsHide: true
513
+ windowsHide: true,
514
+ // Internal call — don't trip work's checkpoint hooks (see internal-claude.ts).
515
+ env: { ...process.env, ...internalClaudeEnv() }
503
516
  });
504
517
  let content;
505
518
  if (result.status !== 0 || !result.stdout?.trim()) {
@@ -1888,6 +1901,25 @@ function toBaseSpec(base) {
1888
1901
  }
1889
1902
 
1890
1903
  // src/core/worktree.ts
1904
+ function pullExistingWorktree(worktreePath, branchName) {
1905
+ const upstream = git(
1906
+ ["rev-parse", "--abbrev-ref", `${branchName}@{upstream}`],
1907
+ worktreePath
1908
+ );
1909
+ if (upstream.exitCode !== 0) return;
1910
+ console.log(` Pulling latest changes for ${branchName}...`);
1911
+ git(["fetch", "--quiet"], worktreePath);
1912
+ const pull = git(["pull", "--quiet"], worktreePath);
1913
+ if (pull.exitCode !== 0) {
1914
+ console.log(
1915
+ chalk5.yellow(
1916
+ ` \u26A0 Could not pull '${branchName}' (uncommitted changes or conflicts). Worktree may be behind origin.`
1917
+ )
1918
+ );
1919
+ const firstErrLine = pull.stderr.split("\n")[0];
1920
+ if (firstErrLine) console.log(chalk5.gray(` ${firstErrLine}`));
1921
+ }
1922
+ }
1891
1923
  function createSingleWorktree(repoPath, worktreePath, branchName, config, baseBranch) {
1892
1924
  debug("createSingleWorktree", { repoPath, worktreePath, branchName, baseBranch });
1893
1925
  if (fs13.existsSync(worktreePath)) {
@@ -1897,6 +1929,7 @@ function createSingleWorktree(repoPath, worktreePath, branchName, config, baseBr
1897
1929
  console.log(
1898
1930
  chalk5.yellow(` Worktree already exists at: ${worktreePath}`)
1899
1931
  );
1932
+ pullExistingWorktree(worktreePath, branchName);
1900
1933
  return true;
1901
1934
  }
1902
1935
  }
@@ -2230,6 +2263,7 @@ async function setupSingleWorktree(targetName, branchName, workTreeDirName, conf
2230
2263
  }
2231
2264
  console.log(`Worktree already exists at: ${existing.path}`);
2232
2265
  workTreePath = existing.path;
2266
+ pullExistingWorktree(workTreePath, branchName);
2233
2267
  } else {
2234
2268
  const success = createSingleWorktree(repoPath, workTreePath, branchName, config, baseBranch);
2235
2269
  if (!success) return null;
@@ -5128,7 +5162,13 @@ function generateSlug(summary) {
5128
5162
  const child = execFile4(
5129
5163
  "claude",
5130
5164
  ["-p", "--model", "haiku"],
5131
- { encoding: "utf-8", timeout: 1e4, windowsHide: true },
5165
+ {
5166
+ encoding: "utf-8",
5167
+ timeout: 1e4,
5168
+ windowsHide: true,
5169
+ // Internal call — don't trip work's checkpoint hooks (see internal-claude.ts).
5170
+ env: { ...process.env, ...internalClaudeEnv() }
5171
+ },
5132
5172
  (err, stdout) => {
5133
5173
  const result = stdout?.trim().toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/^-|-$/g, "");
5134
5174
  resolve(result || fallback);
@@ -9665,6 +9705,106 @@ async function takeCheckpoint(scopeHash, repos, opts = {}) {
9665
9705
  return entry;
9666
9706
  });
9667
9707
  }
9708
+ async function updateCheckpoint(scopeHash, repos, id) {
9709
+ const file = manifestPath(scopeHash);
9710
+ ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));
9711
+ return withFileLock(file, () => {
9712
+ const manifest = loadManifest(scopeHash);
9713
+ const entry = manifest.entries.find((e) => e.id === id);
9714
+ if (!entry) return { status: "missing" };
9715
+ const refName = `refs/wd/${scopeHash}/${id}`;
9716
+ const restoreRefs = () => {
9717
+ for (const repo of repos) {
9718
+ const old = entry.repos[repo.name] ?? null;
9719
+ if (old) {
9720
+ spawn12.sync("git", ["update-ref", refName, old], {
9721
+ cwd: repo.root,
9722
+ encoding: "utf-8",
9723
+ windowsHide: true
9724
+ });
9725
+ } else {
9726
+ spawn12.sync("git", ["update-ref", "-d", refName], {
9727
+ cwd: repo.root,
9728
+ encoding: "utf-8",
9729
+ windowsHide: true
9730
+ });
9731
+ }
9732
+ }
9733
+ };
9734
+ const captured = {};
9735
+ for (const repo of repos) {
9736
+ captured[repo.name] = snapshotRepo(repo.root, scopeHash, id, true);
9737
+ }
9738
+ if (repos.some((r) => captured[r.name] === null)) {
9739
+ restoreRefs();
9740
+ return { status: "missing" };
9741
+ }
9742
+ const treeOf = (root, commitSha) => {
9743
+ if (!commitSha) return null;
9744
+ const r = spawn12.sync("git", ["rev-parse", `${commitSha}^{tree}`], {
9745
+ cwd: root,
9746
+ encoding: "utf-8",
9747
+ windowsHide: true
9748
+ });
9749
+ if (r.status !== 0 || typeof r.stdout !== "string") return null;
9750
+ return r.stdout.trim() || null;
9751
+ };
9752
+ const unchanged = repos.every((repo) => {
9753
+ const curTree = treeOf(repo.root, captured[repo.name]);
9754
+ const prevTree = treeOf(repo.root, entry.repos[repo.name] ?? null);
9755
+ return curTree !== null && curTree === prevTree;
9756
+ });
9757
+ if (unchanged) {
9758
+ restoreRefs();
9759
+ return { status: "unchanged" };
9760
+ }
9761
+ entry.repos = captured;
9762
+ entry.ts = (/* @__PURE__ */ new Date()).toISOString();
9763
+ delete entry.label;
9764
+ atomicWriteFile(file, JSON.stringify(manifest, null, 2));
9765
+ return { status: "updated", entry };
9766
+ });
9767
+ }
9768
+ async function resetBaseline(scopeHash, repos) {
9769
+ const file = manifestPath(scopeHash);
9770
+ ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));
9771
+ return withFileLock(file, () => {
9772
+ const prevIds = loadManifest(scopeHash).entries.map((e) => e.id);
9773
+ const captured = {};
9774
+ for (const repo of repos) {
9775
+ captured[repo.name] = snapshotRepo(repo.root, scopeHash, 0, false);
9776
+ }
9777
+ const delRef = (id) => {
9778
+ for (const repo of repos) {
9779
+ spawn12.sync("git", ["update-ref", "-d", `refs/wd/${scopeHash}/${id}`], {
9780
+ cwd: repo.root,
9781
+ encoding: "utf-8",
9782
+ windowsHide: true
9783
+ });
9784
+ }
9785
+ };
9786
+ if (repos.some((r) => captured[r.name] === null)) {
9787
+ delRef(0);
9788
+ return null;
9789
+ }
9790
+ for (const id of prevIds) {
9791
+ if (id !== 0) delRef(id);
9792
+ }
9793
+ const entry = {
9794
+ id: 0,
9795
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
9796
+ label: "Initial",
9797
+ repos: captured
9798
+ };
9799
+ const manifest = {
9800
+ version: 1,
9801
+ scopeHash,
9802
+ entries: [entry]
9803
+ };
9804
+ atomicWriteFile(file, JSON.stringify(manifest, null, 2));
9805
+ return entry;
9806
+ });
9807
+ }
9668
9808
  async function setCheckpointLabel(scopeHash, id, label2) {
9669
9809
  const file = manifestPath(scopeHash);
9670
9810
  ensureFile(file, JSON.stringify(emptyManifest(scopeHash), null, 2));
@@ -9676,6 +9816,29 @@ async function setCheckpointLabel(scopeHash, id, label2) {
9676
9816
  atomicWriteFile(file, JSON.stringify(manifest, null, 2));
9677
9817
  });
9678
9818
  }
9819
+ function headAdvancedSinceInitial(scopeHash, repos) {
9820
+ const manifest = loadManifest(scopeHash);
9821
+ const initial = manifest.entries.find((e) => e.id === 0);
9822
+ if (!initial) return false;
9823
+ const treeOf = (root, rev) => {
9824
+ const r = spawn12.sync("git", ["rev-parse", `${rev}^{tree}`], {
9825
+ cwd: root,
9826
+ encoding: "utf-8",
9827
+ windowsHide: true
9828
+ });
9829
+ if (r.status !== 0 || typeof r.stdout !== "string") return null;
9830
+ return r.stdout.trim() || null;
9831
+ };
9832
+ return repos.some((repo) => {
9833
+ const headTree = treeOf(repo.root, "HEAD");
9834
+ if (headTree === null) return false;
9835
+ const baselineSha = initial.repos[repo.name];
9836
+ if (!baselineSha) return true;
9837
+ const baselineTree = treeOf(repo.root, baselineSha);
9838
+ if (baselineTree === null) return false;
9839
+ return baselineTree !== headTree;
9840
+ });
9841
+ }
9679
9842
  function clearCheckpoints(scopeHash, repoRoots) {
9680
9843
  const manifest = loadManifest(scopeHash);
9681
9844
  for (const root of repoRoots) {
@@ -9769,7 +9932,10 @@ function runClaude(prompt, timeoutMs = 25e3) {
9769
9932
  try {
9770
9933
  child = spawn13("claude", ["-p"], {
9771
9934
  stdio: ["pipe", "pipe", "ignore"],
9772
- windowsHide: true
9935
+ windowsHide: true,
9936
+ // Tag as internal so this naming run doesn't recursively trip work's
9937
+ // own UserPromptSubmit/Stop checkpoint hooks (see internal-claude.ts).
9938
+ env: { ...process.env, ...internalClaudeEnv() }
9773
9939
  });
9774
9940
  } catch {
9775
9941
  finish(null);
@@ -9965,6 +10131,8 @@ import { streamSSE as streamSSE2 } from "hono/streaming";
9965
10131
  function mountScopeRoutes(app, opts) {
9966
10132
  const checkpointWatched = /* @__PURE__ */ new Set();
9967
10133
  const lastStatus = /* @__PURE__ */ new Map();
10134
+ const liveCheckpoint = /* @__PURE__ */ new Map();
10135
+ const summarizing = /* @__PURE__ */ new Set();
9968
10136
  const snapshotTimers = /* @__PURE__ */ new Map();
9969
10137
  const CHECKPOINT_SETTLE_MS = 4e3;
9970
10138
  const CLAUDE_SESSION_MS = 5 * 6e4;
@@ -9989,6 +10157,31 @@ function mountScopeRoutes(app, opts) {
9989
10157
  function scopeRepos(scopePaths) {
9990
10158
  return scopePaths.map((p) => ({ name: p, root: p }));
9991
10159
  }
10160
+ function ensureSummary(scope, id) {
10161
+ if (id === 0) return;
10162
+ const key = `${scope.hash}:${id}`;
10163
+ if (summarizing.has(key)) return;
10164
+ summarizing.add(key);
10165
+ summarizeCheckpoint(scope.hash, scopeRepos(scope.paths), id).then((label2) => setCheckpointLabel(scope.hash, id, label2)).then(() => {
10166
+ const payload = { scopeHash: scope.hash, id };
10167
+ opts.broadcast("checkpoints-changed", payload);
10168
+ scopeBus.emit("checkpoints-changed", payload);
10169
+ }).catch(() => {
10170
+ }).finally(() => summarizing.delete(key));
10171
+ }
10172
+ async function rebaselineIfHeadAdvanced(hash, paths) {
10173
+ const repos = scopeRepos(paths);
10174
+ if (!headAdvancedSinceInitial(hash, repos)) return false;
10175
+ liveCheckpoint.delete(hash);
10176
+ lastStatus.delete(hash);
10177
+ const entry = await resetBaseline(hash, repos).catch(() => null);
10178
+ if (entry) {
10179
+ const payload = { scopeHash: hash, id: entry.id };
10180
+ opts.broadcast("checkpoints-changed", payload);
10181
+ scopeBus.emit("checkpoints-changed", payload);
10182
+ }
10183
+ return true;
10184
+ }
9992
10185
  app.post(
9993
10186
  "/api/scopes",
9994
10187
  zValidator5(
@@ -10020,6 +10213,10 @@ function mountScopeRoutes(app, opts) {
10020
10213
  }).catch((err) => {
10021
10214
  console.error("[checkpoint] initial snapshot failed:", err);
10022
10215
  });
10216
+ } else {
10217
+ rebaselineIfHeadAdvanced(scope.hash, scope.paths).catch((err) => {
10218
+ console.error("[checkpoint] re-baseline failed:", err);
10219
+ });
10023
10220
  }
10024
10221
  if (!checkpointWatched.has(scope.hash)) {
10025
10222
  checkpointWatched.add(scope.hash);
@@ -10039,8 +10236,11 @@ function mountScopeRoutes(app, opts) {
10039
10236
  lastStatus.set(hash, fp);
10040
10237
  } catch {
10041
10238
  }
10042
- takeCheckpoint(hash, scopeRepos(scope.paths)).then((entry) => {
10043
- if (entry) announceCheckpoint(entry);
10239
+ rebaselineIfHeadAdvanced(hash, scope.paths).then(() => takeCheckpoint(hash, scopeRepos(scope.paths))).then((entry) => {
10240
+ if (entry) {
10241
+ announceCheckpoint(entry);
10242
+ ensureSummary(scope, entry.id);
10243
+ }
10044
10244
  }).catch((err) => {
10045
10245
  console.error("[checkpoint] auto-snapshot failed:", err);
10046
10246
  });
@@ -10073,19 +10273,55 @@ function mountScopeRoutes(app, opts) {
10073
10273
  const matched = scopesForCwd(cwd);
10074
10274
  let snapshotted = 0;
10075
10275
  for (const s of matched) {
10076
- const entry = await takeCheckpoint(s.hash, scopeRepos(s.paths)).catch(
10077
- () => null
10078
- );
10276
+ await rebaselineIfHeadAdvanced(s.hash, s.paths);
10277
+ const liveId = liveCheckpoint.get(s.hash);
10278
+ let entry = null;
10279
+ if (liveId !== void 0) {
10280
+ const res = await updateCheckpoint(
10281
+ s.hash,
10282
+ scopeRepos(s.paths),
10283
+ liveId
10284
+ ).catch(() => ({ status: "missing" }));
10285
+ if (res.status === "updated") {
10286
+ entry = res.entry;
10287
+ } else if (res.status === "missing") {
10288
+ liveCheckpoint.delete(s.hash);
10289
+ }
10290
+ }
10291
+ if (entry === null && !liveCheckpoint.has(s.hash)) {
10292
+ const appended = await takeCheckpoint(
10293
+ s.hash,
10294
+ scopeRepos(s.paths)
10295
+ ).catch(() => null);
10296
+ if (appended) {
10297
+ entry = appended;
10298
+ liveCheckpoint.set(s.hash, appended.id);
10299
+ }
10300
+ }
10079
10301
  if (entry) {
10080
10302
  const payload = { scopeHash: s.hash, id: entry.id };
10081
10303
  opts.broadcast("checkpoints-changed", payload);
10082
10304
  scopeBus.emit("checkpoints-changed", payload);
10305
+ ensureSummary(s, entry.id);
10083
10306
  snapshotted++;
10084
10307
  }
10085
10308
  }
10086
10309
  return c.json({ ok: true, scopes: matched.length, snapshotted });
10087
10310
  }
10088
10311
  );
10312
+ app.post(
10313
+ "/api/checkpoint/seal",
10314
+ zValidator5("json", z4.object({ cwd: z4.string().min(1) })),
10315
+ (c) => {
10316
+ const { cwd } = c.req.valid("json");
10317
+ const matched = scopesForCwd(cwd);
10318
+ let sealed = 0;
10319
+ for (const s of matched) {
10320
+ if (liveCheckpoint.delete(s.hash)) sealed++;
10321
+ }
10322
+ return c.json({ ok: true, scopes: matched.length, sealed });
10323
+ }
10324
+ );
10089
10325
  app.delete("/api/scopes/:hash", (c) => {
10090
10326
  const hash = c.req.param("hash");
10091
10327
  const scope = getScope(hash);
@@ -10093,6 +10329,10 @@ function mountScopeRoutes(app, opts) {
10093
10329
  const ok = removeScope(hash);
10094
10330
  checkpointWatched.delete(hash);
10095
10331
  lastStatus.delete(hash);
10332
+ liveCheckpoint.delete(hash);
10333
+ for (const key of summarizing) {
10334
+ if (key.startsWith(`${hash}:`)) summarizing.delete(key);
10335
+ }
10096
10336
  const pendingTimer = snapshotTimers.get(hash);
10097
10337
  if (pendingTimer) {
10098
10338
  clearTimeout(pendingTimer);
@@ -10823,6 +11063,13 @@ var webCommand = {
10823
11063
  timeoutSec: 5
10824
11064
  }).catch(() => {
10825
11065
  });
11066
+ await installCommandHook({
11067
+ owner: "web-checkpoint",
11068
+ event: "UserPromptSubmit",
11069
+ command: "work hook checkpoint-seal",
11070
+ timeoutSec: 5
11071
+ }).catch(() => {
11072
+ });
10826
11073
  const shutdown = () => {
10827
11074
  info2(chalk23.gray("\nStopping work web."));
10828
11075
  try {
@@ -10847,6 +11094,10 @@ var webCommand = {
10847
11094
  removeCommandHookSync("web-checkpoint", "Stop");
10848
11095
  } catch {
10849
11096
  }
11097
+ try {
11098
+ removeCommandHookSync("web-checkpoint", "UserPromptSubmit");
11099
+ } catch {
11100
+ }
10850
11101
  handle.stop();
10851
11102
  process.exit(0);
10852
11103
  };
@@ -10871,7 +11122,7 @@ var webCommand = {
10871
11122
  import fs42 from "fs";
10872
11123
  import os14 from "os";
10873
11124
  import path42 from "path";
10874
- async function triggerCheckpoint(cwd) {
11125
+ async function postToWeb(route, cwd) {
10875
11126
  let base;
10876
11127
  try {
10877
11128
  base = fs42.readFileSync(path42.join(os14.homedir(), ".work", "web.url"), "utf-8").trim();
@@ -10882,7 +11133,7 @@ async function triggerCheckpoint(cwd) {
10882
11133
  const controller = new AbortController();
10883
11134
  const timer = setTimeout(() => controller.abort(), 3e3);
10884
11135
  try {
10885
- await fetch(`${base}api/checkpoint`, {
11136
+ await fetch(`${base}${route}`, {
10886
11137
  method: "POST",
10887
11138
  headers: { "Content-Type": "application/json" },
10888
11139
  body: JSON.stringify({ cwd }),
@@ -10942,15 +11193,20 @@ var hookCommand = {
10942
11193
  // hidden — humans don't call this directly
10943
11194
  builder: (y) => y.positional("event", {
10944
11195
  type: "string",
10945
- choices: ["prompt-submit", "stop", "checkpoint"],
11196
+ choices: ["prompt-submit", "stop", "checkpoint", "checkpoint-seal"],
10946
11197
  describe: "Hook event name"
10947
11198
  }),
10948
11199
  handler: async (argv) => {
11200
+ if (isInternalClaude()) return;
10949
11201
  const event = argv.event;
10950
11202
  const payload = await readStdinJson();
10951
11203
  const cwd = payload.cwd ?? process.cwd();
10952
11204
  if (event === "checkpoint") {
10953
- await triggerCheckpoint(cwd);
11205
+ await postToWeb("api/checkpoint", cwd);
11206
+ return;
11207
+ }
11208
+ if (event === "checkpoint-seal") {
11209
+ await postToWeb("api/checkpoint/seal", cwd);
10954
11210
  return;
10955
11211
  }
10956
11212
  const result = computeHookOutput({ event, cwd });
@@ -11504,7 +11760,7 @@ function completeGroupBranches(groupName, repoAliases, current, config, done) {
11504
11760
  }
11505
11761
 
11506
11762
  // src/version.ts
11507
- var VERSION = true ? "1.9.1" : "dev";
11763
+ var VERSION = true ? "1.11.0" : "dev";
11508
11764
 
11509
11765
  // src/cli.ts
11510
11766
  function showHelp() {