p-backlog 0.13.1 → 0.14.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +1 -1
  3. package/README.ru.md +1 -1
  4. package/dist/cli.js +1630 -1009
  5. package/dist/web/assets/CodeTab-D7apweTn.js +1 -0
  6. package/dist/web/assets/CostTab-Cbq-tBpi.js +1 -0
  7. package/dist/web/assets/EffectTab-CSJBH_A_.js +1 -0
  8. package/dist/web/assets/Figure-BkubK2zp.js +1 -0
  9. package/dist/web/assets/OverviewTab-D1S-xV7F.js +1 -0
  10. package/dist/web/assets/Page-DcJkvJR8.js +81 -0
  11. package/dist/web/assets/QualityTab-Bvo5sLJL.js +1 -0
  12. package/dist/web/assets/ShareBar-CVoET5r9.js +1 -0
  13. package/dist/web/assets/StatsPage-CC1pIw6W.js +1 -0
  14. package/dist/web/assets/StatsTabState-DsgM-E6r.js +1 -0
  15. package/dist/web/assets/StatsTable-Dfk5L9ju.js +1 -0
  16. package/dist/web/assets/UnavailableRepos-DEI_jdL7.js +1 -0
  17. package/dist/web/assets/index-CrooTAtB.js +2 -0
  18. package/dist/web/assets/start-CTwcHqnH.js +257 -0
  19. package/dist/web/assets/start-D3XxrO_Y.css +1 -0
  20. package/dist/web/assets/use-grain-panel-C8dF5mz1.js +69 -0
  21. package/dist/web/assets/web-paths-Cv9UykyI.js +1 -0
  22. package/dist/web/index.html +1 -1
  23. package/package.json +6 -6
  24. package/dist/web/assets/CodeTab-DeM399k_.js +0 -1
  25. package/dist/web/assets/CostTab-BkuP_lKs.js +0 -1
  26. package/dist/web/assets/EffectTab-C6yxsNf4.js +0 -1
  27. package/dist/web/assets/Figure-CVTyKv4y.js +0 -1
  28. package/dist/web/assets/OverviewTab-B83eJneA.js +0 -1
  29. package/dist/web/assets/Page-DLaFG3Qi.js +0 -59
  30. package/dist/web/assets/QualityTab-DCMWjXz4.js +0 -1
  31. package/dist/web/assets/ShareBar-DLIjLhrg.js +0 -1
  32. package/dist/web/assets/StatsPage-Dyu3XyGq.js +0 -1
  33. package/dist/web/assets/StatsTabState-C2YngECB.js +0 -1
  34. package/dist/web/assets/StatsTable-4QrI6DcN.js +0 -1
  35. package/dist/web/assets/UnavailableRepos-BSMfh0t_.js +0 -1
  36. package/dist/web/assets/index-DBSU7e-A.js +0 -2
  37. package/dist/web/assets/start-B7mNnilg.js +0 -42
  38. package/dist/web/assets/start-BmSqjxn9.css +0 -1
  39. package/dist/web/assets/use-grain-panel-CSj1uVOI.js +0 -55
  40. package/dist/web/assets/web-paths-CziYixFT.js +0 -1
package/dist/cli.js CHANGED
@@ -113,19 +113,20 @@ import { fileURLToPath } from "node:url";
113
113
 
114
114
  // src/core/store/runs.ts
115
115
  import { mkdir } from "node:fs/promises";
116
- import { join as join3 } from "node:path";
116
+ import { join as join4 } from "node:path";
117
117
  import { z } from "zod";
118
118
 
119
119
  // src/core/store/file-lock.ts
120
120
  import { randomUUID } from "node:crypto";
121
121
  import { rm as rm2, utimes, writeFile } from "node:fs/promises";
122
- import { basename, dirname, join } from "node:path";
122
+ import { basename, dirname, join as join2 } from "node:path";
123
123
  import { setTimeout as sleep2 } from "node:timers/promises";
124
124
 
125
125
  // src/core/store/fs-utils.ts
126
126
  import { createHash } from "node:crypto";
127
- import { readFileSync, realpathSync } from "node:fs";
127
+ import { constants, readFileSync, realpathSync } from "node:fs";
128
128
  import { access, lstat, open, readdir, readFile, readlink, rm, stat } from "node:fs/promises";
129
+ import { join } from "node:path";
129
130
  import { setTimeout as sleep } from "node:timers/promises";
130
131
  function contentVersion(text) {
131
132
  return createHash("sha1").update(text).digest("hex");
@@ -244,6 +245,26 @@ async function listDir(path, { recursive = false } = {}) {
244
245
  throw error;
245
246
  }
246
247
  }
248
+ async function listDirFollowingLinks(path) {
249
+ return Promise.all((await listDir(path)).map(async (entry) => ({ name: entry.name, kind: await kindFollowingLink(entry) })));
250
+ }
251
+ var UNREACHABLE_LINK_CODES = [...NO_FILE_CODES, "ELOOP", "EACCES", "EPERM"];
252
+ async function kindFollowingLink(entry) {
253
+ if (!entry.isSymbolicLink()) return kindOf(entry);
254
+ const path = join(entry.parentPath, entry.name);
255
+ try {
256
+ const target = await stat(path);
257
+ await access(path, target.isDirectory() ? constants.R_OK | constants.X_OK : constants.R_OK);
258
+ return kindOf(target);
259
+ } catch (error) {
260
+ if (hasAnyErrorCode(error, UNREACHABLE_LINK_CODES)) return "link-unreachable";
261
+ throw error;
262
+ }
263
+ }
264
+ function kindOf(entry) {
265
+ if (entry.isFile()) return "file";
266
+ return entry.isDirectory() ? "directory" : "other";
267
+ }
247
268
  var BLOCKED_RETRY_DELAYS_MS = [10, 20, 40, 80, 160, 320, 640, 1e3, 1e3, 1e3, 1e3];
248
269
  var BLOCKED_RETRIES_TOTAL_MS = sum(BLOCKED_RETRY_DELAYS_MS);
249
270
  var BLOCKED_CODES = ["EPERM", "EACCES", "EBUSY"];
@@ -291,38 +312,57 @@ var Refusal = class {
291
312
  }
292
313
  error;
293
314
  };
294
- async function withFileLock(path, action, options = {}) {
315
+ function lockPathOf(path) {
316
+ return join2(dirname(path), `.${basename(path)}.lock`);
317
+ }
318
+ async function withWriteLock(path, write, { onErrorAfterPublish, ...options }) {
295
319
  const held = await acquire(path, options);
296
320
  if (held instanceof Refusal) throw held.error;
297
- try {
298
- return await action();
299
- } finally {
300
- await release(held);
301
- }
321
+ return releasingAfter([held], () => write({ onErrorAfterPublish }), onErrorAfterPublish);
302
322
  }
303
- async function withAvailableLocks(paths, action, { waitLimitMs = DEFAULT_WAIT_LIMIT_MS } = {}) {
323
+ async function withAvailableLocks(paths, action, { waitLimitMs = DEFAULT_WAIT_LIMIT_MS, onErrorAfterPublish }) {
304
324
  const held = [];
305
325
  const giveUpAt = Date.now() + waitLimitMs;
306
- try {
307
- for (const path of [...paths].sort()) {
308
- try {
309
- const acquired = await acquire(path, { waitLimitMs: giveUpAt - Date.now() });
310
- if (!(acquired instanceof Refusal)) held.push(acquired);
311
- } catch (error) {
312
- if (!(error instanceof FileBusyError)) throw error;
326
+ return releasingAfter(
327
+ held,
328
+ async () => {
329
+ for (const path of [...paths].sort()) {
330
+ try {
331
+ const acquired = await acquire(path, { waitLimitMs: giveUpAt - Date.now() });
332
+ if (!(acquired instanceof Refusal)) held.push(acquired);
333
+ } catch (error) {
334
+ if (!(error instanceof FileBusyError)) throw error;
335
+ }
313
336
  }
314
- }
315
- return await action(new Set(held.map(({ path }) => path)));
316
- } finally {
317
- await releaseAll(held);
318
- }
337
+ return action(new Set(held.map(({ path }) => path)));
338
+ },
339
+ onErrorAfterPublish
340
+ );
319
341
  }
320
- async function releaseAll(held) {
321
- const failure = (await Promise.allSettled(held.map(release))).find((result) => result.status === "rejected");
322
- if (failure !== void 0) throw failure.reason;
342
+ async function releasingAfter(held, action, onErrorAfterPublish) {
343
+ let outcome;
344
+ try {
345
+ outcome = await action();
346
+ } catch (error) {
347
+ const [failure] = await releaseFailures(held);
348
+ throw failure === void 0 ? error : failure.error;
349
+ }
350
+ for (const { path, error } of await releaseFailures(held)) onErrorAfterPublish(path, error);
351
+ return outcome;
352
+ }
353
+ async function releaseFailures(held) {
354
+ const failures = await Promise.all(
355
+ held.map(
356
+ (lock) => release(lock).then(
357
+ () => [],
358
+ (error) => [{ path: lock.path, error }]
359
+ )
360
+ )
361
+ );
362
+ return failures.flat();
323
363
  }
324
364
  async function acquire(path, { waitLimitMs = DEFAULT_WAIT_LIMIT_MS }) {
325
- const lock = join(dirname(path), `.${basename(path)}.lock`);
365
+ const lock = lockPathOf(path);
326
366
  const token = `${process.pid} ${randomUUID()}`;
327
367
  const giveUpAt = Date.now() + waitLimitMs;
328
368
  let streak = null;
@@ -447,7 +487,7 @@ async function release({ lock, token, stopRefreshing }) {
447
487
  // src/core/store/atomic-write.ts
448
488
  import { randomUUID as randomUUID2 } from "node:crypto";
449
489
  import { chmod, link, rename, rm as rm3 } from "node:fs/promises";
450
- import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
490
+ import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
451
491
  async function writeFileAtomic(path, content, options) {
452
492
  await viaTemporaryFile(path, content, (temporary) => replaceFile(temporary, path), { ...options, durable: true });
453
493
  }
@@ -482,13 +522,13 @@ var TEMPORARY_FILE = /^\..+\.[0-9a-f-]{36}\.tmp$/;
482
522
  async function removeTemporariesBefore(dir, cutoff) {
483
523
  for (const entry of await listDir(dir)) {
484
524
  if (!entry.isFile() || !TEMPORARY_FILE.test(entry.name)) continue;
485
- const path = join2(dir, entry.name);
525
+ const path = join3(dir, entry.name);
486
526
  const info = await statOrNull(path);
487
527
  if (info !== null && info.mtimeMs < cutoff.getTime()) await rm3(path, { force: true });
488
528
  }
489
529
  }
490
530
  function temporaryPathFor(path) {
491
- return join2(dirname2(path), `.${basename2(path)}.${randomUUID2()}.tmp`);
531
+ return join3(dirname2(path), `.${basename2(path)}.${randomUUID2()}.tmp`);
492
532
  }
493
533
  async function viaTemporaryFile(path, content, publish, { mode, durable, onErrorAfterPublish }) {
494
534
  const temporary = temporaryPathFor(path);
@@ -567,7 +607,7 @@ function toJsonLines(values) {
567
607
  return values.map((value) => `${JSON.stringify(value)}
568
608
  `).join("");
569
609
  }
570
- async function appendJsonLines(path, values) {
610
+ async function appendJsonLines(path, values, { onErrorAfterPublish }) {
571
611
  const startedEmpty = await withFile(
572
612
  path,
573
613
  async (handle) => {
@@ -579,7 +619,7 @@ async function appendJsonLines(path, values) {
579
619
  },
580
620
  { flags: "a+" }
581
621
  );
582
- if (startedEmpty) await syncParentDirectory(path);
622
+ if (startedEmpty) await syncParentDirectory(path).catch((error) => onErrorAfterPublish(path, error));
583
623
  }
584
624
 
585
625
  // src/core/model/history-window.ts
@@ -603,24 +643,28 @@ var cliRunSchema = z.object({
603
643
  rssMb: z.number(),
604
644
  exitCode: z.number()
605
645
  });
606
- async function appendRun(root, run) {
646
+ async function appendRun(root, run, onError) {
607
647
  await mkdir(root, { recursive: true });
608
- const path = join3(root, RUNS_FILE);
609
- await withFileLock(path, () => appendJsonLines(path, [run]));
648
+ const path = join4(root, RUNS_FILE);
649
+ await withWriteLock(path, (afterPublish) => appendJsonLines(path, [run], afterPublish), { onErrorAfterPublish: onError });
610
650
  }
611
651
  async function trimRuns(root, { now, onError }) {
612
- const path = join3(root, RUNS_FILE);
613
- return withFileLock(path, async () => {
614
- const { values: runs, invalidLines } = await readJsonLines(path, cliRunSchema);
615
- const cutoff = retainedSince(now);
616
- const kept = runs.filter((run) => Date.parse(run.at) >= cutoff);
617
- const removed = runs.length - kept.length + invalidLines;
618
- if (removed > 0) await writeFileAtomic(path, toJsonLines(kept), { onErrorAfterPublish: onError });
619
- return removed;
620
- });
652
+ const path = join4(root, RUNS_FILE);
653
+ return withWriteLock(
654
+ path,
655
+ async (afterPublish) => {
656
+ const { values: runs, invalidLines } = await readJsonLines(path, cliRunSchema);
657
+ const cutoff = retainedSince(now);
658
+ const kept = runs.filter((run) => Date.parse(run.at) >= cutoff);
659
+ const removed = runs.length - kept.length + invalidLines;
660
+ if (removed > 0) await writeFileAtomic(path, toJsonLines(kept), afterPublish);
661
+ return removed;
662
+ },
663
+ { onErrorAfterPublish: onError }
664
+ );
621
665
  }
622
666
  async function trimRunsWhenStale(root, writes) {
623
- const first = await firstRun(join3(root, RUNS_FILE));
667
+ const first = await firstRun(join4(root, RUNS_FILE));
624
668
  const staleBefore = retainedSince(writes.now) - STALE_RUN_SLACK_DAYS * DAY_MS;
625
669
  const needsTrim = first.kind === "unparsable" || first.kind === "run" && first.at < staleBefore;
626
670
  return needsTrim ? trimRuns(root, writes) : 0;
@@ -637,17 +681,17 @@ async function firstRunIn(handle) {
637
681
  }
638
682
 
639
683
  // src/core/store/paths.ts
640
- import { basename as basename3, dirname as dirname3, isAbsolute, join as join4, relative, resolve, sep } from "node:path";
684
+ import { dirname as dirname3, isAbsolute, join as join5, relative, resolve, sep } from "node:path";
641
685
  var PROJECT_FILE = "project.md";
642
686
  var PID_FILE_ENV = "P_BACKLOG_PID_FILE";
643
687
  var HOME_PREFIX = /^~[\\/]/;
644
688
  function expandHome(path, home2) {
645
689
  if (path === "~") return home2;
646
- return HOME_PREFIX.test(path) ? join4(home2, path.slice(2)) : path;
690
+ return HOME_PREFIX.test(path) ? join5(home2, path.slice(2)) : path;
647
691
  }
648
692
  function resolveBacklogRoot(env, home2) {
649
693
  const configured = env.BACKLOG_DIR;
650
- return configured ? resolve(expandHome(configured, home2)) : join4(home2, "backlog");
694
+ return configured ? resolve(expandHome(configured, home2)) : join5(home2, "backlog");
651
695
  }
652
696
  function taskFileName(id) {
653
697
  return `${id}.md`;
@@ -655,10 +699,6 @@ function taskFileName(id) {
655
699
  function projectDirOf(project) {
656
700
  return dirname3(project.path);
657
701
  }
658
- function projectDir(root, id) {
659
- const isPlainName = id !== "" && id !== "." && id !== ".." && basename3(id) === id && !id.includes("\\");
660
- return isPlainName ? join4(root, id) : null;
661
- }
662
702
  function relativeInside(container, path) {
663
703
  const inside = relative(container, path);
664
704
  const outside = isAbsolute(inside) || inside === ".." || inside.startsWith(`..${sep}`);
@@ -667,7 +707,7 @@ function relativeInside(container, path) {
667
707
 
668
708
  // src/core/store/settings.ts
669
709
  import { mkdir as mkdir2 } from "node:fs/promises";
670
- import { join as join6 } from "node:path";
710
+ import { join as join7 } from "node:path";
671
711
 
672
712
  // src/core/i18n/language.ts
673
713
  var LANGUAGES = ["ru", "en"];
@@ -683,7 +723,7 @@ import { z as z2 } from "zod";
683
723
  var settingsSchema = z2.object({ language: z2.enum(LANGUAGES) });
684
724
 
685
725
  // src/core/store/load.ts
686
- import { basename as basename4, join as join5 } from "node:path";
726
+ import { basename as basename3, join as join6 } from "node:path";
687
727
 
688
728
  // src/core/model/checklist.ts
689
729
  var ITEM = /^\s*[-*+]\s+\[(?<mark>[ xX])\]\s+(?<text>.*)$/;
@@ -781,21 +821,21 @@ function compareIds(a, b) {
781
821
  if (!left || !right) return a.localeCompare(b);
782
822
  return left.prefix === right.prefix ? left.number - right.number : left.prefix.localeCompare(right.prefix);
783
823
  }
784
- function derivePrefix(basename11, taken) {
785
- const base = prefixBase(basename11);
824
+ function derivePrefix(basename10, taken) {
825
+ const base = prefixBase(basename10);
786
826
  return firstFree(base, taken, (n) => `${base}${n}`);
787
827
  }
788
- function projectIdBase(basename11) {
789
- const slug = basename11.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
828
+ function projectIdBase(basename10) {
829
+ const slug = basename10.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
790
830
  return slug === "" ? "project" : slug;
791
831
  }
792
- function deriveProjectId(basename11, taken) {
793
- const base = projectIdBase(basename11);
832
+ function deriveProjectId(basename10, taken) {
833
+ const base = projectIdBase(basename10);
794
834
  return firstFree(base, taken, (n) => `${base}-${n}`);
795
835
  }
796
836
  var PREFIX_BASE_LENGTH = 4;
797
- function prefixBase(basename11) {
798
- const words = basename11.split(/[^A-Za-z0-9]+/).filter(Boolean);
837
+ function prefixBase(basename10) {
838
+ const words = basename10.split(/[^A-Za-z0-9]+/).filter(Boolean);
799
839
  const letters = words.length > 1 ? words.map((word) => word.charAt(0)).join("") : words[0] ?? "";
800
840
  const prefix = letters.slice(0, PREFIX_BASE_LENGTH).toUpperCase();
801
841
  if (prefix === "") return "PROJ";
@@ -1008,21 +1048,29 @@ function indexOfLoaded({ tasks, errors }) {
1008
1048
  return buildIndex(tasks, notLoadedTasks(errors));
1009
1049
  }
1010
1050
  function taskIdOfFile(path) {
1011
- return basename4(path, ".md");
1051
+ return basename3(path, ".md");
1052
+ }
1053
+ async function projectEntries(root) {
1054
+ return (await listDirFollowingLinks(root)).filter((entry) => !entry.name.startsWith(".") && (entry.kind === "directory" || entry.kind === "link-unreachable"));
1012
1055
  }
1013
1056
  async function projectDirNames(root) {
1014
- return (await listDir(root)).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
1057
+ return (await projectEntries(root)).filter((entry) => entry.kind === "directory").map((entry) => entry.name);
1015
1058
  }
1016
1059
  async function loadBacklog(root) {
1017
- const parts = await Promise.all((await projectDirNames(root)).map((name) => loadProjectDir(join5(root, name), name)));
1060
+ const parts = await Promise.all((await projectEntries(root)).map((entry) => loadProjectEntry(root, entry)));
1018
1061
  return {
1019
1062
  projects: parts.flatMap((part) => part.projects).sort((a, b) => a.id.localeCompare(b.id)),
1020
1063
  tasks: parts.flatMap((part) => part.tasks).sort((a, b) => compareIds(a.id, b.id)),
1021
1064
  errors: parts.flatMap((part) => part.errors).sort((a, b) => a.path.localeCompare(b.path))
1022
1065
  };
1023
1066
  }
1067
+ async function loadProjectEntry(root, { name, kind }) {
1068
+ const path = join6(root, name);
1069
+ if (kind === "directory") return loadProjectDir(path, name);
1070
+ return { projects: [], tasks: [], errors: [{ path, projectId: name, fileKind: "project", problems: [{ code: "link-unreachable" }], hiddenTasks: [], claimedRepos: [] }] };
1071
+ }
1024
1072
  async function loadProjectDir(dir, projectId) {
1025
- const projectPath = join5(dir, PROJECT_FILE);
1073
+ const projectPath = join6(dir, PROJECT_FILE);
1026
1074
  const bytes = await readBytesOrNull(projectPath);
1027
1075
  if (bytes === null) return { projects: [], tasks: [], errors: [] };
1028
1076
  const document = documentOf(bytes);
@@ -1032,29 +1080,30 @@ async function loadProjectDir(dir, projectId) {
1032
1080
  const claimedRepos = claimedReposOf(bytes.toString("utf8"));
1033
1081
  return { projects: [], tasks: [], errors: [{ path: projectPath, projectId, fileKind: "project", problems: project.problems, hiddenTasks, claimedRepos }] };
1034
1082
  }
1035
- const taskPaths = (await taskFileNames(dir)).map((name) => join5(dir, name));
1036
- const loaded = await Promise.all(taskPaths.map(async (path) => ({ path, result: await loadTaskFile(path, project.value) })));
1083
+ const taskEntries = (await listDir(dir)).filter((entry) => isTaskFileName(entry.name)).map((entry) => ({ path: join6(dir, entry.name), entry }));
1084
+ const loaded = await Promise.all(taskEntries.map(async ({ path, entry }) => ({ path, result: await loadTaskEntry(path, entry, project.value) })));
1037
1085
  return {
1038
1086
  projects: [project.value],
1039
1087
  tasks: loaded.flatMap(({ result }) => result?.ok ? [result.value] : []),
1040
1088
  errors: loaded.flatMap(({ path, result }) => result && !result.ok ? [{ path, projectId, fileKind: "task", problems: result.problems }] : [])
1041
1089
  };
1042
1090
  }
1091
+ async function loadTaskEntry(path, entry, project) {
1092
+ if (entry.isFile()) return loadTaskFile(path, project);
1093
+ return { ok: false, problems: [{ code: entry.isSymbolicLink() ? "task-is-link" : "not-a-file" }] };
1094
+ }
1043
1095
  async function loadTaskFile(path, project) {
1044
1096
  const parsed = await parseDocumentOrNull(path, (text) => parseTaskFile(text, { projectId: project.id, path, version: contentVersion(text) }));
1045
1097
  if (parsed === null || !parsed.ok) return parsed;
1046
- const stem = basename4(path, ".md");
1098
+ const stem = basename3(path, ".md");
1047
1099
  if (parsed.value.id !== stem) return { ok: false, problems: [{ code: "id-mismatch", id: parsed.value.id, file: stem }] };
1048
1100
  if (parseId(stem)?.prefix !== project.prefix) {
1049
1101
  return { ok: false, problems: [{ code: "prefix-mismatch", file: stem, prefix: project.prefix }] };
1050
1102
  }
1051
1103
  return parsed;
1052
1104
  }
1053
- async function taskIdsOnDisk(projectDir2) {
1054
- return new Set((await taskFileNames(projectDir2)).map((name) => basename4(name, ".md")));
1055
- }
1056
- async function taskFileNames(projectDir2) {
1057
- return (await listDir(projectDir2)).filter((entry) => entry.isFile() && isTaskFileName(entry.name)).map((entry) => entry.name);
1105
+ async function taskIdsOnDisk(projectDir) {
1106
+ return new Set((await listDir(projectDir)).filter((entry) => isTaskFileName(entry.name)).map((entry) => taskIdOfFile(entry.name)));
1058
1107
  }
1059
1108
  function isTaskFileName(name) {
1060
1109
  return name.endsWith(".md") && ID_PATTERN.test(name.slice(0, -".md".length));
@@ -1063,7 +1112,7 @@ function isTaskFileName(name) {
1063
1112
  // src/core/store/settings.ts
1064
1113
  var SETTINGS_FILE = ".settings.json";
1065
1114
  function settingsFilePath(root) {
1066
- return join6(root, SETTINGS_FILE);
1115
+ return join7(root, SETTINGS_FILE);
1067
1116
  }
1068
1117
  async function readSettingsFile(root) {
1069
1118
  const text = await readTextOrNull(settingsFilePath(root));
@@ -1437,6 +1486,12 @@ function problem(p) {
1437
1486
  return `YAML error: ${p.detail}`;
1438
1487
  case "schema":
1439
1488
  return p.path === "" ? schemaIssue2(p.issue) : `${p.path}: ${schemaIssue2(p.issue)}`;
1489
+ case "not-a-file":
1490
+ return "not a file \u2014 the backlog reads only regular files and links to them";
1491
+ case "link-unreachable":
1492
+ return "the link does not lead to an accessible file or directory";
1493
+ case "task-is-link":
1494
+ return "the task is a link; links are supported only for a project directory";
1440
1495
  case "id-mismatch":
1441
1496
  return `id ${p.id} does not match the file name ${p.file}.md`;
1442
1497
  case "prefix-mismatch":
@@ -1527,7 +1582,7 @@ var coreEn = {
1527
1582
  closedNotSwept: (error) => `Could not delete closed tasks: ${error}`,
1528
1583
  serviceLogNotTrimmed: (error) => `Could not trim the service log: ${error}`,
1529
1584
  candidatesRecordFailed: (projectId, detail) => `Could not record candidates to the ${projectId} journal: ${detail}`,
1530
- branchOriginsReadFailed: (projectId, detail) => `Could not read the ${projectId} journal \u2014 tasks from unmerged branches are checked as usual: ${detail}`,
1585
+ markCommitsReadFailed: (projectId, detail) => `Could not read the ${projectId} journal \u2014 the commits tasks were created and confirmed on are unknown: tasks from unmerged branches are checked as usual, and the code at the mark is taken from the reflog: ${detail}`,
1531
1586
  unreadableSkipped: (path, detail) => `Could not read ${path}, skipped: ${detail}`,
1532
1587
  settingsNotSaved: (path, detail) => `Could not save the language to ${path}: ${detail}. It is detected again on every run \u2014 make the backlog directory writable.`,
1533
1588
  settingsFileInvalid: (path) => `${path} could not be parsed, the language for this run was detected automatically. The file was not changed \u2014 fix it manually.`
@@ -1702,6 +1757,12 @@ function problem2(p) {
1702
1757
  return `\u043E\u0448\u0438\u0431\u043A\u0430 YAML: ${p.detail}`;
1703
1758
  case "schema":
1704
1759
  return p.path === "" ? schemaIssue3(p.issue) : `${p.path}: ${schemaIssue3(p.issue)}`;
1760
+ case "not-a-file":
1761
+ return "\u043D\u0435 \u0444\u0430\u0439\u043B \u2014 \u0431\u0435\u043A\u043B\u043E\u0433 \u0447\u0438\u0442\u0430\u0435\u0442 \u0442\u043E\u043B\u044C\u043A\u043E \u043E\u0431\u044B\u0447\u043D\u044B\u0435 \u0444\u0430\u0439\u043B\u044B \u0438 \u0441\u0441\u044B\u043B\u043A\u0438 \u043D\u0430 \u043D\u0438\u0445";
1762
+ case "link-unreachable":
1763
+ return "\u0441\u0441\u044B\u043B\u043A\u0430 \u043D\u0435 \u0432\u0435\u0434\u0451\u0442 \u043A \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u043C\u0443 \u0444\u0430\u0439\u043B\u0443 \u0438\u043B\u0438 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0443";
1764
+ case "task-is-link":
1765
+ return "\u0437\u0430\u0434\u0430\u0447\u0430 \u2014 \u0441\u0441\u044B\u043B\u043A\u0430; \u0441\u0441\u044B\u043B\u043A\u0438 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u044E\u0442\u0441\u044F \u0442\u043E\u043B\u044C\u043A\u043E \u0434\u043B\u044F \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430 \u043F\u0440\u043E\u0435\u043A\u0442\u0430";
1705
1766
  case "id-mismatch":
1706
1767
  return `id ${p.id} \u043D\u0435 \u0441\u043E\u0432\u043F\u0430\u0434\u0430\u0435\u0442 \u0441 \u0438\u043C\u0435\u043D\u0435\u043C \u0444\u0430\u0439\u043B\u0430 ${p.file}.md`;
1707
1768
  case "prefix-mismatch":
@@ -1792,7 +1853,7 @@ var coreRu = {
1792
1853
  closedNotSwept: (error) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0437\u0430\u043A\u0440\u044B\u0442\u044B\u0435 \u0437\u0430\u0434\u0430\u0447\u0438: ${error}`,
1793
1854
  serviceLogNotTrimmed: (error) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0431\u0440\u0435\u0437\u0430\u0442\u044C \u043B\u043E\u0433 \u0441\u043B\u0443\u0436\u0431\u044B: ${error}`,
1794
1855
  candidatesRecordFailed: (projectId, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044C \u043A\u0430\u043D\u0434\u0438\u0434\u0430\u0442\u043E\u0432 \u0432 \u0436\u0443\u0440\u043D\u0430\u043B ${projectId}: ${detail}`,
1795
- branchOriginsReadFailed: (projectId, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0436\u0443\u0440\u043D\u0430\u043B ${projectId} \u2014 \u0437\u0430\u0434\u0430\u0447\u0438 \u0438\u0437 \u043D\u0435\u0432\u043B\u0438\u0442\u044B\u0445 \u0432\u0435\u0442\u043E\u043A \u043F\u0440\u043E\u0432\u0435\u0440\u044F\u044E\u0442\u0441\u044F \u043A\u0430\u043A \u043E\u0431\u044B\u0447\u043D\u044B\u0435: ${detail}`,
1856
+ markCommitsReadFailed: (projectId, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0436\u0443\u0440\u043D\u0430\u043B ${projectId} \u2014 \u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u043E, \u043D\u0430 \u043A\u0430\u043A\u0438\u0445 \u043A\u043E\u043C\u043C\u0438\u0442\u0430\u0445 \u0437\u0430\u0434\u0430\u0447\u0438 \u0437\u0430\u0432\u043E\u0434\u0438\u043B\u0438 \u0438 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0430\u043B\u0438: \u0437\u0430\u0434\u0430\u0447\u0438 \u0438\u0437 \u043D\u0435\u0432\u043B\u0438\u0442\u044B\u0445 \u0432\u0435\u0442\u043E\u043A \u043F\u0440\u043E\u0432\u0435\u0440\u044F\u044E\u0442\u0441\u044F \u043A\u0430\u043A \u043E\u0431\u044B\u0447\u043D\u044B\u0435, \u0430 \u043A\u043E\u0434 \u043D\u0430 \u043C\u043E\u043C\u0435\u043D\u0442 \u043E\u0442\u043C\u0435\u0442\u043A\u0438 \u0431\u0435\u0440\u0451\u0442\u0441\u044F \u0438\u0437 reflog: ${detail}`,
1796
1857
  unreadableSkipped: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C ${path}, \u043E\u043D \u043F\u0440\u043E\u043F\u0443\u0449\u0435\u043D: ${detail}`,
1797
1858
  settingsNotSaved: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u044F\u0437\u044B\u043A \u0432 ${path}: ${detail}. \u041E\u043D \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u044F\u0435\u0442\u0441\u044F \u0437\u0430\u043D\u043E\u0432\u043E \u043F\u0440\u0438 \u043A\u0430\u0436\u0434\u043E\u043C \u0437\u0430\u043F\u0443\u0441\u043A\u0435 \u2014 \u0440\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u0435 \u0437\u0430\u043F\u0438\u0441\u044C \u0432 \u043A\u0430\u0442\u0430\u043B\u043E\u0433 \u0431\u0435\u043A\u043B\u043E\u0433\u0430.`,
1798
1859
  settingsFileInvalid: (path) => `${path} \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D, \u044F\u0437\u044B\u043A \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0451\u043D \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438. \u0424\u0430\u0439\u043B \u043D\u0435 \u0438\u0437\u043C\u0435\u043D\u0451\u043D \u2014 \u043F\u043E\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0435\u0433\u043E \u0432\u0440\u0443\u0447\u043D\u0443\u044E.`
@@ -1815,7 +1876,7 @@ function isBacklogHookFeedback(text) {
1815
1876
  }
1816
1877
 
1817
1878
  // src/core/store/journal-compaction.ts
1818
- import { basename as basename5, join as join9 } from "node:path";
1879
+ import { basename as basename4, join as join10 } from "node:path";
1819
1880
 
1820
1881
  // src/core/collections.ts
1821
1882
  function groupBy(items, keyOf) {
@@ -1891,7 +1952,7 @@ var journalEventSchema = z7.discriminatedUnion("kind", [
1891
1952
  z7.object({ ...eventBase, kind: z7.literal("priority"), from: recordedEnum(PRIORITIES), to: recordedEnum(PRIORITIES) }),
1892
1953
  z7.object({ ...eventBase, kind: z7.literal("deleted"), snapshot: taskSnapshotSchema }),
1893
1954
  z7.object({ ...eventBase, kind: z7.literal("category"), from: recordedEnum(TASK_CATEGORIES).optional(), to: recordedEnum(TASK_CATEGORIES).optional() }),
1894
- z7.object({ ...eventBase, kind: z7.literal("verified"), source: z7.string().optional() }),
1955
+ z7.object({ ...eventBase, kind: z7.literal("verified"), source: z7.string().optional(), commit: z7.string().min(1).optional().catch(void 0) }),
1895
1956
  z7.object({
1896
1957
  ...eventBase,
1897
1958
  kind: z7.literal("candidate"),
@@ -1942,7 +2003,7 @@ function createdEvent(task, now, via, provenance = {}) {
1942
2003
  origin: provenance.origin
1943
2004
  };
1944
2005
  }
1945
- function changeEvents(before, after, now, via) {
2006
+ function changeEvents(before, after, now, via, headCommit) {
1946
2007
  const at = formatLocalIso(now);
1947
2008
  const events = [];
1948
2009
  if (before.status !== after.status) {
@@ -1952,7 +2013,7 @@ function changeEvents(before, after, now, via) {
1952
2013
  if (before.priority !== after.priority) events.push({ at, task: after.id, via, kind: "priority", from: before.priority, to: after.priority });
1953
2014
  if (before.category !== after.category) events.push({ at, task: after.id, via, kind: "category", from: before.category, to: after.category });
1954
2015
  if (before.verified !== after.verified) {
1955
- events.push({ at, task: after.id, via, kind: "verified", source: before.source === after.source ? void 0 : after.source });
2016
+ events.push({ at, task: after.id, via, kind: "verified", source: before.source === after.source ? void 0 : after.source, commit: headCommit });
1956
2017
  }
1957
2018
  return events;
1958
2019
  }
@@ -2089,21 +2150,25 @@ function dedupeSightings(sightings) {
2089
2150
  async function runWhenDue(stampPath, writes, action) {
2090
2151
  if (!await isDue(stampPath, writes.now)) return null;
2091
2152
  try {
2092
- return await withFileLock(stampPath, async () => {
2093
- if (!await isDue(stampPath, writes.now)) return null;
2094
- return runAndStamp(stampPath, writes, action);
2095
- });
2153
+ return await withWriteLock(
2154
+ stampPath,
2155
+ async (afterPublish) => {
2156
+ if (!await isDue(stampPath, writes.now)) return null;
2157
+ return runAndStamp(stampPath, { now: writes.now, ...afterPublish }, action);
2158
+ },
2159
+ { onErrorAfterPublish: writes.onError }
2160
+ );
2096
2161
  } catch (error) {
2097
2162
  if (error instanceof FileBusyError && error.path === stampPath) return null;
2098
2163
  throw error;
2099
2164
  }
2100
2165
  }
2101
- async function runAndStamp(stampPath, { now, onError }, action) {
2166
+ async function runAndStamp(stampPath, { now, ...afterPublish }, action) {
2102
2167
  try {
2103
2168
  return await action();
2104
2169
  } finally {
2105
2170
  await writeFileAtomic(stampPath, `${formatLocalIso(now)}
2106
- `, { onErrorAfterPublish: onError });
2171
+ `, afterPublish);
2107
2172
  }
2108
2173
  }
2109
2174
  async function isDue(stampPath, now) {
@@ -2112,31 +2177,31 @@ async function isDue(stampPath, now) {
2112
2177
  }
2113
2178
 
2114
2179
  // src/core/store/journal.ts
2115
- import { join as join7 } from "node:path";
2180
+ import { join as join8 } from "node:path";
2116
2181
  var JOURNAL_FILE = "journal.jsonl";
2117
- async function appendJournal(projectDir2, events, onError) {
2182
+ async function appendJournal(projectDir, events, onError) {
2118
2183
  if (events.length === 0) return;
2119
- const path = join7(projectDir2, JOURNAL_FILE);
2184
+ const path = join8(projectDir, JOURNAL_FILE);
2120
2185
  try {
2121
- await appendWaitingForLock(path, events);
2186
+ await appendWaitingForLock(path, events, { onErrorAfterPublish: onError });
2122
2187
  } catch (error) {
2123
2188
  onError(path, error);
2124
2189
  }
2125
2190
  }
2126
2191
  var JOURNAL_LOCK_WAIT_MS = 4 * BLOCKED_RETRIES_TOTAL_MS + 10 * SECOND_MS;
2127
- async function appendWaitingForLock(path, events) {
2192
+ async function appendWaitingForLock(path, events, afterPublish) {
2128
2193
  try {
2129
- await withFileLock(path, () => appendJsonLines(path, events), { waitLimitMs: JOURNAL_LOCK_WAIT_MS });
2194
+ await withWriteLock(path, (underLock) => appendJsonLines(path, events, underLock), { ...afterPublish, waitLimitMs: JOURNAL_LOCK_WAIT_MS });
2130
2195
  } catch (error) {
2131
2196
  if (!(error instanceof FileBusyError)) throw error;
2132
- await appendJsonLines(path, events);
2197
+ await appendJsonLines(path, events, afterPublish);
2133
2198
  }
2134
2199
  }
2135
2200
  function appendingJournal(onError) {
2136
- return (projectDir2, events) => appendJournal(projectDir2, events, onError);
2201
+ return (projectDir, events) => appendJournal(projectDir, events, onError);
2137
2202
  }
2138
2203
  function undoJournal(write) {
2139
- return (projectDir2, events) => write(projectDir2, events.map(markedUndo));
2204
+ return (projectDir, events) => write(projectDir, events.map(markedUndo));
2140
2205
  }
2141
2206
  function markedUndo(event) {
2142
2207
  return { ...event, undo: true };
@@ -2144,34 +2209,34 @@ function markedUndo(event) {
2144
2209
  function bufferedJournal(target) {
2145
2210
  const pending = /* @__PURE__ */ new Map();
2146
2211
  return {
2147
- write: (projectDir2, events) => {
2148
- pending.set(projectDir2, [...pending.get(projectDir2) ?? [], ...events]);
2212
+ write: (projectDir, events) => {
2213
+ pending.set(projectDir, [...pending.get(projectDir) ?? [], ...events]);
2149
2214
  return Promise.resolve();
2150
2215
  },
2151
2216
  flush: async () => {
2152
- for (const [projectDir2, events] of pending) await target(projectDir2, events);
2217
+ for (const [projectDir, events] of pending) await target(projectDir, events);
2153
2218
  pending.clear();
2154
2219
  }
2155
2220
  };
2156
2221
  }
2157
- async function readJournal(projectDir2, projectId) {
2158
- return projectJournal(projectId, await readJsonLines(join7(projectDir2, JOURNAL_FILE), journalEventSchema));
2222
+ async function readJournal(projectDir, projectId) {
2223
+ return projectJournal(projectId, await readJsonLines(join8(projectDir, JOURNAL_FILE), journalEventSchema));
2159
2224
  }
2160
2225
  function projectJournal(projectId, { values, invalidLines }) {
2161
2226
  return { projectId, events: values, invalidLines };
2162
2227
  }
2163
2228
  async function readJournals(root, projectIds) {
2164
- return Promise.all(projectIds.map((projectId) => readJournal(join7(root, projectId), projectId)));
2229
+ return Promise.all(projectIds.map((projectId) => readJournal(join8(root, projectId), projectId)));
2165
2230
  }
2166
2231
 
2167
2232
  // src/core/store/projects.ts
2168
2233
  import { rm as rm4 } from "node:fs/promises";
2169
- import { join as join8 } from "node:path";
2234
+ import { join as join9 } from "node:path";
2170
2235
  var NOT_FOUND2 = { ok: false, reason: "not-found" };
2171
2236
  async function setProjectActive(root, id, active, onError) {
2172
- const dir = projectDir(root, id);
2237
+ const dir = await existingProjectDir(root, id);
2173
2238
  if (dir === null) return NOT_FOUND2;
2174
- return editProjectFile({ id, path: join8(dir, PROJECT_FILE) }, onError, (project) => project.active === active ? project : { ...project, active });
2239
+ return editProjectFile({ id, path: join9(dir, PROJECT_FILE) }, onError, (project) => project.active === active ? project : { ...project, active });
2175
2240
  }
2176
2241
  function reserveIssuedUpTo(project, number, onError) {
2177
2242
  return editProjectFile(project, onError, (current) => {
@@ -2188,30 +2253,29 @@ async function readProjectFile({ id, path }) {
2188
2253
  }
2189
2254
  async function editProjectFile({ id, path }, onError, edit) {
2190
2255
  if (!await fileExists(path)) return NOT_FOUND2;
2191
- let written = null;
2192
- try {
2193
- return await withFileLock(path, async () => {
2256
+ return withWriteLock(
2257
+ path,
2258
+ async (afterPublish) => {
2194
2259
  const parsed = await readProjectFile({ id, path });
2195
2260
  if (parsed === null) return NOT_FOUND2;
2196
2261
  if (!parsed.ok) return { ok: false, reason: "invalid", problems: parsed.problems };
2197
2262
  const project = edit(parsed.value);
2198
2263
  const changed = project !== parsed.value;
2199
- if (changed) await writeFileAtomic(path, serializeProject(project), { onErrorAfterPublish: onError });
2200
- written = { ok: true, project, changed };
2201
- return written;
2202
- });
2203
- } catch (error) {
2204
- if (written === null) throw error;
2205
- onError(path, error);
2206
- return written;
2207
- }
2264
+ if (changed) await writeFileAtomic(path, serializeProject(project), afterPublish);
2265
+ return { ok: true, project, changed };
2266
+ },
2267
+ { onErrorAfterPublish: onError }
2268
+ );
2208
2269
  }
2209
2270
  async function deleteProject(root, id) {
2210
- const dir = projectDir(root, id);
2211
- if (dir === null || await readTextOrNull(join8(dir, PROJECT_FILE)) === null) return NOT_FOUND2;
2271
+ const dir = await existingProjectDir(root, id);
2272
+ if (dir === null || await readTextOrNull(join9(dir, PROJECT_FILE)) === null) return NOT_FOUND2;
2212
2273
  await rm4(dir, { recursive: true, force: true });
2213
2274
  return { ok: true };
2214
2275
  }
2276
+ async function existingProjectDir(root, id) {
2277
+ return (await projectDirNames(root)).includes(id) ? join9(root, id) : null;
2278
+ }
2215
2279
 
2216
2280
  // src/core/store/journal-compaction.ts
2217
2281
  var COMPACTED_STAMP = ".journal-compacted-at";
@@ -2219,7 +2283,7 @@ var EPISODE_KINDS = /* @__PURE__ */ new Set(["candidate", "candidate-gone", "can
2219
2283
  async function compactJournalsWhenDue(root, writes, onNotCompacted) {
2220
2284
  const compacted = [];
2221
2285
  for (const name of await projectDirNames(root)) {
2222
- const dir = join9(root, name);
2286
+ const dir = join10(root, name);
2223
2287
  const removed = await compactProjectWhenDue(dir, writes).catch((error) => {
2224
2288
  onNotCompacted(dir, error);
2225
2289
  return null;
@@ -2229,29 +2293,33 @@ async function compactJournalsWhenDue(root, writes, onNotCompacted) {
2229
2293
  return compacted;
2230
2294
  }
2231
2295
  async function compactProjectWhenDue(dir, writes) {
2232
- if (!await fileExists(join9(dir, JOURNAL_FILE))) return null;
2233
- return runWhenDue(join9(dir, COMPACTED_STAMP), writes, async () => compactJournal(dir, await taskIdsOnDisk(dir), writes));
2296
+ if (!await fileExists(join10(dir, JOURNAL_FILE))) return null;
2297
+ return runWhenDue(join10(dir, COMPACTED_STAMP), writes, async () => compactJournal(dir, await taskIdsOnDisk(dir), writes));
2234
2298
  }
2235
- async function compactJournal(projectDir2, liveTaskIds, { now, onError }) {
2236
- const path = join9(projectDir2, JOURNAL_FILE);
2299
+ async function compactJournal(projectDir, liveTaskIds, { now, onError }) {
2300
+ const path = join10(projectDir, JOURNAL_FILE);
2237
2301
  if (!await fileExists(path)) return 0;
2238
- return withFileLock(path, async () => {
2239
- const journal = await readBytesOrNull(path) ?? Buffer.alloc(0);
2240
- const completeLines = journal.subarray(0, journal.lastIndexOf(NEWLINE) + 1);
2241
- const lines = journalLines(completeLines.toString("utf8"));
2242
- const kept = retainedLines(lines, liveTaskIds, retainedSince(now));
2243
- const keptLines = new Set(kept);
2244
- const dropped = lines.filter((line) => !keptLines.has(line));
2245
- if (dropped.length === 0 || !await reserveDroppedNumbers(projectDir2, dropped, onError)) return 0;
2246
- const replaced = await replacePrefixAtomic(path, completeLines, kept.map(({ text }) => `${text}
2247
- `).join(""), { onErrorAfterPublish: onError });
2248
- return replaced ? dropped.length : 0;
2249
- });
2302
+ return withWriteLock(
2303
+ path,
2304
+ async (afterPublish) => {
2305
+ const journal = await readBytesOrNull(path) ?? Buffer.alloc(0);
2306
+ const completeLines = journal.subarray(0, journal.lastIndexOf(NEWLINE) + 1);
2307
+ const lines = journalLines(completeLines.toString("utf8"));
2308
+ const kept = retainedLines(lines, liveTaskIds, retainedSince(now));
2309
+ const keptLines = new Set(kept);
2310
+ const dropped = lines.filter((line) => !keptLines.has(line));
2311
+ if (dropped.length === 0 || !await reserveDroppedNumbers(projectDir, dropped, onError)) return 0;
2312
+ const replaced = await replacePrefixAtomic(path, completeLines, kept.map(({ text }) => `${text}
2313
+ `).join(""), afterPublish);
2314
+ return replaced ? dropped.length : 0;
2315
+ },
2316
+ { onErrorAfterPublish: onError }
2317
+ );
2250
2318
  }
2251
- async function reserveDroppedNumbers(projectDir2, dropped, onError) {
2319
+ async function reserveDroppedNumbers(projectDir, dropped, onError) {
2252
2320
  const highest = dropped.reduce((max, { event }) => event === null ? max : Math.max(max, parseId(event.task)?.number ?? 0), 0);
2253
2321
  if (highest === 0) return true;
2254
- const reservation = await reserveIssuedUpTo({ id: basename5(projectDir2), path: join9(projectDir2, PROJECT_FILE) }, highest, onError);
2322
+ const reservation = await reserveIssuedUpTo({ id: basename4(projectDir), path: join10(projectDir, PROJECT_FILE) }, highest, onError);
2255
2323
  return reservation.ok || reservation.reason === "not-found";
2256
2324
  }
2257
2325
  function journalLines(text) {
@@ -2337,7 +2405,7 @@ function invalidTasksText(invalid2) {
2337
2405
  }
2338
2406
 
2339
2407
  // src/core/store/sweep.ts
2340
- import { dirname as dirname5, join as join10 } from "node:path";
2408
+ import { dirname as dirname5, join as join11 } from "node:path";
2341
2409
 
2342
2410
  // src/core/model/lifecycle.ts
2343
2411
  var RETENTION_DAYS = 7;
@@ -2553,7 +2621,7 @@ async function reopenEpicOfOpenedTask(index, { before, after }, { now, via, onEr
2553
2621
  return void 0;
2554
2622
  }
2555
2623
  }
2556
- async function writeChanges(index, { id, changes, expectedVersion, now, closure, via, onError, journal = appendingJournal(onError) }) {
2624
+ async function writeChanges(index, { id, changes, expectedVersion, now, closure, headCommit, via, onError, journal = appendingJournal(onError) }) {
2557
2625
  const current = index.byId.get(id);
2558
2626
  if (!current) return { ok: false, reason: "not-found" };
2559
2627
  if (expectedVersion !== current.version) return { ok: false, reason: "conflict", current };
@@ -2564,29 +2632,25 @@ async function writeChanges(index, { id, changes, expectedVersion, now, closure,
2564
2632
  const integrity = integrityErrors(task, index).filter((problem3) => !(keepsEpic && isUnloadedEpic(problem3)));
2565
2633
  const problems3 = [...integrity, ...epicClosingProblems(current, task, index)];
2566
2634
  if (problems3.length > 0) return invalid(problems3);
2567
- let written = false;
2568
- try {
2569
- return await withTaskLock(current.path, async () => {
2635
+ const result = await withTaskLock(
2636
+ current.path,
2637
+ async (afterPublish) => {
2570
2638
  const changedOnDisk = await diskChange(current, expectedVersion);
2571
2639
  if (changedOnDisk !== null) return changedOnDisk;
2572
- await writeFileAtomic(current.path, text, { onErrorAfterPublish: onError });
2573
- written = true;
2640
+ await writeFileAtomic(current.path, text, afterPublish);
2574
2641
  return { ok: true, task };
2575
- });
2576
- } catch (error) {
2577
- if (!written) throw error;
2578
- onError(current.path, error);
2579
- return { ok: true, task };
2580
- } finally {
2581
- if (written) await journal(dirname4(current.path), changeEvents(current, task, now, via));
2582
- }
2642
+ },
2643
+ { onErrorAfterPublish: onError }
2644
+ );
2645
+ if (result.ok) await journal(dirname4(current.path), changeEvents(current, task, now, via, headCommit));
2646
+ return result;
2583
2647
  }
2584
2648
  function isUnloadedEpic(problem3) {
2585
2649
  return problem3.code === "epic-missing" || problem3.code === "epic-unparsed";
2586
2650
  }
2587
- async function withTaskLock(path, write) {
2651
+ async function withTaskLock(path, write, afterPublish) {
2588
2652
  try {
2589
- return await withFileLock(path, write);
2653
+ return await withWriteLock(path, write, afterPublish);
2590
2654
  } catch (error) {
2591
2655
  if (!(error instanceof FileBusyError) || error.path !== path) throw error;
2592
2656
  return { ok: false, reason: "busy", path, lock: error.lock, seconds: error.seconds };
@@ -2634,10 +2698,10 @@ function nextOptional(current, change) {
2634
2698
  // src/core/store/sweep.ts
2635
2699
  var SWEPT_AT_FILE = ".swept-at";
2636
2700
  function sweepClosedWhenDue(root, writes, messages) {
2637
- return runWhenDue(join10(root, SWEPT_AT_FILE), writes, () => sweepClosed(root, writes, messages));
2701
+ return runWhenDue(join11(root, SWEPT_AT_FILE), writes, () => sweepClosed(root, writes, messages));
2638
2702
  }
2639
2703
  function sweepClosedAndStamp(root, writes, messages) {
2640
- return runAndStamp(join10(root, SWEPT_AT_FILE), writes, () => sweepClosed(root, writes, messages));
2704
+ return runAndStamp(join11(root, SWEPT_AT_FILE), { now: writes.now, onErrorAfterPublish: writes.onError }, () => sweepClosed(root, writes, messages));
2641
2705
  }
2642
2706
  async function sweepClosed(root, writes, messages) {
2643
2707
  const { now } = writes;
@@ -2663,7 +2727,7 @@ async function sweepClosed(root, writes, messages) {
2663
2727
  }
2664
2728
  async function removeAbandonedTemporaries(root, now) {
2665
2729
  const cutoff = new Date(now.getTime() - DAY_MS);
2666
- const projectDirs = (await projectDirNames(root)).map((name) => join10(root, name));
2730
+ const projectDirs = (await projectDirNames(root)).map((name) => join11(root, name));
2667
2731
  for (const dir of [root, ...projectDirs]) await removeTemporariesBefore(dir, cutoff);
2668
2732
  }
2669
2733
  async function removeWithReferences(remaining, removable, writes) {
@@ -2683,7 +2747,8 @@ async function removeWithReferences(remaining, removable, writes) {
2683
2747
  );
2684
2748
  const untouched = removable.filter((task) => !unchanged.includes(task)).map(conflict);
2685
2749
  return { deleted: removal.deleted, failures: [...updates.failures, ...untouched, ...removal.failures] };
2686
- }
2750
+ },
2751
+ { onErrorAfterPublish: writes.onError }
2687
2752
  );
2688
2753
  } finally {
2689
2754
  await journal.flush();
@@ -2818,8 +2883,11 @@ var cliEn = {
2818
2883
  installHookAdded: (settingsPath) => `Stop hook added to ${settingsPath}`,
2819
2884
  installHookUpdated: (settingsPath) => `Stop hook updated in ${settingsPath}`,
2820
2885
  hookApproval: (agent, command2) => `approve the hook in ${agent}: ${command2}`,
2821
- installHookConfigUnreadable: (path, detail) => `Could not read ${path} (${detail}), Stop hook not added.`,
2822
- installHookConfigInvalid: (path) => `${path} is not a JSON object, Stop hook not added. Fix the file and try again.`,
2886
+ installHookConfigFailed: {
2887
+ unreadable: (path, detail) => `Could not read ${path} (${detail}), Stop hook not added.`,
2888
+ unwritable: (path, detail) => `Could not write ${path} (${detail}), Stop hook not added.`,
2889
+ invalid: (path) => `${path} is not a JSON object, Stop hook not added. Fix the file and try again.`
2890
+ },
2823
2891
  agentNotFound: (dir) => `not found (${dir})`,
2824
2892
  pluginManages: (plugin) => `the ${plugin} plugin provides the skill and the hook. Remove the manual ones with: backlog setup --remove-manual`,
2825
2893
  pluginLanguageHint: (installed, wanted) => `the skill comes from the ${installed} plugin; for this language switch plugins: /plugin uninstall ${installed}, then /plugin install ${wanted}`,
@@ -2834,8 +2902,11 @@ var cliEn = {
2834
2902
  removed: (path) => `Stop hook removed from ${path}`,
2835
2903
  absent: (path) => `no p-backlog Stop hook in ${path}`
2836
2904
  },
2837
- removeHookConfigUnreadable: (path, detail) => `Could not read ${path} (${detail}), the hook was not removed.`,
2838
- removeHookConfigInvalid: (path) => `${path} is not a JSON object, the hook was not removed. Fix the file and try again.`,
2905
+ removeHookConfigFailed: {
2906
+ unreadable: (path, detail) => `Could not read ${path} (${detail}), the hook was not removed.`,
2907
+ unwritable: (path, detail) => `Could not write ${path} (${detail}), the hook was not removed.`,
2908
+ invalid: (path) => `${path} is not a JSON object, the hook was not removed. Fix the file and try again.`
2909
+ },
2839
2910
  serviceInstalled: (file) => `Service installed: ${file}`,
2840
2911
  serviceLogs: (hint) => `Logs: ${hint}`,
2841
2912
  serviceUninstalled: "Service removed",
@@ -3008,8 +3079,11 @@ var cliRu = {
3008
3079
  installHookAdded: (settingsPath) => `\u0425\u0443\u043A Stop \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D \u0432 ${settingsPath}`,
3009
3080
  installHookUpdated: (settingsPath) => `\u0425\u0443\u043A Stop \u043E\u0431\u043D\u043E\u0432\u043B\u0451\u043D \u0432 ${settingsPath}`,
3010
3081
  hookApproval: (agent, command2) => `\u043E\u0434\u043E\u0431\u0440\u0438\u0442\u0435 \u0445\u0443\u043A \u0432 ${agent}: ${command2}`,
3011
- installHookConfigUnreadable: (path, detail) => `${path} \u043D\u0435 \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C (${detail}), \u0445\u0443\u043A Stop \u043D\u0435 \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D.`,
3012
- installHookConfigInvalid: (path) => `${path} \u2014 \u043D\u0435 \u043E\u0431\u044A\u0435\u043A\u0442 JSON, \u0445\u0443\u043A Stop \u043D\u0435 \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D. \u0418\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B \u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0435.`,
3082
+ installHookConfigFailed: {
3083
+ unreadable: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C ${path} (${detail}), \u0445\u0443\u043A Stop \u043D\u0435 \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D.`,
3084
+ unwritable: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044C ${path} (${detail}), \u0445\u0443\u043A Stop \u043D\u0435 \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D.`,
3085
+ invalid: (path) => `${path} \u2014 \u043D\u0435 \u043E\u0431\u044A\u0435\u043A\u0442 JSON, \u0445\u0443\u043A Stop \u043D\u0435 \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D. \u0418\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B \u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0435.`
3086
+ },
3013
3087
  agentNotFound: (dir) => `\u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D (${dir})`,
3014
3088
  pluginManages: (plugin) => `\u0441\u043A\u0438\u043B\u043B \u0438 \u0445\u0443\u043A \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0430\u0435\u0442 \u043F\u043B\u0430\u0433\u0438\u043D ${plugin}. \u0420\u0443\u0447\u043D\u044B\u0435 \u043C\u043E\u0436\u043D\u043E \u0443\u0431\u0440\u0430\u0442\u044C: backlog setup --remove-manual`,
3015
3089
  pluginLanguageHint: (installed, wanted) => `\u0441\u043A\u0438\u043B\u043B \u0434\u0430\u0451\u0442 \u043F\u043B\u0430\u0433\u0438\u043D ${installed}; \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u044F\u0437\u044B\u043A\u0430 \u043F\u043E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0434\u0440\u0443\u0433\u043E\u0439: /plugin uninstall ${installed}, \u0437\u0430\u0442\u0435\u043C /plugin install ${wanted}`,
@@ -3024,8 +3098,11 @@ var cliRu = {
3024
3098
  removed: (path) => `\u0445\u0443\u043A Stop \u0441\u043D\u044F\u0442 \u0438\u0437 ${path}`,
3025
3099
  absent: (path) => `\u0445\u0443\u043A\u0430 Stop p-backlog \u0432 ${path} \u043D\u0435\u0442`
3026
3100
  },
3027
- removeHookConfigUnreadable: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C ${path} (${detail}), \u0445\u0443\u043A \u043D\u0435 \u0441\u043D\u044F\u0442.`,
3028
- removeHookConfigInvalid: (path) => `${path} \u2014 \u043D\u0435 \u043E\u0431\u044A\u0435\u043A\u0442 JSON, \u0445\u0443\u043A \u043D\u0435 \u0441\u043D\u044F\u0442. \u0418\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B \u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0435.`,
3101
+ removeHookConfigFailed: {
3102
+ unreadable: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C ${path} (${detail}), \u0445\u0443\u043A \u043D\u0435 \u0441\u043D\u044F\u0442.`,
3103
+ unwritable: (path, detail) => `\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044C ${path} (${detail}), \u0445\u0443\u043A \u043D\u0435 \u0441\u043D\u044F\u0442.`,
3104
+ invalid: (path) => `${path} \u2014 \u043D\u0435 \u043E\u0431\u044A\u0435\u043A\u0442 JSON, \u0445\u0443\u043A \u043D\u0435 \u0441\u043D\u044F\u0442. \u0418\u0441\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B \u0438 \u043F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0435.`
3105
+ },
3029
3106
  serviceInstalled: (file) => `\u0421\u043B\u0443\u0436\u0431\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0430: ${file}`,
3030
3107
  serviceLogs: (hint) => `\u041B\u043E\u0433\u0438: ${hint}`,
3031
3108
  serviceUninstalled: "\u0421\u043B\u0443\u0436\u0431\u0430 \u0443\u0434\u0430\u043B\u0435\u043D\u0430",
@@ -3323,10 +3400,10 @@ ${" ".repeat(head.length)}`;
3323
3400
  }
3324
3401
 
3325
3402
  // src/cli/lookups.ts
3326
- import { basename as basename8 } from "node:path";
3403
+ import { basename as basename7 } from "node:path";
3327
3404
 
3328
3405
  // src/core/check/project-repo.ts
3329
- import { join as join12 } from "node:path";
3406
+ import { join as join13 } from "node:path";
3330
3407
 
3331
3408
  // src/core/git/run.ts
3332
3409
  import { execFile as execFile2, execFileSync } from "node:child_process";
@@ -3364,14 +3441,30 @@ var RECORD = "";
3364
3441
  var FIELD = "";
3365
3442
  var runFile = promisify(execFile2);
3366
3443
  var GIT_OUTPUT_LIMIT = 64 * BYTES_PER_MEBIBYTE;
3367
- var GREP_NO_MATCH_EXIT = 1;
3444
+ var FOUND_NOTHING_EXIT = 1;
3445
+ var NOT_AN_ANCESTOR_EXIT = 1;
3368
3446
  var GIT_PROCESS_LIMIT = 8;
3369
3447
  var FULL_OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
3370
3448
  var FOUND_OBJECT_FIELDS = 3;
3449
+ var REPOSITORY_BOUND_ENV = /* @__PURE__ */ new Set([
3450
+ "GIT_DIR",
3451
+ "GIT_WORK_TREE",
3452
+ "GIT_IMPLICIT_WORK_TREE",
3453
+ "GIT_INDEX_FILE",
3454
+ "GIT_COMMON_DIR",
3455
+ "GIT_OBJECT_DIRECTORY",
3456
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
3457
+ "GIT_SHALLOW_FILE",
3458
+ "GIT_GRAFT_FILE",
3459
+ "GIT_NO_REPLACE_OBJECTS",
3460
+ "GIT_REPLACE_REF_BASE",
3461
+ "GIT_NAMESPACE",
3462
+ "GIT_PREFIX"
3463
+ ]);
3371
3464
  var gitProcessSlot = createLimiter(GIT_PROCESS_LIMIT);
3372
3465
  var runGitOutcome = (repo, args, input) => gitProcessSlot(async () => {
3373
3466
  try {
3374
- const running = runFile("git", gitArgs(repo, args), { maxBuffer: GIT_OUTPUT_LIMIT });
3467
+ const running = runFile("git", gitArgs(repo, args), { maxBuffer: GIT_OUTPUT_LIMIT, env: envForRepoGit() });
3375
3468
  running.child.stdin?.on("error", ignoreStdinOfExitedGit).end(input);
3376
3469
  const { stdout } = await running;
3377
3470
  return { status: "ok", stdout };
@@ -3383,9 +3476,12 @@ var runGitOutcome = (repo, args, input) => gitProcessSlot(async () => {
3383
3476
  function asGitRunner(git) {
3384
3477
  return async (repo, args, input) => {
3385
3478
  const outcome = await git(repo, args, input);
3386
- return args[0] === "grep" && outcome.status === "exited" && outcome.exitCode === GREP_NO_MATCH_EXIT ? "" : stdoutOf(outcome);
3479
+ return outcome.status === "exited" && outcome.exitCode === FOUND_NOTHING_EXIT && reportsNothingFoundByExitOne(args) ? "" : stdoutOf(outcome);
3387
3480
  };
3388
3481
  }
3482
+ function reportsNothingFoundByExitOne(args) {
3483
+ return args[0] === "grep" || args[0] === "merge-base" && !args.includes("--is-ancestor");
3484
+ }
3389
3485
  var runGit = asGitRunner(runGitOutcome);
3390
3486
  function stdoutOf(outcome) {
3391
3487
  return outcome.status === "ok" ? outcome.stdout : null;
@@ -3408,7 +3504,7 @@ function topLiteralPathspecs(paths) {
3408
3504
  }
3409
3505
  function runGitSync(repo, args) {
3410
3506
  try {
3411
- return execFileSync("git", gitArgs(repo, args), { encoding: "utf8", maxBuffer: GIT_OUTPUT_LIMIT, stdio: ["ignore", "pipe", "ignore"] });
3507
+ return execFileSync("git", gitArgs(repo, args), { encoding: "utf8", maxBuffer: GIT_OUTPUT_LIMIT, stdio: ["ignore", "pipe", "ignore"], env: envForRepoGit() });
3412
3508
  } catch (error) {
3413
3509
  if (isChildProcessFailure(error)) return null;
3414
3510
  throw error;
@@ -3417,6 +3513,9 @@ function runGitSync(repo, args) {
3417
3513
  function isChildProcessFailure(error) {
3418
3514
  return typeof error === "object" && error !== null && "status" in error;
3419
3515
  }
3516
+ function envForRepoGit() {
3517
+ return Object.fromEntries(Object.entries(process.env).filter(([name]) => !REPOSITORY_BOUND_ENV.has(name)));
3518
+ }
3420
3519
  function gitArgs(repo, args) {
3421
3520
  return ["-C", repo, "--no-optional-locks", "--no-literal-pathspecs", "-c", "core.quotePath=false", "-c", "diff.suppressBlankEmpty=false", ...args];
3422
3521
  }
@@ -3454,6 +3553,19 @@ async function resolveObjects(git, repo, revisions, type, nameOf) {
3454
3553
  })
3455
3554
  );
3456
3555
  }
3556
+ async function headAncestryOf(git, repo, commit) {
3557
+ const answer = await git(repo, ["merge-base", "--is-ancestor", commit, "HEAD"]);
3558
+ if (answer.status === "ok") return "ancestor";
3559
+ if (answer.status === "exited" && answer.exitCode === NOT_AN_ANCESTOR_EXIT) return "not-ancestor";
3560
+ const present = await resolveCommits(asGitRunner(git), repo, [commit]);
3561
+ return present !== null && !present.has(commit) ? "missing" : "unknown";
3562
+ }
3563
+ async function cloneCompletenessOf(git, repo) {
3564
+ const answer = outputLine(await git(repo, ["rev-parse", "--is-shallow-repository"]));
3565
+ if (answer === "true") return "shallow";
3566
+ if (answer === "false") return "full";
3567
+ return "unknown";
3568
+ }
3457
3569
  function stderrOf(error) {
3458
3570
  return typeof error === "object" && error !== null && "stderr" in error && typeof error.stderr === "string" ? error.stderr : "";
3459
3571
  }
@@ -3578,6 +3690,13 @@ function hashLines(lines) {
3578
3690
  }
3579
3691
 
3580
3692
  // src/core/check/reviewed-task.ts
3693
+ var NO_MARK_COMMITS = { origins: /* @__PURE__ */ new Map(), verifications: /* @__PURE__ */ new Map() };
3694
+ function markCommitsIn(events) {
3695
+ return {
3696
+ origins: new Map(events.flatMap((event) => event.kind === "created" && event.origin !== void 0 ? [[event.task, event.origin]] : [])),
3697
+ verifications: new Map(events.flatMap((event) => event.kind === "verified" && event.commit !== void 0 ? [[event.task, { at: event.at, commit: event.commit }]] : []))
3698
+ };
3699
+ }
3581
3700
  function isReviewable(task) {
3582
3701
  return task.type === "task" && (task.status === "backlog" || task.status === "blocked");
3583
3702
  }
@@ -3585,11 +3704,16 @@ function reviewMark(task) {
3585
3704
  const verified = task.verified === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(task.verified);
3586
3705
  return Math.max(Date.parse(task.created), verified);
3587
3706
  }
3588
- function creationOrigin(task, origins) {
3589
- return task.verified === void 0 ? origins.get(task.id) : void 0;
3707
+ function commitAtMark(task, marks) {
3708
+ return task.verified === void 0 ? marks.origins.get(task.id)?.commit : verifiedCommit(task, task.verified, marks);
3590
3709
  }
3591
- async function checkoutAtMark(task, origins, headCommitAt) {
3592
- return creationOrigin(task, origins)?.commit ?? headCommitAt(new Date(reviewMark(task)));
3710
+ function latestRecordedCommit(task, marks) {
3711
+ return commitAtMark(task, marks) ?? marks.origins.get(task.id)?.commit;
3712
+ }
3713
+ function verifiedCommit(task, verifiedAt, { verifications }) {
3714
+ const verification = verifications.get(task.id);
3715
+ const recordsCurrentVerification = verification !== void 0 && Date.parse(verification.at) >= Date.parse(verifiedAt);
3716
+ return recordsCurrentVerification ? verification.commit : void 0;
3593
3717
  }
3594
3718
 
3595
3719
  // src/core/check/source-commits.ts
@@ -3664,6 +3788,10 @@ function judgedByCommits(task, anchors) {
3664
3788
  function anchorState(task, facts) {
3665
3789
  return anchorStateIn(task, task.source === void 0 ? void 0 : facts.texts.get(sourcePath(task.source)));
3666
3790
  }
3791
+ function anchorHolds(task, text) {
3792
+ const state = anchorStateIn(task, text ?? void 0);
3793
+ return state.kind === "same" || state.kind === "moved";
3794
+ }
3667
3795
  function anchorStateIn(task, text) {
3668
3796
  if (task.anchor === void 0 || task.source === void 0 || !hasLines(task.source) || !isAnchorFor(task.anchor, task.source)) return { kind: "none" };
3669
3797
  if (text === void 0) return { kind: "none" };
@@ -3683,8 +3811,10 @@ function presenceOffDisk(path, branches) {
3683
3811
  }
3684
3812
  }
3685
3813
  function livesOnAnotherBranch(path, facts) {
3686
- const committedIn = (files) => [...files].some((file) => isWithin(file, path));
3687
- return !committedIn(facts.committedHere) && committedIn(facts.committedAnywhere);
3814
+ return !committedIn(facts.committedHere, path) && committedIn(facts.committedAnywhere, path);
3815
+ }
3816
+ function committedIn(files, path) {
3817
+ return [...files].some((file) => isWithin(file, path));
3688
3818
  }
3689
3819
  function followRenames(path, commits, mark) {
3690
3820
  let current = path;
@@ -3874,7 +4004,41 @@ function baseText(hunks, currentText) {
3874
4004
  }
3875
4005
 
3876
4006
  // src/core/check/repo-facts.ts
3877
- import { isAbsolute as isAbsolute2, join as join11, normalize, sep as sep2 } from "node:path";
4007
+ import { isAbsolute as isAbsolute2, join as join12, normalize, sep as sep2 } from "node:path";
4008
+
4009
+ // src/core/git/landing.ts
4010
+ async function firstParentLanding(git, repo, commit, head) {
4011
+ const chain = await firstParentChain(git, repo, commit, head);
4012
+ if (chain === null || chain.length === 0) return null;
4013
+ const carries = (index) => contains(git, repo, chain[index]?.commit ?? "", commit);
4014
+ const oldest = chain.length - 1;
4015
+ const oldestCarries = await carries(oldest);
4016
+ if (oldestCarries === null) return null;
4017
+ if (oldestCarries) return chain[oldest] ?? null;
4018
+ if (await carries(0) !== true) return null;
4019
+ let carrying = 0;
4020
+ let notCarrying = oldest;
4021
+ while (notCarrying - carrying > 1) {
4022
+ const middle = Math.floor((carrying + notCarrying) / 2);
4023
+ const middleCarries = await carries(middle);
4024
+ if (middleCarries === null) return null;
4025
+ if (middleCarries) carrying = middle;
4026
+ else notCarrying = middle;
4027
+ }
4028
+ return chain[carrying] ?? null;
4029
+ }
4030
+ async function firstParentChain(git, repo, commit, head) {
4031
+ const lines = outputLines(await git(repo, ["log", "--first-parent", `--format=tformat:%H${FIELD}%P${FIELD}%cI`, `${commit}..${head}`, "--"]));
4032
+ if (lines === null) return null;
4033
+ return lines.map((line) => {
4034
+ const [sha = "", parents = "", committedAt = ""] = line.split(FIELD);
4035
+ return { commit: sha, firstParent: parents.split(" ")[0] ?? "", committedAt };
4036
+ });
4037
+ }
4038
+ async function contains(git, repo, descendant, commit) {
4039
+ const missing = await git(repo, ["rev-list", "--max-count=1", commit, `^${descendant}`, "--"]);
4040
+ return missing === null ? null : missing.trim() === "";
4041
+ }
3878
4042
 
3879
4043
  // src/core/remembered.ts
3880
4044
  function remembered(cache, key, compute) {
@@ -3884,113 +4048,415 @@ function remembered(cache, key, compute) {
3884
4048
  return value;
3885
4049
  }
3886
4050
 
3887
- // src/core/check/repo-facts.ts
3888
- var TRUST_COMMAND = /^git config .*safe\.directory/;
3889
- var DIFF_LINE_LIMIT = 80;
3890
- var REFLOG_MOMENT = /\{(\d+)\}$/;
3891
- var STATUS_CODE_WIDTH = 3;
3892
- var RENAME_OR_COPY = /^[RC]/;
3893
- var DELETED_FILE_HEADER = /^deleted file mode /m;
3894
- var ORIGINAL_PATH_FOLLOWS = /^(?:[RC].|.[RC])/;
3895
- var LOG_FORMAT = `--format=${RECORD}%H${FIELD}%h${FIELD}%cI${FIELD}%P${FIELD}%s`;
3896
- var FACTS_HISTORY_OPTIONS = ["--full-history"];
3897
- async function locateRepo(repo) {
3898
- const location = await runGitOutcome(repo, ["rev-parse", "--show-prefix", "--revs-only", "HEAD"]);
3899
- if (location.status === "exited") {
3900
- const trustCommand = trustCommandIn(location.stderr);
3901
- return trustCommand === void 0 ? { history: "not-a-repo" } : { history: "unsafe-repo", trustCommand };
4051
+ // src/core/check/landed-content.ts
4052
+ var PATCH_OPTIONS = ["-p", ...PARSED_DIFF_OPTIONS, "--no-renames", "--no-relative", "--full-index", "--diff-algorithm=myers", "--indent-heuristic", "--unified=0", "--inter-hunk-context=0"];
4053
+ var COMMIT_HEADER = "--format=commit %H";
4054
+ var INSERTION_NEIGHBOURS = 2;
4055
+ var TREE_PAIR_LINE = /^[0-9a-f]+ [0-9a-f]+$/;
4056
+ var NO_COMMIT = /^0+$/;
4057
+ var COMMIT_RECORD = /commit (?<commit>[0-9a-f]+)\0/;
4058
+ var FILE_RECORD = /:\d+ (?<mode>\d+) [0-9a-f]+ (?<object>[0-9a-f]+) [A-Z]\d*\0(?<path>[^\0]*)\0/;
4059
+ var RAW_RECORD = new RegExp(`${COMMIT_RECORD.source}|${FILE_RECORD.source}`, "g");
4060
+ async function landingState(repo, tip, git) {
4061
+ const fork = await forkAt(repo, "HEAD", tip, git);
4062
+ if (fork === "unrelated") return await cloneCompletenessOf(git, repo) === "full" ? "pending" : "unknown";
4063
+ if (fork === null) return "unknown";
4064
+ const view = { ...fork, repo, historyOptions: [], git };
4065
+ const changed = await branchChanges(view, []);
4066
+ if (changed === null) return "unknown";
4067
+ if (changed.length === 0) return "landed";
4068
+ const landed = await headChanges(view, topLiteralPathspecs(changed.map(({ path }) => path)));
4069
+ if (landed === null) return "unknown";
4070
+ const landedVersions = new Set(landed.map(({ version }) => version));
4071
+ let state = "landed";
4072
+ for (const { path, version } of changed) {
4073
+ const pathState = landedVersions.has(version) ? "landed" : await changeLanded(view, path);
4074
+ if (pathState === "pending") return "pending";
4075
+ if (pathState === "unknown") state = "unknown";
3902
4076
  }
3903
- if (location.status === "unfinished") return { history: "unreadable" };
3904
- const [prefix = "", head = ""] = location.stdout.split("\n").map((line) => line.trim());
3905
- return { history: "read", prefix, hasCommits: head !== "" };
3906
- }
3907
- function trustCommandIn(stderr) {
3908
- return stderr.split("\n").map((line) => line.trim()).find((line) => TRUST_COMMAND.test(line));
4077
+ return state;
3909
4078
  }
3910
- async function collectRepoFacts(repo, pathMarks) {
3911
- const paths = [...pathMarks.keys()];
3912
- const [location, files] = await Promise.all([locateRepo(repo), sourceFiles(repo, paths)]);
3913
- const withoutHistory = (noHistory) => ({ ...noHistory, commits: [], renames: [], dirtyModifiedAt: /* @__PURE__ */ new Map(), branches: unknownBranches(noHistory.history), ...files });
3914
- if (location.history !== "read") return withoutHistory(location);
3915
- const { prefix, hasCommits } = location;
3916
- const missing = paths.filter((path) => !files.existing.has(path) && !files.unreadable.has(path));
3917
- const [log, renames, status, branches] = await Promise.all([
3918
- hasCommits && paths.length > 0 ? pathLog(repo, [sinceEarliestMark(pathMarks, paths)], paths) : "",
3919
- hasCommits && missing.length > 0 ? runGit(repo, [...logArgs([sinceEarliestMark(pathMarks, missing)]), "--diff-filter=R"]) : "",
3920
- runGit(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=no"]),
3921
- branchHistoryOf(repo, location, missing)
3922
- ]);
3923
- if (log === null || renames === null || status === null) return withoutHistory({ history: "unreadable" });
3924
- const dirty = withinRepo(parseStatus(status), prefix);
3925
- return { history: "read", commits: parseLog(log), renames: parseLog(renames), dirtyModifiedAt: await modificationTimes(repo, dirty), branches, ...files };
4079
+ function commitsCarryingContent(repo, git, historyOptions) {
4080
+ const forks = /* @__PURE__ */ new Map();
4081
+ return async (tip, scope) => {
4082
+ const fork = await remembered(forks, tip, () => forkBeforeLanding(repo, tip, git));
4083
+ return fork === null ? [] : commitsCarrying({ ...fork, repo, historyOptions, git }, scope);
4084
+ };
3926
4085
  }
3927
- async function branchHistoryOf(repo, location, paths) {
3928
- if (location.history !== "read") return unknownBranches(location.history);
3929
- const [here, anywhere] = await Promise.all([location.hasCommits ? committedPaths(repo, "HEAD", paths) : [], committedPaths(repo, "--all", paths)]);
3930
- return here === null || anywhere === null ? { kind: "unreadable" } : { kind: "read", committedHere: new Set(here), committedAnywhere: new Set(anywhere) };
4086
+ async function commitsCarrying(view, scope) {
4087
+ const changed = await branchChanges(view, scope);
4088
+ if (changed === null || changed.length === 0) return [];
4089
+ const head = await headChanges(view, scope);
4090
+ if (head === null) return [];
4091
+ const tipVersions = new Set(changed.map(({ version }) => version));
4092
+ const branchPaths = new Set(changed.map(({ path }) => path));
4093
+ const copiesByPath = /* @__PURE__ */ new Map();
4094
+ const patchCopiesOf = (path) => remembered(copiesByPath, path, async () => {
4095
+ const copies = await patchCopies(view, path);
4096
+ return new Set(copies === null ? [] : earliestCopies(copies));
4097
+ });
4098
+ const carriesTip = async ({ commit, path, version }) => tipVersions.has(version) || branchPaths.has(path) && (await patchCopiesOf(path)).has(commit);
4099
+ const carriesOnlyTip = async (changes) => (await Promise.all(changes.map(carriesTip))).every(Boolean);
4100
+ const carrying = await Promise.all([...groupBy(head, ({ commit }) => commit)].map(async ([commit, changes]) => await carriesOnlyTip(changes) ? [commit] : []));
4101
+ return carrying.flat();
3931
4102
  }
3932
- function unknownBranches(history) {
3933
- return history === "not-a-repo" ? { kind: "no-repo" } : { kind: "unreadable" };
4103
+ async function forkAt(repo, head, tip, git) {
4104
+ const mergeBase = await git(repo, ["merge-base", head, tip]);
4105
+ if (mergeBase?.trim() === "") return "unrelated";
4106
+ const base = commitHashOf(outputLine(mergeBase));
4107
+ return base === null ? null : { base, tip, head };
3934
4108
  }
3935
- function sinceEarliestMark(marks, paths) {
3936
- return `--since=${new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? []))).toISOString()}`;
4109
+ async function forkBeforeLanding(repo, revision, git) {
4110
+ const tip = (await resolveCommits(git, repo, [revision]))?.get(revision);
4111
+ if (tip === void 0) return null;
4112
+ const sharedHistoryFork = async (head) => {
4113
+ const fork2 = await forkAt(repo, head, tip, git);
4114
+ return fork2 === "unrelated" ? null : fork2;
4115
+ };
4116
+ const fork = await sharedHistoryFork("HEAD");
4117
+ if (fork === null || !tipInHead(fork)) return fork;
4118
+ const landing = await firstParentLanding(git, repo, tip, "HEAD");
4119
+ return landing === null ? fork : sharedHistoryFork(landing.firstParent);
3937
4120
  }
3938
- function logArgs(selection) {
3939
- return ["log", ...selection, "--relative", LOG_FORMAT, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
4121
+ function tipInHead({ base, tip }) {
4122
+ return base === tip;
3940
4123
  }
3941
- async function pathLog(repo, selection, paths) {
3942
- const inside = paths.filter(isInsideRepo);
3943
- if (inside.length === 0) return "";
3944
- return runGit(repo, [...logArgs(selection), "--", ...literalPathspecs(inside)]);
4124
+ async function branchChanges(view, pathspecs) {
4125
+ const { repo, base, tip, git } = view;
4126
+ if (tipInHead(view)) return [];
4127
+ const changed = await git(repo, ["diff-tree", "-r", "-z", "--no-renames", base, tip, "--", ...pathspecs]);
4128
+ return changed === null ? null : rawChanges(changed);
3945
4129
  }
3946
- async function mainlineCommitsOff(repo, base, paths) {
3947
- const log = await pathLog(repo, ["--first-parent", `${base}..HEAD`], paths);
3948
- return log === null ? null : parseLog(log);
4130
+ async function headChanges({ repo, base, head, historyOptions, git }, pathspecs) {
4131
+ const rawLog = await git(repo, ["log", "--stdin", COMMIT_HEADER, "--raw", "-z", "--no-renames", "--no-abbrev", "--no-relative", ...historyOptions], `${base}..${head}
4132
+ --
4133
+ ${pathspecs.join("\n")}
4134
+ `);
4135
+ return rawLog === null ? null : rawChanges(rawLog);
3949
4136
  }
3950
- async function committedPaths(repo, revisions, paths) {
3951
- const inside = paths.filter(isInsideRepo);
3952
- if (inside.length === 0) return [];
3953
- const names = await runGit(repo, ["log", revisions, "--relative", "--format=", "--name-only", "-z", "--", ...literalPathspecs(inside)]);
3954
- return names === null ? null : names.split(/[\0\n]/).filter((name) => name !== "");
4137
+ function rawChanges(raw) {
4138
+ const changes = [];
4139
+ let commit = "";
4140
+ for (const { groups } of raw.matchAll(RAW_RECORD)) {
4141
+ if (groups?.commit === void 0) changes.push({ commit, ...fileVersion(groups) });
4142
+ else commit = groups.commit;
4143
+ }
4144
+ return changes;
3955
4145
  }
3956
- function isInsideRepo(path) {
3957
- const normalized = normalize(path);
3958
- return normalized !== "." && !isAbsolute2(normalized) && normalized !== ".." && !normalized.startsWith(`..${sep2}`);
4146
+ async function changeLanded(view, path) {
4147
+ const copies = await patchCopies(view, path);
4148
+ if (copies === null) return "unknown";
4149
+ if (copies.squashed.length > 0 || everyCommitCopied(copies)) return "landed";
4150
+ return copies.editsComplete ? "pending" : "unknown";
3959
4151
  }
3960
- function diffsSince(repo, git = runGit, diffFrom = diffsFrom(repo, git)) {
3961
- const bases = /* @__PURE__ */ new Map();
3962
- const baseBefore = (since) => remembered(bases, since.getTime(), async () => outputLine(await git(repo, ["rev-list", "-1", "--first-parent", `--before=${since.toISOString()}`, "HEAD"])));
3963
- return async (path, since) => {
3964
- const base = await baseBefore(since);
3965
- return base === null ? null : diffFrom(path, base);
3966
- };
4152
+ function everyCommitCopied({ commitByCommit }) {
4153
+ return commitByCommit.length > 0 && commitByCommit.every((commitCopies) => commitCopies.length > 0);
3967
4154
  }
3968
- function headCommitsAt(repo) {
3969
- let moves = null;
3970
- return async (moment) => {
3971
- moves ??= headMovesNewestFirst(repo);
3972
- return (await moves).find((move) => move.at <= moment.getTime())?.commit ?? null;
4155
+ function earliestCopies(copies) {
4156
+ const earliest = (newestFirst) => newestFirst.slice(-1);
4157
+ return [earliest(copies.squashed), ...everyCommitCopied(copies) ? copies.commitByCommit.map(earliest) : []].flat();
4158
+ }
4159
+ async function patchCopies(view, path) {
4160
+ const { repo, base, tip, head, historyOptions, git } = view;
4161
+ const onlyPath = ["--", ...topLiteralPathspecs([path])];
4162
+ const [squashedPatch, branchPatches, headPatches] = await Promise.all([
4163
+ patchesOf(repo, ["diff", ...PATCH_OPTIONS, base, tip, ...onlyPath], () => base, git),
4164
+ patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, `${base}..${tip}`, ...onlyPath], parentOf, git),
4165
+ patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, "--date-order", ...historyOptions, `${base}..${head}`, ...onlyPath], parentOf, git)
4166
+ ]);
4167
+ if (squashedPatch === null || branchPatches === null || headPatches === null) return null;
4168
+ const headPatchesById = groupBy(headPatches, ({ id }) => id);
4169
+ const sameChanges = (change) => (headPatchesById.get(change.id) ?? []).filter((copy) => isSameChange(change, copy));
4170
+ const pairs = [...squashedPatch, ...branchPatches].flatMap((change) => sameChanges(change).map((copy) => [change, copy]));
4171
+ const { editsBetween, complete } = await preimageEdits(view, path, pairs);
4172
+ const copiesOf = (change) => sameChanges(change).flatMap((copy) => atSamePlace(change, copy, editsBetween) ? [copy.commit] : []);
4173
+ return { squashed: squashedPatch.flatMap(copiesOf), commitByCommit: branchPatches.map(copiesOf), editsComplete: complete };
4174
+ }
4175
+ async function patchesOf(repo, patchArgs, preimageOf, git) {
4176
+ const patches = await git(repo, patchArgs);
4177
+ if (patches === null) return null;
4178
+ const ids = await git(repo, ["patch-id", "--stable"], patches);
4179
+ if (ids === null) return null;
4180
+ const shapeOf = patchShapes(patches);
4181
+ return ids.split("\n").filter((line) => line !== "").map((line) => {
4182
+ const [id = "", label = ""] = line.split(" ");
4183
+ const commit = NO_COMMIT.test(label) ? "" : label;
4184
+ return { id, commit, preimageRevision: preimageOf(commit), ...shapeOf(commit) };
4185
+ });
4186
+ }
4187
+ async function preimageEdits(repoGit, path, pairs) {
4188
+ const comparedPairs = pairs.filter(([change, copy]) => editsNeeded(change, copy));
4189
+ const trees = await resolveTrees(repoGit.git, repoGit.repo, [...new Set(comparedPairs.flatMap(([change, copy]) => [change.preimageRevision, copy.preimageRevision]))]);
4190
+ const treePairOf = (change, copy) => {
4191
+ const from = trees?.get(change.preimageRevision);
4192
+ const to = trees?.get(copy.preimageRevision);
4193
+ return from === void 0 || to === void 0 ? null : `${from} ${to}`;
4194
+ };
4195
+ const editsByTreePair = await treeDiffEdits(repoGit, path, [...new Set(comparedPairs.flatMap(([change, copy]) => treePairOf(change, copy) ?? []))]);
4196
+ const editsBetween = (change, copy) => {
4197
+ if (!editsNeeded(change, copy)) return [];
4198
+ const treePair = treePairOf(change, copy);
4199
+ return treePair === null ? null : editsByTreePair?.get(treePair) ?? null;
4200
+ };
4201
+ return { editsBetween, complete: trees !== null && editsByTreePair !== null };
4202
+ }
4203
+ async function treeDiffEdits({ repo, git }, path, treePairs) {
4204
+ if (treePairs.length === 0) return /* @__PURE__ */ new Map();
4205
+ const preimageDiffs = await git(repo, ["diff-tree", "--stdin", ...PATCH_OPTIONS, "--", ...topLiteralPathspecs([path])], treePairs.map((treePair) => `${treePair}
4206
+ `).join(""));
4207
+ return preimageDiffs === null ? null : preimageEditsByTreePair(preimageDiffs);
4208
+ }
4209
+ function preimageEditsByTreePair(preimageDiffs) {
4210
+ const editsByTreePair = /* @__PURE__ */ new Map();
4211
+ let edits = [];
4212
+ for (const line of preimageDiffs.split("\n")) {
4213
+ if (TREE_PAIR_LINE.test(line)) {
4214
+ edits = [];
4215
+ editsByTreePair.set(line, edits);
4216
+ } else edits.push(...preimageEditsOf(hunkHeaderOf(line)));
4217
+ }
4218
+ return editsByTreePair;
4219
+ }
4220
+ function isSameChange(change, copy) {
4221
+ const changeShownByHunks = change.changeStarts.length > 0;
4222
+ return copy.id === change.id && copy.changedText === change.changedText && copy.changeStarts.length === change.changeStarts.length && (changeShownByHunks || sameBlobs(change.blobs, copy.blobs));
4223
+ }
4224
+ function sameBlobs(change, copy) {
4225
+ return change?.preimage === copy?.preimage && change?.postimage === copy?.postimage;
4226
+ }
4227
+ function samePreimage(change, copy) {
4228
+ return change.blobs !== void 0 && change.blobs.preimage === copy.blobs?.preimage;
4229
+ }
4230
+ function editsNeeded(change, copy) {
4231
+ return change.changeStarts.length > 0 && !samePreimage(change, copy);
4232
+ }
4233
+ function atSamePlace(change, copy, editsBetween) {
4234
+ const edits = editsBetween(change, copy);
4235
+ return edits !== null && change.changeStarts.every((start, index) => copyStartsAtSamePlace(start, copy.changeStarts[index], edits));
4236
+ }
4237
+ function copyStartsAtSamePlace(start, copyStart, edits) {
4238
+ const place = placeOf(start);
4239
+ const placeUntouched = !edits.some((edit) => spansOverlap(edit, place));
4240
+ return placeUntouched && shiftedLine(start.line, edits) === copyStart?.line;
4241
+ }
4242
+ function placeOf({ line, insertion }) {
4243
+ return insertion ? { firstLine: line - 1, lineCount: INSERTION_NEIGHBOURS } : { firstLine: line, lineCount: 1 };
4244
+ }
4245
+ function spansOverlap(edit, place) {
4246
+ return edit.firstLine < lineAfter(place) && place.firstLine < lineAfter(edit);
4247
+ }
4248
+ function lineAfter({ firstLine, lineCount }) {
4249
+ return firstLine + lineCount;
4250
+ }
4251
+ function preimageEditsOf(header) {
4252
+ if (header === null) return [];
4253
+ return [{ firstLine: firstLineOf(header.oldStart, header.oldCount), lineCount: header.oldCount, delta: header.newCount - header.oldCount }];
4254
+ }
4255
+ function shiftedLine(line, edits) {
4256
+ return edits.reduce((shifted, edit) => lineAfter(edit) <= line ? shifted + edit.delta : shifted, line);
4257
+ }
4258
+ function parentOf(commit) {
4259
+ return `${commit}^`;
4260
+ }
4261
+ function fileVersion({ mode = "", object = "", path = "" } = {}) {
4262
+ return { path, version: `${mode} ${object}\0${path}` };
4263
+ }
4264
+
4265
+ // src/core/check/rewritten-branch.ts
4266
+ var DETACHED_HEAD_EXIT = 1;
4267
+ var NOT_AN_ANCESTOR_EXIT2 = 1;
4268
+ var REBASE_FINISHED = /^(?:rebase|pull)\b.*(?:\(finish\)|finished): refs\//;
4269
+ var AMEND = /^commit \(amend\):/;
4270
+ var REWRITTEN_BY_UPDATE_REFS = /^rewritten during rebase$/;
4271
+ function currentBranchRewroteTipOf(repo, git) {
4272
+ let history;
4273
+ const stepLines = /* @__PURE__ */ new Map();
4274
+ const stepLine = (step, index) => remembered(stepLines, index, () => lineOfStep(repo, step, git));
4275
+ return async (tip) => {
4276
+ const branch = await (history ??= currentBranchHistory(repo, git));
4277
+ if (branch.kind === "unreadable") return "unknown";
4278
+ if (branch.kind === "detached") return "not-rewritten";
4279
+ const tipIndex = branch.movesNewestFirst.findIndex(({ commit }) => commit === tip);
4280
+ if (tipIndex <= 0) return "not-rewritten";
4281
+ const stepsSinceTip = branch.stepsNewestFirst.slice(0, tipIndex);
4282
+ if (!stepsSinceTip.some(({ to }) => isRewrite(to))) return "not-rewritten";
4283
+ let rewrite = "rewritten";
4284
+ for (const [index, step] of stepsSinceTip.entries()) {
4285
+ const line = await stepLine(step, index);
4286
+ if (line === "leaves-line") return "not-rewritten";
4287
+ if (line === "unknown") rewrite = "unknown";
4288
+ }
4289
+ return rewrite;
3973
4290
  };
3974
4291
  }
3975
- function ancestorsOfHead(repo) {
3976
- const ancestors = /* @__PURE__ */ new Map();
3977
- return (commit) => remembered(ancestors, commit, async () => await runGit(repo, ["merge-base", "--is-ancestor", commit, "HEAD"]) !== null);
4292
+ async function currentBranchHistory(repo, git) {
4293
+ const symbolicHead = await git(repo, ["symbolic-ref", "-q", "HEAD"]);
4294
+ if (symbolicHead.status === "exited" && symbolicHead.exitCode === DETACHED_HEAD_EXIT) return { kind: "detached" };
4295
+ const branch = outputLine(stdoutOf(symbolicHead));
4296
+ if (branch === null) return { kind: "unreadable" };
4297
+ const reflog = outputLines(stdoutOf(await git(repo, ["log", "--walk-reflogs", `--format=%H${FIELD}%P${FIELD}%gs`, branch, "--"])));
4298
+ if (reflog === null) return { kind: "unreadable" };
4299
+ const movesNewestFirst = reflog.map(branchMove);
4300
+ const stepsNewestFirst = movesNewestFirst.flatMap((to, index) => {
4301
+ const from = movesNewestFirst[index + 1];
4302
+ return from === void 0 ? [] : [{ from: from.commit, to }];
4303
+ });
4304
+ return { kind: "read", movesNewestFirst, stepsNewestFirst };
4305
+ }
4306
+ async function lineOfStep(repo, { from, to }, git) {
4307
+ if (isRewrite(to) || to.parents.includes(from)) return "keeps-line";
4308
+ const fromIsAncestor = await git(repo, ["merge-base", "--is-ancestor", from, to.commit]);
4309
+ if (fromIsAncestor.status === "ok") return "keeps-line";
4310
+ return fromIsAncestor.status === "exited" && fromIsAncestor.exitCode === NOT_AN_ANCESTOR_EXIT2 ? "leaves-line" : "unknown";
4311
+ }
4312
+ function isRewrite({ subject }) {
4313
+ return REBASE_FINISHED.test(subject) || AMEND.test(subject) || REWRITTEN_BY_UPDATE_REFS.test(subject);
4314
+ }
4315
+ function branchMove(line) {
4316
+ const [commit = "", parents = "", subject = ""] = line.split(FIELD);
4317
+ return { commit, parents: parents.split(" ").filter((parent) => parent !== ""), subject };
4318
+ }
4319
+
4320
+ // src/core/check/repo-facts.ts
4321
+ var TRUST_COMMAND = /^git config .*safe\.directory/;
4322
+ var DIFF_LINE_LIMIT = 80;
4323
+ var REFLOG_MOMENT = /\{(\d+)\}$/;
4324
+ var STATUS_CODE_WIDTH = 3;
4325
+ var RENAME_OR_COPY = /^[RC]/;
4326
+ var DELETED_FILE_HEADER = /^deleted file mode /m;
4327
+ var ORIGINAL_PATH_FOLLOWS = /^(?:[RC].|.[RC])/;
4328
+ var LOG_FORMAT = `--format=${RECORD}%H${FIELD}%h${FIELD}%cI${FIELD}%P${FIELD}%s`;
4329
+ var FACTS_HISTORY_OPTIONS = ["--full-history"];
4330
+ async function locateRepo(repo, git = runGitOutcome) {
4331
+ const location = await git(repo, ["rev-parse", "--show-prefix", "--revs-only", "HEAD"]);
4332
+ if (location.status === "exited") {
4333
+ const trustCommand = trustCommandIn(location.stderr);
4334
+ return trustCommand === void 0 ? { history: "not-a-repo" } : { history: "unsafe-repo", trustCommand };
4335
+ }
4336
+ if (location.status === "unfinished") return { history: "unreadable" };
4337
+ const [prefix = "", head = ""] = location.stdout.split("\n").map((line) => line.trim());
4338
+ return { history: "read", prefix, hasCommits: head !== "" };
4339
+ }
4340
+ function trustCommandIn(stderr) {
4341
+ return stderr.split("\n").map((line) => line.trim()).find((line) => TRUST_COMMAND.test(line));
4342
+ }
4343
+ async function collectRepoFacts(repo, pathMarks, known, gitOutcome = runGitOutcome) {
4344
+ const git = asGitRunner(gitOutcome);
4345
+ const paths = [...pathMarks.keys()];
4346
+ const [location, files] = await Promise.all([locateRepo(repo, gitOutcome), sourceFiles(repo, paths)]);
4347
+ const withoutHistory = (noHistory) => ({ ...noHistory, commits: [], renames: [], dirtyModifiedAt: /* @__PURE__ */ new Map(), branches: unknownBranches(noHistory.history), ...files });
4348
+ if (location.history !== "read") return withoutHistory(location);
4349
+ const { prefix, hasCommits } = location;
4350
+ const missing = paths.filter((path) => !files.existing.has(path) && !files.unreadable.has(path));
4351
+ const [log, renames, status, branches] = await Promise.all([
4352
+ hasCommits && paths.length > 0 ? pathLog(repo, [sinceEarliestMark(pathMarks, paths)], paths, git) : "",
4353
+ hasCommits && missing.length > 0 ? git(repo, [...logArgs([sinceEarliestMark(pathMarks, missing)]), "--diff-filter=R"]) : "",
4354
+ git(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=no"]),
4355
+ branchHistoryOf(repo, location, missing, known, git)
4356
+ ]);
4357
+ if (log === null || renames === null || status === null) return withoutHistory({ history: "unreadable" });
4358
+ const dirty = withinRepo(parseStatus(status), prefix);
4359
+ return { history: "read", commits: parseLog(log), renames: parseLog(renames), dirtyModifiedAt: await modificationTimes(repo, dirty), branches, ...files };
4360
+ }
4361
+ async function branchHistoryOf(repo, location, paths, known, git = runGit) {
4362
+ if (location.history !== "read") return unknownBranches(location.history);
4363
+ const [here, anywhere] = await Promise.all([location.hasCommits ? committedPaths(repo, "HEAD", paths, git) : [], knownAnywhere(paths, known) ?? committedPaths(repo, "--all", paths, git)]);
4364
+ return here === null || anywhere === null ? { kind: "unreadable" } : { kind: "read", committedHere: new Set(here), committedAnywhere: new Set(anywhere) };
4365
+ }
4366
+ function knownAnywhere(paths, known) {
4367
+ if (known === void 0 || known.anywhere.kind !== "read" || !paths.every((path) => known.paths.has(path))) return void 0;
4368
+ return [...known.anywhere.committed];
4369
+ }
4370
+ async function pathsEverCommitted(repo, paths) {
4371
+ const location = await locateRepo(repo);
4372
+ if (location.history !== "read") return unknownBranches(location.history);
4373
+ const committed = await committedPaths(repo, "--all", paths);
4374
+ return committed === null ? { kind: "unreadable" } : { kind: "read", committed: new Set(committed) };
4375
+ }
4376
+ function unknownBranches(history) {
4377
+ return history === "not-a-repo" ? { kind: "no-repo" } : { kind: "unreadable" };
4378
+ }
4379
+ function sinceEarliestMark(marks, paths) {
4380
+ return `--since=${new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? []))).toISOString()}`;
4381
+ }
4382
+ function logArgs(selection) {
4383
+ return ["log", ...selection, "--relative", LOG_FORMAT, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
4384
+ }
4385
+ async function pathLog(repo, selection, paths, git) {
4386
+ const inside = paths.filter(isInsideRepo);
4387
+ if (inside.length === 0) return "";
4388
+ return git(repo, [...logArgs(selection), "--", ...literalPathspecs(inside)]);
4389
+ }
4390
+ async function mainlineCommitsOff(repo, base, paths, git = runGit) {
4391
+ const log = await pathLog(repo, ["--first-parent", `${base}..HEAD`], paths, git);
4392
+ return log === null ? null : parseLog(log);
4393
+ }
4394
+ async function committedPaths(repo, revisions, paths, git = runGit) {
4395
+ const inside = paths.filter(isInsideRepo);
4396
+ if (inside.length === 0) return [];
4397
+ const names = await git(repo, ["log", revisions, "--relative", "--format=", "--name-only", ...FACTS_HISTORY_OPTIONS, "-z", "--", ...literalPathspecs(inside)]);
4398
+ return names === null ? null : names.split(/[\0\n]/).filter((name) => name !== "");
4399
+ }
4400
+ function isInsideRepo(path) {
4401
+ const normalized = normalize(path);
4402
+ return normalized !== "." && !isAbsolute2(normalized) && normalized !== ".." && !normalized.startsWith(`..${sep2}`);
4403
+ }
4404
+ function diffsSince(repo, git = runGit, diffFrom = diffsFrom(repo, git)) {
4405
+ const bases = /* @__PURE__ */ new Map();
4406
+ const baseBefore = (since) => remembered(bases, since.getTime(), async () => outputLine(await git(repo, ["rev-list", "-1", "--first-parent", `--before=${since.toISOString()}`, "HEAD"])));
4407
+ return async (path, since) => {
4408
+ const base = await baseBefore(since);
4409
+ return base === null ? null : diffFrom(path, base);
4410
+ };
3978
4411
  }
3979
- function headsAt(headCommitAt, isOnThisLine) {
4412
+ function headCommitsAt(repo, git) {
4413
+ let moves = null;
3980
4414
  return async (moment) => {
3981
- const commit = await headCommitAt(moment);
3982
- return commit === null ? null : { commit, onThisLine: await isOnThisLine(commit) };
4415
+ moves ??= headMovesNewestFirst(repo, git);
4416
+ return (await moves).find((move) => move.at <= moment.getTime())?.commit ?? null;
3983
4417
  };
3984
4418
  }
3985
- async function headMovesNewestFirst(repo) {
3986
- const reflog = await runGit(repo, ["log", "--walk-reflogs", "--date=unix", `--format=%H${FIELD}%gd`, "HEAD"]);
4419
+ function headLineOf(repo, gitOutcome, ancestryOf) {
4420
+ const git = asGitRunner(gitOutcome);
4421
+ const rewroteTip = currentBranchRewroteTipOf(repo, gitOutcome);
4422
+ const answers = /* @__PURE__ */ new Map();
4423
+ return (commit) => remembered(answers, commit, () => lineOfCommit(commit, ancestryOf, () => lineOfNonAncestor(repo, commit, git, rewroteTip)));
4424
+ }
4425
+ async function lineOfCommit(commit, ancestryOf, lineOfNonAncestor2) {
4426
+ const ancestry = await ancestryOf(commit);
4427
+ switch (ancestry) {
4428
+ case "ancestor":
4429
+ return "this-line";
4430
+ case "not-ancestor":
4431
+ return lineOfNonAncestor2();
4432
+ case "missing":
4433
+ case "unknown":
4434
+ return ancestry;
4435
+ }
4436
+ }
4437
+ async function lineOfNonAncestor(repo, commit, git, rewroteTip) {
4438
+ const tip = (await resolveCommits(git, repo, [commit]))?.get(commit);
4439
+ if (tip === void 0) return "unknown";
4440
+ const rewrite = await rewroteTip(tip);
4441
+ if (rewrite === "rewritten") return "this-line";
4442
+ switch (await landingState(repo, tip, git)) {
4443
+ case "landed":
4444
+ return "this-line";
4445
+ case "pending":
4446
+ return rewrite === "unknown" ? "unknown" : "other-branch";
4447
+ case "unknown":
4448
+ return "unknown";
4449
+ }
4450
+ }
4451
+ async function headMovesNewestFirst(repo, git) {
4452
+ const reflog = await git(repo, ["log", "--walk-reflogs", "--date=unix", `--format=%H${FIELD}%gd`, "HEAD"]);
3987
4453
  return (reflog ?? "").split("\n").flatMap((line) => {
3988
4454
  const [commit = "", selector = ""] = line.split(FIELD);
3989
4455
  const seconds = REFLOG_MOMENT.exec(selector)?.[1];
3990
4456
  return seconds === void 0 ? [] : [{ commit, at: Number(seconds) * SECOND_MS }];
3991
4457
  });
3992
4458
  }
3993
- function diffsFrom(repo, git = runGit) {
4459
+ function diffsFrom(repo, git) {
3994
4460
  const diffs = /* @__PURE__ */ new Map();
3995
4461
  const tracked = /* @__PURE__ */ new Map();
3996
4462
  const isConfirmedTracked = (path) => remembered(tracked, path, async () => outputLine(await git(repo, ["ls-files", "--", ...literalPathspecs([path])])) !== null);
@@ -4022,7 +4488,7 @@ async function sourceFiles(repo, paths) {
4022
4488
  };
4023
4489
  }
4024
4490
  async function sourceFile(repo, path) {
4025
- const absolute = join11(repo, path);
4491
+ const absolute = join12(repo, path);
4026
4492
  if (!await fileExists(absolute)) return { kind: "missing", path };
4027
4493
  return { kind: "present", path, text: await readTextIfFile(absolute) };
4028
4494
  }
@@ -4075,29 +4541,89 @@ function withinRepo(gitRootPaths, prefix) {
4075
4541
  async function modificationTimes(repo, paths) {
4076
4542
  const entries = await Promise.all(
4077
4543
  paths.map(async (path) => {
4078
- const info = await lstatOrNull(join11(repo, path));
4544
+ const info = await lstatOrNull(join12(repo, path));
4079
4545
  return info === null ? [] : [[path, info.mtimeMs]];
4080
4546
  })
4081
4547
  );
4082
4548
  return new Map(entries.flat());
4083
4549
  }
4084
4550
 
4551
+ // src/core/check/task-base.ts
4552
+ function taskBases(repo, marks, gitOutcome = runGitOutcome) {
4553
+ const git = asGitRunner(gitOutcome);
4554
+ const diffFrom = diffsFrom(repo, git);
4555
+ const diffSince = diffsSince(repo, git, diffFrom);
4556
+ const headCommitAt = headCommitsAt(repo, git);
4557
+ const ancestries = /* @__PURE__ */ new Map();
4558
+ const ancestry = (commit) => remembered(ancestries, commit, () => headAncestryOf(gitOutcome, repo, commit));
4559
+ const headLine = headLineOf(repo, gitOutcome, ancestry);
4560
+ let completeness;
4561
+ const cloneCompleteness = () => completeness ??= cloneCompletenessOf(git, repo);
4562
+ const markCommits = /* @__PURE__ */ new Map();
4563
+ const markCommit = (task) => remembered(markCommits, task.id, async () => {
4564
+ const reflogCommit = () => headCommitAt(new Date(reviewMark(task)));
4565
+ const recorded = commitAtMark(task, marks);
4566
+ if (recorded === void 0) return reflogCommit();
4567
+ if (task.verified === void 0) return recorded;
4568
+ return seenFromHead(await headLine(recorded)) ? recorded : reflogCommit();
4569
+ });
4570
+ const bases = /* @__PURE__ */ new Map();
4571
+ const baseOf = (task) => remembered(bases, task.id, async () => {
4572
+ const since = new Date(reviewMark(task));
4573
+ const noCommitAtMark = async () => ({ kind: "approximate", since, markLine: await cloneCompleteness() === "full" ? "this-line" : "unknown" });
4574
+ const commit = await markCommit(task);
4575
+ if (commit === null) return noCommitAtMark();
4576
+ const line = await headLine(commit);
4577
+ switch (line) {
4578
+ case "this-line":
4579
+ return { kind: "exact", commit };
4580
+ case "other-branch":
4581
+ return { kind: "approximate", since, markLine: line };
4582
+ case "missing":
4583
+ return noCommitAtMark();
4584
+ case "unknown":
4585
+ return { kind: "unknown" };
4586
+ }
4587
+ });
4588
+ const diffSinceBase = async (task, path) => {
4589
+ const base = await baseOf(task);
4590
+ switch (base.kind) {
4591
+ case "exact":
4592
+ return diffFrom(path, base.commit);
4593
+ case "approximate":
4594
+ return diffSince(path, base.since);
4595
+ case "unknown":
4596
+ return null;
4597
+ }
4598
+ };
4599
+ return { markCommit, baseOf, diffSinceBase, diffFrom, ancestry, cloneCompleteness };
4600
+ }
4601
+ function markLineOf(base) {
4602
+ switch (base.kind) {
4603
+ case "exact":
4604
+ return "this-line";
4605
+ case "approximate":
4606
+ return base.markLine;
4607
+ case "unknown":
4608
+ return "unknown";
4609
+ }
4610
+ }
4611
+ function seenFromHead(line) {
4612
+ switch (line) {
4613
+ case "this-line":
4614
+ case "unknown":
4615
+ return true;
4616
+ case "other-branch":
4617
+ case "missing":
4618
+ return false;
4619
+ }
4620
+ }
4621
+
4085
4622
  // src/core/check/current-source.ts
4086
4623
  var LATER_COMMITS_TO_SEARCH = 5;
4087
4624
  var UNTRACED = { kind: "untraced" };
4088
- function repoDiffs(repo, origins) {
4089
- const from = diffsFrom(repo);
4090
- const since = diffsSince(repo, runGit, from);
4091
- const headCommitAt = headCommitsAt(repo);
4092
- const isOnThisLine = ancestorsOfHead(repo);
4093
- const sinceTaskMark = async (task, path) => {
4094
- const checkout = await checkoutAtMark(task, origins, headCommitAt);
4095
- return checkout !== null && await isOnThisLine(checkout) ? from(path, checkout) : since(path, new Date(reviewMark(task)));
4096
- };
4097
- return { since, from, headAt: headsAt(headCommitAt, isOnThisLine), sinceTaskMark };
4098
- }
4099
- async function traceSources(tasks, history, diffs) {
4100
- return new Map(await Promise.all(tasks.map(async (task) => [task.id, await traceSource(task, history, diffs)])));
4625
+ async function traceSources(tasks, history, bases) {
4626
+ return new Map(await Promise.all(tasks.map(async (task) => [task.id, await traceSource(task, history, bases)])));
4101
4627
  }
4102
4628
  function currentSourcesOf(traces) {
4103
4629
  return new Map([...traces].map(([id, trace]) => [id, currentOf(trace)]));
@@ -4105,12 +4631,12 @@ function currentSourcesOf(traces) {
4105
4631
  async function currentSourceIn(repo, task) {
4106
4632
  if (task.source === void 0) return null;
4107
4633
  const facts = await collectRepoFacts(repo, /* @__PURE__ */ new Map([[sourcePath(task.source), reviewMark(task)]]));
4108
- return currentOf(await traceSource(task, { facts, late: /* @__PURE__ */ new Map() }, repoDiffs(repo, /* @__PURE__ */ new Map())));
4634
+ return currentOf(await traceSource(task, { facts, late: /* @__PURE__ */ new Map() }, taskBases(repo, NO_MARK_COMMITS)));
4109
4635
  }
4110
4636
  function currentOf(trace) {
4111
4637
  return trace.kind === "traced" ? trace.current : null;
4112
4638
  }
4113
- async function traceSource(task, history, diffs) {
4639
+ async function traceSource(task, history, bases) {
4114
4640
  const { source, anchor } = task;
4115
4641
  if (source === void 0 || !hasLines(source)) return UNTRACED;
4116
4642
  const text = history.facts.texts.get(sourcePath(source));
@@ -4119,8 +4645,8 @@ async function traceSource(task, history, diffs) {
4119
4645
  const fileUntouched = commits.length === 0 && !uncommitted;
4120
4646
  if (fileUntouched && (anchor === void 0 || windowMatches(text, source, anchor))) return { kind: "traced", current: source, linesChanged: false };
4121
4647
  const traced = { ...task, source };
4122
- const reference = await referenceOf(traced, text, commits, diffs);
4123
- if (reference.kind === "not-on-branch") return fileUntouched ? { kind: "not-on-branch" } : UNTRACED;
4648
+ const reference = await referenceOf(traced, text, commits, bases);
4649
+ if (reference.kind === "other-branch") return fileUntouched ? reference : UNTRACED;
4124
4650
  if (reference.kind === "untraced") return UNTRACED;
4125
4651
  const lines = anchorRange(reference.source);
4126
4652
  return { kind: "traced", current: currentSource(reference, text, traced), linesChanged: lines === null || modifiesLines(reference.hunks, lines) };
@@ -4130,19 +4656,14 @@ function currentSource(reference, text, { source, anchor }) {
4130
4656
  if (current === null || anchorOf(text, current) === null) return null;
4131
4657
  return anchor === void 0 && current !== source ? null : current;
4132
4658
  }
4133
- async function referenceOf(task, text, laterCommits, diffs) {
4659
+ async function referenceOf(task, text, laterCommits, bases) {
4134
4660
  const path = sourcePath(task.source);
4135
4661
  const { anchor } = task;
4136
- const mark = new Date(reviewMark(task));
4137
- const head = anchor === void 0 ? null : await diffs.headAt(mark);
4138
- const headAtMark = async () => head?.onThisLine === true ? diffs.from(path, head.commit) : null;
4139
- const lastCommitBeforeMark = () => diffs.since(path, mark);
4140
- const sinceTaskMark = () => diffs.sinceTaskMark(task, path);
4141
- const afterMark = laterCommits.toReversed().slice(0, LATER_COMMITS_TO_SEARCH).map((commit) => () => diffs.from(path, commit.sha));
4142
- const references = anchor === void 0 ? [sinceTaskMark] : [headAtMark, lastCommitBeforeMark, ...afterMark];
4143
- const unmatched = head?.onThisLine === false ? { kind: "not-on-branch" } : { kind: "untraced" };
4662
+ const atBase = () => bases.diffSinceBase(task, path);
4663
+ const afterMark = anchor === void 0 ? [] : laterCommits.toReversed().slice(0, LATER_COMMITS_TO_SEARCH).map((commit) => () => bases.diffFrom(path, commit.sha));
4664
+ const unmatched = unmatchedOn(await bases.baseOf(task));
4144
4665
  let search = { kind: "untraced" };
4145
- for (const diffFromReference of references) {
4666
+ for (const diffFromReference of [atBase, ...afterMark]) {
4146
4667
  const hunks = (await diffFromReference())?.hunks ?? null;
4147
4668
  if (hunks === null) continue;
4148
4669
  const source = anchor === void 0 ? task.source : locateAnchor(baseText(hunks, text), task.source, anchor);
@@ -4151,17 +4672,20 @@ async function referenceOf(task, text, laterCommits, diffs) {
4151
4672
  }
4152
4673
  return search;
4153
4674
  }
4675
+ function unmatchedOn(base) {
4676
+ return markLineOf(base) === "other-branch" ? { kind: "other-branch" } : { kind: "untraced" };
4677
+ }
4154
4678
 
4155
4679
  // src/core/check/project-repo.ts
4156
4680
  async function sourceAnchor(repo, source, onUnreadable) {
4157
- const text = repo === void 0 ? null : await attemptReportingFailure(join12(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4681
+ const text = repo === void 0 ? null : await attemptReportingFailure(join13(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4158
4682
  if (text === null) return { kind: "no-file" };
4159
4683
  const anchor = anchorOf(text, source);
4160
4684
  return anchor === null ? { kind: "uncomputable" } : { kind: "anchor", anchor };
4161
4685
  }
4162
4686
  async function sourcePresence(repo, source, onUnreadable) {
4163
4687
  const path = sourcePath(source);
4164
- const onDisk = await attemptReportingFailure(join12(repo, path), fileExists, onUnreadable);
4688
+ const onDisk = await attemptReportingFailure(join13(repo, path), fileExists, onUnreadable);
4165
4689
  const presentOrUnreadable = onDisk !== false;
4166
4690
  if (presentOrUnreadable) return { kind: "present" };
4167
4691
  const location = await locateRepo(repo);
@@ -4172,20 +4696,154 @@ async function relocatedSource(repo, task) {
4172
4696
  const current = repo === void 0 ? null : await currentSourceIn(repo, task);
4173
4697
  return current === null || current === task.source ? void 0 : current;
4174
4698
  }
4175
- async function findRepo(project, { workingRoots, ...context }) {
4176
- return (await projectCheckout(project, workingRoots, context))?.path;
4699
+ async function projectCheckouts(project, { workingRoots, ...context }) {
4700
+ const repos = await existingRepos(project, context);
4701
+ const cwdRepo = workingRoots === null ? void 0 : repos.find((repo) => realpathOrNull(repo) === workingRoots.main);
4702
+ const others = repos.filter((repo) => repo !== cwdRepo).map((path) => ({ path, linkedWorktree: false, holdsCwd: false }));
4703
+ if (cwdRepo === void 0 || workingRoots === null) return others;
4704
+ return [{ path: workingRoots.worktree, linkedWorktree: workingRoots.worktree !== workingRoots.main, holdsCwd: true }, ...others];
4705
+ }
4706
+ async function explicitSourceRepo(project, lookup, source) {
4707
+ const [choice] = (await sourceChoices(await projectCheckouts(project, lookup), [{ source }])).choices;
4708
+ return choice === void 0 ? void 0 : repoChoice(choice.checkout, choice.settled || choice.checkout.holdsCwd);
4709
+ }
4710
+ async function taskRepo(project, lookup, task, marks) {
4711
+ const [choice] = (await sourceChoices(await projectCheckouts(project, lookup), [ownedSource(task, marks)])).choices;
4712
+ return choice === void 0 ? void 0 : repoChoice(choice.checkout, choice.settled);
4713
+ }
4714
+ async function tasksByCheckout(checkouts, tasks, marks) {
4715
+ const { choices, histories } = await sourceChoices(
4716
+ checkouts,
4717
+ tasks.map((task) => ownedSource(task, marks))
4718
+ );
4719
+ const chosen = tasks.map((task, index) => ({ task, choice: choices[index] }));
4720
+ return checkouts.flatMap((checkout) => {
4721
+ const own = chosen.filter(({ choice }) => choice?.checkout === checkout);
4722
+ const unsettled = new Set(own.filter(({ choice }) => choice?.settled === false).map(({ task }) => task.id));
4723
+ return own.length === 0 ? [] : [{ checkout, tasks: own.map(({ task }) => task), unsettled, history: histories.get(checkout) }];
4724
+ });
4725
+ }
4726
+ function repoChoice({ path }, recordable) {
4727
+ return { path, recordIn: recordable ? path : void 0 };
4728
+ }
4729
+ function ownedSource(task, marks) {
4730
+ return { source: task.source, anchor: task.anchor, ownerCommit: latestRecordedCommit(task, marks) };
4177
4731
  }
4178
- async function projectCheckout(project, workingRoots, context) {
4179
- const repo = await firstExistingRepo(project, context);
4180
- if (repo === void 0) return void 0;
4181
- if (workingRoots === null || workingRoots.main !== realpathOrNull(repo)) return { path: repo, linkedWorktree: false };
4182
- return { path: workingRoots.worktree, linkedWorktree: workingRoots.worktree !== workingRoots.main };
4732
+ async function sourceChoices(checkouts, tasks) {
4733
+ const [first] = checkouts;
4734
+ if (first === void 0) return { choices: tasks.map(() => void 0), histories: /* @__PURE__ */ new Map() };
4735
+ if (checkouts.length === 1) return { choices: tasks.map(() => ({ checkout: first, settled: true })), histories: /* @__PURE__ */ new Map() };
4736
+ const [onDisk, ownerOf] = await Promise.all([Promise.all(tasks.map((task) => checkoutsWithSource(checkouts, task.source))), ownerCheckouts(checkouts, tasks)]);
4737
+ const ownerHistories = await askHistories(
4738
+ checkouts,
4739
+ tasks.flatMap((task, index) => ownerQuestion(task, onDisk[index] ?? [], ownerOf(task)))
4740
+ );
4741
+ const otherHistories = await askHistories(
4742
+ checkouts,
4743
+ tasks.flatMap((task, index) => otherQuestions(checkouts, task, onDisk[index] ?? [], ownerOf(task), ownerHistories))
4744
+ );
4745
+ const histories = mergedHistories(ownerHistories, otherHistories);
4746
+ const choices = await Promise.all(
4747
+ tasks.map((task, index) => {
4748
+ const path = task.source === void 0 ? void 0 : sourcePath(task.source);
4749
+ const traceIn = (checkout) => path === void 0 ? "none" : traceOf(histories, checkout, path);
4750
+ return sourceChoice(checkouts, first, task, { onDisk: onDisk[index] ?? [], owner: ownerOf(task), traceIn });
4751
+ })
4752
+ );
4753
+ return { choices, histories };
4754
+ }
4755
+ async function sourceChoice(checkouts, first, task, evidence2) {
4756
+ if (task.source === void 0) return { checkout: first, settled: true };
4757
+ const path = sourcePath(task.source);
4758
+ const { onDisk, owner, traceIn } = evidence2;
4759
+ if (owner !== void 0 && onDisk.includes(owner)) return { checkout: owner, settled: true };
4760
+ if (owner !== void 0 && traceIn(owner) !== "none") return ownerWithoutFile(owner, path, task, evidence2);
4761
+ const [preferred] = onDisk;
4762
+ if (preferred !== void 0) return anchoredChoice(preferred, onDisk, path, task);
4763
+ const committed = checkouts.filter((checkout) => traceIn(checkout) === "committed");
4764
+ if (committed[0] !== void 0) return { checkout: committed[0], settled: committed.length === 1 };
4765
+ const unknown = checkouts.filter((checkout) => traceIn(checkout) === "unknown");
4766
+ return { checkout: unknown[0] ?? first, settled: unknown.length === 0 };
4767
+ }
4768
+ async function ownerWithoutFile(owner, path, task, { onDisk, traceIn }) {
4769
+ if (onDisk.length === 0) return { checkout: owner, settled: traceIn(owner) === "committed" };
4770
+ const anchored = await anchoredIn(onDisk, path, task);
4771
+ return anchored.length === 1 && anchored[0] !== void 0 ? { checkout: anchored[0], settled: true } : { checkout: owner, settled: false };
4772
+ }
4773
+ async function anchoredChoice(preferred, onDisk, path, task) {
4774
+ if (onDisk.length === 1) return { checkout: preferred, settled: true };
4775
+ const anchored = await anchoredIn(onDisk, path, task);
4776
+ return { checkout: anchored[0] ?? preferred, settled: anchored.length === 1 };
4777
+ }
4778
+ async function anchoredIn(onDisk, path, task) {
4779
+ if (task.anchor === void 0) return [];
4780
+ const texts = await Promise.all(onDisk.map((checkout) => attemptReportingFailure(join13(checkout.path, path), readTextIfFile, unreadableIsLeftToReview)));
4781
+ return onDisk.filter((_, index) => anchorHolds(task, texts[index] ?? null));
4782
+ }
4783
+ async function checkoutsWithSource(checkouts, source) {
4784
+ if (source === void 0) return [];
4785
+ const path = sourcePath(source);
4786
+ const onDisk = await Promise.all(checkouts.map((checkout) => attemptReportingFailure(join13(checkout.path, path), fileExists, unreadableIsLeftToReview)));
4787
+ return checkouts.filter((_, index) => onDisk[index] !== false);
4788
+ }
4789
+ async function ownerCheckouts(checkouts, tasks) {
4790
+ const commits = [...new Set(tasks.flatMap((task) => task.source === void 0 || task.ownerCommit === void 0 ? [] : [task.ownerCommit]))];
4791
+ const found = commits.length === 0 ? [] : await Promise.all(checkouts.map((checkout) => resolveCommits(runGit, checkout.path, commits)));
4792
+ return ({ ownerCommit }) => {
4793
+ if (ownerCommit === void 0) return void 0;
4794
+ const holders = checkouts.filter((_, index) => found[index]?.has(ownerCommit) === true);
4795
+ return holders.length === 1 ? holders[0] : void 0;
4796
+ };
4183
4797
  }
4184
- async function firstExistingRepo(project, { home: home2, onUnreadable }) {
4185
- for (const repo of project.repos.map((path) => expandHome(path, home2))) {
4186
- if (await attemptReportingFailure(repo, fileExists, onUnreadable) === true) return repo;
4798
+ function ownerQuestion(task, onDisk, owner) {
4799
+ return task.source === void 0 || owner === void 0 || onDisk.includes(owner) ? [] : [[owner, sourcePath(task.source)]];
4800
+ }
4801
+ function otherQuestions(checkouts, task, onDisk, owner, ownerHistories) {
4802
+ if (task.source === void 0 || onDisk.length > 0) return [];
4803
+ const path = sourcePath(task.source);
4804
+ if (owner !== void 0 && traceOf(ownerHistories, owner, path) !== "none") return [];
4805
+ return checkouts.filter((checkout) => checkout !== owner).map((checkout) => [checkout, path]);
4806
+ }
4807
+ async function askHistories(checkouts, asked) {
4808
+ const answers = await Promise.all(
4809
+ checkouts.map(async (checkout) => {
4810
+ const paths = new Set(asked.flatMap(([asker, path]) => asker === checkout ? [path] : []));
4811
+ return paths.size === 0 ? [] : [[checkout, { paths, anywhere: await pathsEverCommitted(checkout.path, [...paths]) }]];
4812
+ })
4813
+ );
4814
+ return new Map(answers.flat());
4815
+ }
4816
+ function mergedHistories(first, second) {
4817
+ const merged = new Map(first);
4818
+ for (const [checkout, known] of second) {
4819
+ const earlier = merged.get(checkout);
4820
+ merged.set(checkout, earlier === void 0 ? known : { paths: /* @__PURE__ */ new Set([...earlier.paths, ...known.paths]), anywhere: combinedAnswer(earlier.anywhere, known.anywhere) });
4187
4821
  }
4188
- return void 0;
4822
+ return merged;
4823
+ }
4824
+ function combinedAnswer(one, other) {
4825
+ if (one.kind !== "read") return one;
4826
+ if (other.kind !== "read") return other;
4827
+ return { kind: "read", committed: /* @__PURE__ */ new Set([...one.committed, ...other.committed]) };
4828
+ }
4829
+ function traceOf(histories, checkout, path) {
4830
+ const known = histories.get(checkout);
4831
+ if (known?.paths.has(path) !== true) return "none";
4832
+ switch (known.anywhere.kind) {
4833
+ case "no-repo":
4834
+ return "none";
4835
+ case "unreadable":
4836
+ return "unknown";
4837
+ case "read":
4838
+ return committedIn(known.anywhere.committed, path) ? "committed" : "none";
4839
+ }
4840
+ }
4841
+ function unreadableIsLeftToReview() {
4842
+ }
4843
+ async function existingRepos(project, { home: home2, onUnreadable }) {
4844
+ const repos = project.repos.map((path) => expandHome(path, home2));
4845
+ const exists = await Promise.all(repos.map((repo) => attemptReportingFailure(repo, fileExists, onUnreadable)));
4846
+ return repos.filter((_, index) => exists[index] === true);
4189
4847
  }
4190
4848
  async function hasCommit(repo, sha) {
4191
4849
  return await runGit(repo, ["cat-file", "-e", `${sha}^{commit}`]) !== null;
@@ -4193,14 +4851,14 @@ async function hasCommit(repo, sha) {
4193
4851
 
4194
4852
  // src/core/store/create.ts
4195
4853
  import { mkdir as mkdir3 } from "node:fs/promises";
4196
- import { basename as basename6, join as join13 } from "node:path";
4854
+ import { basename as basename5, join as join14 } from "node:path";
4197
4855
  var MAX_ID_ATTEMPTS = 20;
4198
4856
  async function createTask(root, request) {
4199
4857
  const { project, index } = request;
4200
- const dir = join13(root, project.id);
4858
+ const dir = join14(root, project.id);
4201
4859
  for (let attempt = 0; attempt < MAX_ID_ATTEMPTS; attempt++) {
4202
4860
  const id = formatId(project.prefix, await nextTaskNumber(dir, project, request.onError));
4203
- const path = join13(dir, taskFileName(id));
4861
+ const path = join14(dir, taskFileName(id));
4204
4862
  const normalized = taskText(draftTask(id, path, request));
4205
4863
  if (!normalized.ok) return invalid(normalized.problems);
4206
4864
  const { text, task } = normalized.value;
@@ -4233,19 +4891,19 @@ async function createProject(root, repoRoot, existingProjects, onError) {
4233
4891
  }
4234
4892
  }
4235
4893
  async function draftProjectFile(root, repoRoot, existingProjects) {
4236
- const name = basename6(repoRoot);
4237
- const entries = await listDir(root);
4238
- const joinable = await Promise.all(entries.map((entry) => entry.isDirectory() ? isJoinableProjectDir(join13(root, entry.name), repoRoot) : Promise.resolve(false)));
4894
+ const name = basename5(repoRoot);
4895
+ const entries = await listDirFollowingLinks(root);
4896
+ const joinable = await Promise.all(entries.map((entry) => entry.kind === "directory" ? isJoinableProjectDir(join14(root, entry.name), repoRoot) : Promise.resolve(false)));
4239
4897
  const id = deriveProjectId(name, new Set(entries.filter((_, index) => !joinable[index]).map((entry) => entry.name)));
4240
- const prefixesOnDisk = await Promise.all(entries.filter((entry) => entry.isDirectory()).map((entry) => takenPrefixes(join13(root, entry.name))));
4898
+ const prefixesOnDisk = await Promise.all(entries.filter((entry) => entry.kind === "directory").map((entry) => takenPrefixes(join14(root, entry.name))));
4241
4899
  const prefix = derivePrefix(name, /* @__PURE__ */ new Set([...existingProjects.map((project) => project.prefix), ...prefixesOnDisk.flat()]));
4242
- const dir = join13(root, id);
4900
+ const dir = join14(root, id);
4243
4901
  await mkdir3(dir, { recursive: true });
4244
- return { id, path: join13(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
4902
+ return { id, path: join14(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
4245
4903
  }
4246
4904
  async function isJoinableProjectDir(dir, repoRoot) {
4247
4905
  const entries = await listDir(dir);
4248
- if (entries.some((entry) => entry.name === PROJECT_FILE)) return await projectOfRepo(basename6(dir), join13(dir, PROJECT_FILE), repoRoot) !== null;
4906
+ if (entries.some((entry) => entry.name === PROJECT_FILE)) return await projectOfRepo(basename5(dir), join14(dir, PROJECT_FILE), repoRoot) !== null;
4249
4907
  return entries.every((entry) => !entry.name.endsWith(".md"));
4250
4908
  }
4251
4909
  async function projectOfRepo(id, path, repoRoot) {
@@ -4259,7 +4917,7 @@ async function nextTaskNumber(dir, project, onError) {
4259
4917
  return Math.max(onDisk, reserved, journaled, project.issuedUpTo ?? 0) + 1;
4260
4918
  }
4261
4919
  async function maxJournaledNumber(dir, project, onError) {
4262
- const journal = await attemptReportingFailure(join13(dir, JOURNAL_FILE), () => readJournal(dir, project.id), onError);
4920
+ const journal = await attemptReportingFailure(join14(dir, JOURNAL_FILE), () => readJournal(dir, project.id), onError);
4263
4921
  const journaledIds = (journal?.events ?? []).flatMap((event) => parseId(event.task) ?? []);
4264
4922
  return maxNumberWithPrefix(journaledIds, project.prefix);
4265
4923
  }
@@ -4271,7 +4929,7 @@ function maxNumberWithPrefix(ids, prefix) {
4271
4929
  }
4272
4930
  var PREFIX_LINE = /^prefix:\s*["']?([^\s"']+)/m;
4273
4931
  async function takenPrefixes(dir) {
4274
- const declared = PREFIX_LINE.exec(await readTextOrNull(join13(dir, PROJECT_FILE)) ?? "")?.[1];
4932
+ const declared = PREFIX_LINE.exec(await readTextOrNull(join14(dir, PROJECT_FILE)) ?? "")?.[1];
4275
4933
  return [...declared !== void 0 && PREFIX_PATTERN.test(declared) ? [declared] : [], ...(await taskFileIds(dir)).map((parsed) => parsed.prefix)];
4276
4934
  }
4277
4935
  async function taskFileIds(dir) {
@@ -4300,7 +4958,7 @@ function draftTask(id, path, { project, input, now }) {
4300
4958
  }
4301
4959
 
4302
4960
  // src/core/store/resolve-project.ts
4303
- import { basename as basename7, dirname as dirname6, resolve as resolve2 } from "node:path";
4961
+ import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute3, join as join15, resolve as resolve2 } from "node:path";
4304
4962
  var REPO_ROOT_TTL_MS = 6e4;
4305
4963
  var SHOW_ROOTS = ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"];
4306
4964
  var LIST_WORKTREES = ["worktree", "list", "--porcelain"];
@@ -4329,9 +4987,17 @@ function cachedRepoRoots({ onUnreadable, ttlMs = REPO_ROOT_TTL_MS, now = Date.no
4329
4987
  function rootsOf({ topLevel }, worktreeList) {
4330
4988
  return canonicalRoots(topLevel, mainWorktreeIn(worktreeList) ?? topLevel);
4331
4989
  }
4332
- function plainDirRoots(dir) {
4333
- const path = realpathOrNull(dir);
4334
- return path === null ? null : { worktree: path, main: path };
4990
+ function nearestExistingAncestor(path) {
4991
+ const real = realpathOrNull(path);
4992
+ if (real !== null) return { real, missing: [] };
4993
+ const parent = dirname6(path);
4994
+ if (parent === path || !isAbsolute3(path)) return null;
4995
+ const ancestor = nearestExistingAncestor(parent);
4996
+ return ancestor === null ? null : { real: ancestor.real, missing: [...ancestor.missing, basename6(path)] };
4997
+ }
4998
+ function realpathThroughExistingAncestor(path) {
4999
+ const ancestor = nearestExistingAncestor(path);
5000
+ return ancestor === null ? null : join15(ancestor.real, ...ancestor.missing);
4335
5001
  }
4336
5002
  function parseRevParse(dir, output) {
4337
5003
  const [topLevel = "", gitDir = "", commonDir = ""] = (output ?? "").split("\n").map((line) => line.trim());
@@ -4356,11 +5022,39 @@ function readGitRoots(dir, onUnreadable) {
4356
5022
  function repoRootsOf(dirRoots) {
4357
5023
  return typeof dirRoots === "string" ? null : dirRoots;
4358
5024
  }
5025
+ var strictly = (context) => ({ ...context, canonicalize: realpathOrNull });
4359
5026
  function lookupProjectForDir(known, dir, dirRoots, context) {
5027
+ return lookupProjectCanonicalizing(known, dir, dirRoots, strictly(context));
5028
+ }
5029
+ async function lookupProjectForRecordedDir(known, dir, { lookupRepoRoot, worktreeRepos }, context) {
5030
+ const dirRoots = await lookupRepoRoot(dir);
5031
+ const leniently = { ...context, canonicalize: realpathThroughExistingAncestor };
5032
+ const byPath = lookupProjectCanonicalizing(known, dir, dirRoots, leniently);
5033
+ if ("project" in byPath || byPath.broken.length > 0 || dirRoots !== "not-in-repo") return byPath;
5034
+ const byLiveAncestor = await lookupThroughLiveAncestor(known, dir, lookupRepoRoot, context);
5035
+ if (byLiveAncestor !== null) return byLiveAncestor;
5036
+ const recordedWorktree = recordedWorktreeOf(dir, worktreeRepos, context);
5037
+ return recordedWorktree === null ? byPath : lookupProjectCanonicalizing(known, dir, recordedWorktree, leniently);
5038
+ }
5039
+ async function lookupThroughLiveAncestor(known, dir, lookupRepoRoot, context) {
5040
+ const ancestor = attemptReportingFailureSync(dir, nearestExistingAncestor, context.onUnreadable);
5041
+ if (ancestor === null || ancestor.missing.length === 0) return null;
5042
+ const roots = repoRootsOf(await lookupRepoRoot(ancestor.real));
5043
+ return roots === null ? null : lookupProjectForDir(known, ancestor.real, roots, context);
5044
+ }
5045
+ function unreadableDirHasNoRepo() {
5046
+ }
5047
+ function recordedWorktreeOf(dir, worktreeRepos, { onUnreadable }) {
5048
+ const path = attemptReportingFailureSync(dir, realpathThroughExistingAncestor, onUnreadable);
5049
+ if (path === null) return null;
5050
+ const [deepest] = Object.entries(worktreeRepos).filter(([worktree]) => isSameOrInside(path, worktree)).sort(([a], [b]) => b.length - a.length);
5051
+ return deepest === void 0 ? null : { worktree: deepest[0], main: deepest[1] };
5052
+ }
5053
+ function lookupProjectCanonicalizing(known, dir, dirRoots, context) {
4360
5054
  const roots = matchingRoots(dir, dirRoots, context);
4361
5055
  if (roots === null) return { broken: [] };
4362
5056
  const repo = repoRootsOf(dirRoots);
4363
- return lookupProject(known, { roots, repoDirName: repo === null ? void 0 : projectIdBase(basename7(repo.main)) }, context);
5057
+ return lookupProject(known, { roots, repoDirName: repo === null ? void 0 : projectIdBase(basename6(repo.main)) }, context);
4364
5058
  }
4365
5059
  function lookupProject({ projects, errors }, { roots, repoDirName }, context) {
4366
5060
  const coveredLength = (repos) => closestCoveringRepo(repos, roots, context)?.length ?? 0;
@@ -4374,9 +5068,11 @@ function lookupProject({ projects, errors }, { roots, repoDirName }, context) {
4374
5068
  if (project !== void 0 && covering.every(({ length }) => length <= projectLength)) return { project };
4375
5069
  return { broken: covering.map(({ error }) => error) };
4376
5070
  }
4377
- function matchingRoots(dir, dirRoots, context) {
5071
+ function matchingRoots(dir, dirRoots, { canonicalize, onUnreadable }) {
4378
5072
  if (dirRoots === "unreadable") return null;
4379
- return dirRoots === "not-in-repo" ? attemptReportingFailureSync(dir, plainDirRoots, context.onUnreadable) : dirRoots;
5073
+ if (dirRoots !== "not-in-repo") return dirRoots;
5074
+ const path = attemptReportingFailureSync(dir, canonicalize, onUnreadable);
5075
+ return path === null ? null : { worktree: path, main: path };
4380
5076
  }
4381
5077
  function findProjectForRoots(projects, roots, context) {
4382
5078
  const matches = projects.flatMap((project) => {
@@ -4386,7 +5082,7 @@ function findProjectForRoots(projects, roots, context) {
4386
5082
  return matches.sort((a, b) => b.repoPath.length - a.repoPath.length || Number(b.project.active) - Number(a.project.active))[0]?.project;
4387
5083
  }
4388
5084
  function pathFromProjectRepo(project, roots, context, path) {
4389
- const repoPath = closestCoveringRepo(project.repos, roots, context);
5085
+ const repoPath = closestCoveringRepo(project.repos, roots, strictly(context));
4390
5086
  if (repoPath === void 0) return null;
4391
5087
  const enclosingRootsOf = (dir) => repoRootsOf(readGitRoots(dirname6(dir), context.onUnreadable));
4392
5088
  return relativeInside(repoPath, asInProjectRepoCheckout(path, roots, { repoPath, enclosingRootsOf }));
@@ -4416,8 +5112,9 @@ function repoCovers(repoPath, { worktree, main }) {
4416
5112
  function isSameOrInside(path, container) {
4417
5113
  return relativeInside(container, path) !== null;
4418
5114
  }
4419
- function resolvedRepo(repo, { home: home2, onUnreadable }) {
4420
- return attemptReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
5115
+ function resolvedRepo(repo, { home: home2, onUnreadable, canonicalize }) {
5116
+ const path = expandHome(repo, home2);
5117
+ return isAbsolute3(path) ? attemptReportingFailureSync(path, canonicalize, onUnreadable) : null;
4421
5118
  }
4422
5119
 
4423
5120
  // src/cli/lookups.ts
@@ -4480,7 +5177,7 @@ function findTaskOrWarn(loaded, io, id) {
4480
5177
  function missingTaskMessage(loaded, io, id) {
4481
5178
  if (!ID_PATTERN.test(id)) return io.cli.taskNotFound(id);
4482
5179
  const fileName = taskFileName(id);
4483
- const broken = loaded.errors.find((error) => basename8(error.path) === fileName);
5180
+ const broken = loaded.errors.find((error) => basename7(error.path) === fileName);
4484
5181
  if (broken) return io.cli.taskFileUnparsed(id, io.core.problems(broken.problems));
4485
5182
  const hidingProject = unparsedProjectFiles(loaded.errors).find((error) => error.hiddenTasks.includes(id));
4486
5183
  return hidingProject ? io.cli.taskOfUnparsedProject(id, hidingProject.path, io.core.problems(hidingProject.problems)) : io.cli.taskNotFound(id);
@@ -4533,8 +5230,8 @@ async function ensureProject(loaded, io, explicitId) {
4533
5230
  // src/cli/task-write.ts
4534
5231
  function taskWriter(io, index) {
4535
5232
  const onError = warnPathErrors(io.warn);
4536
- return async (task, changes, closure) => {
4537
- const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, now: io.now(), via: "cli", onError, closure });
5233
+ return async (task, changes, details = {}) => {
5234
+ const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, now: io.now(), via: "cli", onError, ...details });
4538
5235
  if (!result.ok) return { ok: false, exitCode: reportUpdateFailure(io, task.id, result) };
4539
5236
  if (result.reopenedEpic !== void 0) io.warn(io.cli.epicReopened(result.reopenedEpic.id));
4540
5237
  return result;
@@ -4600,7 +5297,7 @@ var categoryCommand = taskFieldCommand({
4600
5297
  });
4601
5298
 
4602
5299
  // src/core/check/check-backlog.ts
4603
- import { join as join17 } from "node:path";
5300
+ import { join as join19 } from "node:path";
4604
5301
 
4605
5302
  // src/core/check/check-fixes.ts
4606
5303
  async function applyFixes(loaded, inScope, { messages, ...writes }) {
@@ -4671,387 +5368,150 @@ function goneTaskCheck({ projects }, index) {
4671
5368
  return (id) => {
4672
5369
  const prefix = parseId(id)?.prefix;
4673
5370
  return prefix !== void 0 && loadedPrefixes.has(prefix) && !index.byId.has(id) && !index.notLoaded.has(id);
4674
- };
4675
- }
4676
-
4677
- // src/core/check/find-problems.ts
4678
- function findProblems(loaded, projects, repos, inScope) {
4679
- const index = indexOfLoaded(loaded);
4680
- const integrity = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => integrityErrors(task, index).map((problem3) => ({ kind: "task-invalid", taskId: task.id, problem: problem3 })));
4681
- const missingRepos = projects.filter((project) => repos.get(project.id) === void 0).map(missingRepoProblem);
4682
- return [...parseProblems(loaded, inScope), ...integrity, ...missingRepos, ...sharedPrefixes(loaded.projects, inScope)];
4683
- }
4684
- function sharedPrefixes(projects, inScope) {
4685
- const idsByPrefix = /* @__PURE__ */ new Map();
4686
- for (const project of projects) idsByPrefix.set(project.prefix, [...idsByPrefix.get(project.prefix) ?? [], project.id]);
4687
- return [...idsByPrefix].filter(([, projectIds]) => projectIds.length > 1 && projectIds.some(inScope)).map(([prefix, projectIds]) => ({ kind: "prefix-shared", prefix, projectIds }));
4688
- }
4689
- function parseProblems(loaded, inScope) {
4690
- const waitingEpicIds = planEpicClosing(loaded.tasks, loaded.errors).waiting.filter(({ epic }) => inScope(epic.projectId)).map(({ epic }) => epic.id);
4691
- const everyFileMayHoldWaitingChild = waitingEpicIds.length > 0;
4692
- const reported = loaded.errors.filter((error) => everyFileMayHoldWaitingChild || concernsScope(error, inScope)).map((error) => ({ kind: "file-not-parsed", path: error.path, problems: error.problems }));
4693
- if (waitingEpicIds.length === 0) return reported;
4694
- return [...reported, { kind: "epics-wait-for-files", epicIds: waitingEpicIds }];
4695
- }
4696
- function concernsScope(error, inScope) {
4697
- return inScope(error.projectId) || isProjectFileError(error);
4698
- }
4699
- function missingRepoProblem(project) {
4700
- return project.repos.length === 0 ? { kind: "project-without-repos", projectId: project.id } : { kind: "project-repos-missing", projectId: project.id, repos: project.repos };
4701
- }
4702
-
4703
- // src/core/check/project-review.ts
4704
- import { join as join16 } from "node:path";
4705
-
4706
- // src/core/code-review-graph/graph-db.ts
4707
- import { existsSync, realpathSync as realpathSync2 } from "node:fs";
4708
- import { join as join14 } from "node:path";
4709
- var SYMBOL_KINDS = ["Class", "Function", "Type", "Test"];
4710
- var GRAPH_FILE = join14(".code-review-graph", "graph.db");
4711
- var SUPPORTED_SCHEMA = "13";
4712
- function hasCodeGraph(repo) {
4713
- return existsSync(join14(repo, GRAPH_FILE));
4714
- }
4715
- function openCodeGraph(repo) {
4716
- let db = null;
4717
- try {
4718
- const { DatabaseSync: SqliteDatabase } = process.getBuiltinModule("node:sqlite");
4719
- db = new SqliteDatabase(join14(repo, GRAPH_FILE), { readOnly: true });
4720
- const meta = readMetadata(db);
4721
- const root = meta.get("repo_root");
4722
- if (meta.get("schema_version") !== SUPPORTED_SCHEMA || root === void 0 || realpathSync2(root) !== realpathSync2(repo)) {
4723
- db.close();
4724
- return null;
4725
- }
4726
- return codeGraph(db, root);
4727
- } catch (error) {
4728
- closeIfOpen(db);
4729
- if (isEnvironmentFailure(error)) return null;
4730
- throw error;
4731
- }
4732
- }
4733
- function readMetadata(db) {
4734
- const rows = db.prepare("select key, value from metadata").all();
4735
- return new Map(rows.map((row) => [row.key, row.value]));
4736
- }
4737
- function codeGraph(db, repo) {
4738
- const fileNode = db.prepare("select file_hash from nodes where kind = 'File' and file_path = ?");
4739
- const enclosing = db.prepare(
4740
- "select qualified_name, kind, line_start, line_end from nodes where file_path = ? and kind != 'File' and line_start <= ? and line_end >= ? order by line_end - line_start asc limit 1"
4741
- );
4742
- const fileState = (path, fileHash2) => {
4743
- const row = ask(fileNode, (statement) => statement.get(join14(repo, path)), void 0);
4744
- if (row === void 0) return "absent";
4745
- return row.file_hash === fileHash2 ? "fresh" : "changed";
4746
- };
4747
- return {
4748
- fileState,
4749
- symbolAt(path, line, fileHash2) {
4750
- if (fileState(path, fileHash2) !== "fresh") return null;
4751
- const file = join14(repo, path);
4752
- const row = ask(enclosing, (statement) => statement.get(file, line, line), void 0);
4753
- return row === void 0 ? null : { qualifiedName: row.qualified_name, kind: symbolKindOf(row.kind), from: row.line_start, to: row.line_end };
4754
- },
4755
- close() {
4756
- closeIfOpen(db);
4757
- }
4758
- };
4759
- }
4760
- function symbolKindOf(stored) {
4761
- return SYMBOL_KINDS.find((kind) => kind === stored) ?? "other";
4762
- }
4763
- function ask(statement, run, fallback) {
4764
- try {
4765
- return run(statement);
4766
- } catch (error) {
4767
- if (isEnvironmentFailure(error)) return fallback;
4768
- throw error;
4769
- }
4770
- }
4771
- function isEnvironmentFailure(error) {
4772
- return typeof errorCode(error) === "string";
4773
- }
4774
- function closeIfOpen(db) {
4775
- try {
4776
- db?.close();
4777
- } catch (error) {
4778
- if (!hasErrorCode(error, "ERR_INVALID_STATE")) throw error;
4779
- }
4780
- }
4781
-
4782
- // src/core/git/landing.ts
4783
- async function firstParentLanding(git, repo, commit, head) {
4784
- const chain = await firstParentChain(git, repo, commit, head);
4785
- if (chain === null || chain.length === 0) return null;
4786
- const carries = (index) => contains(git, repo, chain[index]?.commit ?? "", commit);
4787
- const oldest = chain.length - 1;
4788
- const oldestCarries = await carries(oldest);
4789
- if (oldestCarries === null) return null;
4790
- if (oldestCarries) return chain[oldest] ?? null;
4791
- if (await carries(0) !== true) return null;
4792
- let carrying = 0;
4793
- let notCarrying = oldest;
4794
- while (notCarrying - carrying > 1) {
4795
- const middle = Math.floor((carrying + notCarrying) / 2);
4796
- const middleCarries = await carries(middle);
4797
- if (middleCarries === null) return null;
4798
- if (middleCarries) carrying = middle;
4799
- else notCarrying = middle;
4800
- }
4801
- return chain[carrying] ?? null;
4802
- }
4803
- async function firstParentChain(git, repo, commit, head) {
4804
- const lines = outputLines(await git(repo, ["log", "--first-parent", `--format=tformat:%H${FIELD}%P${FIELD}%cI`, `${commit}..${head}`, "--"]));
4805
- if (lines === null) return null;
4806
- return lines.map((line) => {
4807
- const [sha = "", parents = "", committedAt = ""] = line.split(FIELD);
4808
- return { commit: sha, firstParent: parents.split(" ")[0] ?? "", committedAt };
4809
- });
4810
- }
4811
- async function contains(git, repo, descendant, commit) {
4812
- const missing = await git(repo, ["rev-list", "--max-count=1", commit, `^${descendant}`, "--"]);
4813
- return missing === null ? null : missing.trim() === "";
4814
- }
4815
-
4816
- // src/core/check/landed-content.ts
4817
- var PATCH_OPTIONS = ["-p", ...PARSED_DIFF_OPTIONS, "--no-renames", "--no-relative", "--full-index", "--diff-algorithm=myers", "--indent-heuristic", "--unified=0", "--inter-hunk-context=0"];
4818
- var COMMIT_HEADER = "--format=commit %H";
4819
- var INSERTION_NEIGHBOURS = 2;
4820
- var TREE_PAIR_LINE = /^[0-9a-f]+ [0-9a-f]+$/;
4821
- var NO_COMMIT = /^0+$/;
4822
- var COMMIT_RECORD = /commit (?<commit>[0-9a-f]+)\0/;
4823
- var FILE_RECORD = /:\d+ (?<mode>\d+) [0-9a-f]+ (?<object>[0-9a-f]+) [A-Z]\d*\0(?<path>[^\0]*)\0/;
4824
- var RAW_RECORD = new RegExp(`${COMMIT_RECORD.source}|${FILE_RECORD.source}`, "g");
4825
- async function landingState(repo, tip, git) {
4826
- const fork = await forkAt(repo, "HEAD", tip, git);
4827
- if (fork === null) return "unknown";
4828
- const view = { ...fork, repo, historyOptions: [], git };
4829
- const changed = await branchChanges(view, []);
4830
- if (changed === null) return "unknown";
4831
- if (changed.length === 0) return "landed";
4832
- const landed = await headChanges(view, topLiteralPathspecs(changed.map(({ path }) => path)));
4833
- if (landed === null) return "unknown";
4834
- const landedVersions = new Set(landed.map(({ version }) => version));
4835
- let state = "landed";
4836
- for (const { path, version } of changed) {
4837
- const pathState = landedVersions.has(version) ? "landed" : await changeLanded(view, path);
4838
- if (pathState === "pending") return "pending";
4839
- if (pathState === "unknown") state = "unknown";
4840
- }
4841
- return state;
4842
- }
4843
- function commitsCarryingContent(repo, git, historyOptions) {
4844
- const forks = /* @__PURE__ */ new Map();
4845
- return async (tip, scope) => {
4846
- const fork = await remembered(forks, tip, () => forkBeforeLanding(repo, tip, git));
4847
- return fork === null ? [] : commitsCarrying({ ...fork, repo, historyOptions, git }, scope);
4848
- };
4849
- }
4850
- async function commitsCarrying(view, scope) {
4851
- const changed = await branchChanges(view, scope);
4852
- if (changed === null || changed.length === 0) return [];
4853
- const head = await headChanges(view, scope);
4854
- if (head === null) return [];
4855
- const tipVersions = new Set(changed.map(({ version }) => version));
4856
- const branchPaths = new Set(changed.map(({ path }) => path));
4857
- const copiesByPath = /* @__PURE__ */ new Map();
4858
- const patchCopiesOf = (path) => remembered(copiesByPath, path, async () => {
4859
- const copies = await patchCopies(view, path);
4860
- return new Set(copies === null ? [] : earliestCopies(copies));
4861
- });
4862
- const carriesTip = async ({ commit, path, version }) => tipVersions.has(version) || branchPaths.has(path) && (await patchCopiesOf(path)).has(commit);
4863
- const carriesOnlyTip = async (changes) => (await Promise.all(changes.map(carriesTip))).every(Boolean);
4864
- const carrying = await Promise.all([...groupBy(head, ({ commit }) => commit)].map(async ([commit, changes]) => await carriesOnlyTip(changes) ? [commit] : []));
4865
- return carrying.flat();
4866
- }
4867
- async function forkAt(repo, head, tip, git) {
4868
- const base = commitHashOf(outputLine(await git(repo, ["merge-base", head, tip])));
4869
- return base === null ? null : { base, tip, head };
4870
- }
4871
- async function forkBeforeLanding(repo, revision, git) {
4872
- const tip = (await resolveCommits(git, repo, [revision]))?.get(revision);
4873
- if (tip === void 0) return null;
4874
- const fork = await forkAt(repo, "HEAD", tip, git);
4875
- if (fork === null || !tipInHead(fork)) return fork;
4876
- const landing = await firstParentLanding(git, repo, tip, "HEAD");
4877
- return landing === null ? fork : forkAt(repo, landing.firstParent, tip, git);
4878
- }
4879
- function tipInHead({ base, tip }) {
4880
- return base === tip;
4881
- }
4882
- async function branchChanges(view, pathspecs) {
4883
- const { repo, base, tip, git } = view;
4884
- if (tipInHead(view)) return [];
4885
- const changed = await git(repo, ["diff-tree", "-r", "-z", "--no-renames", base, tip, "--", ...pathspecs]);
4886
- return changed === null ? null : rawChanges(changed);
4887
- }
4888
- async function headChanges({ repo, base, head, historyOptions, git }, pathspecs) {
4889
- const rawLog = await git(repo, ["log", "--stdin", COMMIT_HEADER, "--raw", "-z", "--no-renames", "--no-abbrev", "--no-relative", ...historyOptions], `${base}..${head}
4890
- --
4891
- ${pathspecs.join("\n")}
4892
- `);
4893
- return rawLog === null ? null : rawChanges(rawLog);
4894
- }
4895
- function rawChanges(raw) {
4896
- const changes = [];
4897
- let commit = "";
4898
- for (const { groups } of raw.matchAll(RAW_RECORD)) {
4899
- if (groups?.commit === void 0) changes.push({ commit, ...fileVersion(groups) });
4900
- else commit = groups.commit;
4901
- }
4902
- return changes;
4903
- }
4904
- async function changeLanded(view, path) {
4905
- const copies = await patchCopies(view, path);
4906
- if (copies === null) return "unknown";
4907
- if (copies.squashed.length > 0 || everyCommitCopied(copies)) return "landed";
4908
- return copies.editsComplete ? "pending" : "unknown";
4909
- }
4910
- function everyCommitCopied({ commitByCommit }) {
4911
- return commitByCommit.length > 0 && commitByCommit.every((commitCopies) => commitCopies.length > 0);
4912
- }
4913
- function earliestCopies(copies) {
4914
- const earliest = (newestFirst) => newestFirst.slice(-1);
4915
- return [earliest(copies.squashed), ...everyCommitCopied(copies) ? copies.commitByCommit.map(earliest) : []].flat();
4916
- }
4917
- async function patchCopies(view, path) {
4918
- const { repo, base, tip, head, historyOptions, git } = view;
4919
- const onlyPath = ["--", ...topLiteralPathspecs([path])];
4920
- const [squashedPatch, branchPatches, headPatches] = await Promise.all([
4921
- patchesOf(repo, ["diff", ...PATCH_OPTIONS, base, tip, ...onlyPath], () => base, git),
4922
- patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, `${base}..${tip}`, ...onlyPath], parentOf, git),
4923
- patchesOf(repo, ["log", ...PATCH_OPTIONS, COMMIT_HEADER, "--date-order", ...historyOptions, `${base}..${head}`, ...onlyPath], parentOf, git)
4924
- ]);
4925
- if (squashedPatch === null || branchPatches === null || headPatches === null) return null;
4926
- const headPatchesById = groupBy(headPatches, ({ id }) => id);
4927
- const sameChanges = (change) => (headPatchesById.get(change.id) ?? []).filter((copy) => isSameChange(change, copy));
4928
- const pairs = [...squashedPatch, ...branchPatches].flatMap((change) => sameChanges(change).map((copy) => [change, copy]));
4929
- const { editsBetween, complete } = await preimageEdits(view, path, pairs);
4930
- const copiesOf = (change) => sameChanges(change).flatMap((copy) => atSamePlace(change, copy, editsBetween) ? [copy.commit] : []);
4931
- return { squashed: squashedPatch.flatMap(copiesOf), commitByCommit: branchPatches.map(copiesOf), editsComplete: complete };
4932
- }
4933
- async function patchesOf(repo, patchArgs, preimageOf, git) {
4934
- const patches = await git(repo, patchArgs);
4935
- if (patches === null) return null;
4936
- const ids = await git(repo, ["patch-id", "--stable"], patches);
4937
- if (ids === null) return null;
4938
- const shapeOf = patchShapes(patches);
4939
- return ids.split("\n").filter((line) => line !== "").map((line) => {
4940
- const [id = "", label = ""] = line.split(" ");
4941
- const commit = NO_COMMIT.test(label) ? "" : label;
4942
- return { id, commit, preimageRevision: preimageOf(commit), ...shapeOf(commit) };
4943
- });
4944
- }
4945
- async function preimageEdits(repoGit, path, pairs) {
4946
- const comparedPairs = pairs.filter(([change, copy]) => editsNeeded(change, copy));
4947
- const trees = await resolveTrees(repoGit.git, repoGit.repo, [...new Set(comparedPairs.flatMap(([change, copy]) => [change.preimageRevision, copy.preimageRevision]))]);
4948
- const treePairOf = (change, copy) => {
4949
- const from = trees?.get(change.preimageRevision);
4950
- const to = trees?.get(copy.preimageRevision);
4951
- return from === void 0 || to === void 0 ? null : `${from} ${to}`;
4952
- };
4953
- const editsByTreePair = await treeDiffEdits(repoGit, path, [...new Set(comparedPairs.flatMap(([change, copy]) => treePairOf(change, copy) ?? []))]);
4954
- const editsBetween = (change, copy) => {
4955
- if (!editsNeeded(change, copy)) return [];
4956
- const treePair = treePairOf(change, copy);
4957
- return treePair === null ? null : editsByTreePair?.get(treePair) ?? null;
4958
- };
4959
- return { editsBetween, complete: trees !== null && editsByTreePair !== null };
4960
- }
4961
- async function treeDiffEdits({ repo, git }, path, treePairs) {
4962
- if (treePairs.length === 0) return /* @__PURE__ */ new Map();
4963
- const preimageDiffs = await git(repo, ["diff-tree", "--stdin", ...PATCH_OPTIONS, "--", ...topLiteralPathspecs([path])], treePairs.map((treePair) => `${treePair}
4964
- `).join(""));
4965
- return preimageDiffs === null ? null : preimageEditsByTreePair(preimageDiffs);
4966
- }
4967
- function preimageEditsByTreePair(preimageDiffs) {
4968
- const editsByTreePair = /* @__PURE__ */ new Map();
4969
- let edits = [];
4970
- for (const line of preimageDiffs.split("\n")) {
4971
- if (TREE_PAIR_LINE.test(line)) {
4972
- edits = [];
4973
- editsByTreePair.set(line, edits);
4974
- } else edits.push(...preimageEditsOf(hunkHeaderOf(line)));
4975
- }
4976
- return editsByTreePair;
4977
- }
4978
- function isSameChange(change, copy) {
4979
- const changeShownByHunks = change.changeStarts.length > 0;
4980
- return copy.id === change.id && copy.changedText === change.changedText && copy.changeStarts.length === change.changeStarts.length && (changeShownByHunks || sameBlobs(change.blobs, copy.blobs));
5371
+ };
4981
5372
  }
4982
- function sameBlobs(change, copy) {
4983
- return change?.preimage === copy?.preimage && change?.postimage === copy?.postimage;
5373
+
5374
+ // src/core/check/find-problems.ts
5375
+ function findProblems(loaded, projects, repos, inScope) {
5376
+ const index = indexOfLoaded(loaded);
5377
+ const integrity = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => integrityErrors(task, index).map((problem3) => ({ kind: "task-invalid", taskId: task.id, problem: problem3 })));
5378
+ const missingRepos = projects.filter((project) => repos.get(project.id) === void 0).map(missingRepoProblem);
5379
+ return [...parseProblems(loaded, inScope), ...integrity, ...missingRepos, ...sharedPrefixes(loaded.projects, inScope)];
4984
5380
  }
4985
- function samePreimage(change, copy) {
4986
- return change.blobs !== void 0 && change.blobs.preimage === copy.blobs?.preimage;
5381
+ function sharedPrefixes(projects, inScope) {
5382
+ const idsByPrefix = /* @__PURE__ */ new Map();
5383
+ for (const project of projects) idsByPrefix.set(project.prefix, [...idsByPrefix.get(project.prefix) ?? [], project.id]);
5384
+ return [...idsByPrefix].filter(([, projectIds]) => projectIds.length > 1 && projectIds.some(inScope)).map(([prefix, projectIds]) => ({ kind: "prefix-shared", prefix, projectIds }));
4987
5385
  }
4988
- function editsNeeded(change, copy) {
4989
- return change.changeStarts.length > 0 && !samePreimage(change, copy);
5386
+ function parseProblems(loaded, inScope) {
5387
+ const waitingEpicIds = planEpicClosing(loaded.tasks, loaded.errors).waiting.filter(({ epic }) => inScope(epic.projectId)).map(({ epic }) => epic.id);
5388
+ const everyFileMayHoldWaitingChild = waitingEpicIds.length > 0;
5389
+ const reported = loaded.errors.filter((error) => everyFileMayHoldWaitingChild || concernsScope(error, inScope)).map((error) => ({ kind: "file-not-parsed", path: error.path, problems: error.problems }));
5390
+ if (waitingEpicIds.length === 0) return reported;
5391
+ return [...reported, { kind: "epics-wait-for-files", epicIds: waitingEpicIds }];
4990
5392
  }
4991
- function atSamePlace(change, copy, editsBetween) {
4992
- const edits = editsBetween(change, copy);
4993
- return edits !== null && change.changeStarts.every((start, index) => copyStartsAtSamePlace(start, copy.changeStarts[index], edits));
5393
+ function concernsScope(error, inScope) {
5394
+ return inScope(error.projectId) || isProjectFileError(error);
4994
5395
  }
4995
- function copyStartsAtSamePlace(start, copyStart, edits) {
4996
- const place = placeOf(start);
4997
- const placeUntouched = !edits.some((edit) => spansOverlap(edit, place));
4998
- return placeUntouched && shiftedLine(start.line, edits) === copyStart?.line;
5396
+ function missingRepoProblem(project) {
5397
+ return project.repos.length === 0 ? { kind: "project-without-repos", projectId: project.id } : { kind: "project-repos-missing", projectId: project.id, repos: project.repos };
4999
5398
  }
5000
- function placeOf({ line, insertion }) {
5001
- return insertion ? { firstLine: line - 1, lineCount: INSERTION_NEIGHBOURS } : { firstLine: line, lineCount: 1 };
5399
+
5400
+ // src/core/check/project-review.ts
5401
+ import { join as join18 } from "node:path";
5402
+
5403
+ // src/core/code-review-graph/graph-db.ts
5404
+ import { existsSync, realpathSync as realpathSync2 } from "node:fs";
5405
+ import { join as join16 } from "node:path";
5406
+ var SYMBOL_KINDS = ["Class", "Function", "Type", "Test"];
5407
+ var GRAPH_FILE = join16(".code-review-graph", "graph.db");
5408
+ var SUPPORTED_SCHEMA = "13";
5409
+ function hasCodeGraph(repo) {
5410
+ return existsSync(join16(repo, GRAPH_FILE));
5002
5411
  }
5003
- function spansOverlap(edit, place) {
5004
- return edit.firstLine < lineAfter(place) && place.firstLine < lineAfter(edit);
5412
+ function openCodeGraph(repo) {
5413
+ let db = null;
5414
+ try {
5415
+ const { DatabaseSync: SqliteDatabase } = process.getBuiltinModule("node:sqlite");
5416
+ db = new SqliteDatabase(join16(repo, GRAPH_FILE), { readOnly: true });
5417
+ const meta = readMetadata(db);
5418
+ const root = meta.get("repo_root");
5419
+ if (meta.get("schema_version") !== SUPPORTED_SCHEMA || root === void 0 || realpathSync2(root) !== realpathSync2(repo)) {
5420
+ db.close();
5421
+ return null;
5422
+ }
5423
+ return codeGraph(db, root);
5424
+ } catch (error) {
5425
+ closeIfOpen(db);
5426
+ if (isEnvironmentFailure(error)) return null;
5427
+ throw error;
5428
+ }
5005
5429
  }
5006
- function lineAfter({ firstLine, lineCount }) {
5007
- return firstLine + lineCount;
5430
+ function readMetadata(db) {
5431
+ const rows = db.prepare("select key, value from metadata").all();
5432
+ return new Map(rows.map((row) => [row.key, row.value]));
5008
5433
  }
5009
- function preimageEditsOf(header) {
5010
- if (header === null) return [];
5011
- return [{ firstLine: firstLineOf(header.oldStart, header.oldCount), lineCount: header.oldCount, delta: header.newCount - header.oldCount }];
5434
+ function codeGraph(db, repo) {
5435
+ const fileNode = db.prepare("select file_hash from nodes where kind = 'File' and file_path = ?");
5436
+ const enclosing = db.prepare(
5437
+ "select qualified_name, kind, line_start, line_end from nodes where file_path = ? and kind != 'File' and line_start <= ? and line_end >= ? order by line_end - line_start asc limit 1"
5438
+ );
5439
+ const fileState = (path, fileHash2) => {
5440
+ const row = ask(fileNode, (statement) => statement.get(join16(repo, path)), void 0);
5441
+ if (row === void 0) return "absent";
5442
+ return row.file_hash === fileHash2 ? "fresh" : "changed";
5443
+ };
5444
+ return {
5445
+ fileState,
5446
+ symbolAt(path, line, fileHash2) {
5447
+ if (fileState(path, fileHash2) !== "fresh") return null;
5448
+ const file = join16(repo, path);
5449
+ const row = ask(enclosing, (statement) => statement.get(file, line, line), void 0);
5450
+ return row === void 0 ? null : { qualifiedName: row.qualified_name, kind: symbolKindOf(row.kind), from: row.line_start, to: row.line_end };
5451
+ },
5452
+ close() {
5453
+ closeIfOpen(db);
5454
+ }
5455
+ };
5012
5456
  }
5013
- function shiftedLine(line, edits) {
5014
- return edits.reduce((shifted, edit) => lineAfter(edit) <= line ? shifted + edit.delta : shifted, line);
5457
+ function symbolKindOf(stored) {
5458
+ return SYMBOL_KINDS.find((kind) => kind === stored) ?? "other";
5015
5459
  }
5016
- function parentOf(commit) {
5017
- return `${commit}^`;
5460
+ function ask(statement, run, fallback) {
5461
+ try {
5462
+ return run(statement);
5463
+ } catch (error) {
5464
+ if (isEnvironmentFailure(error)) return fallback;
5465
+ throw error;
5466
+ }
5018
5467
  }
5019
- function fileVersion({ mode = "", object = "", path = "" } = {}) {
5020
- return { path, version: `${mode} ${object}\0${path}` };
5468
+ function isEnvironmentFailure(error) {
5469
+ return typeof errorCode(error) === "string";
5470
+ }
5471
+ function closeIfOpen(db) {
5472
+ try {
5473
+ db?.close();
5474
+ } catch (error) {
5475
+ if (!hasErrorCode(error, "ERR_INVALID_STATE")) throw error;
5476
+ }
5021
5477
  }
5022
5478
 
5023
5479
  // src/core/check/known-commits.ts
5024
5480
  var MERGE_PARENTS = 2;
5025
- async function commitsKnownAtCreation({ repo, tasks, facts, anchors, origins, git = runGit }) {
5026
- const questions = tasks.flatMap((task) => {
5027
- const origin = creationOrigin(task, origins);
5028
- if (origin === void 0 || task.source === void 0 || !judgedByCommits(task, anchors)) return [];
5029
- const path = sourcePath(task.source);
5030
- return [{ taskId: task.id, site: { commit: origin.commit, path }, changes: commitsTouchingSince(facts.commits, path, reviewMark(task)) }];
5031
- });
5032
- const copies = creationCopies(repo, git);
5481
+ async function commitsKnownAtMark({ repo, tasks, facts, anchors, git = runGit, bases }) {
5482
+ const asked = await Promise.all(
5483
+ tasks.map(async (task) => {
5484
+ if (task.source === void 0 || !judgedByCommits(task, anchors)) return [];
5485
+ const path = sourcePath(task.source);
5486
+ const changes = commitsTouchingSince(facts.commits, path, reviewMark(task));
5487
+ const commit = changes.length === 0 ? null : await bases.markCommit(task);
5488
+ return commit === null ? [] : [{ taskId: task.id, site: { commit, path }, changes }];
5489
+ })
5490
+ );
5491
+ const questions = asked.flat();
5492
+ const copies = markCopies(repo, git);
5033
5493
  const answers = await Promise.all(
5034
5494
  questions.map(async ({ taskId, site, changes }) => {
5035
- const known = await Promise.all(changes.map(async (commit) => await isKnownAtCreation(copies, commit, site) ? [commit.sha] : []));
5495
+ const known = await Promise.all(changes.map(async (commit) => await isKnownAtMark(copies, commit, site) ? [commit.sha] : []));
5036
5496
  return { taskId, known: known.flat() };
5037
5497
  })
5038
5498
  );
5039
5499
  return new Map(answers.filter(({ known }) => known.length > 0).map(({ taskId, known }) => [taskId, new Set(known)]));
5040
5500
  }
5041
- function creationCopies(repo, git) {
5501
+ function markCopies(repo, git) {
5042
5502
  const carryingContent = commitsCarryingContent(repo, git, FACTS_HISTORY_OPTIONS);
5043
5503
  const branchCommitsByMerge = /* @__PURE__ */ new Map();
5044
- const copiesByCreation = /* @__PURE__ */ new Map();
5504
+ const copiesByMark = /* @__PURE__ */ new Map();
5045
5505
  return {
5046
5506
  broughtByMerge: (merge, { commit, path }) => remembered(
5047
5507
  branchCommitsByMerge,
5048
5508
  `${merge.sha} ${commit} ${path}`,
5049
5509
  async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${commit}`, "--", ...literalPathspecs([path])]))
5050
5510
  ),
5051
- copiesOf: ({ commit, path }) => remembered(copiesByCreation, `${commit} ${path}`, async () => new Set(await carryingContent(commit, literalPathspecs([path]))))
5511
+ copiesOf: ({ commit, path }) => remembered(copiesByMark, `${commit} ${path}`, async () => new Set(await carryingContent(commit, literalPathspecs([path]))))
5052
5512
  };
5053
5513
  }
5054
- async function isKnownAtCreation(copies, commit, site) {
5514
+ async function isKnownAtMark(copies, commit, site) {
5055
5515
  if (commit.parents.length !== MERGE_PARENTS) return (await copies.copiesOf(site)).has(commit.sha);
5056
5516
  const brought = await copies.broughtByMerge(commit, site);
5057
5517
  if (brought === null) return false;
@@ -5062,31 +5522,43 @@ async function isKnownAtCreation(copies, commit, site) {
5062
5522
 
5063
5523
  // src/core/check/late-commits.ts
5064
5524
  var NO_LATE_COMMITS = /* @__PURE__ */ new Map();
5525
+ var NO_LATE_ARRIVALS = { late: NO_LATE_COMMITS, unknown: /* @__PURE__ */ new Set() };
5065
5526
  async function commitsArrivedLate(question) {
5066
- if (question.facts.history !== "read") return NO_LATE_COMMITS;
5067
- const { repo } = question;
5068
- const edited = await editedSinceCheckout(repo, await markedSources(question));
5069
- const checkouts = [...new Set(edited.map(({ checkout }) => checkout))];
5070
- const late = await Promise.all(
5071
- checkouts.map(
5072
- (checkout) => arrivedAfter(
5073
- repo,
5074
- checkout,
5075
- edited.filter((source) => source.checkout === checkout)
5527
+ if (question.facts.history !== "read") return NO_LATE_ARRIVALS;
5528
+ const { repo, git = runGitOutcome, bases = taskBases(repo, question.marks, git) } = question;
5529
+ const history = { repo, git: asGitRunner(git), bases };
5530
+ const arrivals = await arrivalsOf(history, await markedSources(question, bases));
5531
+ return {
5532
+ late: new Map(arrivals.flatMap(({ taskId, commits }) => commits === null ? [] : [[taskId, commits]])),
5533
+ unknown: new Set(arrivals.filter(({ commits }) => commits === null).map(({ taskId }) => taskId))
5534
+ };
5535
+ }
5536
+ async function arrivalsOf(history, marked) {
5537
+ const edited = await editedSinceMarkCommit(history, marked);
5538
+ if (edited === null) return marked.map(({ task }) => ({ taskId: task.id, commits: null }));
5539
+ const judged = await Promise.all(edited.map(async (source) => ({ source, base: await history.bases.baseOf(source.task) })));
5540
+ const unknown = judged.flatMap(({ source, base }) => base.kind === "unknown" ? [{ taskId: source.task.id, commits: null }] : []);
5541
+ const onLine = judged.flatMap(({ source, base }) => base.kind === "exact" ? [source] : []);
5542
+ const markCommits = [...new Set(onLine.map(({ markCommit }) => markCommit))];
5543
+ const byMarkCommit = await Promise.all(
5544
+ markCommits.map(
5545
+ (markCommit) => arrivedAfter(
5546
+ history,
5547
+ markCommit,
5548
+ onLine.filter((source) => source.markCommit === markCommit)
5076
5549
  )
5077
5550
  )
5078
5551
  );
5079
- return new Map(late.flat());
5552
+ return [...unknown, ...byMarkCommit.flat()];
5080
5553
  }
5081
- async function markedSources({ repo, tasks, facts, anchors, origins, knownCommits }) {
5082
- const headCommitAt = headCommitsAt(repo);
5554
+ async function markedSources({ tasks, facts, anchors, knownCommits }, bases) {
5083
5555
  const sourcesByTask = await Promise.all(
5084
5556
  tasks.map(async (task) => {
5085
5557
  if (task.source === void 0 || !judgedByCommits(task, anchors)) return [];
5086
5558
  const path = sourcePath(task.source);
5087
5559
  if (!facts.existing.has(path) || !isInsideRepo(path) || changedByDate(task, path, facts, knownCommits)) return [];
5088
- const checkout = await checkoutAtMark(task, origins, headCommitAt);
5089
- return checkout === null ? [] : [{ taskId: task.id, path, mark: reviewMark(task), checkout }];
5560
+ const markCommit = await bases.markCommit(task);
5561
+ return markCommit === null ? [] : [{ task, path, mark: reviewMark(task), markCommit }];
5090
5562
  })
5091
5563
  );
5092
5564
  return sourcesByTask.flat();
@@ -5095,25 +5567,23 @@ function changedByDate(task, path, facts, knownCommits) {
5095
5567
  const { commits, uncommitted } = changesSinceMark({ facts, late: NO_LATE_COMMITS }, task, path);
5096
5568
  return uncommitted || commits.some((commit) => knownCommits.get(task.id)?.has(commit.sha) !== true);
5097
5569
  }
5098
- async function editedSinceCheckout(repo, sources) {
5099
- const objects = ({ checkout, path }) => ({ commit: `${checkout}^{commit}`, atCheckout: `${checkout}^{commit}:./${path}`, atHead: `HEAD:./${path}` });
5570
+ async function editedSinceMarkCommit({ repo, git }, sources) {
5571
+ const objects = ({ markCommit, path }) => ({ commit: `${markCommit}^{commit}`, atMark: `${markCommit}^{commit}:./${path}`, atHead: `HEAD:./${path}` });
5100
5572
  const ids = await objectIds(
5101
- runGit,
5573
+ git,
5102
5574
  repo,
5103
5575
  sources.flatMap((source) => Object.values(objects(source)))
5104
5576
  );
5105
- if (ids === null) return [];
5577
+ if (ids === null) return null;
5106
5578
  return sources.flatMap((source) => {
5107
- const { commit, atCheckout, atHead } = objects(source);
5108
- const checkout = commitHashOf(ids.get(commit) ?? null);
5109
- return checkout === null || ids.get(atCheckout) === ids.get(atHead) ? [] : [{ ...source, checkout }];
5579
+ const { commit, atMark, atHead } = objects(source);
5580
+ const markCommit = commitHashOf(ids.get(commit) ?? null);
5581
+ return markCommit === null || ids.get(atMark) === ids.get(atHead) ? [] : [{ ...source, markCommit }];
5110
5582
  });
5111
5583
  }
5112
- async function arrivedAfter(repo, checkout, sources) {
5113
- const headDescendsFromCheckout = await runGit(repo, ["merge-base", "--is-ancestor", checkout, "HEAD"]) !== null;
5114
- if (!headDescendsFromCheckout) return [];
5115
- const arrived = await mainlineCommitsOff(repo, checkout, [...new Set(sources.map(({ path }) => path))]) ?? [];
5116
- return sources.map(({ taskId, path, mark }) => [taskId, commitsTouchingUntil(arrived, path, mark)]);
5584
+ async function arrivedAfter({ repo, git }, markCommit, sources) {
5585
+ const arrived = await mainlineCommitsOff(repo, markCommit, [...new Set(sources.map(({ path }) => path))], git);
5586
+ return sources.map(({ task, path, mark }) => ({ taskId: task.id, commits: arrived === null ? null : commitsTouchingUntil(arrived, path, mark) }));
5117
5587
  }
5118
5588
 
5119
5589
  // src/core/model/query.ts
@@ -5292,28 +5762,26 @@ function bothConfirmedAfterCreation(a, b) {
5292
5762
  }
5293
5763
 
5294
5764
  // src/core/check/awaiting-merge.ts
5295
- var NOT_AN_ANCESTOR_EXIT = 1;
5296
5765
  var NO_SUCH_REF_EXIT = 1;
5297
- async function awaitingMerge({ repo, taskIds, origins, git = runGitOutcome }) {
5298
- const branched = taskIds.flatMap((id) => {
5299
- const origin = origins.get(id);
5300
- return origin?.branch === void 0 ? [] : [{ id, commit: origin.commit, branch: origin.branch }];
5766
+ async function awaitingMerge({ repo, tasks, marks, git = runGitOutcome, bases = taskBases(repo, marks, git) }) {
5767
+ const branched = tasks.flatMap((task) => {
5768
+ const branch = marks.origins.get(task.id)?.branch;
5769
+ const recordedCommit = latestRecordedCommit(task, marks);
5770
+ return branch === void 0 || recordedCommit === void 0 ? [] : [{ id: task.id, recordedCommit, branch }];
5301
5771
  });
5302
5772
  if (branched.length === 0) return { pending: /* @__PURE__ */ new Set(), unknownBranches: [] };
5303
5773
  const current = lineOf(await git(repo, ["rev-parse", "--abbrev-ref", "HEAD"]));
5304
5774
  const branchStates = /* @__PURE__ */ new Map();
5305
- let completenessLookup;
5306
- const cloneCompleteness = () => completenessLookup ??= cloneCompletenessOf(repo, git);
5307
5775
  const nested = await Promise.all(
5308
- branched.map(async ({ id, commit, branch }) => {
5776
+ branched.map(async ({ id, recordedCommit, branch }) => {
5309
5777
  if (branch === current) return [];
5310
- const ancestry = await git(repo, ["merge-base", "--is-ancestor", commit, "HEAD"]);
5311
- if (ancestry.status === "unfinished") return [{ id, branch, state: "unknown" }];
5312
- if (ancestry.status === "ok") return [];
5313
- const creationCommitUnreadable = ancestry.exitCode !== NOT_AN_ANCESTOR_EXIT;
5314
- if (creationCommitUnreadable && await cloneCompleteness() === "full") return [];
5778
+ const ancestry = await bases.ancestry(recordedCommit);
5779
+ if (ancestry === "unknown") return [{ id, branch, state: "unknown" }];
5780
+ if (ancestry === "ancestor") return [];
5781
+ const recordedCommitMissing = ancestry === "missing";
5782
+ if (recordedCommitMissing && await bases.cloneCompleteness() === "full") return [];
5315
5783
  const state = await remembered(branchStates, branch, () => branchState(repo, branch, git));
5316
- const pendingOnlyIfShallow = creationCommitUnreadable && state === "pending" && await cloneCompleteness() === "unknown";
5784
+ const pendingOnlyIfShallow = recordedCommitMissing && state === "pending" && await bases.cloneCompleteness() === "unknown";
5317
5785
  return [{ id, branch, state: pendingOnlyIfShallow ? "unknown" : state }];
5318
5786
  })
5319
5787
  );
@@ -5328,22 +5796,16 @@ async function branchState(repo, branch, git) {
5328
5796
  if (tip !== null) return landingState(repo, tip, asGitRunner(git));
5329
5797
  return lookup.status === "exited" && lookup.exitCode === NO_SUCH_REF_EXIT ? "deleted" : "unknown";
5330
5798
  }
5331
- async function cloneCompletenessOf(repo, git) {
5332
- const answer = lineOf(await git(repo, ["rev-parse", "--is-shallow-repository"]));
5333
- if (answer === "true") return "shallow";
5334
- if (answer === "false") return "full";
5335
- return "unknown";
5336
- }
5337
5799
  function lineOf(outcome) {
5338
5800
  return outputLine(stdoutOf(outcome));
5339
5801
  }
5340
5802
 
5341
5803
  // src/core/check/symbol-filter.ts
5342
5804
  import { createHash as createHash3 } from "node:crypto";
5343
- import { join as join15 } from "node:path";
5805
+ import { join as join17 } from "node:path";
5344
5806
  function fileHashes(repo, onUnreadable) {
5345
5807
  const hashes = /* @__PURE__ */ new Map();
5346
- return (path) => remembered(hashes, path, () => fileHash(join15(repo, path), onUnreadable));
5808
+ return (path) => remembered(hashes, path, () => fileHash(join17(repo, path), onUnreadable));
5347
5809
  }
5348
5810
  function symbolLookup(graph, hashOf) {
5349
5811
  if (graph === null) return () => null;
@@ -5401,62 +5863,109 @@ function overlaps(range, watched) {
5401
5863
 
5402
5864
  // src/core/check/project-review.ts
5403
5865
  var PROBLEM_LIMIT = 400;
5404
- async function creationOrigins(root, projectId, onJournalUnreadable) {
5405
- const journal = await readJournal(join16(root, projectId), projectId).catch((error) => {
5866
+ async function readMarkCommits(root, projectId, onJournalUnreadable) {
5867
+ const journal = await readJournal(join18(root, projectId), projectId).catch((error) => {
5406
5868
  onJournalUnreadable(error);
5407
5869
  return null;
5408
5870
  });
5409
- return new Map((journal?.events ?? []).flatMap((event) => event.kind === "created" && event.origin !== void 0 ? [[event.task, event.origin]] : []));
5871
+ return markCommitsIn(journal?.events ?? []);
5410
5872
  }
5411
- async function projectReview(project, allTasks, { repo, origins, mode, onUnreadable }) {
5873
+ async function projectReview(project, allTasks, { checkouts, git = runGitOutcome, ...scope }) {
5412
5874
  const tasks = allTasks.filter((task) => task.projectId === project.id && isReviewable(task));
5413
5875
  const nothing = { projectId: project.id, candidates: [], filtered: [], plans: [], problems: [], unchecked: [], awaitingMerge: [], skipped: [] };
5414
5876
  if (tasks.length === 0) return nothing;
5415
- if (repo === void 0) return { ...nothing, candidates: mode === "full" ? duplicateCandidates(tasks) : [], unchecked: [...evidenceOf(tasks, "source-changed"), ...evidenceOf(tasks, "source-missing")] };
5416
- const facts = await collectRepoFacts(repo, earliestMarks(tasks));
5417
- for (const [path, error] of facts.unreadable) onUnreadable(join16(repo, path), error);
5877
+ if (checkouts.length === 0)
5878
+ return { ...nothing, candidates: scope.mode === "full" ? duplicateCandidates(tasks) : [], unchecked: [...evidenceOf(tasks, "source-changed"), ...evidenceOf(tasks, "source-missing")] };
5879
+ const reviews = await Promise.all(
5880
+ (await tasksByCheckout(checkouts, tasks, scope.marks)).map(async ({ checkout, tasks: own, unsettled, history }) => {
5881
+ const review = await repoReview(project, own, { ...scope, repo: checkout.path, git, history });
5882
+ return { ...review, plans: checkout.linkedWorktree ? [] : review.plans.filter((plan) => !unsettled.has(plan.id)) };
5883
+ })
5884
+ );
5885
+ const skipped = new Set(reviews.flatMap((review) => review.skipped));
5886
+ const symbols = new Map(reviews.flatMap((review) => [...review.symbols]));
5887
+ const duplicates = scope.mode === "full" ? duplicateCandidates(tasks, (task) => symbols.get(task.id) ?? null).filter((candidate) => !skipped.has(candidate.task.id)) : [];
5888
+ return {
5889
+ projectId: project.id,
5890
+ candidates: [...reviews.flatMap((review) => review.candidates), ...duplicates],
5891
+ filtered: reviews.flatMap((review) => review.filtered),
5892
+ plans: reviews.flatMap((review) => review.plans),
5893
+ problems: reviews.flatMap((review) => review.problems),
5894
+ unchecked: reviews.flatMap((review) => review.unchecked),
5895
+ awaitingMerge: reviews.flatMap((review) => review.awaitingMerge),
5896
+ skipped: [...skipped]
5897
+ };
5898
+ }
5899
+ async function repoReview(project, tasks, scope) {
5900
+ const { repo, marks, mode, onUnreadable, git } = scope;
5901
+ const facts = await collectRepoFacts(repo, earliestMarks(tasks), scope.history, git);
5902
+ for (const [path, error] of facts.unreadable) onUnreadable(join18(repo, path), error);
5418
5903
  const skipped = new Set(tasks.filter((task) => task.source !== void 0 && facts.unreadable.has(sourcePath(task.source))).map((task) => task.id));
5419
5904
  const readable = tasks.filter((task) => !skipped.has(task.id));
5420
5905
  const graph = openCodeGraph(repo);
5421
5906
  try {
5422
5907
  const anchors = anchorStates(readable, facts);
5423
- const question = { repo, tasks: readable, facts, anchors, origins };
5424
- const knownCommits = await commitsKnownAtCreation(question);
5425
- const late = await commitsArrivedLate({ ...question, knownCommits });
5426
- const scope = { repo, facts, late, origins, mode, onUnreadable, graph };
5427
- const review = await withRenamesFollowed(codeReview(readable, { facts, late }, knownCommits, anchors), readable, scope);
5428
- const context = await projectContext(readable, review, scope);
5429
- const sighted = await sightedBySymbol(tasks, review, context, { mode, skipped });
5430
- const { problems: mergeProblems, ...judged } = await judgedAgainstMerges(sighted, context, { repo, origins, projectId: project.id });
5431
- return { projectId: project.id, ...judged, skipped: [...skipped], problems: [...historyProblems(project, repo, facts), ...mergeProblems], unchecked: uncheckedEvidence(tasks, anchors, facts) };
5908
+ const bases = taskBases(repo, marks, git);
5909
+ const question = { repo, tasks: readable, facts, anchors, marks, bases };
5910
+ const knownCommits = await commitsKnownAtMark({ ...question, git: asGitRunner(git) });
5911
+ const { late, unknown: lateUnknown } = await commitsArrivedLate({ ...question, knownCommits, git });
5912
+ const repoScope = { ...scope, facts, late, graph, bases };
5913
+ const review = await withRenamesFollowed(codeReview(readable, { facts, late }, knownCommits, anchors), readable, repoScope);
5914
+ const context = await projectContext(readable, review, repoScope);
5915
+ const sighted = await sightedBySymbol(review, context);
5916
+ const { problems: mergeProblems, ...judged } = await judgedAgainstMerges(sighted, context, { repo, marks, projectId: project.id, git, bases });
5917
+ return {
5918
+ ...judged,
5919
+ skipped: [...skipped],
5920
+ problems: [...historyProblems(project, repo, facts), ...mergeProblems],
5921
+ unchecked: uncheckedEvidence(tasks, anchors, facts, lateUnknown),
5922
+ symbols: mode === "full" ? repoSymbolNames(repo, readable, context) : /* @__PURE__ */ new Map()
5923
+ };
5432
5924
  } finally {
5433
5925
  graph?.close();
5434
5926
  }
5435
5927
  }
5436
- async function projectContext(tasks, review, { repo, facts, late, origins, mode, onUnreadable, graph }) {
5437
- const diffs = repoDiffs(repo, origins);
5928
+ function repoSymbolNames(repo, tasks, { symbolAt, located }) {
5929
+ const symbolOf = symbolNames(symbolAt, located);
5930
+ return new Map(
5931
+ tasks.map((task) => {
5932
+ const name = symbolOf(task);
5933
+ return [task.id, name === null ? null : `${repo}\0${name}`];
5934
+ })
5935
+ );
5936
+ }
5937
+ async function projectContext(tasks, review, { repo, facts, late, mode, onUnreadable, graph, bases }) {
5438
5938
  const symbolAt = symbolLookup(graph, fileHashes(repo, onUnreadable));
5439
5939
  const changedIds = new Set(review.candidates.flatMap((candidate) => candidate.kind === "source-changed" ? [candidate.task.id] : []));
5440
5940
  const locating = mode === "full" && graph !== null ? tasks : tasks.filter((task) => changedIds.has(task.id));
5441
- const traces = await traceSources(locating, { facts, late }, diffs);
5442
- return { tasksById: new Map(tasks.map((task) => [task.id, task])), located: currentSourcesOf(traces), traces, facts, diffOf: diffs.sinceTaskMark, symbolAt };
5941
+ const traces = await traceSources(locating, { facts, late }, bases);
5942
+ return { tasksById: new Map(tasks.map((task) => [task.id, task])), located: currentSourcesOf(traces), traces, facts, diffOf: bases.diffSinceBase, bases, symbolAt };
5443
5943
  }
5444
- async function sightedBySymbol(tasks, review, context, { mode, skipped }) {
5445
- const duplicates = mode === "full" ? duplicateCandidates(tasks, symbolNames(context.symbolAt, context.located)).filter((candidate) => !skipped.has(candidate.task.id)) : [];
5944
+ async function sightedBySymbol(review, context) {
5446
5945
  const byLines = judgedByLines(review.candidates, context.traces);
5447
5946
  const { kept, filtered } = await filterBySymbol(byLines.kept, context);
5947
+ const relocatable = [...filtered.map((sighting) => sighting.task), ...byLines.linesIntact];
5948
+ const markedOffThisLine = await unanchoredMarkedOffThisLine(
5949
+ review.plans.map((plan) => plan.id),
5950
+ context
5951
+ );
5448
5952
  const settlement = {
5449
- untouchable: /* @__PURE__ */ new Set([...kept.map((candidate) => candidate.task.id), ...byLines.notOnBranch]),
5450
- relocatable: [...filtered.map((sighting) => sighting.task), ...byLines.linesIntact]
5953
+ untouchable: /* @__PURE__ */ new Set([...kept.map((candidate) => candidate.task.id), ...byLines.onOtherBranch, ...markedOffThisLine]),
5954
+ relocatable
5451
5955
  };
5452
- return { kept, filtered, plans: settledPlans(review.plans, settlement, context), duplicates };
5956
+ return { kept, filtered, plans: settledPlans(review.plans, settlement, context) };
5453
5957
  }
5454
- async function judgedAgainstMerges(sighted, context, { repo, origins, projectId }) {
5455
- const { pending, unknownBranches: unknownBranches2 } = await awaitingMerge({ repo, taskIds: involvedTaskIds(sighted), origins });
5958
+ async function unanchoredMarkedOffThisLine(ids, { tasksById, bases }) {
5959
+ const unanchored = tasksOf([...new Set(ids)], tasksById).filter((task) => task.anchor === void 0);
5960
+ const lines = await Promise.all(unanchored.map(async (task) => ({ id: task.id, line: markLineOf(await bases.baseOf(task)) })));
5961
+ return new Set(lines.filter(({ line }) => line !== "this-line").map(({ id }) => id));
5962
+ }
5963
+ async function judgedAgainstMerges(sighted, context, { repo, marks, projectId, git, bases }) {
5964
+ const { pending, unknownBranches: unknownBranches2 } = await awaitingMerge({ repo, tasks: tasksOf(involvedTaskIds(sighted), context.tasksById), marks, git, bases });
5456
5965
  const judged = (id) => !pending.has(id);
5457
5966
  const code = await Promise.all(sighted.kept.filter((candidate) => judged(candidate.task.id)).map((candidate) => withContext2(candidate, context)));
5458
5967
  return {
5459
- candidates: [...code, ...sighted.duplicates],
5968
+ candidates: code,
5460
5969
  filtered: sighted.filtered.filter((sighting) => judged(sighting.task)),
5461
5970
  plans: sighted.plans.filter((plan) => judged(plan.id)),
5462
5971
  awaitingMerge: [...pending],
@@ -5464,10 +5973,10 @@ async function judgedAgainstMerges(sighted, context, { repo, origins, projectId
5464
5973
  };
5465
5974
  }
5466
5975
  function judgedByLines(candidates, traces) {
5467
- const judgement = { kept: [], linesIntact: [], notOnBranch: [] };
5976
+ const judgement = { kept: [], linesIntact: [], onOtherBranch: [] };
5468
5977
  for (const candidate of candidates) {
5469
5978
  const trace = candidate.kind === "source-changed" && candidate.method === "anchor" ? traces.get(candidate.task.id) : void 0;
5470
- if (trace?.kind === "not-on-branch") judgement.notOnBranch.push(candidate.task.id);
5979
+ if (trace?.kind === "other-branch") judgement.onOtherBranch.push(candidate.task.id);
5471
5980
  else if (trace?.kind === "traced" && !trace.linesChanged) judgement.linesIntact.push(candidate.task.id);
5472
5981
  else judgement.kept.push(candidate);
5473
5982
  }
@@ -5479,7 +5988,7 @@ async function withRenamesFollowed(review, tasks, { repo, onUnreadable }) {
5479
5988
  review.candidates.map(async (candidate) => {
5480
5989
  const task = tasksById.get(candidate.task.id);
5481
5990
  if (candidate.kind !== "source-missing" || candidate.renamedTo === void 0 || task === void 0) return null;
5482
- const text = await attemptReportingFailure(join16(repo, candidate.renamedTo), readTextIfFile, onUnreadable);
5991
+ const text = await attemptReportingFailure(join18(repo, candidate.renamedTo), readTextIfFile, onUnreadable);
5483
5992
  return text === null ? null : renamePlan(task, candidate.renamedTo, text);
5484
5993
  })
5485
5994
  );
@@ -5488,11 +5997,14 @@ async function withRenamesFollowed(review, tasks, { repo, onUnreadable }) {
5488
5997
  plans: [...review.plans, ...renamePlans.filter((plan) => plan !== null)]
5489
5998
  };
5490
5999
  }
6000
+ function tasksOf(ids, tasksById) {
6001
+ return ids.flatMap((id) => tasksById.get(id) ?? []);
6002
+ }
5491
6003
  function involvedTaskIds({ kept, filtered, plans }) {
5492
6004
  return [.../* @__PURE__ */ new Set([...kept.map((candidate) => candidate.task.id), ...filtered.map((sighting) => sighting.task), ...plans.map((plan) => plan.id)])];
5493
6005
  }
5494
- function uncheckedEvidence(tasks, anchors, { history, branches, existing }) {
5495
- const changeUnchecked = history === "read" ? [] : tasks.filter((task) => judgedByCommits(task, anchors));
6006
+ function uncheckedEvidence(tasks, anchors, { history, branches, existing }, lateUnknown) {
6007
+ const changeUnchecked = tasks.filter((task) => history === "read" ? lateUnknown.has(task.id) : judgedByCommits(task, anchors));
5496
6008
  const missingUnchecked = branches.kind === "unreadable" ? tasks.filter((task) => task.source !== void 0 && !existing.has(sourcePath(task.source))) : [];
5497
6009
  return [...evidenceOf(changeUnchecked, "source-changed"), ...evidenceOf(missingUnchecked, "source-missing")];
5498
6010
  }
@@ -5567,25 +6079,29 @@ async function checkBacklog(root, loaded, request) {
5567
6079
  const projects = current.projects.filter((project) => inScope(project.id));
5568
6080
  const checked = await reviewProjects(root, current.tasks, projects, request);
5569
6081
  const reviews = checked.map(({ review }) => review);
5570
- const anchors = await applyAnchorPlans(current, checked.flatMap(plansToApply), writes);
6082
+ const anchors = await applyAnchorPlans(
6083
+ current,
6084
+ reviews.flatMap((review) => review.plans),
6085
+ writes
6086
+ );
5571
6087
  const outcome = candidateOutcome(reviews);
5572
6088
  await recordCandidates(root, current.tasks, outcome, request);
5573
- const repos = new Map(checked.map(({ review, checkout }) => [review.projectId, checkout?.path]));
6089
+ const repos = new Map(checked.map(({ review, repo }) => [review.projectId, repo]));
5574
6090
  const problems3 = full ? [...fixes.failed, ...anchors.failed, ...findProblems(current, projects, repos, inScope), ...reviews.flatMap((review) => review.problems)] : [];
5575
6091
  return { fixed: [...fixes.fixed, ...anchors.fixed], problems: problems3, candidates: outcome.candidates };
5576
6092
  }
5577
6093
  async function reviewProjects(root, tasks, projects, request) {
5578
- const originsOf = (projectId) => creationOrigins(root, projectId, (error) => request.warn(request.messages.branchOriginsReadFailed(projectId, errorText(error))));
6094
+ const marksOf = (projectId) => readMarkCommits(root, projectId, (error) => request.warn(request.messages.markCommitsReadFailed(projectId, errorText(error))));
5579
6095
  return Promise.all(
5580
6096
  projects.map(async (project) => {
5581
- const checkout = await projectCheckout(project, request.workingRoots, request.context);
5582
- return { review: await projectReview(project, tasks, { repo: checkout?.path, origins: await originsOf(project.id), mode: request.mode, onUnreadable: request.context.onUnreadable }), checkout };
6097
+ const checkouts = await projectCheckouts(project, { ...request.context, workingRoots: request.workingRoots });
6098
+ return {
6099
+ review: await projectReview(project, tasks, { checkouts, marks: await marksOf(project.id), mode: request.mode, onUnreadable: request.context.onUnreadable, git: request.git }),
6100
+ repo: checkouts[0]?.path
6101
+ };
5583
6102
  })
5584
6103
  );
5585
6104
  }
5586
- function plansToApply({ review, checkout }) {
5587
- return checkout?.linkedWorktree === true ? [] : review.plans;
5588
- }
5589
6105
  function candidateOutcome(reviews) {
5590
6106
  return {
5591
6107
  candidates: reviews.flatMap((review) => review.candidates),
@@ -5597,7 +6113,7 @@ function candidateOutcome(reviews) {
5597
6113
  async function recordCandidates(root, tasks, { candidates, filtered, unchecked, unjudged }, { mode, now, projectIds, messages, warn: warn2 }) {
5598
6114
  const projectOf2 = new Map(tasks.map((task) => [task.id, task.projectId]));
5599
6115
  for (const projectId of projectIds) {
5600
- const dir = join17(root, projectId);
6116
+ const dir = join19(root, projectId);
5601
6117
  const found = candidates.filter((candidate) => projectOf2.get(candidate.task.id) === projectId);
5602
6118
  const filteredHere = filtered.filter((sighting) => projectOf2.get(sighting.task) === projectId);
5603
6119
  const reviewed = tasks.filter((task) => task.projectId === projectId && isReviewable(task) && !unjudged.has(task.id)).map((task) => task.id);
@@ -6022,7 +6538,7 @@ async function runClose(args, io) {
6022
6538
  return EXIT.invalid;
6023
6539
  }
6024
6540
  const index = indexOfLoaded(loaded);
6025
- const written = await taskWriter(io, index)(task, { status, related }, { resolution, reason });
6541
+ const written = await taskWriter(io, index)(task, { status, related }, { closure: { resolution, reason } });
6026
6542
  if (!written.ok) return written.exitCode;
6027
6543
  const deletion = scheduledDeletion(written.task, indexWithWritten(index, [written]));
6028
6544
  const change = attachesFix ? status : `${task.status} \u2192 ${status}`;
@@ -6037,28 +6553,28 @@ function originalProblem(cli, task, original) {
6037
6553
  }
6038
6554
  async function fixCommitFound(loaded, task, reason, io) {
6039
6555
  const project = projectOf(loaded, task);
6040
- const repo = project === void 0 ? void 0 : await findRepo(project, repoLookup(io));
6041
- if (repo === void 0) return true;
6042
- for (const sha of reasonHashes(reason)) if (await hasCommit(repo, sha)) return true;
6556
+ const checkouts = project === void 0 ? [] : await projectCheckouts(project, repoLookup(io));
6557
+ if (checkouts.length === 0) return true;
6558
+ for (const sha of reasonHashes(reason)) for (const { path } of checkouts) if (await hasCommit(path, sha)) return true;
6043
6559
  return false;
6044
6560
  }
6045
6561
 
6046
6562
  // src/cli/agents/agent.ts
6047
- import { join as join19 } from "node:path";
6563
+ import { join as join21 } from "node:path";
6048
6564
 
6049
6565
  // src/core/claude-dir.ts
6050
- import { join as join18 } from "node:path";
6566
+ import { join as join20 } from "node:path";
6051
6567
  function claudeDir(env, home2) {
6052
- return env.CLAUDE_CONFIG_DIR || join18(home2, ".claude");
6568
+ return env.CLAUDE_CONFIG_DIR || join20(home2, ".claude");
6053
6569
  }
6054
6570
  function claudeSkillsDir(env, home2) {
6055
- return env.CLAUDE_SKILLS_DIR || join18(claudeDir(env, home2), "skills");
6571
+ return env.CLAUDE_SKILLS_DIR || join20(claudeDir(env, home2), "skills");
6056
6572
  }
6057
6573
  function claudeSettingsPath(env, home2) {
6058
- return env.CLAUDE_SETTINGS_PATH || join18(claudeDir(env, home2), "settings.json");
6574
+ return env.CLAUDE_SETTINGS_PATH || join20(claudeDir(env, home2), "settings.json");
6059
6575
  }
6060
6576
  function claudeProjectsDir(env, home2) {
6061
- return join18(claudeDir(env, home2), "projects");
6577
+ return join20(claudeDir(env, home2), "projects");
6062
6578
  }
6063
6579
 
6064
6580
  // src/cli/agents/agent.ts
@@ -6070,9 +6586,9 @@ function hooksJsonAgent(label, homeDir, { stopProtocol, hookApprovalCommand }) {
6070
6586
  label,
6071
6587
  stopProtocol,
6072
6588
  homeDir,
6073
- skillsDir: ({ home: home2 }) => join19(home2, ".agents", "skills"),
6074
- legacySkillsDirs: (places) => [join19(homeDir(places), "skills")],
6075
- hookConfigPath: (places) => join19(homeDir(places), AGENT_HOOKS_FILE),
6589
+ skillsDir: ({ home: home2 }) => join21(home2, ".agents", "skills"),
6590
+ legacySkillsDirs: (places) => [join21(homeDir(places), "skills")],
6591
+ hookConfigPath: (places) => join21(homeDir(places), AGENT_HOOKS_FILE),
6076
6592
  pluginSettingsPath: null,
6077
6593
  alwaysInstalled: false,
6078
6594
  skillOnLanguageChange: "relinkExisting",
@@ -6092,8 +6608,8 @@ var AGENT_SPECS = {
6092
6608
  skillOnLanguageChange: "link",
6093
6609
  hookApprovalCommand: null
6094
6610
  },
6095
- codex: hooksJsonAgent("Codex", ({ env, home: home2 }) => env.CODEX_HOME || join19(home2, ".codex"), { stopProtocol: "claude", hookApprovalCommand: "/hooks" }),
6096
- cursor: hooksJsonAgent("Cursor", ({ home: home2 }) => join19(home2, ".cursor"), { stopProtocol: "cursor", hookApprovalCommand: null })
6611
+ codex: hooksJsonAgent("Codex", ({ env, home: home2 }) => env.CODEX_HOME || join21(home2, ".codex"), { stopProtocol: "claude", hookApprovalCommand: "/hooks" }),
6612
+ cursor: hooksJsonAgent("Cursor", ({ home: home2 }) => join21(home2, ".cursor"), { stopProtocol: "cursor", hookApprovalCommand: null })
6097
6613
  };
6098
6614
  function agentVoice(agent, output) {
6099
6615
  const { label } = AGENT_SPECS[agent];
@@ -6116,7 +6632,7 @@ async function isDirectory(path) {
6116
6632
 
6117
6633
  // src/cli/skill-link.ts
6118
6634
  import { mkdir as mkdir4, readlink as readlink2, symlink, unlink } from "node:fs/promises";
6119
- import { basename as basename9, dirname as dirname7, join as join20, resolve as resolve3 } from "node:path";
6635
+ import { basename as basename8, dirname as dirname7, join as join22, resolve as resolve3 } from "node:path";
6120
6636
  import { z as z8 } from "zod";
6121
6637
 
6122
6638
  // src/core/skill-name.ts
@@ -6133,14 +6649,14 @@ var SKILL_VARIANTS = {
6133
6649
  var SKILL_SOURCE_DIRS = new Set(Object.values(SKILL_VARIANTS).map((variant) => variant.sourceDir));
6134
6650
  var packageManifestSchema = z8.object({ name: z8.string() });
6135
6651
  function skillSourceDir(packageRoot2, language) {
6136
- return join20(packageRoot2, SKILL_SOURCES_DIR, SKILL_VARIANTS[language].sourceDir);
6652
+ return join22(packageRoot2, SKILL_SOURCES_DIR, SKILL_VARIANTS[language].sourceDir);
6137
6653
  }
6138
6654
  function skillLinkPath(skillsDir) {
6139
- return join20(skillsDir, SKILL_NAME);
6655
+ return join22(skillsDir, SKILL_NAME);
6140
6656
  }
6141
6657
  async function isPBacklogSkill(path) {
6142
- if (!SKILL_SOURCE_DIRS.has(basename9(path)) || basename9(dirname7(path)) !== SKILL_SOURCES_DIR) return false;
6143
- const manifest = await readTextOrNull(join20(dirname7(dirname7(path)), "package.json"));
6658
+ if (!SKILL_SOURCE_DIRS.has(basename8(path)) || basename8(dirname7(path)) !== SKILL_SOURCES_DIR) return false;
6659
+ const manifest = await readTextOrNull(join22(dirname7(dirname7(path)), "package.json"));
6144
6660
  if (manifest !== null) return parseJson(manifest, packageManifestSchema)?.name === "p-backlog";
6145
6661
  return !await pathExists(path);
6146
6662
  }
@@ -6304,20 +6820,20 @@ async function moveOne(id, { loaded, epic, write, io }) {
6304
6820
  import { parseArgs as parseArgs2 } from "node:util";
6305
6821
 
6306
6822
  // src/core/store/hook-turns.ts
6307
- import { join as join21 } from "node:path";
6823
+ import { join as join23 } from "node:path";
6308
6824
  import { z as z10 } from "zod";
6309
6825
 
6310
6826
  // src/core/store/json-under-lock.ts
6311
- function updateJsonUnderLock(path, schema, empty, update, { onErrorAfterPublish, ...lockOptions }) {
6312
- return withFileLock(
6827
+ function updateJsonUnderLock(path, schema, empty, update, options) {
6828
+ return withWriteLock(
6313
6829
  path,
6314
- async () => {
6830
+ async (afterPublish) => {
6315
6831
  const next = update(await readJsonFile(path, schema) ?? empty);
6316
6832
  if (next === null) return "unchanged";
6317
- await writeJsonFile(path, next, { onErrorAfterPublish });
6833
+ await writeJsonFile(path, next, afterPublish);
6318
6834
  return "written";
6319
6835
  },
6320
- lockOptions
6836
+ options
6321
6837
  );
6322
6838
  }
6323
6839
 
@@ -6327,7 +6843,7 @@ var CLAIM_WINDOW_MS = 6e4;
6327
6843
  var hookTurnsSchema = z10.record(z10.string(), z10.iso.datetime({ offset: true }));
6328
6844
  async function claimHookTurn(backlogRoot2, turnKey, { now, onError }) {
6329
6845
  const outcome = await updateJsonUnderLock(
6330
- join21(backlogRoot2, HOOK_TURNS_FILE),
6846
+ join23(backlogRoot2, HOOK_TURNS_FILE),
6331
6847
  hookTurnsSchema,
6332
6848
  {},
6333
6849
  (turns) => {
@@ -6341,7 +6857,7 @@ async function claimHookTurn(backlogRoot2, turnKey, { now, onError }) {
6341
6857
  }
6342
6858
 
6343
6859
  // src/core/store/signals-shown.ts
6344
- import { join as join22 } from "node:path";
6860
+ import { join as join24 } from "node:path";
6345
6861
  import { z as z11 } from "zod";
6346
6862
 
6347
6863
  // src/core/model/signals-shown.ts
@@ -6355,15 +6871,15 @@ function signalsToShow(signals, shown, today) {
6355
6871
  // src/core/store/signals-shown.ts
6356
6872
  var SIGNALS_SHOWN_FILE = ".signals-shown.json";
6357
6873
  var shownSchema = z11.record(z11.string(), z11.string());
6358
- async function readSignalsShown(projectDir2) {
6359
- return await readJsonFile(join22(projectDir2, SIGNALS_SHOWN_FILE), shownSchema) ?? {};
6874
+ async function readSignalsShown(projectDir) {
6875
+ return await readJsonFile(join24(projectDir, SIGNALS_SHOWN_FILE), shownSchema) ?? {};
6360
6876
  }
6361
- async function rememberSignalsShown(projectDir2, signals, today, onError) {
6362
- await updateJsonUnderLock(join22(projectDir2, SIGNALS_SHOWN_FILE), shownSchema, {}, (shown) => markShown(shown, signals, today), { onErrorAfterPublish: onError });
6877
+ async function rememberSignalsShown(projectDir, signals, today, onError) {
6878
+ await updateJsonUnderLock(join24(projectDir, SIGNALS_SHOWN_FILE), shownSchema, {}, (shown) => markShown(shown, signals, today), { onErrorAfterPublish: onError });
6363
6879
  }
6364
6880
 
6365
6881
  // src/core/store/session-shown.ts
6366
- import { join as join23 } from "node:path";
6882
+ import { join as join25 } from "node:path";
6367
6883
  import { z as z12 } from "zod";
6368
6884
  var SESSION_SHOWN_FILE = ".candidates-shown.json";
6369
6885
  var SESSION_RETENTION_MS = WEEK_MS;
@@ -6375,14 +6891,14 @@ function shownKey({ taskId, codeState }) {
6375
6891
  function taskIdOf(key) {
6376
6892
  return key.split(CODE_STATE_MARK, 1)[0] ?? key;
6377
6893
  }
6378
- async function readSessionShown(projectDir2, session) {
6379
- const sessions = await readJsonFile(join23(projectDir2, SESSION_SHOWN_FILE), sessionsShownSchema) ?? {};
6894
+ async function readSessionShown(projectDir, session) {
6895
+ const sessions = await readJsonFile(join25(projectDir, SESSION_SHOWN_FILE), sessionsShownSchema) ?? {};
6380
6896
  return sessions[session]?.tasks ?? [];
6381
6897
  }
6382
- async function rememberSessionShown(projectDir2, session, shown, { now, onError }) {
6898
+ async function rememberSessionShown(projectDir, session, shown, { now, onError }) {
6383
6899
  const shownAgain = new Set(shown.map(({ taskId }) => taskId));
6384
6900
  await updateJsonUnderLock(
6385
- join23(projectDir2, SESSION_SHOWN_FILE),
6901
+ join25(projectDir, SESSION_SHOWN_FILE),
6386
6902
  sessionsShownSchema,
6387
6903
  {},
6388
6904
  (sessions) => {
@@ -6852,12 +7368,12 @@ function shownTask(candidate) {
6852
7368
  var NO_SESSION_MEMORY = { told: /* @__PURE__ */ new Set(), remember: rememberNothing };
6853
7369
  async function sessionMemory(project, session, io) {
6854
7370
  if (session === void 0) return NO_SESSION_MEMORY;
6855
- const projectDir2 = projectDirOf(project);
7371
+ const projectDir = projectDirOf(project);
6856
7372
  try {
6857
7373
  return {
6858
- told: new Set(await readSessionShown(projectDir2, session)),
7374
+ told: new Set(await readSessionShown(projectDir, session)),
6859
7375
  remember: async (shown) => {
6860
- if (shown.length > 0) await rememberSessionShown(projectDir2, session, shown, writesOf(io)).catch((error) => io.warn(io.cli.sessionShownWriteFailed(errorText(error))));
7376
+ if (shown.length > 0) await rememberSessionShown(projectDir, session, shown, writesOf(io)).catch((error) => io.warn(io.cli.sessionShownWriteFailed(errorText(error))));
6861
7377
  }
6862
7378
  };
6863
7379
  } catch (error) {
@@ -6871,21 +7387,21 @@ function lowChangedSignals(count3) {
6871
7387
  return [{ kind: "low-changed", params: { count: count3 } }];
6872
7388
  }
6873
7389
  async function freshSignals(project, tasks, extra, io) {
6874
- const projectDir2 = projectDirOf(project);
7390
+ const projectDir = projectDirOf(project);
6875
7391
  const today = formatLocalDay(io.now());
6876
7392
  try {
6877
- const journal = await readJournal(projectDir2, project.id);
6878
- const shown = await readSignalsShown(projectDir2);
7393
+ const journal = await readJournal(projectDir, project.id);
7394
+ const shown = await readSignalsShown(projectDir);
6879
7395
  const fresh = signalsToShow([...statsSignals(reportContext({ tasks, journals: [journal], now: io.now(), projectId: project.id })), ...extra], shown, today);
6880
- return { fresh, remember: fresh.length === 0 ? rememberNothing : () => rememberShown(projectDir2, fresh, today, io) };
7396
+ return { fresh, remember: fresh.length === 0 ? rememberNothing : () => rememberShown(projectDir, fresh, today, io) };
6881
7397
  } catch (error) {
6882
7398
  io.warn(io.cli.alertsComputeFailed(errorText(error)));
6883
7399
  return NO_SIGNALS;
6884
7400
  }
6885
7401
  }
6886
- async function rememberShown(projectDir2, signals, today, io) {
7402
+ async function rememberShown(projectDir, signals, today, io) {
6887
7403
  try {
6888
- await rememberSignalsShown(projectDir2, signals, today, warnPathErrors(io.warn));
7404
+ await rememberSignalsShown(projectDir, signals, today, warnPathErrors(io.warn));
6889
7405
  } catch (error) {
6890
7406
  io.warn(io.cli.alertsShownWriteFailed(errorText(error)));
6891
7407
  }
@@ -6978,10 +7494,13 @@ async function runList(args, io) {
6978
7494
  // src/cli/origin.ts
6979
7495
  var DETACHED_HEAD = "HEAD";
6980
7496
  async function readOrigin(dir) {
6981
- const [commit, branch] = await Promise.all([gitLine(dir, ["rev-parse", "--short", "HEAD"]), gitLine(dir, ["rev-parse", "--abbrev-ref", "HEAD"])]);
6982
- if (commit === null) return void 0;
7497
+ const [commit, branch] = await Promise.all([readHeadCommit(dir), gitLine(dir, ["rev-parse", "--abbrev-ref", "HEAD"])]);
7498
+ if (commit === void 0) return void 0;
6983
7499
  return branch === null || branch === DETACHED_HEAD ? { commit } : { branch, commit };
6984
7500
  }
7501
+ async function readHeadCommit(dir) {
7502
+ return await gitLine(dir, ["rev-parse", "--short", "HEAD"]) ?? void 0;
7503
+ }
6985
7504
  async function gitLine(dir, args) {
6986
7505
  return outputLine(await runGit(dir, args));
6987
7506
  }
@@ -7022,11 +7541,8 @@ async function runNew(args, io) {
7022
7541
  if (!project) return EXIT.notFound;
7023
7542
  const projectTasks = loaded.tasks.filter((task2) => task2.projectId === project.id);
7024
7543
  if (!values.force && warnedOfSimilarTask({ title: values.title, source: values.source }, projectTasks, io)) return EXIT.refused;
7025
- const [atSource, body, origin] = await allAfterSettling([
7026
- values.source === void 0 ? void 0 : anchorOf2(project, values.source, io),
7027
- io.readStdin(),
7028
- values.project === void 0 || cwdBelongsTo(project, loaded, io) ? readOrigin(io.cwd) : void 0
7029
- ]);
7544
+ const mayRecordOrigin = values.project === void 0 || cwdBelongsTo(project, loaded, io);
7545
+ const [{ anchor, origin }, body] = await allAfterSettling([creationFacts(project, values.source, mayRecordOrigin, io), io.readStdin()]);
7030
7546
  const index = indexOfLoaded(loaded);
7031
7547
  const result = await createTask(io.backlogRoot, {
7032
7548
  project,
@@ -7037,7 +7553,7 @@ async function runNew(args, io) {
7037
7553
  category,
7038
7554
  tags: splitList(values.tags),
7039
7555
  source: values.source,
7040
- anchor: atSource?.kind === "anchor" ? atSource.anchor : void 0,
7556
+ anchor: anchor?.kind === "anchor" ? anchor.anchor : void 0,
7041
7557
  epic: values.epic,
7042
7558
  blockedBy: splitList(values["blocked-by"]),
7043
7559
  related: splitList(values.related),
@@ -7065,11 +7581,16 @@ function warnedOfSimilarTask(draft, projectTasks, io) {
7065
7581
  io.warn(io.cli.similarTaskWarning(similar.task.id, similar.task.title, why));
7066
7582
  return true;
7067
7583
  }
7068
- async function anchorOf2(project, source, io) {
7584
+ async function creationFacts(project, source, mayRecordOrigin, io) {
7585
+ const atSource = source === void 0 ? void 0 : await sourceAtCreation(project, source, io);
7586
+ const originDir = atSource === void 0 ? io.cwd : atSource.recordIn;
7587
+ return { anchor: atSource?.anchor, origin: mayRecordOrigin && originDir !== void 0 ? await readOrigin(originDir) : void 0 };
7588
+ }
7589
+ async function sourceAtCreation(project, source, io) {
7069
7590
  const lookup = repoLookup(io);
7070
- const repo = await findRepo(project, lookup);
7071
- if (repo !== void 0) await sourcePresenceOrWarn(io, repo, source);
7072
- return sourceAnchor(repo, source, lookup.onUnreadable);
7591
+ const choice = await explicitSourceRepo(project, lookup, source);
7592
+ if (choice !== void 0) await sourcePresenceOrWarn(io, choice.path, source);
7593
+ return { anchor: await sourceAnchor(choice?.recordIn, source, lookup.onUnreadable), recordIn: choice?.recordIn };
7073
7594
  }
7074
7595
  async function allAfterSettling(work) {
7075
7596
  await Promise.allSettled(work);
@@ -7180,7 +7701,7 @@ async function runPrune(args, io) {
7180
7701
  }
7181
7702
  const write = taskWriter(io, indexOfLoaded(loaded));
7182
7703
  return applyAll(stale, async (task) => {
7183
- const written = await write(task, { status: "cancelled" }, { resolution: "obsolete", reason: io.cli.pruneReason(STALE_LOW_DAYS) });
7704
+ const written = await write(task, { status: "cancelled" }, { closure: { resolution: "obsolete", reason: io.cli.pruneReason(STALE_LOW_DAYS) } });
7184
7705
  if (!written.ok) return written.exitCode;
7185
7706
  io.print(io.cli.taskCancelled(task.id));
7186
7707
  return EXIT.ok;
@@ -7190,13 +7711,13 @@ async function runPrune(args, io) {
7190
7711
  // src/server/start.ts
7191
7712
  import { serve } from "@hono/node-server";
7192
7713
  import { mkdir as mkdir6, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
7193
- import { join as join32 } from "node:path";
7714
+ import { join as join35 } from "node:path";
7194
7715
 
7195
7716
  // src/server/app.ts
7196
7717
  import { serveStatic } from "@hono/node-server/serve-static";
7197
7718
  import { Hono as Hono3 } from "hono";
7198
7719
  import { secureHeaders } from "hono/secure-headers";
7199
- import { join as join28 } from "node:path";
7720
+ import { join as join31 } from "node:path";
7200
7721
 
7201
7722
  // src/server/api.ts
7202
7723
  import { Hono as Hono2 } from "hono";
@@ -7246,7 +7767,7 @@ var batchRequestSchema = z14.strictObject({
7246
7767
  // src/core/check/graph-health.ts
7247
7768
  async function projectGraphHealth(project, tasks, home2) {
7248
7769
  return graphHealth(
7249
- await findRepo(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph, workingRoots: null }),
7770
+ (await projectCheckouts(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph, workingRoots: null }))[0]?.path,
7250
7771
  tasks.filter((task) => task.projectId === project.id)
7251
7772
  );
7252
7773
  }
@@ -7354,7 +7875,7 @@ function fileBusyResponse(c, language, busy) {
7354
7875
  }
7355
7876
 
7356
7877
  // src/server/journal-sources.ts
7357
- import { join as join24 } from "node:path";
7878
+ import { join as join26 } from "node:path";
7358
7879
 
7359
7880
  // src/core/store/jsonl-tail.ts
7360
7881
  import { createHash as createHash5 } from "node:crypto";
@@ -7453,7 +7974,7 @@ function createJournalSources(root) {
7453
7974
  const tailOf = (projectId) => {
7454
7975
  const known = tails.get(projectId);
7455
7976
  if (known !== void 0) return known;
7456
- const created = createJsonlTail(join24(root, projectId, JOURNAL_FILE), journalEventSchema);
7977
+ const created = createJsonlTail(join26(root, projectId, JOURNAL_FILE), journalEventSchema);
7457
7978
  tails.set(projectId, created);
7458
7979
  return created;
7459
7980
  };
@@ -7635,7 +8156,7 @@ function markIfReadable(path) {
7635
8156
  }
7636
8157
 
7637
8158
  // src/server/snapshot-cache.ts
7638
- import { dirname as dirname8, join as join25 } from "node:path";
8159
+ import { dirname as dirname8, join as join27 } from "node:path";
7639
8160
 
7640
8161
  // src/core/journal/closed-in-web.ts
7641
8162
  function tasksClosedInWeb(tasks, journals) {
@@ -7700,7 +8221,7 @@ function createChangeHub({ revisions, snapshots, derived, changes }) {
7700
8221
  });
7701
8222
  const recordOwnWrites = async (writes) => {
7702
8223
  if (writes.length === 0) return snapshots.forget();
7703
- await revisions.recordOwnWrites(writes, [...new Set(writes.map((write) => join25(dirname8(write.path), JOURNAL_FILE)))]);
8224
+ await revisions.recordOwnWrites(writes, [...new Set(writes.map((write) => join27(dirname8(write.path), JOURNAL_FILE)))]);
7704
8225
  forgetChanged(writes.map((write) => write.path));
7705
8226
  };
7706
8227
  return {
@@ -7723,7 +8244,7 @@ async function loadSnapshot(root, revision, journalSources, warn2) {
7723
8244
  const loaded = await loadBacklog(root);
7724
8245
  const projectIds = loaded.projects.map((project) => project.id);
7725
8246
  const readableJournal = (projectId) => journalSources.journal(projectId).catch(async (error) => {
7726
- await warn2((messages) => messages.journalReadFailed(join25(root, projectId, JOURNAL_FILE), errorText(error)));
8247
+ await warn2((messages) => messages.journalReadFailed(join27(root, projectId, JOURNAL_FILE), errorText(error)));
7727
8248
  return { projectId, events: [], invalidLines: 0 };
7728
8249
  });
7729
8250
  const journals = await Promise.all(projectIds.map(readableJournal));
@@ -7746,7 +8267,7 @@ var STATS_REPORT_ROUTES = {
7746
8267
  var STATS_MEMORY_ROUTE = "/stats/memory";
7747
8268
 
7748
8269
  // src/core/code/code-cache.ts
7749
- import { join as join26 } from "node:path";
8270
+ import { join as join28 } from "node:path";
7750
8271
  import { z as z15 } from "zod";
7751
8272
  var CODE_CACHE_FILE = ".code-cache.json";
7752
8273
  var CODE_CACHE_VERSION = 3;
@@ -7768,7 +8289,7 @@ function emptyCodeCache() {
7768
8289
  return { repos: {}, fixes: {}, unsettled: {} };
7769
8290
  }
7770
8291
  function createCodeCacheFile(root) {
7771
- const path = join26(root, CODE_CACHE_FILE);
8292
+ const path = join28(root, CODE_CACHE_FILE);
7772
8293
  return {
7773
8294
  read: async () => {
7774
8295
  const snapshot = await readJsonFile(path, snapshotSchema);
@@ -8361,9 +8882,6 @@ function totalsOf(deferred, units, estimate) {
8361
8882
  const realLines = sum(units.map((unit) => unit.lines));
8362
8883
  const fixedLines = sum(fixed.map((item) => item.lines));
8363
8884
  const deferredLines = fixedLines + (estimatedLines ?? 0);
8364
- const denominator = realLines + (estimatedLines ?? 0);
8365
- const openSizeUnknown = estimatedLines === null && open2.length > 0;
8366
- const measurable = realLines > 0 && deferred.length > 0 && !openSizeUnknown;
8367
8885
  return {
8368
8886
  realLines,
8369
8887
  fixedTasks: fixed.length,
@@ -8373,9 +8891,15 @@ function totalsOf(deferred, units, estimate) {
8373
8891
  estimatedLines,
8374
8892
  deferredLines,
8375
8893
  deferredTestLines: sum(fixed.map((item) => item.testLines)) + (estimated?.testLines ?? 0),
8376
- noiseShare: measurable ? Math.min(1, deferredLines / denominator) : null
8894
+ ...noiseOf(realLines, deferred.length, deferredLines, estimatedLines)
8377
8895
  };
8378
8896
  }
8897
+ function noiseOf(realLines, deferredTasks, deferredLines, estimatedLines) {
8898
+ if (realLines === 0) return { noiseShare: null, noiseMissing: "no-commits" };
8899
+ if (deferredTasks === 0) return { noiseShare: null, noiseMissing: "no-deferred-tasks" };
8900
+ if (estimatedLines === null) return { noiseShare: null, noiseMissing: "estimate-pending" };
8901
+ return { noiseShare: Math.min(1, deferredLines / (realLines + estimatedLines)), noiseMissing: null };
8902
+ }
8379
8903
  function byKind(deferred) {
8380
8904
  return { fixed: deferred.filter((item) => item.kind === "fixed"), open: deferred.filter((item) => item.kind === "open") };
8381
8905
  }
@@ -8550,7 +9074,7 @@ function leadTimesIn(histories, span2) {
8550
9074
  }
8551
9075
 
8552
9076
  // src/server/cost-source.ts
8553
- import { join as join27 } from "node:path";
9077
+ import { join as join30 } from "node:path";
8554
9078
 
8555
9079
  // src/core/stats/cost/token-counts.ts
8556
9080
  import { z as z16 } from "zod";
@@ -8569,54 +9093,77 @@ function tokensGrowth(before, after) {
8569
9093
  const grown = (key) => Math.max(0, after[key] - before[key]);
8570
9094
  return { input: grown("input"), cacheWrite5m: grown("cacheWrite5m"), cacheWrite1h: grown("cacheWrite1h"), cacheRead: grown("cacheRead"), output: grown("output") };
8571
9095
  }
9096
+ function promptTokens(tokens) {
9097
+ return tokens.input + tokens.cacheWrite5m + tokens.cacheWrite1h + tokens.cacheRead;
9098
+ }
8572
9099
  function totalTokens(tokens) {
8573
- return tokens.input + tokens.cacheWrite5m + tokens.cacheWrite1h + tokens.cacheRead + tokens.output;
9100
+ return promptTokens(tokens) + tokens.output;
8574
9101
  }
8575
9102
 
8576
9103
  // src/core/stats/cost/pricing.ts
8577
9104
  var FAST_MODEL_MARKER = ":fast";
9105
+ var LONG_PROMPT_MARKER = ":long-prompt";
9106
+ var LONG_PROMPT_TOKENS = 1e5;
8578
9107
  var FAST_PRICE_FACTOR = 2;
8579
9108
  var CACHE_WRITE_5M_FACTOR = 1.25;
8580
9109
  var CACHE_WRITE_1H_FACTOR = 2;
8581
9110
  var TOKENS_PER_PRICE = 1e6;
8582
9111
  var PRICE_TABLE = /* @__PURE__ */ new Map([
9112
+ ["claude-fable-5-2", { input: 8, output: 40, cacheRead: 0.2, fastMode: true }],
9113
+ ["claude-mythos-5-2", { input: 8, output: 40, cacheRead: 0.2, fastMode: true }],
8583
9114
  ["claude-fable-5-1", { input: 10, output: 50, cacheRead: 0.25 }],
8584
9115
  ["claude-mythos-5-1", { input: 10, output: 50, cacheRead: 0.25 }],
8585
9116
  ["claude-fable-5", { input: 10, output: 50, cacheRead: 1 }],
8586
9117
  ["claude-mythos-5", { input: 10, output: 50, cacheRead: 1 }],
8587
- ["claude-opus-5-5", { input: 4, output: 20, cacheRead: 0.2 }],
8588
- ["claude-opus-5", { input: 5, output: 25, cacheRead: 0.5 }],
8589
- ["claude-opus-4-8", { input: 5, output: 25, cacheRead: 0.5 }],
9118
+ ["claude-opus-5-5", { input: 4, output: 20, cacheRead: 0.2, fastMode: true }],
9119
+ ["claude-opus-5", { input: 5, output: 25, cacheRead: 0.5, fastMode: true }],
9120
+ ["claude-opus-4-8", { input: 5, output: 25, cacheRead: 0.5, fastMode: true }],
8590
9121
  ["claude-opus-4-7", { input: 5, output: 25, cacheRead: 0.5 }],
8591
9122
  ["claude-opus-4-6", { input: 5, output: 25, cacheRead: 0.5 }],
9123
+ ["claude-opus-4-5", { input: 5, output: 25, cacheRead: 0.5 }],
9124
+ ["claude-sonnet-5-5", { input: 2, output: 10, cacheRead: 0.1 }],
8592
9125
  ["claude-sonnet-5", { input: 2, output: 10, cacheRead: 0.2 }],
8593
9126
  ["claude-sonnet-4-6", { input: 3, output: 15, cacheRead: 0.3 }],
9127
+ ["claude-sonnet-4-5", { input: 3, output: 15, cacheRead: 0.3 }],
9128
+ ["claude-haiku-5-5", { input: 0.1, output: 0.5, cacheRead: 0.01, longPrompt: { input: 0.5, output: 2.5, cacheRead: 0.05 } }],
8594
9129
  ["claude-haiku-4-5", { input: 1, output: 5, cacheRead: 0.1 }]
8595
9130
  ]);
8596
- var FAST_PRICED_MODELS = /* @__PURE__ */ new Set(["claude-opus-5-5", "claude-opus-5"]);
8597
9131
  var DATED_SUFFIX = /-\d{8}$/;
8598
9132
  var BRACKET_SUFFIX = /\[[^\]]*\]$/;
8599
9133
  function baseModelId(model) {
8600
9134
  return model.replace(BRACKET_SUFFIX, "").replace(DATED_SUFFIX, "");
8601
9135
  }
8602
- function fastModel(model) {
8603
- return `${model}${FAST_MODEL_MARKER}`;
9136
+ function modelKey({ model, fast, tokens }) {
9137
+ const longPrompt = promptTokens(tokens) > LONG_PROMPT_TOKENS && PRICE_TABLE.get(baseModelId(model))?.longPrompt !== void 0;
9138
+ return `${model}${fast ? FAST_MODEL_MARKER : ""}${longPrompt ? LONG_PROMPT_MARKER : ""}`;
9139
+ }
9140
+ function stripMarker(key, marker) {
9141
+ const marked = key.endsWith(marker);
9142
+ return { rest: marked ? key.slice(0, -marker.length) : key, marked };
8604
9143
  }
8605
- function splitFastModel(modelKey) {
8606
- const fast = modelKey.endsWith(FAST_MODEL_MARKER);
8607
- return { model: fast ? modelKey.slice(0, -FAST_MODEL_MARKER.length) : modelKey, fast };
9144
+ function parseModelKey(key) {
9145
+ const { rest, marked: longPrompt } = stripMarker(key, LONG_PROMPT_MARKER);
9146
+ const { rest: model, marked: fast } = stripMarker(rest, FAST_MODEL_MARKER);
9147
+ return { model, fast, longPrompt };
8608
9148
  }
8609
- function priceOf(modelKey) {
8610
- const { model, fast } = splitFastModel(modelKey);
8611
- const baseId = baseModelId(model);
8612
- const price = PRICE_TABLE.get(baseId);
8613
- if (price === void 0) return null;
9149
+ function modelRowKey(key) {
9150
+ return stripMarker(key, LONG_PROMPT_MARKER).rest;
9151
+ }
9152
+ function splitFastModel(key) {
9153
+ const { model, fast } = parseModelKey(key);
9154
+ return { model, fast };
9155
+ }
9156
+ function priceOf(key) {
9157
+ const { model, fast, longPrompt } = parseModelKey(key);
9158
+ const pricing = PRICE_TABLE.get(baseModelId(model));
9159
+ if (pricing === void 0) return null;
9160
+ const price = longPrompt ? pricing.longPrompt ?? pricing : pricing;
8614
9161
  if (!fast) return price;
8615
- if (!FAST_PRICED_MODELS.has(baseId)) return null;
9162
+ if (pricing.fastMode !== true) return null;
8616
9163
  return { input: price.input * FAST_PRICE_FACTOR, output: price.output * FAST_PRICE_FACTOR, cacheRead: price.cacheRead * FAST_PRICE_FACTOR };
8617
9164
  }
8618
- function costOf(model, tokens) {
8619
- const price = priceOf(model);
9165
+ function costOf(key, tokens) {
9166
+ const price = priceOf(key);
8620
9167
  if (price === null) return null;
8621
9168
  const { input, cacheWrite5m, cacheWrite1h, cacheRead, output } = tokens;
8622
9169
  const total = input * price.input + cacheWrite5m * price.input * CACHE_WRITE_5M_FACTOR + cacheWrite1h * price.input * CACHE_WRITE_1H_FACTOR + cacheRead * price.cacheRead + output * price.output;
@@ -8693,7 +9240,7 @@ function costNumbers({ buckets, runs }) {
8693
9240
  };
8694
9241
  }
8695
9242
  function modelsOf(buckets) {
8696
- return [...groupBy(buckets, (bucket) => bucket.model).entries()].map(([key, modelBuckets]) => ({ ...splitFastModel(key), tokens: tokensTotalOf(modelBuckets), cost: costOfBuckets(modelBuckets) })).filter((row) => row.tokens > 0).sort((a, b) => b.tokens - a.tokens);
9243
+ return [...groupBy(buckets, (bucket) => modelRowKey(bucket.model)).entries()].map(([key, modelBuckets]) => ({ ...splitFastModel(key), tokens: tokensTotalOf(modelBuckets), cost: costOfBuckets(modelBuckets) })).filter((row) => row.tokens > 0).sort((a, b) => b.tokens - a.tokens);
8697
9244
  }
8698
9245
  function commandsOf(runs) {
8699
9246
  return [...groupBy(runs, (run) => run.command).entries()].map(([command2, commandRuns]) => ({
@@ -8708,11 +9255,79 @@ function average(values) {
8708
9255
  return sum(values) / values.length;
8709
9256
  }
8710
9257
 
9258
+ // src/core/usage/usage-cache.ts
9259
+ import { mkdir as mkdir5 } from "node:fs/promises";
9260
+ import { join as join29 } from "node:path";
9261
+ import { z as z18 } from "zod";
9262
+
9263
+ // src/core/stats/cost/usage-state.ts
9264
+ import { z as z17 } from "zod";
9265
+ var estimatedKindSchema = z17.enum(["cli", "skill"]);
9266
+ var usageBucketSchema = z17.object({
9267
+ slot: z17.string(),
9268
+ cwd: z17.string(),
9269
+ model: z17.string(),
9270
+ kind: z17.enum(["hook", ...estimatedKindSchema.options]),
9271
+ tokens: tokenCountsSchema,
9272
+ hookTurns: z17.number()
9273
+ });
9274
+ var transcriptStateSchema = z17.object({
9275
+ hookOpen: z17.boolean(),
9276
+ lastModel: z17.string().nullable(),
9277
+ lastMessageId: z17.string().nullable(),
9278
+ lastMessageTokens: tokenCountsSchema.nullable().optional(),
9279
+ pending: z17.record(z17.string(), estimatedKindSchema),
9280
+ pendingEstimates: z17.array(z17.object({ kind: estimatedKindSchema, chars: z17.number(), slot: z17.string(), cwd: z17.string() }))
9281
+ });
9282
+
9283
+ // src/core/usage/usage-cache.ts
9284
+ var USAGE_CACHE_FILE = ".usage-cache.json";
9285
+ var USAGE_CACHE_VERSION = 6;
9286
+ var bucketsSchema = z18.array(usageBucketSchema);
9287
+ var worktreeReposSchema = z18.record(z18.string(), z18.string());
9288
+ var usageCacheEntrySchema = z18.object({
9289
+ size: z18.number(),
9290
+ mtimeMs: z18.number().optional(),
9291
+ offset: z18.number(),
9292
+ fingerprint: z18.string(),
9293
+ state: transcriptStateSchema,
9294
+ buckets: bucketsSchema
9295
+ });
9296
+ var usageCacheSchema = z18.object({
9297
+ version: z18.literal(USAGE_CACHE_VERSION),
9298
+ files: z18.record(z18.string(), usageCacheEntrySchema),
9299
+ carried: z18.record(z18.string(), bucketsSchema).default({}),
9300
+ worktreeRepos: worktreeReposSchema.default({})
9301
+ });
9302
+ var salvagedEntrySchema = z18.object({ buckets: bucketsSchema }).transform((entry) => entry.buckets);
9303
+ var salvagedCacheSchema = z18.object({
9304
+ files: z18.record(z18.string(), salvagedEntrySchema.nullable().catch(null)).catch({}),
9305
+ carried: z18.record(z18.string(), bucketsSchema.nullable().catch(null)).catch({}),
9306
+ worktreeRepos: worktreeReposSchema.catch({})
9307
+ }).transform(({ files, carried, worktreeRepos }) => {
9308
+ const salvaged = [...Object.entries(carried), ...Object.entries(files)].flatMap(([path, buckets]) => buckets === null ? [] : [[path, buckets]]);
9309
+ return { ...emptyUsageCache(), carried: Object.fromEntries(salvaged), worktreeRepos };
9310
+ });
9311
+ var storedCacheSchema = z18.union([usageCacheSchema, salvagedCacheSchema]);
9312
+ function emptyUsageCache() {
9313
+ return { version: USAGE_CACHE_VERSION, files: {}, carried: {}, worktreeRepos: {} };
9314
+ }
9315
+ function usageBucketsOf(cache) {
9316
+ return [...Object.values(cache.files).flatMap((entry) => entry.buckets), ...Object.values(cache.carried).flat()];
9317
+ }
9318
+ async function readUsageCache(root) {
9319
+ return await readJsonFile(join29(root, USAGE_CACHE_FILE), storedCacheSchema) ?? emptyUsageCache();
9320
+ }
9321
+ async function writeUsageCache(root, cache, onErrorAfterPublish) {
9322
+ await mkdir5(root, { recursive: true });
9323
+ await writeFileAtomic(join29(root, USAGE_CACHE_FILE), JSON.stringify(cache), { onErrorAfterPublish });
9324
+ }
9325
+
8711
9326
  // src/server/cost-source.ts
8712
9327
  function createCostSource(root, home2) {
8713
- const runsTail = createJsonlTail(join27(root, RUNS_FILE), cliRunSchema);
8714
- const context = { home: home2, onUnreadable: unreadablePathHasNoProject };
8715
- const lookupRepoRoot = cachedRepoRoots({ onUnreadable: unreadablePathHasNoProject });
9328
+ const runsTail = createJsonlTail(join30(root, RUNS_FILE), cliRunSchema);
9329
+ const context = { home: home2, onUnreadable: unreadableDirHasNoRepo };
9330
+ const lookupRepoRoot = cachedRepoRoots({ onUnreadable: unreadableDirHasNoRepo });
8716
9331
  return {
8717
9332
  stateKey: async (usage) => {
8718
9333
  const { length, generation } = await runsTail.read();
@@ -8730,24 +9345,16 @@ async function computeCostReport({ usage: { cache, scan }, runs, known, projectI
8730
9345
  [...buckets, ...runs].map((entry) => entry.cwd),
8731
9346
  known,
8732
9347
  context,
8733
- lookupRepoRoot
9348
+ { lookupRepoRoot, worktreeRepos: cache.worktreeRepos }
8734
9349
  );
8735
9350
  return costReport({ buckets, runs, projectOf: (cwd) => projectIds.get(cwd) ?? null, projectId, now, scan });
8736
9351
  }
8737
- async function projectIdsOfCwds(cwds, known, context, lookupRepoRoot) {
8738
- const unique = [...new Set(cwds)];
8739
- const dirRoots = await Promise.all(unique.map(lookupRepoRoot));
8740
- return new Map(
8741
- unique.map((cwd, position) => {
8742
- const lookup = lookupProjectForDir(known, cwd, dirRoots[position] ?? "unreadable", context);
8743
- return [cwd, "project" in lookup ? lookup.project.id : null];
8744
- })
8745
- );
8746
- }
8747
- function unreadablePathHasNoProject() {
8748
- }
8749
- function usageBucketsOf(cache) {
8750
- return Object.values(cache.files).flatMap((entry) => entry.buckets);
9352
+ async function projectIdsOfCwds(cwds, known, context, recordedRepos) {
9353
+ const projectIdOf = async (cwd) => {
9354
+ const lookup = await lookupProjectForRecordedDir(known, cwd, recordedRepos, context);
9355
+ return [cwd, "project" in lookup ? lookup.project.id : null];
9356
+ };
9357
+ return new Map(await Promise.all([...new Set(cwds)].map(projectIdOf)));
8751
9358
  }
8752
9359
 
8753
9360
  // src/server/stats-api.ts
@@ -9070,14 +9677,14 @@ function createApp({ root, readLanguage, changes, allowedHosts, home: home2, sta
9070
9677
  });
9071
9678
  if (staticDir !== void 0) {
9072
9679
  app.use("*", serveStatic({ root: staticDir }));
9073
- app.get("*", serveStatic({ path: join28(staticDir, "index.html") }));
9680
+ app.get("*", serveStatic({ path: join31(staticDir, "index.html") }));
9074
9681
  }
9075
9682
  return app;
9076
9683
  }
9077
9684
 
9078
9685
  // src/server/change-feed.ts
9079
9686
  import { setMaxListeners } from "node:events";
9080
- import { join as join29, relative as relative3, sep as sep4 } from "node:path";
9687
+ import { join as join32, relative as relative3, sep as sep4 } from "node:path";
9081
9688
  import { watch } from "chokidar";
9082
9689
  var CHANGE_DEBOUNCE_MS = 100;
9083
9690
  function createDebouncer(delayMs, run) {
@@ -9094,7 +9701,7 @@ function isHiddenPath(root, path) {
9094
9701
  return relative3(root, path).split(sep4).some((segment) => segment.startsWith("."));
9095
9702
  }
9096
9703
  async function watchDirectoriesMissedAtStart(watcher, root) {
9097
- const directories = (await listDir(root)).filter((entry) => entry.isDirectory()).map((entry) => join29(root, entry.name));
9704
+ const directories = (await listDir(root)).filter((entry) => entry.isDirectory()).map((entry) => join32(root, entry.name));
9098
9705
  const watched = watcher.getWatched();
9099
9706
  const missed = directories.filter((path) => !isHiddenPath(root, path) && !(path in watched));
9100
9707
  if (missed.length > 0 && !watcher.closed) watcher.add(missed);
@@ -9190,14 +9797,16 @@ function logReport({ closedEpics, reopenedEpics, blockingFiles, deleted, conflic
9190
9797
  }
9191
9798
 
9192
9799
  // src/server/usage-scanner.ts
9800
+ import { existsSync as existsSync2 } from "node:fs";
9801
+ import { isAbsolute as isAbsolute4, join as join34 } from "node:path";
9193
9802
  import { isDeepStrictEqual } from "node:util";
9194
9803
 
9195
9804
  // src/core/usage/transcripts.ts
9196
9805
  import { createHash as createHash6 } from "node:crypto";
9197
- import { basename as basename10, join as join31 } from "node:path";
9806
+ import { basename as basename9, join as join33 } from "node:path";
9198
9807
 
9199
9808
  // src/core/stats/cost/attribute.ts
9200
- import { z as z17 } from "zod";
9809
+ import { z as z19 } from "zod";
9201
9810
 
9202
9811
  // src/core/stats/cost/shell-commands.ts
9203
9812
  var ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
@@ -9423,21 +10032,21 @@ var PENDING_TOOL_LIMIT = 64;
9423
10032
  var ZONE_OFFSETS_PER_HOUR = 4;
9424
10033
  var ZONE_OFFSET_STEP_MS = HOUR_MS / ZONE_OFFSETS_PER_HOUR;
9425
10034
  var BASH_TOOL = "Bash";
9426
- var usageSchema = z17.object({
9427
- input_tokens: z17.number().optional(),
9428
- output_tokens: z17.number().optional(),
9429
- cache_read_input_tokens: z17.number().optional(),
9430
- cache_creation_input_tokens: z17.number().optional(),
9431
- speed: z17.string().optional(),
9432
- cache_creation: z17.object({ ephemeral_5m_input_tokens: z17.number().optional(), ephemeral_1h_input_tokens: z17.number().optional() }).passthrough().optional()
10035
+ var usageSchema = z19.object({
10036
+ input_tokens: z19.number().optional(),
10037
+ output_tokens: z19.number().optional(),
10038
+ cache_read_input_tokens: z19.number().optional(),
10039
+ cache_creation_input_tokens: z19.number().optional(),
10040
+ speed: z19.string().optional(),
10041
+ cache_creation: z19.object({ ephemeral_5m_input_tokens: z19.number().optional(), ephemeral_1h_input_tokens: z19.number().optional() }).passthrough().optional()
9433
10042
  }).passthrough();
9434
- var assistantMessageSchema = z17.object({ id: z17.string().optional(), model: z17.string().optional(), usage: usageSchema.optional(), content: z17.array(z17.unknown()).optional() }).passthrough();
9435
- var userMessageSchema = z17.object({ content: z17.unknown().optional() }).passthrough();
9436
- var toolUseBlockSchema = z17.object({ type: z17.literal("tool_use"), id: z17.string(), name: z17.string(), input: z17.unknown().optional() }).passthrough();
9437
- var toolResultBlockSchema = z17.object({ type: z17.literal("tool_result"), tool_use_id: z17.string().optional(), content: z17.unknown().optional() }).passthrough();
9438
- var textBlockSchema = z17.object({ type: z17.literal("text"), text: z17.string() }).passthrough();
9439
- var bashInputSchema = z17.object({ command: z17.string() }).passthrough();
9440
- var transcriptLineSchema = z17.object({ type: z17.string().optional(), timestamp: z17.string().optional(), cwd: z17.string().optional(), isMeta: z17.boolean().optional(), message: z17.unknown().optional() }).passthrough();
10043
+ var assistantMessageSchema = z19.object({ id: z19.string().optional(), model: z19.string().optional(), usage: usageSchema.optional(), content: z19.array(z19.unknown()).optional() }).passthrough();
10044
+ var userMessageSchema = z19.object({ content: z19.unknown().optional() }).passthrough();
10045
+ var toolUseBlockSchema = z19.object({ type: z19.literal("tool_use"), id: z19.string(), name: z19.string(), input: z19.unknown().optional() }).passthrough();
10046
+ var toolResultBlockSchema = z19.object({ type: z19.literal("tool_result"), tool_use_id: z19.string().optional(), content: z19.unknown().optional() }).passthrough();
10047
+ var textBlockSchema = z19.object({ type: z19.literal("text"), text: z19.string() }).passthrough();
10048
+ var bashInputSchema = z19.object({ command: z19.string() }).passthrough();
10049
+ var transcriptLineSchema = z19.object({ type: z19.string().optional(), timestamp: z19.string().optional(), cwd: z19.string().optional(), isMeta: z19.boolean().optional(), message: z19.unknown().optional() }).passthrough();
9441
10050
  function newTranscriptState() {
9442
10051
  return { hookOpen: false, lastModel: null, lastMessageId: null, lastMessageTokens: null, pending: {}, pendingEstimates: [] };
9443
10052
  }
@@ -9461,8 +10070,8 @@ function attributeAssistant(rawMessage, state, context) {
9461
10070
  const buckets = [];
9462
10071
  const repeatOfCountedMessage = id !== void 0 && id === state.lastMessageId;
9463
10072
  if (usage !== void 0 && isPricedModel(model)) {
9464
- const pricedModel = usage.speed === FAST_SPEED ? fastModel(model) : model;
9465
10073
  const tokens = tokensFrom(usage);
10074
+ const pricedModel = modelKey({ model, fast: usage.speed === FAST_SPEED, tokens });
9466
10075
  if (repeatOfCountedMessage) {
9467
10076
  const counted = state.lastMessageTokens ?? tokens;
9468
10077
  const growth = tokensGrowth(counted, tokens);
@@ -9560,57 +10169,6 @@ function slotOf(timestamp) {
9560
10169
  return Number.isNaN(moment) ? "" : new Date(moment - moment % ZONE_OFFSET_STEP_MS).toISOString();
9561
10170
  }
9562
10171
 
9563
- // src/core/usage/usage-cache.ts
9564
- import { mkdir as mkdir5 } from "node:fs/promises";
9565
- import { join as join30 } from "node:path";
9566
- import { z as z19 } from "zod";
9567
-
9568
- // src/core/stats/cost/usage-state.ts
9569
- import { z as z18 } from "zod";
9570
- var estimatedKindSchema = z18.enum(["cli", "skill"]);
9571
- var usageBucketSchema = z18.object({
9572
- slot: z18.string(),
9573
- cwd: z18.string(),
9574
- model: z18.string(),
9575
- kind: z18.enum(["hook", ...estimatedKindSchema.options]),
9576
- tokens: tokenCountsSchema,
9577
- hookTurns: z18.number()
9578
- });
9579
- var transcriptStateSchema = z18.object({
9580
- hookOpen: z18.boolean(),
9581
- lastModel: z18.string().nullable(),
9582
- lastMessageId: z18.string().nullable(),
9583
- lastMessageTokens: tokenCountsSchema.nullable().optional(),
9584
- pending: z18.record(z18.string(), estimatedKindSchema),
9585
- pendingEstimates: z18.array(z18.object({ kind: estimatedKindSchema, chars: z18.number(), slot: z18.string(), cwd: z18.string() }))
9586
- });
9587
-
9588
- // src/core/usage/usage-cache.ts
9589
- var USAGE_CACHE_FILE = ".usage-cache.json";
9590
- var USAGE_CACHE_VERSION = 6;
9591
- var usageCacheEntrySchema = z19.object({
9592
- size: z19.number(),
9593
- mtimeMs: z19.number().optional(),
9594
- offset: z19.number(),
9595
- fingerprint: z19.string(),
9596
- state: transcriptStateSchema,
9597
- buckets: z19.array(usageBucketSchema)
9598
- });
9599
- var usageCacheSchema = z19.object({
9600
- version: z19.literal(USAGE_CACHE_VERSION),
9601
- files: z19.record(z19.string(), usageCacheEntrySchema)
9602
- });
9603
- function emptyUsageCache() {
9604
- return { version: USAGE_CACHE_VERSION, files: {} };
9605
- }
9606
- async function readUsageCache(root) {
9607
- return await readJsonFile(join30(root, USAGE_CACHE_FILE), usageCacheSchema) ?? emptyUsageCache();
9608
- }
9609
- async function writeUsageCache(root, cache) {
9610
- await mkdir5(root, { recursive: true });
9611
- await writeRecomputableFileAtomic(join30(root, USAGE_CACHE_FILE), JSON.stringify(cache));
9612
- }
9613
-
9614
10172
  // src/core/usage/transcripts.ts
9615
10173
  var FINGERPRINT_BYTES = 256;
9616
10174
  var ABANDONED_LINE_MS = 10 * 60 * 1e3;
@@ -9619,16 +10177,16 @@ async function listTranscripts(claudeProjectsDir2) {
9619
10177
  const files = [];
9620
10178
  for (const projectEntry of await listDir(claudeProjectsDir2)) {
9621
10179
  if (!projectEntry.isDirectory()) continue;
9622
- const projectDir2 = join31(claudeProjectsDir2, projectEntry.name);
9623
- for (const entry of await listDir(projectDir2)) {
9624
- const entryPath = join31(projectDir2, entry.name);
10180
+ const projectDir = join33(claudeProjectsDir2, projectEntry.name);
10181
+ for (const entry of await listDir(projectDir)) {
10182
+ const entryPath = join33(projectDir, entry.name);
9625
10183
  if (entry.isFile() && entry.name.endsWith(".jsonl")) {
9626
10184
  files.push(...await listedFile(entryPath));
9627
10185
  continue;
9628
10186
  }
9629
10187
  if (!entry.isDirectory()) continue;
9630
- for (const subagentEntry of await listDir(join31(entryPath, "subagents"), { recursive: true })) {
9631
- if (subagentEntry.isFile() && subagentEntry.name.endsWith(".jsonl")) files.push(...await listedFile(join31(subagentEntry.parentPath, subagentEntry.name)));
10188
+ for (const subagentEntry of await listDir(join33(entryPath, "subagents"), { recursive: true })) {
10189
+ if (subagentEntry.isFile() && subagentEntry.name.endsWith(".jsonl")) files.push(...await listedFile(join33(subagentEntry.parentPath, subagentEntry.name)));
9632
10190
  }
9633
10191
  }
9634
10192
  }
@@ -9647,14 +10205,19 @@ async function scanTranscripts({ files, cache, byteBudget, now }) {
9647
10205
  remainingBudget -= budgetUsed;
9648
10206
  await yieldToEventLoop();
9649
10207
  }
9650
- const merged = { ...deletedStillReported(cache, listedFiles, now), ...listedFiles };
9651
- const pruned = pruneStaleBuckets(merged, now);
10208
+ const stillReported = deletedStillReported(listedFiles, now);
10209
+ const merged = {
10210
+ ...cache,
10211
+ files: { ...entriesWhere(cache.files, (path, entry) => stillReported(path, entry.buckets)), ...listedFiles },
10212
+ carried: entriesWhere(cache.carried, stillReported)
10213
+ };
10214
+ const pruned = withoutStaleBuckets(merged, now);
9652
10215
  return {
9653
- cache: { version: USAGE_CACHE_VERSION, files: pruned.files },
10216
+ cache: pruned,
9654
10217
  bytesRead: byteBudget - remainingBudget,
9655
10218
  bytesLeft: sum(Object.values(listedFiles).map((entry) => entry.size - entry.offset)),
9656
10219
  filesDone: Object.values(listedFiles).filter((entry) => entry.offset === entry.size).length,
9657
- prunedBuckets: pruned.prunedBuckets
10220
+ prunedBuckets: bucketCount(merged) - bucketCount(pruned)
9658
10221
  };
9659
10222
  }
9660
10223
  async function scanFile(file, previous, budget, limits) {
@@ -9666,21 +10229,28 @@ async function scanFile(file, previous, budget, limits) {
9666
10229
  const fingerprint = unmoved ? previous.fingerprint : await fingerprintOf3(file.path, scanned.offset);
9667
10230
  return { entry: { ...scanned, mtimeMs: file.mtimeMs, fingerprint }, budgetUsed: Math.max(chunkSize, 0) };
9668
10231
  }
9669
- function pruneStaleBuckets(entries, now) {
10232
+ function withoutStaleBuckets(cache, now) {
9670
10233
  const retained = retainedSince(now);
9671
- const files = {};
9672
- let prunedBuckets = 0;
9673
- for (const [path, entry] of Object.entries(entries)) {
9674
- const buckets = entry.buckets.filter((bucket) => Date.parse(bucket.slot) >= retained);
9675
- files[path] = buckets.length === entry.buckets.length ? entry : { ...entry, buckets };
9676
- prunedBuckets += entry.buckets.length - buckets.length;
9677
- }
9678
- return { files, prunedBuckets };
10234
+ const fresh = (buckets) => {
10235
+ const kept = buckets.filter((bucket) => Date.parse(bucket.slot) >= retained);
10236
+ return kept.length === buckets.length ? buckets : kept;
10237
+ };
10238
+ return {
10239
+ ...cache,
10240
+ files: Object.fromEntries(Object.entries(cache.files).map(([path, entry]) => [path, { ...entry, buckets: fresh(entry.buckets) }])),
10241
+ carried: Object.fromEntries(Object.entries(cache.carried).map(([path, buckets]) => [path, fresh(buckets)]))
10242
+ };
9679
10243
  }
9680
- function deletedStillReported(cache, listedFiles, now) {
10244
+ function bucketCount(cache) {
10245
+ return sum([...Object.values(cache.files).map((entry) => entry.buckets.length), ...Object.values(cache.carried).map((buckets) => buckets.length)]);
10246
+ }
10247
+ function deletedStillReported(listedFiles, now) {
9681
10248
  const reportStart = statsPeriod(now).from;
9682
- const listedSessions = new Set(Object.keys(listedFiles).map((path) => basename10(path)));
9683
- return Object.fromEntries(Object.entries(cache.files).filter(([path, entry]) => !listedSessions.has(basename10(path)) && entry.buckets.some((bucket) => Date.parse(bucket.slot) >= reportStart)));
10249
+ const listedSessions = new Set(Object.keys(listedFiles).map((path) => basename9(path)));
10250
+ return (path, buckets) => !listedSessions.has(basename9(path)) && buckets.some((bucket) => Date.parse(bucket.slot) >= reportStart);
10251
+ }
10252
+ function entriesWhere(records2, keeps) {
10253
+ return Object.fromEntries(Object.entries(records2).filter(([path, value]) => keeps(path, value)));
9684
10254
  }
9685
10255
  async function scanChunk(file, start, chunkSize, { longestReadableLine, now }) {
9686
10256
  if (chunkSize <= 0) return { size: file.size, offset: start.offset, state: start.state, buckets: start.buckets };
@@ -9743,6 +10313,9 @@ function createUsageScanner({ root, claudeProjectsDir: claudeProjectsDir2, byteB
9743
10313
  let revision = 0;
9744
10314
  let inFlight = null;
9745
10315
  let schedule = STOPPED;
10316
+ const onErrorAfterPublish = warnPathErrors((line) => void warn2(() => line));
10317
+ const runsTail = createJsonlTail(join34(root, RUNS_FILE), cliRunSchema);
10318
+ const newOutsideWorktrees = outsideWorktreeRecorder();
9746
10319
  const setScan = (next) => {
9747
10320
  if (!scanEquals(scan, next)) revision += 1;
9748
10321
  scan = next;
@@ -9753,10 +10326,13 @@ function createUsageScanner({ root, claudeProjectsDir: claudeProjectsDir2, byteB
9753
10326
  const files = await listTranscripts(claudeProjectsDir2);
9754
10327
  setScan(progressBefore(files, current));
9755
10328
  const result = await scanTranscripts({ files, cache: current, byteBudget, now: now() });
9756
- if (cacheChanged(published, result.cache)) revision += 1;
9757
- cache = result.cache;
10329
+ const { values: runs } = await runsTail.read();
10330
+ const added = await newOutsideWorktrees(result.cache, runs);
10331
+ const next = added.length === 0 ? result.cache : { ...result.cache, worktreeRepos: { ...result.cache.worktreeRepos, ...Object.fromEntries(added) } };
10332
+ if (cacheChanged(published, next)) revision += 1;
10333
+ cache = next;
9758
10334
  setScan({ listed: true, filesTotal: files.length, filesDone: result.filesDone, bytesLeft: result.bytesLeft });
9759
- if (result.bytesRead > 0 || result.prunedBuckets > 0) await writeUsageCache(root, result.cache);
10335
+ if (result.bytesRead > 0 || result.prunedBuckets > 0 || added.length > 0) await writeUsageCache(root, next, onErrorAfterPublish);
9760
10336
  return result.bytesRead >= byteBudget ? "budget-spent" : "settled";
9761
10337
  };
9762
10338
  const scanOnce = () => {
@@ -9789,12 +10365,30 @@ function createUsageScanner({ root, claudeProjectsDir: claudeProjectsDir2, byteB
9789
10365
  snapshot: () => ({ cache: cache ?? emptyUsageCache(), scan, revision })
9790
10366
  };
9791
10367
  }
10368
+ function outsideWorktreeRecorder() {
10369
+ const lookupRepoRoot = cachedRepoRoots({ onUnreadable: unreadableDirHasNoRepo });
10370
+ const settledCwds = /* @__PURE__ */ new Set();
10371
+ const settledRootsOf = async (cwd) => {
10372
+ const roots = existsSync2(cwd) ? await lookupRepoRoot(cwd) : "missing";
10373
+ if (roots !== "not-in-repo" && roots !== "unreadable") settledCwds.add(cwd);
10374
+ return roots;
10375
+ };
10376
+ return async (scanned, runs) => {
10377
+ const cwds = new Set([...usageBucketsOf(scanned), ...runs].map((entry) => entry.cwd));
10378
+ const unsettled = [...cwds].filter((cwd) => isAbsolute4(cwd) && !settledCwds.has(cwd));
10379
+ const found = (await Promise.all(unsettled.map(settledRootsOf))).filter((roots) => typeof roots !== "string");
10380
+ const outside = found.filter(({ worktree, main }) => relativeInside(main, worktree) === null && scanned.worktreeRepos[worktree] !== main);
10381
+ return [...new Map(outside.map(({ worktree, main }) => [worktree, main])).entries()];
10382
+ };
10383
+ }
9792
10384
  function scanEquals(a, b) {
9793
10385
  return a.listed === b.listed && a.filesTotal === b.filesTotal && a.filesDone === b.filesDone && a.bytesLeft === b.bytesLeft;
9794
10386
  }
9795
10387
  function cacheChanged(previous, next) {
9796
10388
  const previousPaths = Object.keys(previous.files);
9797
- if (previousPaths.length !== Object.keys(next.files).length) return true;
10389
+ const sameFileSet = previousPaths.length === Object.keys(next.files).length;
10390
+ const sameKeptRecords = isDeepStrictEqual(previous.carried, next.carried) && isDeepStrictEqual(previous.worktreeRepos, next.worktreeRepos);
10391
+ if (!sameFileSet || !sameKeptRecords) return true;
9798
10392
  return previousPaths.some((path) => entryChanged(previous.files[path], next.files[path]));
9799
10393
  }
9800
10394
  function entryChanged(previous, next) {
@@ -9817,7 +10411,7 @@ function progressBefore(files, cache) {
9817
10411
  // src/server/start.ts
9818
10412
  var SWEEP_INTERVAL_MS = HOUR_MS;
9819
10413
  var STOP_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
9820
- var BUNDLED_WEB_DIR = join32(import.meta.dirname, "web");
10414
+ var BUNDLED_WEB_DIR = join35(import.meta.dirname, "web");
9821
10415
  async function startServer({ root, port, home: home2, env, platform, log, warn: warn2, pidFile, staticDir, settledLanguage, now = () => /* @__PURE__ */ new Date() }) {
9822
10416
  await mkdir6(root, { recursive: true });
9823
10417
  const startupMessages = serverMessages(settledLanguage);
@@ -9928,7 +10522,7 @@ function isFailure(outcome) {
9928
10522
 
9929
10523
  // src/cli/service/launchd.ts
9930
10524
  import { mkdir as mkdir7, rm as rm6, writeFile as writeFile3 } from "node:fs/promises";
9931
- import { dirname as dirname9, join as join33 } from "node:path";
10525
+ import { dirname as dirname9, join as join36 } from "node:path";
9932
10526
  import { setTimeout as sleep3 } from "node:timers/promises";
9933
10527
 
9934
10528
  // src/cli/service/service.ts
@@ -9936,13 +10530,13 @@ import { readFile as readFile3 } from "node:fs/promises";
9936
10530
  function serviceEnvironment(launch) {
9937
10531
  return { BACKLOG_DIR: launch.backlogRoot, PORT: String(launch.port), PATH: launch.env.PATH ?? "", HOME: launch.home };
9938
10532
  }
9939
- async function numberRecordedIn(file, pattern, encoding = "utf8") {
10533
+ async function numberRecordedIn(file, pattern, parse2, encoding = "utf8") {
9940
10534
  const text = await readFile3(file, encoding).catch((error) => {
9941
10535
  if (hasErrorCode(error, "ENOENT")) return "";
9942
10536
  throw error;
9943
10537
  });
9944
10538
  const recorded = pattern.exec(text)?.[1];
9945
- return recorded === void 0 ? null : portNumber(recorded);
10539
+ return recorded === void 0 ? null : parse2(recorded);
9946
10540
  }
9947
10541
 
9948
10542
  // src/cli/service/launchd.ts
@@ -9992,7 +10586,7 @@ ${entries}
9992
10586
  `;
9993
10587
  }
9994
10588
  function launchdManager(context, delay = sleep3) {
9995
- const file = join33(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
10589
+ const file = join36(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
9996
10590
  const domain = `gui/${context.uid}`;
9997
10591
  const bootout = () => context.exec("launchctl", ["bootout", `${domain}/${LABEL}`]);
9998
10592
  const bootstrap = () => context.exec("launchctl", ["bootstrap", domain, file]);
@@ -10021,30 +10615,32 @@ function launchdManager(context, delay = sleep3) {
10021
10615
  async registered() {
10022
10616
  return await fileExists(file) && (await context.exec("launchctl", ["print", `${domain}/${LABEL}`])).code === 0;
10023
10617
  },
10024
- installedPort: () => numberRecordedIn(file, /<key>PORT<\/key>\s*<string>(\d+)<\/string>/)
10618
+ installedPort: () => numberRecordedIn(file, /<key>PORT<\/key>\s*<string>(\d+)<\/string>/, portNumber)
10025
10619
  };
10026
10620
  }
10027
10621
 
10028
10622
  // src/cli/service/startup-folder.ts
10029
10623
  import { mkdir as mkdir8, rm as rm7, writeFile as writeFile4 } from "node:fs/promises";
10030
- import { dirname as dirname10, join as join34, win32 } from "node:path";
10624
+ import { dirname as dirname10, join as join37, win32 } from "node:path";
10031
10625
  var SCRIPT_NAME = "p-backlog.vbs";
10032
10626
  var COMMAND_LINE_ARGUMENT = /"[^"]*"|\S+/g;
10033
10627
  var PROCESS_QUERY_TIMEOUT_MS = 15e3;
10628
+ var WINDOWS_MAX_PID = 4294967295;
10629
+ var RECORDED_PID = /^(\d+)\s*$/;
10034
10630
  function vbsString(value) {
10035
10631
  return `"${value.replaceAll('"', '""')}"`;
10036
10632
  }
10037
10633
  function appDataDir(site) {
10038
- return join34(site.env.LOCALAPPDATA ?? join34(site.home, "AppData", "Local"), "p-backlog");
10634
+ return join37(site.env.LOCALAPPDATA ?? join37(site.home, "AppData", "Local"), "p-backlog");
10039
10635
  }
10040
10636
  function startupFolder(site) {
10041
- return join34(site.env.APPDATA ?? join34(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
10637
+ return join37(site.env.APPDATA ?? join37(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
10042
10638
  }
10043
10639
  function logPath(site) {
10044
- return join34(appDataDir(site), "p-backlog.log");
10640
+ return join37(appDataDir(site), "p-backlog.log");
10045
10641
  }
10046
10642
  function pidFilePath(site) {
10047
- return join34(appDataDir(site), "server.pid");
10643
+ return join37(appDataDir(site), "server.pid");
10048
10644
  }
10049
10645
  var NODE_PATH_ENV = "P_BACKLOG_NODE";
10050
10646
  var CLI_PATH_ENV = "P_BACKLOG_CLI";
@@ -10085,9 +10681,14 @@ function startupScript(launch) {
10085
10681
  ""
10086
10682
  ].join("\r\n");
10087
10683
  }
10684
+ function pidNumber(recorded) {
10685
+ if (!/^\d+$/.test(recorded)) return null;
10686
+ const pid = Number(recorded);
10687
+ return pid > 0 && pid <= WINDOWS_MAX_PID ? pid : null;
10688
+ }
10088
10689
  async function stopRunningServer(context) {
10089
10690
  const file = pidFilePath(context);
10090
- const pid = await numberRecordedIn(file, /^(\d+)$/);
10691
+ const pid = await numberRecordedIn(file, RECORDED_PID, pidNumber);
10091
10692
  if (pid !== null) {
10092
10693
  const identity = await processIdentity(context, pid);
10093
10694
  if (identity === "unknown") {
@@ -10114,7 +10715,7 @@ function sameWindowsPath(left, right) {
10114
10715
  return win32.normalize(left).toLowerCase() === win32.normalize(right).toLowerCase();
10115
10716
  }
10116
10717
  function startupFolderManager(context) {
10117
- const file = join34(startupFolder(context), SCRIPT_NAME);
10718
+ const file = join37(startupFolder(context), SCRIPT_NAME);
10118
10719
  return {
10119
10720
  file,
10120
10721
  logsHint: logPath(context),
@@ -10135,13 +10736,13 @@ function startupFolderManager(context) {
10135
10736
  async registered() {
10136
10737
  return fileExists(file);
10137
10738
  },
10138
- installedPort: () => numberRecordedIn(file, /env\("PORT"\) = "(\d+)"/, "utf16le")
10739
+ installedPort: () => numberRecordedIn(file, /env\("PORT"\) = "(\d+)"/, portNumber, "utf16le")
10139
10740
  };
10140
10741
  }
10141
10742
 
10142
10743
  // src/cli/service/systemd.ts
10143
10744
  import { mkdir as mkdir9, rm as rm8, writeFile as writeFile5 } from "node:fs/promises";
10144
- import { dirname as dirname11, join as join35 } from "node:path";
10745
+ import { dirname as dirname11, join as join38 } from "node:path";
10145
10746
  var SERVICE_NAME = "p-backlog";
10146
10747
  var UNIT = `${SERVICE_NAME}.service`;
10147
10748
  function quoted(value) {
@@ -10176,7 +10777,7 @@ async function systemctlSteps(exec, steps) {
10176
10777
  return "done";
10177
10778
  }
10178
10779
  function systemdManager(context) {
10179
- const file = join35(context.home, ".config/systemd/user", UNIT);
10780
+ const file = join38(context.home, ".config/systemd/user", UNIT);
10180
10781
  return {
10181
10782
  file,
10182
10783
  logsHint: `journalctl --user -u ${SERVICE_NAME}`,
@@ -10195,7 +10796,7 @@ function systemdManager(context) {
10195
10796
  async registered() {
10196
10797
  return await fileExists(file) && (await context.exec("systemctl", ["--user", "is-enabled", UNIT])).code === 0;
10197
10798
  },
10198
- installedPort: () => numberRecordedIn(file, /^Environment="PORT=(\d+)"$/m)
10799
+ installedPort: () => numberRecordedIn(file, /^Environment="PORT=(\d+)"$/m, portNumber)
10199
10800
  };
10200
10801
  }
10201
10802
 
@@ -10318,10 +10919,15 @@ async function readJsonConfig(path, schema) {
10318
10919
  return schema.safeParse(value).success ? { config: value } : { failed: "invalid" };
10319
10920
  }
10320
10921
  async function writeJsonConfig({ path, onError }, config) {
10321
- await mkdir10(dirname12(path), { recursive: true });
10322
- const target = await writeTargetOf(path);
10323
- const existing = await statOrNull(target);
10324
- await writeJsonFile(target, config, { mode: existing === null ? void 0 : existing.mode & 511, onErrorAfterPublish: onError });
10922
+ try {
10923
+ await mkdir10(dirname12(path), { recursive: true });
10924
+ const target = await writeTargetOf(path);
10925
+ const existing = await statOrNull(target);
10926
+ await writeJsonFile(target, config, { mode: existing === null ? void 0 : existing.mode & 511, onErrorAfterPublish: onError });
10927
+ return "written";
10928
+ } catch (error) {
10929
+ return { failed: "unwritable", code: errorCodeOrText(error) };
10930
+ }
10325
10931
  }
10326
10932
  async function readConfigText(path) {
10327
10933
  try {
@@ -10376,15 +10982,16 @@ async function addStopHookIn(file, schema, slotsOf, hook, ourHook) {
10376
10982
  const refreshed = refreshOurHook(slots.lists, hook, ourHook);
10377
10983
  if (refreshed === "exists") return "exists";
10378
10984
  if (refreshed === "missing") slots.append(hook);
10379
- await writeJsonConfig(file, read.config);
10985
+ const written = await writeJsonConfig(file, read.config);
10986
+ if (isFailure(written)) return written;
10380
10987
  return refreshed === "missing" ? "added" : "updated";
10381
10988
  }
10382
10989
  async function removeStopHookIn(file, schema, removeOurs) {
10383
10990
  const read = await readJsonConfig(file.path, schema);
10384
10991
  if (!("config" in read)) return read;
10385
10992
  if (!removeOurs(read.config)) return "absent";
10386
- await writeJsonConfig(file, read.config);
10387
- return "removed";
10993
+ const written = await writeJsonConfig(file, read.config);
10994
+ return isFailure(written) ? written : "removed";
10388
10995
  }
10389
10996
  function addGroupedStopHook(file, hook, ourHook) {
10390
10997
  return addStopHookIn(file, groupedConfigSchema, groupedSlots, hook, ourHook);
@@ -10600,7 +11207,7 @@ function unlinkReportingFailure(skillsDir, io, voice) {
10600
11207
  }
10601
11208
  function reportHook(result, configPath, io, voice) {
10602
11209
  if (isFailure(result)) {
10603
- voice.warn(result.failed === "unreadable" ? io.cli.installHookConfigUnreadable(configPath, result.code) : io.cli.installHookConfigInvalid(configPath));
11210
+ voice.warn(configFailureText(result, configPath, io.cli.installHookConfigFailed));
10604
11211
  return false;
10605
11212
  }
10606
11213
  const report = { added: io.cli.installHookAdded, exists: io.cli.installHookExists, updated: io.cli.installHookUpdated }[result];
@@ -10634,12 +11241,15 @@ async function remainingSkillDirUser(agent, { removing, installed }, io) {
10634
11241
  }
10635
11242
  function reportHookRemoval(result, configPath, io, voice) {
10636
11243
  if (isFailure(result)) {
10637
- voice.warn(result.failed === "unreadable" ? io.cli.removeHookConfigUnreadable(configPath, result.code) : io.cli.removeHookConfigInvalid(configPath));
11244
+ voice.warn(configFailureText(result, configPath, io.cli.removeHookConfigFailed));
10638
11245
  return false;
10639
11246
  }
10640
11247
  voice.print(io.cli.manualHookRemoval[result](configPath));
10641
11248
  return true;
10642
11249
  }
11250
+ function configFailureText(failure, configPath, texts) {
11251
+ return failure.failed === "invalid" ? texts.invalid(configPath) : texts[failure.failed](configPath, failure.code);
11252
+ }
10643
11253
 
10644
11254
  // src/cli/commands/show.ts
10645
11255
  import { readFile as readFile5 } from "node:fs/promises";
@@ -10941,17 +11551,24 @@ async function verifyOne(id, { loaded, source, write, io }) {
10941
11551
  return EXIT.refused;
10942
11552
  }
10943
11553
  const project = projectOf(loaded, task);
10944
- const lookup = repoLookup(io);
10945
- const repo = project === void 0 ? void 0 : await findRepo(project, lookup);
10946
- if (source !== void 0 && repo !== void 0 && (await sourcePresenceOrWarn(io, repo, source)).kind === "missing") return EXIT.invalid;
10947
- const target = source ?? await relocatedSource(repo, task);
11554
+ const choice = project === void 0 ? void 0 : await verifiedRepo(project, task, source, io);
11555
+ if (source !== void 0 && choice !== void 0 && (await sourcePresenceOrWarn(io, choice.path, source)).kind === "missing") return EXIT.invalid;
11556
+ const recordIn = choice?.recordIn;
11557
+ const target = source ?? await relocatedSource(recordIn, task);
10948
11558
  const anchored = target ?? task.source;
10949
- const anchor = anchored === void 0 ? void 0 : anchorChange(await sourceAnchor(repo, anchored, lookup.onUnreadable));
10950
- const written = await write(task, { verified: formatLocalIso(io.now()), source: target, anchor });
11559
+ const anchor = anchored === void 0 ? void 0 : anchorChange(await sourceAnchor(recordIn, anchored, repoContext(io).onUnreadable));
11560
+ const headCommit = recordIn === void 0 ? void 0 : await readHeadCommit(recordIn);
11561
+ const written = await write(task, { verified: formatLocalIso(io.now()), source: target, anchor }, { headCommit });
10951
11562
  if (!written.ok) return written.exitCode;
10952
11563
  io.print(target === void 0 ? io.cli.verified(id) : io.cli.verifiedWithSource(id, target));
10953
11564
  return EXIT.ok;
10954
11565
  }
11566
+ async function verifiedRepo(project, task, source, io) {
11567
+ const lookup = repoLookup(io);
11568
+ if (source !== void 0) return explicitSourceRepo(project, lookup, source);
11569
+ const marks = project.repos.length > 1 ? await readMarkCommits(io.backlogRoot, project.id, (error) => io.warn(io.core.markCommitsReadFailed(project.id, errorText(error)))) : NO_MARK_COMMITS;
11570
+ return taskRepo(project, lookup, task, marks);
11571
+ }
10955
11572
  function anchorChange(found) {
10956
11573
  switch (found.kind) {
10957
11574
  case "no-file":
@@ -11048,6 +11665,10 @@ var packageRoot = resolve6(dirname13(cliPath), "..");
11048
11665
  var argv = process.argv.slice(2);
11049
11666
  var warn = (line) => void process.stderr.write(`${line}
11050
11667
  `);
11668
+ var CLOSED_READER_CODES = ["EPIPE", "EOF"];
11669
+ process.stdout.on("error", (error) => {
11670
+ if (!hasAnyErrorCode(error, CLOSED_READER_CODES)) throw error;
11671
+ });
11051
11672
  var exitCode = await runCli(argv, {
11052
11673
  cwd: process.cwd(),
11053
11674
  home,
@@ -11081,6 +11702,6 @@ if (command !== SERVE_COMMAND_NAME) {
11081
11702
  exitCode
11082
11703
  };
11083
11704
  const language = await readLanguageOrLocale(backlogRoot, process.env, alreadyReportedByRunCli);
11084
- await appendRun(backlogRoot, run).catch((error) => warn(cliMessages(language).runNotRecorded(errorText(error))));
11705
+ await appendRun(backlogRoot, run, warnPathErrors(warn)).catch((error) => warn(cliMessages(language).runNotRecorded(errorText(error))));
11085
11706
  await tidyAfterCommand({ backlogRoot, command, language, now: /* @__PURE__ */ new Date(), warn });
11086
11707
  }