p-backlog 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +1 -1
  3. package/README.ru.md +1 -1
  4. package/dist/cli.js +1524 -1003
  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,356 @@ 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;
3973
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/repo-facts.ts
4266
+ var TRUST_COMMAND = /^git config .*safe\.directory/;
4267
+ var DIFF_LINE_LIMIT = 80;
4268
+ var REFLOG_MOMENT = /\{(\d+)\}$/;
4269
+ var STATUS_CODE_WIDTH = 3;
4270
+ var RENAME_OR_COPY = /^[RC]/;
4271
+ var DELETED_FILE_HEADER = /^deleted file mode /m;
4272
+ var ORIGINAL_PATH_FOLLOWS = /^(?:[RC].|.[RC])/;
4273
+ var LOG_FORMAT = `--format=${RECORD}%H${FIELD}%h${FIELD}%cI${FIELD}%P${FIELD}%s`;
4274
+ var FACTS_HISTORY_OPTIONS = ["--full-history"];
4275
+ async function locateRepo(repo, git = runGitOutcome) {
4276
+ const location = await git(repo, ["rev-parse", "--show-prefix", "--revs-only", "HEAD"]);
4277
+ if (location.status === "exited") {
4278
+ const trustCommand = trustCommandIn(location.stderr);
4279
+ return trustCommand === void 0 ? { history: "not-a-repo" } : { history: "unsafe-repo", trustCommand };
4280
+ }
4281
+ if (location.status === "unfinished") return { history: "unreadable" };
4282
+ const [prefix = "", head = ""] = location.stdout.split("\n").map((line) => line.trim());
4283
+ return { history: "read", prefix, hasCommits: head !== "" };
3974
4284
  }
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);
4285
+ function trustCommandIn(stderr) {
4286
+ return stderr.split("\n").map((line) => line.trim()).find((line) => TRUST_COMMAND.test(line));
4287
+ }
4288
+ async function collectRepoFacts(repo, pathMarks, known, gitOutcome = runGitOutcome) {
4289
+ const git = asGitRunner(gitOutcome);
4290
+ const paths = [...pathMarks.keys()];
4291
+ const [location, files] = await Promise.all([locateRepo(repo, gitOutcome), sourceFiles(repo, paths)]);
4292
+ const withoutHistory = (noHistory) => ({ ...noHistory, commits: [], renames: [], dirtyModifiedAt: /* @__PURE__ */ new Map(), branches: unknownBranches(noHistory.history), ...files });
4293
+ if (location.history !== "read") return withoutHistory(location);
4294
+ const { prefix, hasCommits } = location;
4295
+ const missing = paths.filter((path) => !files.existing.has(path) && !files.unreadable.has(path));
4296
+ const [log, renames, status, branches] = await Promise.all([
4297
+ hasCommits && paths.length > 0 ? pathLog(repo, [sinceEarliestMark(pathMarks, paths)], paths, git) : "",
4298
+ hasCommits && missing.length > 0 ? git(repo, [...logArgs([sinceEarliestMark(pathMarks, missing)]), "--diff-filter=R"]) : "",
4299
+ git(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=no"]),
4300
+ branchHistoryOf(repo, location, missing, known, git)
4301
+ ]);
4302
+ if (log === null || renames === null || status === null) return withoutHistory({ history: "unreadable" });
4303
+ const dirty = withinRepo(parseStatus(status), prefix);
4304
+ return { history: "read", commits: parseLog(log), renames: parseLog(renames), dirtyModifiedAt: await modificationTimes(repo, dirty), branches, ...files };
4305
+ }
4306
+ async function branchHistoryOf(repo, location, paths, known, git = runGit) {
4307
+ if (location.history !== "read") return unknownBranches(location.history);
4308
+ const [here, anywhere] = await Promise.all([location.hasCommits ? committedPaths(repo, "HEAD", paths, git) : [], knownAnywhere(paths, known) ?? committedPaths(repo, "--all", paths, git)]);
4309
+ return here === null || anywhere === null ? { kind: "unreadable" } : { kind: "read", committedHere: new Set(here), committedAnywhere: new Set(anywhere) };
4310
+ }
4311
+ function knownAnywhere(paths, known) {
4312
+ if (known === void 0 || known.anywhere.kind !== "read" || !paths.every((path) => known.paths.has(path))) return void 0;
4313
+ return [...known.anywhere.committed];
4314
+ }
4315
+ async function pathsEverCommitted(repo, paths) {
4316
+ const location = await locateRepo(repo);
4317
+ if (location.history !== "read") return unknownBranches(location.history);
4318
+ const committed = await committedPaths(repo, "--all", paths);
4319
+ return committed === null ? { kind: "unreadable" } : { kind: "read", committed: new Set(committed) };
4320
+ }
4321
+ function unknownBranches(history) {
4322
+ return history === "not-a-repo" ? { kind: "no-repo" } : { kind: "unreadable" };
4323
+ }
4324
+ function sinceEarliestMark(marks, paths) {
4325
+ return `--since=${new Date(Math.min(...paths.flatMap((path) => marks.get(path) ?? []))).toISOString()}`;
4326
+ }
4327
+ function logArgs(selection) {
4328
+ return ["log", ...selection, "--relative", LOG_FORMAT, "--name-status", "-M", "--diff-merges=first-parent", ...FACTS_HISTORY_OPTIONS, "-z"];
4329
+ }
4330
+ async function pathLog(repo, selection, paths, git) {
4331
+ const inside = paths.filter(isInsideRepo);
4332
+ if (inside.length === 0) return "";
4333
+ return git(repo, [...logArgs(selection), "--", ...literalPathspecs(inside)]);
3978
4334
  }
3979
- function headsAt(headCommitAt, isOnThisLine) {
4335
+ async function mainlineCommitsOff(repo, base, paths, git = runGit) {
4336
+ const log = await pathLog(repo, ["--first-parent", `${base}..HEAD`], paths, git);
4337
+ return log === null ? null : parseLog(log);
4338
+ }
4339
+ async function committedPaths(repo, revisions, paths, git = runGit) {
4340
+ const inside = paths.filter(isInsideRepo);
4341
+ if (inside.length === 0) return [];
4342
+ const names = await git(repo, ["log", revisions, "--relative", "--format=", "--name-only", ...FACTS_HISTORY_OPTIONS, "-z", "--", ...literalPathspecs(inside)]);
4343
+ return names === null ? null : names.split(/[\0\n]/).filter((name) => name !== "");
4344
+ }
4345
+ function isInsideRepo(path) {
4346
+ const normalized = normalize(path);
4347
+ return normalized !== "." && !isAbsolute2(normalized) && normalized !== ".." && !normalized.startsWith(`..${sep2}`);
4348
+ }
4349
+ function diffsSince(repo, git = runGit, diffFrom = diffsFrom(repo, git)) {
4350
+ const bases = /* @__PURE__ */ new Map();
4351
+ const baseBefore = (since) => remembered(bases, since.getTime(), async () => outputLine(await git(repo, ["rev-list", "-1", "--first-parent", `--before=${since.toISOString()}`, "HEAD"])));
4352
+ return async (path, since) => {
4353
+ const base = await baseBefore(since);
4354
+ return base === null ? null : diffFrom(path, base);
4355
+ };
4356
+ }
4357
+ function headCommitsAt(repo, git) {
4358
+ let moves = null;
3980
4359
  return async (moment) => {
3981
- const commit = await headCommitAt(moment);
3982
- return commit === null ? null : { commit, onThisLine: await isOnThisLine(commit) };
4360
+ moves ??= headMovesNewestFirst(repo, git);
4361
+ return (await moves).find((move) => move.at <= moment.getTime())?.commit ?? null;
3983
4362
  };
3984
4363
  }
3985
- async function headMovesNewestFirst(repo) {
3986
- const reflog = await runGit(repo, ["log", "--walk-reflogs", "--date=unix", `--format=%H${FIELD}%gd`, "HEAD"]);
4364
+ function headLineOf(repo, git, ancestryOf) {
4365
+ const answers = /* @__PURE__ */ new Map();
4366
+ return (commit) => remembered(answers, commit, () => lineOfCommit(repo, commit, git, ancestryOf));
4367
+ }
4368
+ async function lineOfCommit(repo, commit, git, ancestryOf) {
4369
+ const ancestry = await ancestryOf(commit);
4370
+ switch (ancestry) {
4371
+ case "ancestor":
4372
+ return "this-line";
4373
+ case "not-ancestor":
4374
+ return lineOfNonAncestor(repo, commit, asGitRunner(git));
4375
+ case "missing":
4376
+ case "unknown":
4377
+ return ancestry;
4378
+ }
4379
+ }
4380
+ async function lineOfNonAncestor(repo, commit, git) {
4381
+ const tip = (await resolveCommits(git, repo, [commit]))?.get(commit);
4382
+ if (tip === void 0) return "unknown";
4383
+ switch (await landingState(repo, tip, git)) {
4384
+ case "landed":
4385
+ return "this-line";
4386
+ case "pending":
4387
+ return "other-branch";
4388
+ case "unknown":
4389
+ return "unknown";
4390
+ }
4391
+ }
4392
+ async function headMovesNewestFirst(repo, git) {
4393
+ const reflog = await git(repo, ["log", "--walk-reflogs", "--date=unix", `--format=%H${FIELD}%gd`, "HEAD"]);
3987
4394
  return (reflog ?? "").split("\n").flatMap((line) => {
3988
4395
  const [commit = "", selector = ""] = line.split(FIELD);
3989
4396
  const seconds = REFLOG_MOMENT.exec(selector)?.[1];
3990
4397
  return seconds === void 0 ? [] : [{ commit, at: Number(seconds) * SECOND_MS }];
3991
4398
  });
3992
4399
  }
3993
- function diffsFrom(repo, git = runGit) {
4400
+ function diffsFrom(repo, git) {
3994
4401
  const diffs = /* @__PURE__ */ new Map();
3995
4402
  const tracked = /* @__PURE__ */ new Map();
3996
4403
  const isConfirmedTracked = (path) => remembered(tracked, path, async () => outputLine(await git(repo, ["ls-files", "--", ...literalPathspecs([path])])) !== null);
@@ -4022,7 +4429,7 @@ async function sourceFiles(repo, paths) {
4022
4429
  };
4023
4430
  }
4024
4431
  async function sourceFile(repo, path) {
4025
- const absolute = join11(repo, path);
4432
+ const absolute = join12(repo, path);
4026
4433
  if (!await fileExists(absolute)) return { kind: "missing", path };
4027
4434
  return { kind: "present", path, text: await readTextIfFile(absolute) };
4028
4435
  }
@@ -4075,29 +4482,89 @@ function withinRepo(gitRootPaths, prefix) {
4075
4482
  async function modificationTimes(repo, paths) {
4076
4483
  const entries = await Promise.all(
4077
4484
  paths.map(async (path) => {
4078
- const info = await lstatOrNull(join11(repo, path));
4485
+ const info = await lstatOrNull(join12(repo, path));
4079
4486
  return info === null ? [] : [[path, info.mtimeMs]];
4080
4487
  })
4081
4488
  );
4082
4489
  return new Map(entries.flat());
4083
4490
  }
4084
4491
 
4492
+ // src/core/check/task-base.ts
4493
+ function taskBases(repo, marks, gitOutcome = runGitOutcome) {
4494
+ const git = asGitRunner(gitOutcome);
4495
+ const diffFrom = diffsFrom(repo, git);
4496
+ const diffSince = diffsSince(repo, git, diffFrom);
4497
+ const headCommitAt = headCommitsAt(repo, git);
4498
+ const ancestries = /* @__PURE__ */ new Map();
4499
+ const ancestry = (commit) => remembered(ancestries, commit, () => headAncestryOf(gitOutcome, repo, commit));
4500
+ const headLine = headLineOf(repo, gitOutcome, ancestry);
4501
+ let completeness;
4502
+ const cloneCompleteness = () => completeness ??= cloneCompletenessOf(git, repo);
4503
+ const markCommits = /* @__PURE__ */ new Map();
4504
+ const markCommit = (task) => remembered(markCommits, task.id, async () => {
4505
+ const reflogCommit = () => headCommitAt(new Date(reviewMark(task)));
4506
+ const recorded = commitAtMark(task, marks);
4507
+ if (recorded === void 0) return reflogCommit();
4508
+ if (task.verified === void 0) return recorded;
4509
+ return seenFromHead(await headLine(recorded)) ? recorded : reflogCommit();
4510
+ });
4511
+ const bases = /* @__PURE__ */ new Map();
4512
+ const baseOf = (task) => remembered(bases, task.id, async () => {
4513
+ const since = new Date(reviewMark(task));
4514
+ const noCommitAtMark = async () => ({ kind: "approximate", since, markLine: await cloneCompleteness() === "full" ? "this-line" : "unknown" });
4515
+ const commit = await markCommit(task);
4516
+ if (commit === null) return noCommitAtMark();
4517
+ const line = await headLine(commit);
4518
+ switch (line) {
4519
+ case "this-line":
4520
+ return { kind: "exact", commit };
4521
+ case "other-branch":
4522
+ return { kind: "approximate", since, markLine: line };
4523
+ case "missing":
4524
+ return noCommitAtMark();
4525
+ case "unknown":
4526
+ return { kind: "unknown" };
4527
+ }
4528
+ });
4529
+ const diffSinceBase = async (task, path) => {
4530
+ const base = await baseOf(task);
4531
+ switch (base.kind) {
4532
+ case "exact":
4533
+ return diffFrom(path, base.commit);
4534
+ case "approximate":
4535
+ return diffSince(path, base.since);
4536
+ case "unknown":
4537
+ return null;
4538
+ }
4539
+ };
4540
+ return { markCommit, baseOf, diffSinceBase, diffFrom, ancestry, cloneCompleteness };
4541
+ }
4542
+ function markLineOf(base) {
4543
+ switch (base.kind) {
4544
+ case "exact":
4545
+ return "this-line";
4546
+ case "approximate":
4547
+ return base.markLine;
4548
+ case "unknown":
4549
+ return "unknown";
4550
+ }
4551
+ }
4552
+ function seenFromHead(line) {
4553
+ switch (line) {
4554
+ case "this-line":
4555
+ case "unknown":
4556
+ return true;
4557
+ case "other-branch":
4558
+ case "missing":
4559
+ return false;
4560
+ }
4561
+ }
4562
+
4085
4563
  // src/core/check/current-source.ts
4086
4564
  var LATER_COMMITS_TO_SEARCH = 5;
4087
4565
  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)])));
4566
+ async function traceSources(tasks, history, bases) {
4567
+ return new Map(await Promise.all(tasks.map(async (task) => [task.id, await traceSource(task, history, bases)])));
4101
4568
  }
4102
4569
  function currentSourcesOf(traces) {
4103
4570
  return new Map([...traces].map(([id, trace]) => [id, currentOf(trace)]));
@@ -4105,12 +4572,12 @@ function currentSourcesOf(traces) {
4105
4572
  async function currentSourceIn(repo, task) {
4106
4573
  if (task.source === void 0) return null;
4107
4574
  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())));
4575
+ return currentOf(await traceSource(task, { facts, late: /* @__PURE__ */ new Map() }, taskBases(repo, NO_MARK_COMMITS)));
4109
4576
  }
4110
4577
  function currentOf(trace) {
4111
4578
  return trace.kind === "traced" ? trace.current : null;
4112
4579
  }
4113
- async function traceSource(task, history, diffs) {
4580
+ async function traceSource(task, history, bases) {
4114
4581
  const { source, anchor } = task;
4115
4582
  if (source === void 0 || !hasLines(source)) return UNTRACED;
4116
4583
  const text = history.facts.texts.get(sourcePath(source));
@@ -4119,8 +4586,8 @@ async function traceSource(task, history, diffs) {
4119
4586
  const fileUntouched = commits.length === 0 && !uncommitted;
4120
4587
  if (fileUntouched && (anchor === void 0 || windowMatches(text, source, anchor))) return { kind: "traced", current: source, linesChanged: false };
4121
4588
  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;
4589
+ const reference = await referenceOf(traced, text, commits, bases);
4590
+ if (reference.kind === "other-branch") return fileUntouched ? reference : UNTRACED;
4124
4591
  if (reference.kind === "untraced") return UNTRACED;
4125
4592
  const lines = anchorRange(reference.source);
4126
4593
  return { kind: "traced", current: currentSource(reference, text, traced), linesChanged: lines === null || modifiesLines(reference.hunks, lines) };
@@ -4130,19 +4597,14 @@ function currentSource(reference, text, { source, anchor }) {
4130
4597
  if (current === null || anchorOf(text, current) === null) return null;
4131
4598
  return anchor === void 0 && current !== source ? null : current;
4132
4599
  }
4133
- async function referenceOf(task, text, laterCommits, diffs) {
4600
+ async function referenceOf(task, text, laterCommits, bases) {
4134
4601
  const path = sourcePath(task.source);
4135
4602
  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" };
4603
+ const atBase = () => bases.diffSinceBase(task, path);
4604
+ const afterMark = anchor === void 0 ? [] : laterCommits.toReversed().slice(0, LATER_COMMITS_TO_SEARCH).map((commit) => () => bases.diffFrom(path, commit.sha));
4605
+ const unmatched = unmatchedOn(await bases.baseOf(task));
4144
4606
  let search = { kind: "untraced" };
4145
- for (const diffFromReference of references) {
4607
+ for (const diffFromReference of [atBase, ...afterMark]) {
4146
4608
  const hunks = (await diffFromReference())?.hunks ?? null;
4147
4609
  if (hunks === null) continue;
4148
4610
  const source = anchor === void 0 ? task.source : locateAnchor(baseText(hunks, text), task.source, anchor);
@@ -4151,17 +4613,20 @@ async function referenceOf(task, text, laterCommits, diffs) {
4151
4613
  }
4152
4614
  return search;
4153
4615
  }
4616
+ function unmatchedOn(base) {
4617
+ return markLineOf(base) === "other-branch" ? { kind: "other-branch" } : { kind: "untraced" };
4618
+ }
4154
4619
 
4155
4620
  // src/core/check/project-repo.ts
4156
4621
  async function sourceAnchor(repo, source, onUnreadable) {
4157
- const text = repo === void 0 ? null : await attemptReportingFailure(join12(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4622
+ const text = repo === void 0 ? null : await attemptReportingFailure(join13(repo, sourcePath(source)), readTextIfFile, onUnreadable);
4158
4623
  if (text === null) return { kind: "no-file" };
4159
4624
  const anchor = anchorOf(text, source);
4160
4625
  return anchor === null ? { kind: "uncomputable" } : { kind: "anchor", anchor };
4161
4626
  }
4162
4627
  async function sourcePresence(repo, source, onUnreadable) {
4163
4628
  const path = sourcePath(source);
4164
- const onDisk = await attemptReportingFailure(join12(repo, path), fileExists, onUnreadable);
4629
+ const onDisk = await attemptReportingFailure(join13(repo, path), fileExists, onUnreadable);
4165
4630
  const presentOrUnreadable = onDisk !== false;
4166
4631
  if (presentOrUnreadable) return { kind: "present" };
4167
4632
  const location = await locateRepo(repo);
@@ -4172,20 +4637,154 @@ async function relocatedSource(repo, task) {
4172
4637
  const current = repo === void 0 ? null : await currentSourceIn(repo, task);
4173
4638
  return current === null || current === task.source ? void 0 : current;
4174
4639
  }
4175
- async function findRepo(project, { workingRoots, ...context }) {
4176
- return (await projectCheckout(project, workingRoots, context))?.path;
4640
+ async function projectCheckouts(project, { workingRoots, ...context }) {
4641
+ const repos = await existingRepos(project, context);
4642
+ const cwdRepo = workingRoots === null ? void 0 : repos.find((repo) => realpathOrNull(repo) === workingRoots.main);
4643
+ const others = repos.filter((repo) => repo !== cwdRepo).map((path) => ({ path, linkedWorktree: false, holdsCwd: false }));
4644
+ if (cwdRepo === void 0 || workingRoots === null) return others;
4645
+ return [{ path: workingRoots.worktree, linkedWorktree: workingRoots.worktree !== workingRoots.main, holdsCwd: true }, ...others];
4646
+ }
4647
+ async function explicitSourceRepo(project, lookup, source) {
4648
+ const [choice] = (await sourceChoices(await projectCheckouts(project, lookup), [{ source }])).choices;
4649
+ return choice === void 0 ? void 0 : repoChoice(choice.checkout, choice.settled || choice.checkout.holdsCwd);
4650
+ }
4651
+ async function taskRepo(project, lookup, task, marks) {
4652
+ const [choice] = (await sourceChoices(await projectCheckouts(project, lookup), [ownedSource(task, marks)])).choices;
4653
+ return choice === void 0 ? void 0 : repoChoice(choice.checkout, choice.settled);
4654
+ }
4655
+ async function tasksByCheckout(checkouts, tasks, marks) {
4656
+ const { choices, histories } = await sourceChoices(
4657
+ checkouts,
4658
+ tasks.map((task) => ownedSource(task, marks))
4659
+ );
4660
+ const chosen = tasks.map((task, index) => ({ task, choice: choices[index] }));
4661
+ return checkouts.flatMap((checkout) => {
4662
+ const own = chosen.filter(({ choice }) => choice?.checkout === checkout);
4663
+ const unsettled = new Set(own.filter(({ choice }) => choice?.settled === false).map(({ task }) => task.id));
4664
+ return own.length === 0 ? [] : [{ checkout, tasks: own.map(({ task }) => task), unsettled, history: histories.get(checkout) }];
4665
+ });
4666
+ }
4667
+ function repoChoice({ path }, recordable) {
4668
+ return { path, recordIn: recordable ? path : void 0 };
4669
+ }
4670
+ function ownedSource(task, marks) {
4671
+ return { source: task.source, anchor: task.anchor, ownerCommit: latestRecordedCommit(task, marks) };
4672
+ }
4673
+ async function sourceChoices(checkouts, tasks) {
4674
+ const [first] = checkouts;
4675
+ if (first === void 0) return { choices: tasks.map(() => void 0), histories: /* @__PURE__ */ new Map() };
4676
+ if (checkouts.length === 1) return { choices: tasks.map(() => ({ checkout: first, settled: true })), histories: /* @__PURE__ */ new Map() };
4677
+ const [onDisk, ownerOf] = await Promise.all([Promise.all(tasks.map((task) => checkoutsWithSource(checkouts, task.source))), ownerCheckouts(checkouts, tasks)]);
4678
+ const ownerHistories = await askHistories(
4679
+ checkouts,
4680
+ tasks.flatMap((task, index) => ownerQuestion(task, onDisk[index] ?? [], ownerOf(task)))
4681
+ );
4682
+ const otherHistories = await askHistories(
4683
+ checkouts,
4684
+ tasks.flatMap((task, index) => otherQuestions(checkouts, task, onDisk[index] ?? [], ownerOf(task), ownerHistories))
4685
+ );
4686
+ const histories = mergedHistories(ownerHistories, otherHistories);
4687
+ const choices = await Promise.all(
4688
+ tasks.map((task, index) => {
4689
+ const path = task.source === void 0 ? void 0 : sourcePath(task.source);
4690
+ const traceIn = (checkout) => path === void 0 ? "none" : traceOf(histories, checkout, path);
4691
+ return sourceChoice(checkouts, first, task, { onDisk: onDisk[index] ?? [], owner: ownerOf(task), traceIn });
4692
+ })
4693
+ );
4694
+ return { choices, histories };
4695
+ }
4696
+ async function sourceChoice(checkouts, first, task, evidence2) {
4697
+ if (task.source === void 0) return { checkout: first, settled: true };
4698
+ const path = sourcePath(task.source);
4699
+ const { onDisk, owner, traceIn } = evidence2;
4700
+ if (owner !== void 0 && onDisk.includes(owner)) return { checkout: owner, settled: true };
4701
+ if (owner !== void 0 && traceIn(owner) !== "none") return ownerWithoutFile(owner, path, task, evidence2);
4702
+ const [preferred] = onDisk;
4703
+ if (preferred !== void 0) return anchoredChoice(preferred, onDisk, path, task);
4704
+ const committed = checkouts.filter((checkout) => traceIn(checkout) === "committed");
4705
+ if (committed[0] !== void 0) return { checkout: committed[0], settled: committed.length === 1 };
4706
+ const unknown = checkouts.filter((checkout) => traceIn(checkout) === "unknown");
4707
+ return { checkout: unknown[0] ?? first, settled: unknown.length === 0 };
4708
+ }
4709
+ async function ownerWithoutFile(owner, path, task, { onDisk, traceIn }) {
4710
+ if (onDisk.length === 0) return { checkout: owner, settled: traceIn(owner) === "committed" };
4711
+ const anchored = await anchoredIn(onDisk, path, task);
4712
+ return anchored.length === 1 && anchored[0] !== void 0 ? { checkout: anchored[0], settled: true } : { checkout: owner, settled: false };
4713
+ }
4714
+ async function anchoredChoice(preferred, onDisk, path, task) {
4715
+ if (onDisk.length === 1) return { checkout: preferred, settled: true };
4716
+ const anchored = await anchoredIn(onDisk, path, task);
4717
+ return { checkout: anchored[0] ?? preferred, settled: anchored.length === 1 };
4718
+ }
4719
+ async function anchoredIn(onDisk, path, task) {
4720
+ if (task.anchor === void 0) return [];
4721
+ const texts = await Promise.all(onDisk.map((checkout) => attemptReportingFailure(join13(checkout.path, path), readTextIfFile, unreadableIsLeftToReview)));
4722
+ return onDisk.filter((_, index) => anchorHolds(task, texts[index] ?? null));
4723
+ }
4724
+ async function checkoutsWithSource(checkouts, source) {
4725
+ if (source === void 0) return [];
4726
+ const path = sourcePath(source);
4727
+ const onDisk = await Promise.all(checkouts.map((checkout) => attemptReportingFailure(join13(checkout.path, path), fileExists, unreadableIsLeftToReview)));
4728
+ return checkouts.filter((_, index) => onDisk[index] !== false);
4729
+ }
4730
+ async function ownerCheckouts(checkouts, tasks) {
4731
+ const commits = [...new Set(tasks.flatMap((task) => task.source === void 0 || task.ownerCommit === void 0 ? [] : [task.ownerCommit]))];
4732
+ const found = commits.length === 0 ? [] : await Promise.all(checkouts.map((checkout) => resolveCommits(runGit, checkout.path, commits)));
4733
+ return ({ ownerCommit }) => {
4734
+ if (ownerCommit === void 0) return void 0;
4735
+ const holders = checkouts.filter((_, index) => found[index]?.has(ownerCommit) === true);
4736
+ return holders.length === 1 ? holders[0] : void 0;
4737
+ };
4738
+ }
4739
+ function ownerQuestion(task, onDisk, owner) {
4740
+ return task.source === void 0 || owner === void 0 || onDisk.includes(owner) ? [] : [[owner, sourcePath(task.source)]];
4741
+ }
4742
+ function otherQuestions(checkouts, task, onDisk, owner, ownerHistories) {
4743
+ if (task.source === void 0 || onDisk.length > 0) return [];
4744
+ const path = sourcePath(task.source);
4745
+ if (owner !== void 0 && traceOf(ownerHistories, owner, path) !== "none") return [];
4746
+ return checkouts.filter((checkout) => checkout !== owner).map((checkout) => [checkout, path]);
4177
4747
  }
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 };
4748
+ async function askHistories(checkouts, asked) {
4749
+ const answers = await Promise.all(
4750
+ checkouts.map(async (checkout) => {
4751
+ const paths = new Set(asked.flatMap(([asker, path]) => asker === checkout ? [path] : []));
4752
+ return paths.size === 0 ? [] : [[checkout, { paths, anywhere: await pathsEverCommitted(checkout.path, [...paths]) }]];
4753
+ })
4754
+ );
4755
+ return new Map(answers.flat());
4183
4756
  }
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;
4757
+ function mergedHistories(first, second) {
4758
+ const merged = new Map(first);
4759
+ for (const [checkout, known] of second) {
4760
+ const earlier = merged.get(checkout);
4761
+ merged.set(checkout, earlier === void 0 ? known : { paths: /* @__PURE__ */ new Set([...earlier.paths, ...known.paths]), anywhere: combinedAnswer(earlier.anywhere, known.anywhere) });
4187
4762
  }
4188
- return void 0;
4763
+ return merged;
4764
+ }
4765
+ function combinedAnswer(one, other) {
4766
+ if (one.kind !== "read") return one;
4767
+ if (other.kind !== "read") return other;
4768
+ return { kind: "read", committed: /* @__PURE__ */ new Set([...one.committed, ...other.committed]) };
4769
+ }
4770
+ function traceOf(histories, checkout, path) {
4771
+ const known = histories.get(checkout);
4772
+ if (known?.paths.has(path) !== true) return "none";
4773
+ switch (known.anywhere.kind) {
4774
+ case "no-repo":
4775
+ return "none";
4776
+ case "unreadable":
4777
+ return "unknown";
4778
+ case "read":
4779
+ return committedIn(known.anywhere.committed, path) ? "committed" : "none";
4780
+ }
4781
+ }
4782
+ function unreadableIsLeftToReview() {
4783
+ }
4784
+ async function existingRepos(project, { home: home2, onUnreadable }) {
4785
+ const repos = project.repos.map((path) => expandHome(path, home2));
4786
+ const exists = await Promise.all(repos.map((repo) => attemptReportingFailure(repo, fileExists, onUnreadable)));
4787
+ return repos.filter((_, index) => exists[index] === true);
4189
4788
  }
4190
4789
  async function hasCommit(repo, sha) {
4191
4790
  return await runGit(repo, ["cat-file", "-e", `${sha}^{commit}`]) !== null;
@@ -4193,14 +4792,14 @@ async function hasCommit(repo, sha) {
4193
4792
 
4194
4793
  // src/core/store/create.ts
4195
4794
  import { mkdir as mkdir3 } from "node:fs/promises";
4196
- import { basename as basename6, join as join13 } from "node:path";
4795
+ import { basename as basename5, join as join14 } from "node:path";
4197
4796
  var MAX_ID_ATTEMPTS = 20;
4198
4797
  async function createTask(root, request) {
4199
4798
  const { project, index } = request;
4200
- const dir = join13(root, project.id);
4799
+ const dir = join14(root, project.id);
4201
4800
  for (let attempt = 0; attempt < MAX_ID_ATTEMPTS; attempt++) {
4202
4801
  const id = formatId(project.prefix, await nextTaskNumber(dir, project, request.onError));
4203
- const path = join13(dir, taskFileName(id));
4802
+ const path = join14(dir, taskFileName(id));
4204
4803
  const normalized = taskText(draftTask(id, path, request));
4205
4804
  if (!normalized.ok) return invalid(normalized.problems);
4206
4805
  const { text, task } = normalized.value;
@@ -4233,19 +4832,19 @@ async function createProject(root, repoRoot, existingProjects, onError) {
4233
4832
  }
4234
4833
  }
4235
4834
  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)));
4835
+ const name = basename5(repoRoot);
4836
+ const entries = await listDirFollowingLinks(root);
4837
+ const joinable = await Promise.all(entries.map((entry) => entry.kind === "directory" ? isJoinableProjectDir(join14(root, entry.name), repoRoot) : Promise.resolve(false)));
4239
4838
  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))));
4839
+ const prefixesOnDisk = await Promise.all(entries.filter((entry) => entry.kind === "directory").map((entry) => takenPrefixes(join14(root, entry.name))));
4241
4840
  const prefix = derivePrefix(name, /* @__PURE__ */ new Set([...existingProjects.map((project) => project.prefix), ...prefixesOnDisk.flat()]));
4242
- const dir = join13(root, id);
4841
+ const dir = join14(root, id);
4243
4842
  await mkdir3(dir, { recursive: true });
4244
- return { id, path: join13(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
4843
+ return { id, path: join14(dir, PROJECT_FILE), text: serializeProject({ name, prefix, repos: [repoRoot], active: true, extra: {}, body: "" }) };
4245
4844
  }
4246
4845
  async function isJoinableProjectDir(dir, repoRoot) {
4247
4846
  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;
4847
+ if (entries.some((entry) => entry.name === PROJECT_FILE)) return await projectOfRepo(basename5(dir), join14(dir, PROJECT_FILE), repoRoot) !== null;
4249
4848
  return entries.every((entry) => !entry.name.endsWith(".md"));
4250
4849
  }
4251
4850
  async function projectOfRepo(id, path, repoRoot) {
@@ -4259,7 +4858,7 @@ async function nextTaskNumber(dir, project, onError) {
4259
4858
  return Math.max(onDisk, reserved, journaled, project.issuedUpTo ?? 0) + 1;
4260
4859
  }
4261
4860
  async function maxJournaledNumber(dir, project, onError) {
4262
- const journal = await attemptReportingFailure(join13(dir, JOURNAL_FILE), () => readJournal(dir, project.id), onError);
4861
+ const journal = await attemptReportingFailure(join14(dir, JOURNAL_FILE), () => readJournal(dir, project.id), onError);
4263
4862
  const journaledIds = (journal?.events ?? []).flatMap((event) => parseId(event.task) ?? []);
4264
4863
  return maxNumberWithPrefix(journaledIds, project.prefix);
4265
4864
  }
@@ -4271,7 +4870,7 @@ function maxNumberWithPrefix(ids, prefix) {
4271
4870
  }
4272
4871
  var PREFIX_LINE = /^prefix:\s*["']?([^\s"']+)/m;
4273
4872
  async function takenPrefixes(dir) {
4274
- const declared = PREFIX_LINE.exec(await readTextOrNull(join13(dir, PROJECT_FILE)) ?? "")?.[1];
4873
+ const declared = PREFIX_LINE.exec(await readTextOrNull(join14(dir, PROJECT_FILE)) ?? "")?.[1];
4275
4874
  return [...declared !== void 0 && PREFIX_PATTERN.test(declared) ? [declared] : [], ...(await taskFileIds(dir)).map((parsed) => parsed.prefix)];
4276
4875
  }
4277
4876
  async function taskFileIds(dir) {
@@ -4300,7 +4899,7 @@ function draftTask(id, path, { project, input, now }) {
4300
4899
  }
4301
4900
 
4302
4901
  // src/core/store/resolve-project.ts
4303
- import { basename as basename7, dirname as dirname6, resolve as resolve2 } from "node:path";
4902
+ import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute3, join as join15, resolve as resolve2 } from "node:path";
4304
4903
  var REPO_ROOT_TTL_MS = 6e4;
4305
4904
  var SHOW_ROOTS = ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"];
4306
4905
  var LIST_WORKTREES = ["worktree", "list", "--porcelain"];
@@ -4329,9 +4928,17 @@ function cachedRepoRoots({ onUnreadable, ttlMs = REPO_ROOT_TTL_MS, now = Date.no
4329
4928
  function rootsOf({ topLevel }, worktreeList) {
4330
4929
  return canonicalRoots(topLevel, mainWorktreeIn(worktreeList) ?? topLevel);
4331
4930
  }
4332
- function plainDirRoots(dir) {
4333
- const path = realpathOrNull(dir);
4334
- return path === null ? null : { worktree: path, main: path };
4931
+ function nearestExistingAncestor(path) {
4932
+ const real = realpathOrNull(path);
4933
+ if (real !== null) return { real, missing: [] };
4934
+ const parent = dirname6(path);
4935
+ if (parent === path || !isAbsolute3(path)) return null;
4936
+ const ancestor = nearestExistingAncestor(parent);
4937
+ return ancestor === null ? null : { real: ancestor.real, missing: [...ancestor.missing, basename6(path)] };
4938
+ }
4939
+ function realpathThroughExistingAncestor(path) {
4940
+ const ancestor = nearestExistingAncestor(path);
4941
+ return ancestor === null ? null : join15(ancestor.real, ...ancestor.missing);
4335
4942
  }
4336
4943
  function parseRevParse(dir, output) {
4337
4944
  const [topLevel = "", gitDir = "", commonDir = ""] = (output ?? "").split("\n").map((line) => line.trim());
@@ -4356,11 +4963,24 @@ function readGitRoots(dir, onUnreadable) {
4356
4963
  function repoRootsOf(dirRoots) {
4357
4964
  return typeof dirRoots === "string" ? null : dirRoots;
4358
4965
  }
4966
+ var strictly = (context) => ({ ...context, canonicalize: realpathOrNull });
4359
4967
  function lookupProjectForDir(known, dir, dirRoots, context) {
4968
+ return lookupProjectCanonicalizing(known, dir, dirRoots, strictly(context));
4969
+ }
4970
+ async function lookupProjectForRecordedDir(known, dir, lookupRepoRoot, context) {
4971
+ const dirRoots = await lookupRepoRoot(dir);
4972
+ const byPath = lookupProjectCanonicalizing(known, dir, dirRoots, { ...context, canonicalize: realpathThroughExistingAncestor });
4973
+ if ("project" in byPath || byPath.broken.length > 0 || dirRoots !== "not-in-repo") return byPath;
4974
+ const ancestor = attemptReportingFailureSync(dir, nearestExistingAncestor, context.onUnreadable);
4975
+ if (ancestor === null || ancestor.missing.length === 0) return byPath;
4976
+ const ancestorRoots = await lookupRepoRoot(ancestor.real);
4977
+ return typeof ancestorRoots === "string" ? byPath : lookupProjectForDir(known, ancestor.real, ancestorRoots, context);
4978
+ }
4979
+ function lookupProjectCanonicalizing(known, dir, dirRoots, context) {
4360
4980
  const roots = matchingRoots(dir, dirRoots, context);
4361
4981
  if (roots === null) return { broken: [] };
4362
4982
  const repo = repoRootsOf(dirRoots);
4363
- return lookupProject(known, { roots, repoDirName: repo === null ? void 0 : projectIdBase(basename7(repo.main)) }, context);
4983
+ return lookupProject(known, { roots, repoDirName: repo === null ? void 0 : projectIdBase(basename6(repo.main)) }, context);
4364
4984
  }
4365
4985
  function lookupProject({ projects, errors }, { roots, repoDirName }, context) {
4366
4986
  const coveredLength = (repos) => closestCoveringRepo(repos, roots, context)?.length ?? 0;
@@ -4374,9 +4994,11 @@ function lookupProject({ projects, errors }, { roots, repoDirName }, context) {
4374
4994
  if (project !== void 0 && covering.every(({ length }) => length <= projectLength)) return { project };
4375
4995
  return { broken: covering.map(({ error }) => error) };
4376
4996
  }
4377
- function matchingRoots(dir, dirRoots, context) {
4997
+ function matchingRoots(dir, dirRoots, { canonicalize, onUnreadable }) {
4378
4998
  if (dirRoots === "unreadable") return null;
4379
- return dirRoots === "not-in-repo" ? attemptReportingFailureSync(dir, plainDirRoots, context.onUnreadable) : dirRoots;
4999
+ if (dirRoots !== "not-in-repo") return dirRoots;
5000
+ const path = attemptReportingFailureSync(dir, canonicalize, onUnreadable);
5001
+ return path === null ? null : { worktree: path, main: path };
4380
5002
  }
4381
5003
  function findProjectForRoots(projects, roots, context) {
4382
5004
  const matches = projects.flatMap((project) => {
@@ -4386,7 +5008,7 @@ function findProjectForRoots(projects, roots, context) {
4386
5008
  return matches.sort((a, b) => b.repoPath.length - a.repoPath.length || Number(b.project.active) - Number(a.project.active))[0]?.project;
4387
5009
  }
4388
5010
  function pathFromProjectRepo(project, roots, context, path) {
4389
- const repoPath = closestCoveringRepo(project.repos, roots, context);
5011
+ const repoPath = closestCoveringRepo(project.repos, roots, strictly(context));
4390
5012
  if (repoPath === void 0) return null;
4391
5013
  const enclosingRootsOf = (dir) => repoRootsOf(readGitRoots(dirname6(dir), context.onUnreadable));
4392
5014
  return relativeInside(repoPath, asInProjectRepoCheckout(path, roots, { repoPath, enclosingRootsOf }));
@@ -4416,8 +5038,9 @@ function repoCovers(repoPath, { worktree, main }) {
4416
5038
  function isSameOrInside(path, container) {
4417
5039
  return relativeInside(container, path) !== null;
4418
5040
  }
4419
- function resolvedRepo(repo, { home: home2, onUnreadable }) {
4420
- return attemptReportingFailureSync(expandHome(repo, home2), realpathOrNull, onUnreadable);
5041
+ function resolvedRepo(repo, { home: home2, onUnreadable, canonicalize }) {
5042
+ const path = expandHome(repo, home2);
5043
+ return isAbsolute3(path) ? attemptReportingFailureSync(path, canonicalize, onUnreadable) : null;
4421
5044
  }
4422
5045
 
4423
5046
  // src/cli/lookups.ts
@@ -4480,7 +5103,7 @@ function findTaskOrWarn(loaded, io, id) {
4480
5103
  function missingTaskMessage(loaded, io, id) {
4481
5104
  if (!ID_PATTERN.test(id)) return io.cli.taskNotFound(id);
4482
5105
  const fileName = taskFileName(id);
4483
- const broken = loaded.errors.find((error) => basename8(error.path) === fileName);
5106
+ const broken = loaded.errors.find((error) => basename7(error.path) === fileName);
4484
5107
  if (broken) return io.cli.taskFileUnparsed(id, io.core.problems(broken.problems));
4485
5108
  const hidingProject = unparsedProjectFiles(loaded.errors).find((error) => error.hiddenTasks.includes(id));
4486
5109
  return hidingProject ? io.cli.taskOfUnparsedProject(id, hidingProject.path, io.core.problems(hidingProject.problems)) : io.cli.taskNotFound(id);
@@ -4533,8 +5156,8 @@ async function ensureProject(loaded, io, explicitId) {
4533
5156
  // src/cli/task-write.ts
4534
5157
  function taskWriter(io, index) {
4535
5158
  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 });
5159
+ return async (task, changes, details = {}) => {
5160
+ const result = await updateTaskInIndex(index, { id: task.id, changes, expectedVersion: task.version, now: io.now(), via: "cli", onError, ...details });
4538
5161
  if (!result.ok) return { ok: false, exitCode: reportUpdateFailure(io, task.id, result) };
4539
5162
  if (result.reopenedEpic !== void 0) io.warn(io.cli.epicReopened(result.reopenedEpic.id));
4540
5163
  return result;
@@ -4600,7 +5223,7 @@ var categoryCommand = taskFieldCommand({
4600
5223
  });
4601
5224
 
4602
5225
  // src/core/check/check-backlog.ts
4603
- import { join as join17 } from "node:path";
5226
+ import { join as join19 } from "node:path";
4604
5227
 
4605
5228
  // src/core/check/check-fixes.ts
4606
5229
  async function applyFixes(loaded, inScope, { messages, ...writes }) {
@@ -4668,390 +5291,153 @@ function goneReferences(task, isGone) {
4668
5291
  }
4669
5292
  function goneTaskCheck({ projects }, index) {
4670
5293
  const loadedPrefixes = new Set(projects.map((project) => project.prefix));
4671
- return (id) => {
4672
- const prefix = parseId(id)?.prefix;
4673
- 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;
5294
+ return (id) => {
5295
+ const prefix = parseId(id)?.prefix;
5296
+ return prefix !== void 0 && loadedPrefixes.has(prefix) && !index.byId.has(id) && !index.notLoaded.has(id);
5297
+ };
4977
5298
  }
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));
5299
+
5300
+ // src/core/check/find-problems.ts
5301
+ function findProblems(loaded, projects, repos, inScope) {
5302
+ const index = indexOfLoaded(loaded);
5303
+ const integrity = loaded.tasks.filter((task) => inScope(task.projectId)).flatMap((task) => integrityErrors(task, index).map((problem3) => ({ kind: "task-invalid", taskId: task.id, problem: problem3 })));
5304
+ const missingRepos = projects.filter((project) => repos.get(project.id) === void 0).map(missingRepoProblem);
5305
+ return [...parseProblems(loaded, inScope), ...integrity, ...missingRepos, ...sharedPrefixes(loaded.projects, inScope)];
4981
5306
  }
4982
- function sameBlobs(change, copy) {
4983
- return change?.preimage === copy?.preimage && change?.postimage === copy?.postimage;
5307
+ function sharedPrefixes(projects, inScope) {
5308
+ const idsByPrefix = /* @__PURE__ */ new Map();
5309
+ for (const project of projects) idsByPrefix.set(project.prefix, [...idsByPrefix.get(project.prefix) ?? [], project.id]);
5310
+ return [...idsByPrefix].filter(([, projectIds]) => projectIds.length > 1 && projectIds.some(inScope)).map(([prefix, projectIds]) => ({ kind: "prefix-shared", prefix, projectIds }));
4984
5311
  }
4985
- function samePreimage(change, copy) {
4986
- return change.blobs !== void 0 && change.blobs.preimage === copy.blobs?.preimage;
5312
+ function parseProblems(loaded, inScope) {
5313
+ const waitingEpicIds = planEpicClosing(loaded.tasks, loaded.errors).waiting.filter(({ epic }) => inScope(epic.projectId)).map(({ epic }) => epic.id);
5314
+ const everyFileMayHoldWaitingChild = waitingEpicIds.length > 0;
5315
+ const reported = loaded.errors.filter((error) => everyFileMayHoldWaitingChild || concernsScope(error, inScope)).map((error) => ({ kind: "file-not-parsed", path: error.path, problems: error.problems }));
5316
+ if (waitingEpicIds.length === 0) return reported;
5317
+ return [...reported, { kind: "epics-wait-for-files", epicIds: waitingEpicIds }];
4987
5318
  }
4988
- function editsNeeded(change, copy) {
4989
- return change.changeStarts.length > 0 && !samePreimage(change, copy);
5319
+ function concernsScope(error, inScope) {
5320
+ return inScope(error.projectId) || isProjectFileError(error);
4990
5321
  }
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));
5322
+ function missingRepoProblem(project) {
5323
+ return project.repos.length === 0 ? { kind: "project-without-repos", projectId: project.id } : { kind: "project-repos-missing", projectId: project.id, repos: project.repos };
4994
5324
  }
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;
5325
+
5326
+ // src/core/check/project-review.ts
5327
+ import { join as join18 } from "node:path";
5328
+
5329
+ // src/core/code-review-graph/graph-db.ts
5330
+ import { existsSync, realpathSync as realpathSync2 } from "node:fs";
5331
+ import { join as join16 } from "node:path";
5332
+ var SYMBOL_KINDS = ["Class", "Function", "Type", "Test"];
5333
+ var GRAPH_FILE = join16(".code-review-graph", "graph.db");
5334
+ var SUPPORTED_SCHEMA = "13";
5335
+ function hasCodeGraph(repo) {
5336
+ return existsSync(join16(repo, GRAPH_FILE));
4999
5337
  }
5000
- function placeOf({ line, insertion }) {
5001
- return insertion ? { firstLine: line - 1, lineCount: INSERTION_NEIGHBOURS } : { firstLine: line, lineCount: 1 };
5338
+ function openCodeGraph(repo) {
5339
+ let db = null;
5340
+ try {
5341
+ const { DatabaseSync: SqliteDatabase } = process.getBuiltinModule("node:sqlite");
5342
+ db = new SqliteDatabase(join16(repo, GRAPH_FILE), { readOnly: true });
5343
+ const meta = readMetadata(db);
5344
+ const root = meta.get("repo_root");
5345
+ if (meta.get("schema_version") !== SUPPORTED_SCHEMA || root === void 0 || realpathSync2(root) !== realpathSync2(repo)) {
5346
+ db.close();
5347
+ return null;
5348
+ }
5349
+ return codeGraph(db, root);
5350
+ } catch (error) {
5351
+ closeIfOpen(db);
5352
+ if (isEnvironmentFailure(error)) return null;
5353
+ throw error;
5354
+ }
5002
5355
  }
5003
- function spansOverlap(edit, place) {
5004
- return edit.firstLine < lineAfter(place) && place.firstLine < lineAfter(edit);
5356
+ function readMetadata(db) {
5357
+ const rows = db.prepare("select key, value from metadata").all();
5358
+ return new Map(rows.map((row) => [row.key, row.value]));
5005
5359
  }
5006
- function lineAfter({ firstLine, lineCount }) {
5007
- return firstLine + lineCount;
5360
+ function codeGraph(db, repo) {
5361
+ const fileNode = db.prepare("select file_hash from nodes where kind = 'File' and file_path = ?");
5362
+ const enclosing = db.prepare(
5363
+ "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"
5364
+ );
5365
+ const fileState = (path, fileHash2) => {
5366
+ const row = ask(fileNode, (statement) => statement.get(join16(repo, path)), void 0);
5367
+ if (row === void 0) return "absent";
5368
+ return row.file_hash === fileHash2 ? "fresh" : "changed";
5369
+ };
5370
+ return {
5371
+ fileState,
5372
+ symbolAt(path, line, fileHash2) {
5373
+ if (fileState(path, fileHash2) !== "fresh") return null;
5374
+ const file = join16(repo, path);
5375
+ const row = ask(enclosing, (statement) => statement.get(file, line, line), void 0);
5376
+ return row === void 0 ? null : { qualifiedName: row.qualified_name, kind: symbolKindOf(row.kind), from: row.line_start, to: row.line_end };
5377
+ },
5378
+ close() {
5379
+ closeIfOpen(db);
5380
+ }
5381
+ };
5008
5382
  }
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 }];
5383
+ function symbolKindOf(stored) {
5384
+ return SYMBOL_KINDS.find((kind) => kind === stored) ?? "other";
5012
5385
  }
5013
- function shiftedLine(line, edits) {
5014
- return edits.reduce((shifted, edit) => lineAfter(edit) <= line ? shifted + edit.delta : shifted, line);
5386
+ function ask(statement, run, fallback) {
5387
+ try {
5388
+ return run(statement);
5389
+ } catch (error) {
5390
+ if (isEnvironmentFailure(error)) return fallback;
5391
+ throw error;
5392
+ }
5015
5393
  }
5016
- function parentOf(commit) {
5017
- return `${commit}^`;
5394
+ function isEnvironmentFailure(error) {
5395
+ return typeof errorCode(error) === "string";
5018
5396
  }
5019
- function fileVersion({ mode = "", object = "", path = "" } = {}) {
5020
- return { path, version: `${mode} ${object}\0${path}` };
5397
+ function closeIfOpen(db) {
5398
+ try {
5399
+ db?.close();
5400
+ } catch (error) {
5401
+ if (!hasErrorCode(error, "ERR_INVALID_STATE")) throw error;
5402
+ }
5021
5403
  }
5022
5404
 
5023
5405
  // src/core/check/known-commits.ts
5024
5406
  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);
5407
+ async function commitsKnownAtMark({ repo, tasks, facts, anchors, git = runGit, bases }) {
5408
+ const asked = await Promise.all(
5409
+ tasks.map(async (task) => {
5410
+ if (task.source === void 0 || !judgedByCommits(task, anchors)) return [];
5411
+ const path = sourcePath(task.source);
5412
+ const changes = commitsTouchingSince(facts.commits, path, reviewMark(task));
5413
+ const commit = changes.length === 0 ? null : await bases.markCommit(task);
5414
+ return commit === null ? [] : [{ taskId: task.id, site: { commit, path }, changes }];
5415
+ })
5416
+ );
5417
+ const questions = asked.flat();
5418
+ const copies = markCopies(repo, git);
5033
5419
  const answers = await Promise.all(
5034
5420
  questions.map(async ({ taskId, site, changes }) => {
5035
- const known = await Promise.all(changes.map(async (commit) => await isKnownAtCreation(copies, commit, site) ? [commit.sha] : []));
5421
+ const known = await Promise.all(changes.map(async (commit) => await isKnownAtMark(copies, commit, site) ? [commit.sha] : []));
5036
5422
  return { taskId, known: known.flat() };
5037
5423
  })
5038
5424
  );
5039
5425
  return new Map(answers.filter(({ known }) => known.length > 0).map(({ taskId, known }) => [taskId, new Set(known)]));
5040
5426
  }
5041
- function creationCopies(repo, git) {
5427
+ function markCopies(repo, git) {
5042
5428
  const carryingContent = commitsCarryingContent(repo, git, FACTS_HISTORY_OPTIONS);
5043
5429
  const branchCommitsByMerge = /* @__PURE__ */ new Map();
5044
- const copiesByCreation = /* @__PURE__ */ new Map();
5430
+ const copiesByMark = /* @__PURE__ */ new Map();
5045
5431
  return {
5046
5432
  broughtByMerge: (merge, { commit, path }) => remembered(
5047
5433
  branchCommitsByMerge,
5048
5434
  `${merge.sha} ${commit} ${path}`,
5049
5435
  async () => outputLines(await git(repo, ["rev-list", `${merge.sha}^2`, `^${merge.sha}^1`, `^${commit}`, "--", ...literalPathspecs([path])]))
5050
5436
  ),
5051
- copiesOf: ({ commit, path }) => remembered(copiesByCreation, `${commit} ${path}`, async () => new Set(await carryingContent(commit, literalPathspecs([path]))))
5437
+ copiesOf: ({ commit, path }) => remembered(copiesByMark, `${commit} ${path}`, async () => new Set(await carryingContent(commit, literalPathspecs([path]))))
5052
5438
  };
5053
5439
  }
5054
- async function isKnownAtCreation(copies, commit, site) {
5440
+ async function isKnownAtMark(copies, commit, site) {
5055
5441
  if (commit.parents.length !== MERGE_PARENTS) return (await copies.copiesOf(site)).has(commit.sha);
5056
5442
  const brought = await copies.broughtByMerge(commit, site);
5057
5443
  if (brought === null) return false;
@@ -5062,31 +5448,43 @@ async function isKnownAtCreation(copies, commit, site) {
5062
5448
 
5063
5449
  // src/core/check/late-commits.ts
5064
5450
  var NO_LATE_COMMITS = /* @__PURE__ */ new Map();
5451
+ var NO_LATE_ARRIVALS = { late: NO_LATE_COMMITS, unknown: /* @__PURE__ */ new Set() };
5065
5452
  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)
5453
+ if (question.facts.history !== "read") return NO_LATE_ARRIVALS;
5454
+ const { repo, git = runGitOutcome, bases = taskBases(repo, question.marks, git) } = question;
5455
+ const history = { repo, git: asGitRunner(git), bases };
5456
+ const arrivals = await arrivalsOf(history, await markedSources(question, bases));
5457
+ return {
5458
+ late: new Map(arrivals.flatMap(({ taskId, commits }) => commits === null ? [] : [[taskId, commits]])),
5459
+ unknown: new Set(arrivals.filter(({ commits }) => commits === null).map(({ taskId }) => taskId))
5460
+ };
5461
+ }
5462
+ async function arrivalsOf(history, marked) {
5463
+ const edited = await editedSinceMarkCommit(history, marked);
5464
+ if (edited === null) return marked.map(({ task }) => ({ taskId: task.id, commits: null }));
5465
+ const judged = await Promise.all(edited.map(async (source) => ({ source, base: await history.bases.baseOf(source.task) })));
5466
+ const unknown = judged.flatMap(({ source, base }) => base.kind === "unknown" ? [{ taskId: source.task.id, commits: null }] : []);
5467
+ const onLine = judged.flatMap(({ source, base }) => base.kind === "exact" ? [source] : []);
5468
+ const markCommits = [...new Set(onLine.map(({ markCommit }) => markCommit))];
5469
+ const byMarkCommit = await Promise.all(
5470
+ markCommits.map(
5471
+ (markCommit) => arrivedAfter(
5472
+ history,
5473
+ markCommit,
5474
+ onLine.filter((source) => source.markCommit === markCommit)
5076
5475
  )
5077
5476
  )
5078
5477
  );
5079
- return new Map(late.flat());
5478
+ return [...unknown, ...byMarkCommit.flat()];
5080
5479
  }
5081
- async function markedSources({ repo, tasks, facts, anchors, origins, knownCommits }) {
5082
- const headCommitAt = headCommitsAt(repo);
5480
+ async function markedSources({ tasks, facts, anchors, knownCommits }, bases) {
5083
5481
  const sourcesByTask = await Promise.all(
5084
5482
  tasks.map(async (task) => {
5085
5483
  if (task.source === void 0 || !judgedByCommits(task, anchors)) return [];
5086
5484
  const path = sourcePath(task.source);
5087
5485
  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 }];
5486
+ const markCommit = await bases.markCommit(task);
5487
+ return markCommit === null ? [] : [{ task, path, mark: reviewMark(task), markCommit }];
5090
5488
  })
5091
5489
  );
5092
5490
  return sourcesByTask.flat();
@@ -5095,25 +5493,23 @@ function changedByDate(task, path, facts, knownCommits) {
5095
5493
  const { commits, uncommitted } = changesSinceMark({ facts, late: NO_LATE_COMMITS }, task, path);
5096
5494
  return uncommitted || commits.some((commit) => knownCommits.get(task.id)?.has(commit.sha) !== true);
5097
5495
  }
5098
- async function editedSinceCheckout(repo, sources) {
5099
- const objects = ({ checkout, path }) => ({ commit: `${checkout}^{commit}`, atCheckout: `${checkout}^{commit}:./${path}`, atHead: `HEAD:./${path}` });
5496
+ async function editedSinceMarkCommit({ repo, git }, sources) {
5497
+ const objects = ({ markCommit, path }) => ({ commit: `${markCommit}^{commit}`, atMark: `${markCommit}^{commit}:./${path}`, atHead: `HEAD:./${path}` });
5100
5498
  const ids = await objectIds(
5101
- runGit,
5499
+ git,
5102
5500
  repo,
5103
5501
  sources.flatMap((source) => Object.values(objects(source)))
5104
5502
  );
5105
- if (ids === null) return [];
5503
+ if (ids === null) return null;
5106
5504
  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 }];
5505
+ const { commit, atMark, atHead } = objects(source);
5506
+ const markCommit = commitHashOf(ids.get(commit) ?? null);
5507
+ return markCommit === null || ids.get(atMark) === ids.get(atHead) ? [] : [{ ...source, markCommit }];
5110
5508
  });
5111
5509
  }
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)]);
5510
+ async function arrivedAfter({ repo, git }, markCommit, sources) {
5511
+ const arrived = await mainlineCommitsOff(repo, markCommit, [...new Set(sources.map(({ path }) => path))], git);
5512
+ return sources.map(({ task, path, mark }) => ({ taskId: task.id, commits: arrived === null ? null : commitsTouchingUntil(arrived, path, mark) }));
5117
5513
  }
5118
5514
 
5119
5515
  // src/core/model/query.ts
@@ -5292,28 +5688,26 @@ function bothConfirmedAfterCreation(a, b) {
5292
5688
  }
5293
5689
 
5294
5690
  // src/core/check/awaiting-merge.ts
5295
- var NOT_AN_ANCESTOR_EXIT = 1;
5296
5691
  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 }];
5692
+ async function awaitingMerge({ repo, tasks, marks, git = runGitOutcome, bases = taskBases(repo, marks, git) }) {
5693
+ const branched = tasks.flatMap((task) => {
5694
+ const branch = marks.origins.get(task.id)?.branch;
5695
+ const recordedCommit = latestRecordedCommit(task, marks);
5696
+ return branch === void 0 || recordedCommit === void 0 ? [] : [{ id: task.id, recordedCommit, branch }];
5301
5697
  });
5302
5698
  if (branched.length === 0) return { pending: /* @__PURE__ */ new Set(), unknownBranches: [] };
5303
5699
  const current = lineOf(await git(repo, ["rev-parse", "--abbrev-ref", "HEAD"]));
5304
5700
  const branchStates = /* @__PURE__ */ new Map();
5305
- let completenessLookup;
5306
- const cloneCompleteness = () => completenessLookup ??= cloneCompletenessOf(repo, git);
5307
5701
  const nested = await Promise.all(
5308
- branched.map(async ({ id, commit, branch }) => {
5702
+ branched.map(async ({ id, recordedCommit, branch }) => {
5309
5703
  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 [];
5704
+ const ancestry = await bases.ancestry(recordedCommit);
5705
+ if (ancestry === "unknown") return [{ id, branch, state: "unknown" }];
5706
+ if (ancestry === "ancestor") return [];
5707
+ const recordedCommitMissing = ancestry === "missing";
5708
+ if (recordedCommitMissing && await bases.cloneCompleteness() === "full") return [];
5315
5709
  const state = await remembered(branchStates, branch, () => branchState(repo, branch, git));
5316
- const pendingOnlyIfShallow = creationCommitUnreadable && state === "pending" && await cloneCompleteness() === "unknown";
5710
+ const pendingOnlyIfShallow = recordedCommitMissing && state === "pending" && await bases.cloneCompleteness() === "unknown";
5317
5711
  return [{ id, branch, state: pendingOnlyIfShallow ? "unknown" : state }];
5318
5712
  })
5319
5713
  );
@@ -5328,22 +5722,16 @@ async function branchState(repo, branch, git) {
5328
5722
  if (tip !== null) return landingState(repo, tip, asGitRunner(git));
5329
5723
  return lookup.status === "exited" && lookup.exitCode === NO_SUCH_REF_EXIT ? "deleted" : "unknown";
5330
5724
  }
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
5725
  function lineOf(outcome) {
5338
5726
  return outputLine(stdoutOf(outcome));
5339
5727
  }
5340
5728
 
5341
5729
  // src/core/check/symbol-filter.ts
5342
5730
  import { createHash as createHash3 } from "node:crypto";
5343
- import { join as join15 } from "node:path";
5731
+ import { join as join17 } from "node:path";
5344
5732
  function fileHashes(repo, onUnreadable) {
5345
5733
  const hashes = /* @__PURE__ */ new Map();
5346
- return (path) => remembered(hashes, path, () => fileHash(join15(repo, path), onUnreadable));
5734
+ return (path) => remembered(hashes, path, () => fileHash(join17(repo, path), onUnreadable));
5347
5735
  }
5348
5736
  function symbolLookup(graph, hashOf) {
5349
5737
  if (graph === null) return () => null;
@@ -5401,62 +5789,109 @@ function overlaps(range, watched) {
5401
5789
 
5402
5790
  // src/core/check/project-review.ts
5403
5791
  var PROBLEM_LIMIT = 400;
5404
- async function creationOrigins(root, projectId, onJournalUnreadable) {
5405
- const journal = await readJournal(join16(root, projectId), projectId).catch((error) => {
5792
+ async function readMarkCommits(root, projectId, onJournalUnreadable) {
5793
+ const journal = await readJournal(join18(root, projectId), projectId).catch((error) => {
5406
5794
  onJournalUnreadable(error);
5407
5795
  return null;
5408
5796
  });
5409
- return new Map((journal?.events ?? []).flatMap((event) => event.kind === "created" && event.origin !== void 0 ? [[event.task, event.origin]] : []));
5797
+ return markCommitsIn(journal?.events ?? []);
5410
5798
  }
5411
- async function projectReview(project, allTasks, { repo, origins, mode, onUnreadable }) {
5799
+ async function projectReview(project, allTasks, { checkouts, git = runGitOutcome, ...scope }) {
5412
5800
  const tasks = allTasks.filter((task) => task.projectId === project.id && isReviewable(task));
5413
5801
  const nothing = { projectId: project.id, candidates: [], filtered: [], plans: [], problems: [], unchecked: [], awaitingMerge: [], skipped: [] };
5414
5802
  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);
5803
+ if (checkouts.length === 0)
5804
+ return { ...nothing, candidates: scope.mode === "full" ? duplicateCandidates(tasks) : [], unchecked: [...evidenceOf(tasks, "source-changed"), ...evidenceOf(tasks, "source-missing")] };
5805
+ const reviews = await Promise.all(
5806
+ (await tasksByCheckout(checkouts, tasks, scope.marks)).map(async ({ checkout, tasks: own, unsettled, history }) => {
5807
+ const review = await repoReview(project, own, { ...scope, repo: checkout.path, git, history });
5808
+ return { ...review, plans: checkout.linkedWorktree ? [] : review.plans.filter((plan) => !unsettled.has(plan.id)) };
5809
+ })
5810
+ );
5811
+ const skipped = new Set(reviews.flatMap((review) => review.skipped));
5812
+ const symbols = new Map(reviews.flatMap((review) => [...review.symbols]));
5813
+ const duplicates = scope.mode === "full" ? duplicateCandidates(tasks, (task) => symbols.get(task.id) ?? null).filter((candidate) => !skipped.has(candidate.task.id)) : [];
5814
+ return {
5815
+ projectId: project.id,
5816
+ candidates: [...reviews.flatMap((review) => review.candidates), ...duplicates],
5817
+ filtered: reviews.flatMap((review) => review.filtered),
5818
+ plans: reviews.flatMap((review) => review.plans),
5819
+ problems: reviews.flatMap((review) => review.problems),
5820
+ unchecked: reviews.flatMap((review) => review.unchecked),
5821
+ awaitingMerge: reviews.flatMap((review) => review.awaitingMerge),
5822
+ skipped: [...skipped]
5823
+ };
5824
+ }
5825
+ async function repoReview(project, tasks, scope) {
5826
+ const { repo, marks, mode, onUnreadable, git } = scope;
5827
+ const facts = await collectRepoFacts(repo, earliestMarks(tasks), scope.history, git);
5828
+ for (const [path, error] of facts.unreadable) onUnreadable(join18(repo, path), error);
5418
5829
  const skipped = new Set(tasks.filter((task) => task.source !== void 0 && facts.unreadable.has(sourcePath(task.source))).map((task) => task.id));
5419
5830
  const readable = tasks.filter((task) => !skipped.has(task.id));
5420
5831
  const graph = openCodeGraph(repo);
5421
5832
  try {
5422
5833
  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) };
5834
+ const bases = taskBases(repo, marks, git);
5835
+ const question = { repo, tasks: readable, facts, anchors, marks, bases };
5836
+ const knownCommits = await commitsKnownAtMark({ ...question, git: asGitRunner(git) });
5837
+ const { late, unknown: lateUnknown } = await commitsArrivedLate({ ...question, knownCommits, git });
5838
+ const repoScope = { ...scope, facts, late, graph, bases };
5839
+ const review = await withRenamesFollowed(codeReview(readable, { facts, late }, knownCommits, anchors), readable, repoScope);
5840
+ const context = await projectContext(readable, review, repoScope);
5841
+ const sighted = await sightedBySymbol(review, context);
5842
+ const { problems: mergeProblems, ...judged } = await judgedAgainstMerges(sighted, context, { repo, marks, projectId: project.id, git, bases });
5843
+ return {
5844
+ ...judged,
5845
+ skipped: [...skipped],
5846
+ problems: [...historyProblems(project, repo, facts), ...mergeProblems],
5847
+ unchecked: uncheckedEvidence(tasks, anchors, facts, lateUnknown),
5848
+ symbols: mode === "full" ? repoSymbolNames(repo, readable, context) : /* @__PURE__ */ new Map()
5849
+ };
5432
5850
  } finally {
5433
5851
  graph?.close();
5434
5852
  }
5435
5853
  }
5436
- async function projectContext(tasks, review, { repo, facts, late, origins, mode, onUnreadable, graph }) {
5437
- const diffs = repoDiffs(repo, origins);
5854
+ function repoSymbolNames(repo, tasks, { symbolAt, located }) {
5855
+ const symbolOf = symbolNames(symbolAt, located);
5856
+ return new Map(
5857
+ tasks.map((task) => {
5858
+ const name = symbolOf(task);
5859
+ return [task.id, name === null ? null : `${repo}\0${name}`];
5860
+ })
5861
+ );
5862
+ }
5863
+ async function projectContext(tasks, review, { repo, facts, late, mode, onUnreadable, graph, bases }) {
5438
5864
  const symbolAt = symbolLookup(graph, fileHashes(repo, onUnreadable));
5439
5865
  const changedIds = new Set(review.candidates.flatMap((candidate) => candidate.kind === "source-changed" ? [candidate.task.id] : []));
5440
5866
  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 };
5867
+ const traces = await traceSources(locating, { facts, late }, bases);
5868
+ return { tasksById: new Map(tasks.map((task) => [task.id, task])), located: currentSourcesOf(traces), traces, facts, diffOf: bases.diffSinceBase, bases, symbolAt };
5443
5869
  }
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)) : [];
5870
+ async function sightedBySymbol(review, context) {
5446
5871
  const byLines = judgedByLines(review.candidates, context.traces);
5447
5872
  const { kept, filtered } = await filterBySymbol(byLines.kept, context);
5873
+ const relocatable = [...filtered.map((sighting) => sighting.task), ...byLines.linesIntact];
5874
+ const markedOffThisLine = await unanchoredMarkedOffThisLine(
5875
+ review.plans.map((plan) => plan.id),
5876
+ context
5877
+ );
5448
5878
  const settlement = {
5449
- untouchable: /* @__PURE__ */ new Set([...kept.map((candidate) => candidate.task.id), ...byLines.notOnBranch]),
5450
- relocatable: [...filtered.map((sighting) => sighting.task), ...byLines.linesIntact]
5879
+ untouchable: /* @__PURE__ */ new Set([...kept.map((candidate) => candidate.task.id), ...byLines.onOtherBranch, ...markedOffThisLine]),
5880
+ relocatable
5451
5881
  };
5452
- return { kept, filtered, plans: settledPlans(review.plans, settlement, context), duplicates };
5882
+ return { kept, filtered, plans: settledPlans(review.plans, settlement, context) };
5883
+ }
5884
+ async function unanchoredMarkedOffThisLine(ids, { tasksById, bases }) {
5885
+ const unanchored = tasksOf([...new Set(ids)], tasksById).filter((task) => task.anchor === void 0);
5886
+ const lines = await Promise.all(unanchored.map(async (task) => ({ id: task.id, line: markLineOf(await bases.baseOf(task)) })));
5887
+ return new Set(lines.filter(({ line }) => line !== "this-line").map(({ id }) => id));
5453
5888
  }
5454
- async function judgedAgainstMerges(sighted, context, { repo, origins, projectId }) {
5455
- const { pending, unknownBranches: unknownBranches2 } = await awaitingMerge({ repo, taskIds: involvedTaskIds(sighted), origins });
5889
+ async function judgedAgainstMerges(sighted, context, { repo, marks, projectId, git, bases }) {
5890
+ const { pending, unknownBranches: unknownBranches2 } = await awaitingMerge({ repo, tasks: tasksOf(involvedTaskIds(sighted), context.tasksById), marks, git, bases });
5456
5891
  const judged = (id) => !pending.has(id);
5457
5892
  const code = await Promise.all(sighted.kept.filter((candidate) => judged(candidate.task.id)).map((candidate) => withContext2(candidate, context)));
5458
5893
  return {
5459
- candidates: [...code, ...sighted.duplicates],
5894
+ candidates: code,
5460
5895
  filtered: sighted.filtered.filter((sighting) => judged(sighting.task)),
5461
5896
  plans: sighted.plans.filter((plan) => judged(plan.id)),
5462
5897
  awaitingMerge: [...pending],
@@ -5464,10 +5899,10 @@ async function judgedAgainstMerges(sighted, context, { repo, origins, projectId
5464
5899
  };
5465
5900
  }
5466
5901
  function judgedByLines(candidates, traces) {
5467
- const judgement = { kept: [], linesIntact: [], notOnBranch: [] };
5902
+ const judgement = { kept: [], linesIntact: [], onOtherBranch: [] };
5468
5903
  for (const candidate of candidates) {
5469
5904
  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);
5905
+ if (trace?.kind === "other-branch") judgement.onOtherBranch.push(candidate.task.id);
5471
5906
  else if (trace?.kind === "traced" && !trace.linesChanged) judgement.linesIntact.push(candidate.task.id);
5472
5907
  else judgement.kept.push(candidate);
5473
5908
  }
@@ -5479,7 +5914,7 @@ async function withRenamesFollowed(review, tasks, { repo, onUnreadable }) {
5479
5914
  review.candidates.map(async (candidate) => {
5480
5915
  const task = tasksById.get(candidate.task.id);
5481
5916
  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);
5917
+ const text = await attemptReportingFailure(join18(repo, candidate.renamedTo), readTextIfFile, onUnreadable);
5483
5918
  return text === null ? null : renamePlan(task, candidate.renamedTo, text);
5484
5919
  })
5485
5920
  );
@@ -5488,11 +5923,14 @@ async function withRenamesFollowed(review, tasks, { repo, onUnreadable }) {
5488
5923
  plans: [...review.plans, ...renamePlans.filter((plan) => plan !== null)]
5489
5924
  };
5490
5925
  }
5926
+ function tasksOf(ids, tasksById) {
5927
+ return ids.flatMap((id) => tasksById.get(id) ?? []);
5928
+ }
5491
5929
  function involvedTaskIds({ kept, filtered, plans }) {
5492
5930
  return [.../* @__PURE__ */ new Set([...kept.map((candidate) => candidate.task.id), ...filtered.map((sighting) => sighting.task), ...plans.map((plan) => plan.id)])];
5493
5931
  }
5494
- function uncheckedEvidence(tasks, anchors, { history, branches, existing }) {
5495
- const changeUnchecked = history === "read" ? [] : tasks.filter((task) => judgedByCommits(task, anchors));
5932
+ function uncheckedEvidence(tasks, anchors, { history, branches, existing }, lateUnknown) {
5933
+ const changeUnchecked = tasks.filter((task) => history === "read" ? lateUnknown.has(task.id) : judgedByCommits(task, anchors));
5496
5934
  const missingUnchecked = branches.kind === "unreadable" ? tasks.filter((task) => task.source !== void 0 && !existing.has(sourcePath(task.source))) : [];
5497
5935
  return [...evidenceOf(changeUnchecked, "source-changed"), ...evidenceOf(missingUnchecked, "source-missing")];
5498
5936
  }
@@ -5567,25 +6005,29 @@ async function checkBacklog(root, loaded, request) {
5567
6005
  const projects = current.projects.filter((project) => inScope(project.id));
5568
6006
  const checked = await reviewProjects(root, current.tasks, projects, request);
5569
6007
  const reviews = checked.map(({ review }) => review);
5570
- const anchors = await applyAnchorPlans(current, checked.flatMap(plansToApply), writes);
6008
+ const anchors = await applyAnchorPlans(
6009
+ current,
6010
+ reviews.flatMap((review) => review.plans),
6011
+ writes
6012
+ );
5571
6013
  const outcome = candidateOutcome(reviews);
5572
6014
  await recordCandidates(root, current.tasks, outcome, request);
5573
- const repos = new Map(checked.map(({ review, checkout }) => [review.projectId, checkout?.path]));
6015
+ const repos = new Map(checked.map(({ review, repo }) => [review.projectId, repo]));
5574
6016
  const problems3 = full ? [...fixes.failed, ...anchors.failed, ...findProblems(current, projects, repos, inScope), ...reviews.flatMap((review) => review.problems)] : [];
5575
6017
  return { fixed: [...fixes.fixed, ...anchors.fixed], problems: problems3, candidates: outcome.candidates };
5576
6018
  }
5577
6019
  async function reviewProjects(root, tasks, projects, request) {
5578
- const originsOf = (projectId) => creationOrigins(root, projectId, (error) => request.warn(request.messages.branchOriginsReadFailed(projectId, errorText(error))));
6020
+ const marksOf = (projectId) => readMarkCommits(root, projectId, (error) => request.warn(request.messages.markCommitsReadFailed(projectId, errorText(error))));
5579
6021
  return Promise.all(
5580
6022
  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 };
6023
+ const checkouts = await projectCheckouts(project, { ...request.context, workingRoots: request.workingRoots });
6024
+ return {
6025
+ review: await projectReview(project, tasks, { checkouts, marks: await marksOf(project.id), mode: request.mode, onUnreadable: request.context.onUnreadable, git: request.git }),
6026
+ repo: checkouts[0]?.path
6027
+ };
5583
6028
  })
5584
6029
  );
5585
6030
  }
5586
- function plansToApply({ review, checkout }) {
5587
- return checkout?.linkedWorktree === true ? [] : review.plans;
5588
- }
5589
6031
  function candidateOutcome(reviews) {
5590
6032
  return {
5591
6033
  candidates: reviews.flatMap((review) => review.candidates),
@@ -5597,7 +6039,7 @@ function candidateOutcome(reviews) {
5597
6039
  async function recordCandidates(root, tasks, { candidates, filtered, unchecked, unjudged }, { mode, now, projectIds, messages, warn: warn2 }) {
5598
6040
  const projectOf2 = new Map(tasks.map((task) => [task.id, task.projectId]));
5599
6041
  for (const projectId of projectIds) {
5600
- const dir = join17(root, projectId);
6042
+ const dir = join19(root, projectId);
5601
6043
  const found = candidates.filter((candidate) => projectOf2.get(candidate.task.id) === projectId);
5602
6044
  const filteredHere = filtered.filter((sighting) => projectOf2.get(sighting.task) === projectId);
5603
6045
  const reviewed = tasks.filter((task) => task.projectId === projectId && isReviewable(task) && !unjudged.has(task.id)).map((task) => task.id);
@@ -6022,7 +6464,7 @@ async function runClose(args, io) {
6022
6464
  return EXIT.invalid;
6023
6465
  }
6024
6466
  const index = indexOfLoaded(loaded);
6025
- const written = await taskWriter(io, index)(task, { status, related }, { resolution, reason });
6467
+ const written = await taskWriter(io, index)(task, { status, related }, { closure: { resolution, reason } });
6026
6468
  if (!written.ok) return written.exitCode;
6027
6469
  const deletion = scheduledDeletion(written.task, indexWithWritten(index, [written]));
6028
6470
  const change = attachesFix ? status : `${task.status} \u2192 ${status}`;
@@ -6037,28 +6479,28 @@ function originalProblem(cli, task, original) {
6037
6479
  }
6038
6480
  async function fixCommitFound(loaded, task, reason, io) {
6039
6481
  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;
6482
+ const checkouts = project === void 0 ? [] : await projectCheckouts(project, repoLookup(io));
6483
+ if (checkouts.length === 0) return true;
6484
+ for (const sha of reasonHashes(reason)) for (const { path } of checkouts) if (await hasCommit(path, sha)) return true;
6043
6485
  return false;
6044
6486
  }
6045
6487
 
6046
6488
  // src/cli/agents/agent.ts
6047
- import { join as join19 } from "node:path";
6489
+ import { join as join21 } from "node:path";
6048
6490
 
6049
6491
  // src/core/claude-dir.ts
6050
- import { join as join18 } from "node:path";
6492
+ import { join as join20 } from "node:path";
6051
6493
  function claudeDir(env, home2) {
6052
- return env.CLAUDE_CONFIG_DIR || join18(home2, ".claude");
6494
+ return env.CLAUDE_CONFIG_DIR || join20(home2, ".claude");
6053
6495
  }
6054
6496
  function claudeSkillsDir(env, home2) {
6055
- return env.CLAUDE_SKILLS_DIR || join18(claudeDir(env, home2), "skills");
6497
+ return env.CLAUDE_SKILLS_DIR || join20(claudeDir(env, home2), "skills");
6056
6498
  }
6057
6499
  function claudeSettingsPath(env, home2) {
6058
- return env.CLAUDE_SETTINGS_PATH || join18(claudeDir(env, home2), "settings.json");
6500
+ return env.CLAUDE_SETTINGS_PATH || join20(claudeDir(env, home2), "settings.json");
6059
6501
  }
6060
6502
  function claudeProjectsDir(env, home2) {
6061
- return join18(claudeDir(env, home2), "projects");
6503
+ return join20(claudeDir(env, home2), "projects");
6062
6504
  }
6063
6505
 
6064
6506
  // src/cli/agents/agent.ts
@@ -6070,9 +6512,9 @@ function hooksJsonAgent(label, homeDir, { stopProtocol, hookApprovalCommand }) {
6070
6512
  label,
6071
6513
  stopProtocol,
6072
6514
  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),
6515
+ skillsDir: ({ home: home2 }) => join21(home2, ".agents", "skills"),
6516
+ legacySkillsDirs: (places) => [join21(homeDir(places), "skills")],
6517
+ hookConfigPath: (places) => join21(homeDir(places), AGENT_HOOKS_FILE),
6076
6518
  pluginSettingsPath: null,
6077
6519
  alwaysInstalled: false,
6078
6520
  skillOnLanguageChange: "relinkExisting",
@@ -6092,8 +6534,8 @@ var AGENT_SPECS = {
6092
6534
  skillOnLanguageChange: "link",
6093
6535
  hookApprovalCommand: null
6094
6536
  },
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 })
6537
+ codex: hooksJsonAgent("Codex", ({ env, home: home2 }) => env.CODEX_HOME || join21(home2, ".codex"), { stopProtocol: "claude", hookApprovalCommand: "/hooks" }),
6538
+ cursor: hooksJsonAgent("Cursor", ({ home: home2 }) => join21(home2, ".cursor"), { stopProtocol: "cursor", hookApprovalCommand: null })
6097
6539
  };
6098
6540
  function agentVoice(agent, output) {
6099
6541
  const { label } = AGENT_SPECS[agent];
@@ -6116,7 +6558,7 @@ async function isDirectory(path) {
6116
6558
 
6117
6559
  // src/cli/skill-link.ts
6118
6560
  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";
6561
+ import { basename as basename8, dirname as dirname7, join as join22, resolve as resolve3 } from "node:path";
6120
6562
  import { z as z8 } from "zod";
6121
6563
 
6122
6564
  // src/core/skill-name.ts
@@ -6133,14 +6575,14 @@ var SKILL_VARIANTS = {
6133
6575
  var SKILL_SOURCE_DIRS = new Set(Object.values(SKILL_VARIANTS).map((variant) => variant.sourceDir));
6134
6576
  var packageManifestSchema = z8.object({ name: z8.string() });
6135
6577
  function skillSourceDir(packageRoot2, language) {
6136
- return join20(packageRoot2, SKILL_SOURCES_DIR, SKILL_VARIANTS[language].sourceDir);
6578
+ return join22(packageRoot2, SKILL_SOURCES_DIR, SKILL_VARIANTS[language].sourceDir);
6137
6579
  }
6138
6580
  function skillLinkPath(skillsDir) {
6139
- return join20(skillsDir, SKILL_NAME);
6581
+ return join22(skillsDir, SKILL_NAME);
6140
6582
  }
6141
6583
  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"));
6584
+ if (!SKILL_SOURCE_DIRS.has(basename8(path)) || basename8(dirname7(path)) !== SKILL_SOURCES_DIR) return false;
6585
+ const manifest = await readTextOrNull(join22(dirname7(dirname7(path)), "package.json"));
6144
6586
  if (manifest !== null) return parseJson(manifest, packageManifestSchema)?.name === "p-backlog";
6145
6587
  return !await pathExists(path);
6146
6588
  }
@@ -6304,20 +6746,20 @@ async function moveOne(id, { loaded, epic, write, io }) {
6304
6746
  import { parseArgs as parseArgs2 } from "node:util";
6305
6747
 
6306
6748
  // src/core/store/hook-turns.ts
6307
- import { join as join21 } from "node:path";
6749
+ import { join as join23 } from "node:path";
6308
6750
  import { z as z10 } from "zod";
6309
6751
 
6310
6752
  // src/core/store/json-under-lock.ts
6311
- function updateJsonUnderLock(path, schema, empty, update, { onErrorAfterPublish, ...lockOptions }) {
6312
- return withFileLock(
6753
+ function updateJsonUnderLock(path, schema, empty, update, options) {
6754
+ return withWriteLock(
6313
6755
  path,
6314
- async () => {
6756
+ async (afterPublish) => {
6315
6757
  const next = update(await readJsonFile(path, schema) ?? empty);
6316
6758
  if (next === null) return "unchanged";
6317
- await writeJsonFile(path, next, { onErrorAfterPublish });
6759
+ await writeJsonFile(path, next, afterPublish);
6318
6760
  return "written";
6319
6761
  },
6320
- lockOptions
6762
+ options
6321
6763
  );
6322
6764
  }
6323
6765
 
@@ -6327,7 +6769,7 @@ var CLAIM_WINDOW_MS = 6e4;
6327
6769
  var hookTurnsSchema = z10.record(z10.string(), z10.iso.datetime({ offset: true }));
6328
6770
  async function claimHookTurn(backlogRoot2, turnKey, { now, onError }) {
6329
6771
  const outcome = await updateJsonUnderLock(
6330
- join21(backlogRoot2, HOOK_TURNS_FILE),
6772
+ join23(backlogRoot2, HOOK_TURNS_FILE),
6331
6773
  hookTurnsSchema,
6332
6774
  {},
6333
6775
  (turns) => {
@@ -6341,7 +6783,7 @@ async function claimHookTurn(backlogRoot2, turnKey, { now, onError }) {
6341
6783
  }
6342
6784
 
6343
6785
  // src/core/store/signals-shown.ts
6344
- import { join as join22 } from "node:path";
6786
+ import { join as join24 } from "node:path";
6345
6787
  import { z as z11 } from "zod";
6346
6788
 
6347
6789
  // src/core/model/signals-shown.ts
@@ -6355,15 +6797,15 @@ function signalsToShow(signals, shown, today) {
6355
6797
  // src/core/store/signals-shown.ts
6356
6798
  var SIGNALS_SHOWN_FILE = ".signals-shown.json";
6357
6799
  var shownSchema = z11.record(z11.string(), z11.string());
6358
- async function readSignalsShown(projectDir2) {
6359
- return await readJsonFile(join22(projectDir2, SIGNALS_SHOWN_FILE), shownSchema) ?? {};
6800
+ async function readSignalsShown(projectDir) {
6801
+ return await readJsonFile(join24(projectDir, SIGNALS_SHOWN_FILE), shownSchema) ?? {};
6360
6802
  }
6361
- async function rememberSignalsShown(projectDir2, signals, today, onError) {
6362
- await updateJsonUnderLock(join22(projectDir2, SIGNALS_SHOWN_FILE), shownSchema, {}, (shown) => markShown(shown, signals, today), { onErrorAfterPublish: onError });
6803
+ async function rememberSignalsShown(projectDir, signals, today, onError) {
6804
+ await updateJsonUnderLock(join24(projectDir, SIGNALS_SHOWN_FILE), shownSchema, {}, (shown) => markShown(shown, signals, today), { onErrorAfterPublish: onError });
6363
6805
  }
6364
6806
 
6365
6807
  // src/core/store/session-shown.ts
6366
- import { join as join23 } from "node:path";
6808
+ import { join as join25 } from "node:path";
6367
6809
  import { z as z12 } from "zod";
6368
6810
  var SESSION_SHOWN_FILE = ".candidates-shown.json";
6369
6811
  var SESSION_RETENTION_MS = WEEK_MS;
@@ -6375,14 +6817,14 @@ function shownKey({ taskId, codeState }) {
6375
6817
  function taskIdOf(key) {
6376
6818
  return key.split(CODE_STATE_MARK, 1)[0] ?? key;
6377
6819
  }
6378
- async function readSessionShown(projectDir2, session) {
6379
- const sessions = await readJsonFile(join23(projectDir2, SESSION_SHOWN_FILE), sessionsShownSchema) ?? {};
6820
+ async function readSessionShown(projectDir, session) {
6821
+ const sessions = await readJsonFile(join25(projectDir, SESSION_SHOWN_FILE), sessionsShownSchema) ?? {};
6380
6822
  return sessions[session]?.tasks ?? [];
6381
6823
  }
6382
- async function rememberSessionShown(projectDir2, session, shown, { now, onError }) {
6824
+ async function rememberSessionShown(projectDir, session, shown, { now, onError }) {
6383
6825
  const shownAgain = new Set(shown.map(({ taskId }) => taskId));
6384
6826
  await updateJsonUnderLock(
6385
- join23(projectDir2, SESSION_SHOWN_FILE),
6827
+ join25(projectDir, SESSION_SHOWN_FILE),
6386
6828
  sessionsShownSchema,
6387
6829
  {},
6388
6830
  (sessions) => {
@@ -6852,12 +7294,12 @@ function shownTask(candidate) {
6852
7294
  var NO_SESSION_MEMORY = { told: /* @__PURE__ */ new Set(), remember: rememberNothing };
6853
7295
  async function sessionMemory(project, session, io) {
6854
7296
  if (session === void 0) return NO_SESSION_MEMORY;
6855
- const projectDir2 = projectDirOf(project);
7297
+ const projectDir = projectDirOf(project);
6856
7298
  try {
6857
7299
  return {
6858
- told: new Set(await readSessionShown(projectDir2, session)),
7300
+ told: new Set(await readSessionShown(projectDir, session)),
6859
7301
  remember: async (shown) => {
6860
- if (shown.length > 0) await rememberSessionShown(projectDir2, session, shown, writesOf(io)).catch((error) => io.warn(io.cli.sessionShownWriteFailed(errorText(error))));
7302
+ if (shown.length > 0) await rememberSessionShown(projectDir, session, shown, writesOf(io)).catch((error) => io.warn(io.cli.sessionShownWriteFailed(errorText(error))));
6861
7303
  }
6862
7304
  };
6863
7305
  } catch (error) {
@@ -6871,21 +7313,21 @@ function lowChangedSignals(count3) {
6871
7313
  return [{ kind: "low-changed", params: { count: count3 } }];
6872
7314
  }
6873
7315
  async function freshSignals(project, tasks, extra, io) {
6874
- const projectDir2 = projectDirOf(project);
7316
+ const projectDir = projectDirOf(project);
6875
7317
  const today = formatLocalDay(io.now());
6876
7318
  try {
6877
- const journal = await readJournal(projectDir2, project.id);
6878
- const shown = await readSignalsShown(projectDir2);
7319
+ const journal = await readJournal(projectDir, project.id);
7320
+ const shown = await readSignalsShown(projectDir);
6879
7321
  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) };
7322
+ return { fresh, remember: fresh.length === 0 ? rememberNothing : () => rememberShown(projectDir, fresh, today, io) };
6881
7323
  } catch (error) {
6882
7324
  io.warn(io.cli.alertsComputeFailed(errorText(error)));
6883
7325
  return NO_SIGNALS;
6884
7326
  }
6885
7327
  }
6886
- async function rememberShown(projectDir2, signals, today, io) {
7328
+ async function rememberShown(projectDir, signals, today, io) {
6887
7329
  try {
6888
- await rememberSignalsShown(projectDir2, signals, today, warnPathErrors(io.warn));
7330
+ await rememberSignalsShown(projectDir, signals, today, warnPathErrors(io.warn));
6889
7331
  } catch (error) {
6890
7332
  io.warn(io.cli.alertsShownWriteFailed(errorText(error)));
6891
7333
  }
@@ -6978,10 +7420,13 @@ async function runList(args, io) {
6978
7420
  // src/cli/origin.ts
6979
7421
  var DETACHED_HEAD = "HEAD";
6980
7422
  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;
7423
+ const [commit, branch] = await Promise.all([readHeadCommit(dir), gitLine(dir, ["rev-parse", "--abbrev-ref", "HEAD"])]);
7424
+ if (commit === void 0) return void 0;
6983
7425
  return branch === null || branch === DETACHED_HEAD ? { commit } : { branch, commit };
6984
7426
  }
7427
+ async function readHeadCommit(dir) {
7428
+ return await gitLine(dir, ["rev-parse", "--short", "HEAD"]) ?? void 0;
7429
+ }
6985
7430
  async function gitLine(dir, args) {
6986
7431
  return outputLine(await runGit(dir, args));
6987
7432
  }
@@ -7022,11 +7467,8 @@ async function runNew(args, io) {
7022
7467
  if (!project) return EXIT.notFound;
7023
7468
  const projectTasks = loaded.tasks.filter((task2) => task2.projectId === project.id);
7024
7469
  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
- ]);
7470
+ const mayRecordOrigin = values.project === void 0 || cwdBelongsTo(project, loaded, io);
7471
+ const [{ anchor, origin }, body] = await allAfterSettling([creationFacts(project, values.source, mayRecordOrigin, io), io.readStdin()]);
7030
7472
  const index = indexOfLoaded(loaded);
7031
7473
  const result = await createTask(io.backlogRoot, {
7032
7474
  project,
@@ -7037,7 +7479,7 @@ async function runNew(args, io) {
7037
7479
  category,
7038
7480
  tags: splitList(values.tags),
7039
7481
  source: values.source,
7040
- anchor: atSource?.kind === "anchor" ? atSource.anchor : void 0,
7482
+ anchor: anchor?.kind === "anchor" ? anchor.anchor : void 0,
7041
7483
  epic: values.epic,
7042
7484
  blockedBy: splitList(values["blocked-by"]),
7043
7485
  related: splitList(values.related),
@@ -7065,11 +7507,16 @@ function warnedOfSimilarTask(draft, projectTasks, io) {
7065
7507
  io.warn(io.cli.similarTaskWarning(similar.task.id, similar.task.title, why));
7066
7508
  return true;
7067
7509
  }
7068
- async function anchorOf2(project, source, io) {
7510
+ async function creationFacts(project, source, mayRecordOrigin, io) {
7511
+ const atSource = source === void 0 ? void 0 : await sourceAtCreation(project, source, io);
7512
+ const originDir = atSource === void 0 ? io.cwd : atSource.recordIn;
7513
+ return { anchor: atSource?.anchor, origin: mayRecordOrigin && originDir !== void 0 ? await readOrigin(originDir) : void 0 };
7514
+ }
7515
+ async function sourceAtCreation(project, source, io) {
7069
7516
  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);
7517
+ const choice = await explicitSourceRepo(project, lookup, source);
7518
+ if (choice !== void 0) await sourcePresenceOrWarn(io, choice.path, source);
7519
+ return { anchor: await sourceAnchor(choice?.recordIn, source, lookup.onUnreadable), recordIn: choice?.recordIn };
7073
7520
  }
7074
7521
  async function allAfterSettling(work) {
7075
7522
  await Promise.allSettled(work);
@@ -7180,7 +7627,7 @@ async function runPrune(args, io) {
7180
7627
  }
7181
7628
  const write = taskWriter(io, indexOfLoaded(loaded));
7182
7629
  return applyAll(stale, async (task) => {
7183
- const written = await write(task, { status: "cancelled" }, { resolution: "obsolete", reason: io.cli.pruneReason(STALE_LOW_DAYS) });
7630
+ const written = await write(task, { status: "cancelled" }, { closure: { resolution: "obsolete", reason: io.cli.pruneReason(STALE_LOW_DAYS) } });
7184
7631
  if (!written.ok) return written.exitCode;
7185
7632
  io.print(io.cli.taskCancelled(task.id));
7186
7633
  return EXIT.ok;
@@ -7190,13 +7637,13 @@ async function runPrune(args, io) {
7190
7637
  // src/server/start.ts
7191
7638
  import { serve } from "@hono/node-server";
7192
7639
  import { mkdir as mkdir6, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
7193
- import { join as join32 } from "node:path";
7640
+ import { join as join34 } from "node:path";
7194
7641
 
7195
7642
  // src/server/app.ts
7196
7643
  import { serveStatic } from "@hono/node-server/serve-static";
7197
7644
  import { Hono as Hono3 } from "hono";
7198
7645
  import { secureHeaders } from "hono/secure-headers";
7199
- import { join as join28 } from "node:path";
7646
+ import { join as join31 } from "node:path";
7200
7647
 
7201
7648
  // src/server/api.ts
7202
7649
  import { Hono as Hono2 } from "hono";
@@ -7246,7 +7693,7 @@ var batchRequestSchema = z14.strictObject({
7246
7693
  // src/core/check/graph-health.ts
7247
7694
  async function projectGraphHealth(project, tasks, home2) {
7248
7695
  return graphHealth(
7249
- await findRepo(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph, workingRoots: null }),
7696
+ (await projectCheckouts(project, { home: home2, onUnreadable: unreadableRepoHasNoGraph, workingRoots: null }))[0]?.path,
7250
7697
  tasks.filter((task) => task.projectId === project.id)
7251
7698
  );
7252
7699
  }
@@ -7354,7 +7801,7 @@ function fileBusyResponse(c, language, busy) {
7354
7801
  }
7355
7802
 
7356
7803
  // src/server/journal-sources.ts
7357
- import { join as join24 } from "node:path";
7804
+ import { join as join26 } from "node:path";
7358
7805
 
7359
7806
  // src/core/store/jsonl-tail.ts
7360
7807
  import { createHash as createHash5 } from "node:crypto";
@@ -7453,7 +7900,7 @@ function createJournalSources(root) {
7453
7900
  const tailOf = (projectId) => {
7454
7901
  const known = tails.get(projectId);
7455
7902
  if (known !== void 0) return known;
7456
- const created = createJsonlTail(join24(root, projectId, JOURNAL_FILE), journalEventSchema);
7903
+ const created = createJsonlTail(join26(root, projectId, JOURNAL_FILE), journalEventSchema);
7457
7904
  tails.set(projectId, created);
7458
7905
  return created;
7459
7906
  };
@@ -7635,7 +8082,7 @@ function markIfReadable(path) {
7635
8082
  }
7636
8083
 
7637
8084
  // src/server/snapshot-cache.ts
7638
- import { dirname as dirname8, join as join25 } from "node:path";
8085
+ import { dirname as dirname8, join as join27 } from "node:path";
7639
8086
 
7640
8087
  // src/core/journal/closed-in-web.ts
7641
8088
  function tasksClosedInWeb(tasks, journals) {
@@ -7700,7 +8147,7 @@ function createChangeHub({ revisions, snapshots, derived, changes }) {
7700
8147
  });
7701
8148
  const recordOwnWrites = async (writes) => {
7702
8149
  if (writes.length === 0) return snapshots.forget();
7703
- await revisions.recordOwnWrites(writes, [...new Set(writes.map((write) => join25(dirname8(write.path), JOURNAL_FILE)))]);
8150
+ await revisions.recordOwnWrites(writes, [...new Set(writes.map((write) => join27(dirname8(write.path), JOURNAL_FILE)))]);
7704
8151
  forgetChanged(writes.map((write) => write.path));
7705
8152
  };
7706
8153
  return {
@@ -7723,7 +8170,7 @@ async function loadSnapshot(root, revision, journalSources, warn2) {
7723
8170
  const loaded = await loadBacklog(root);
7724
8171
  const projectIds = loaded.projects.map((project) => project.id);
7725
8172
  const readableJournal = (projectId) => journalSources.journal(projectId).catch(async (error) => {
7726
- await warn2((messages) => messages.journalReadFailed(join25(root, projectId, JOURNAL_FILE), errorText(error)));
8173
+ await warn2((messages) => messages.journalReadFailed(join27(root, projectId, JOURNAL_FILE), errorText(error)));
7727
8174
  return { projectId, events: [], invalidLines: 0 };
7728
8175
  });
7729
8176
  const journals = await Promise.all(projectIds.map(readableJournal));
@@ -7746,7 +8193,7 @@ var STATS_REPORT_ROUTES = {
7746
8193
  var STATS_MEMORY_ROUTE = "/stats/memory";
7747
8194
 
7748
8195
  // src/core/code/code-cache.ts
7749
- import { join as join26 } from "node:path";
8196
+ import { join as join28 } from "node:path";
7750
8197
  import { z as z15 } from "zod";
7751
8198
  var CODE_CACHE_FILE = ".code-cache.json";
7752
8199
  var CODE_CACHE_VERSION = 3;
@@ -7768,7 +8215,7 @@ function emptyCodeCache() {
7768
8215
  return { repos: {}, fixes: {}, unsettled: {} };
7769
8216
  }
7770
8217
  function createCodeCacheFile(root) {
7771
- const path = join26(root, CODE_CACHE_FILE);
8218
+ const path = join28(root, CODE_CACHE_FILE);
7772
8219
  return {
7773
8220
  read: async () => {
7774
8221
  const snapshot = await readJsonFile(path, snapshotSchema);
@@ -8361,9 +8808,6 @@ function totalsOf(deferred, units, estimate) {
8361
8808
  const realLines = sum(units.map((unit) => unit.lines));
8362
8809
  const fixedLines = sum(fixed.map((item) => item.lines));
8363
8810
  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
8811
  return {
8368
8812
  realLines,
8369
8813
  fixedTasks: fixed.length,
@@ -8373,9 +8817,15 @@ function totalsOf(deferred, units, estimate) {
8373
8817
  estimatedLines,
8374
8818
  deferredLines,
8375
8819
  deferredTestLines: sum(fixed.map((item) => item.testLines)) + (estimated?.testLines ?? 0),
8376
- noiseShare: measurable ? Math.min(1, deferredLines / denominator) : null
8820
+ ...noiseOf(realLines, deferred.length, deferredLines, estimatedLines)
8377
8821
  };
8378
8822
  }
8823
+ function noiseOf(realLines, deferredTasks, deferredLines, estimatedLines) {
8824
+ if (realLines === 0) return { noiseShare: null, noiseMissing: "no-commits" };
8825
+ if (deferredTasks === 0) return { noiseShare: null, noiseMissing: "no-deferred-tasks" };
8826
+ if (estimatedLines === null) return { noiseShare: null, noiseMissing: "estimate-pending" };
8827
+ return { noiseShare: Math.min(1, deferredLines / (realLines + estimatedLines)), noiseMissing: null };
8828
+ }
8379
8829
  function byKind(deferred) {
8380
8830
  return { fixed: deferred.filter((item) => item.kind === "fixed"), open: deferred.filter((item) => item.kind === "open") };
8381
8831
  }
@@ -8550,7 +9000,7 @@ function leadTimesIn(histories, span2) {
8550
9000
  }
8551
9001
 
8552
9002
  // src/server/cost-source.ts
8553
- import { join as join27 } from "node:path";
9003
+ import { join as join30 } from "node:path";
8554
9004
 
8555
9005
  // src/core/stats/cost/token-counts.ts
8556
9006
  import { z as z16 } from "zod";
@@ -8569,54 +9019,77 @@ function tokensGrowth(before, after) {
8569
9019
  const grown = (key) => Math.max(0, after[key] - before[key]);
8570
9020
  return { input: grown("input"), cacheWrite5m: grown("cacheWrite5m"), cacheWrite1h: grown("cacheWrite1h"), cacheRead: grown("cacheRead"), output: grown("output") };
8571
9021
  }
9022
+ function promptTokens(tokens) {
9023
+ return tokens.input + tokens.cacheWrite5m + tokens.cacheWrite1h + tokens.cacheRead;
9024
+ }
8572
9025
  function totalTokens(tokens) {
8573
- return tokens.input + tokens.cacheWrite5m + tokens.cacheWrite1h + tokens.cacheRead + tokens.output;
9026
+ return promptTokens(tokens) + tokens.output;
8574
9027
  }
8575
9028
 
8576
9029
  // src/core/stats/cost/pricing.ts
8577
9030
  var FAST_MODEL_MARKER = ":fast";
9031
+ var LONG_PROMPT_MARKER = ":long-prompt";
9032
+ var LONG_PROMPT_TOKENS = 1e5;
8578
9033
  var FAST_PRICE_FACTOR = 2;
8579
9034
  var CACHE_WRITE_5M_FACTOR = 1.25;
8580
9035
  var CACHE_WRITE_1H_FACTOR = 2;
8581
9036
  var TOKENS_PER_PRICE = 1e6;
8582
9037
  var PRICE_TABLE = /* @__PURE__ */ new Map([
9038
+ ["claude-fable-5-2", { input: 8, output: 40, cacheRead: 0.2, fastMode: true }],
9039
+ ["claude-mythos-5-2", { input: 8, output: 40, cacheRead: 0.2, fastMode: true }],
8583
9040
  ["claude-fable-5-1", { input: 10, output: 50, cacheRead: 0.25 }],
8584
9041
  ["claude-mythos-5-1", { input: 10, output: 50, cacheRead: 0.25 }],
8585
9042
  ["claude-fable-5", { input: 10, output: 50, cacheRead: 1 }],
8586
9043
  ["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 }],
9044
+ ["claude-opus-5-5", { input: 4, output: 20, cacheRead: 0.2, fastMode: true }],
9045
+ ["claude-opus-5", { input: 5, output: 25, cacheRead: 0.5, fastMode: true }],
9046
+ ["claude-opus-4-8", { input: 5, output: 25, cacheRead: 0.5, fastMode: true }],
8590
9047
  ["claude-opus-4-7", { input: 5, output: 25, cacheRead: 0.5 }],
8591
9048
  ["claude-opus-4-6", { input: 5, output: 25, cacheRead: 0.5 }],
9049
+ ["claude-opus-4-5", { input: 5, output: 25, cacheRead: 0.5 }],
9050
+ ["claude-sonnet-5-5", { input: 2, output: 10, cacheRead: 0.1 }],
8592
9051
  ["claude-sonnet-5", { input: 2, output: 10, cacheRead: 0.2 }],
8593
9052
  ["claude-sonnet-4-6", { input: 3, output: 15, cacheRead: 0.3 }],
9053
+ ["claude-sonnet-4-5", { input: 3, output: 15, cacheRead: 0.3 }],
9054
+ ["claude-haiku-5-5", { input: 0.1, output: 0.5, cacheRead: 0.01, longPrompt: { input: 0.5, output: 2.5, cacheRead: 0.05 } }],
8594
9055
  ["claude-haiku-4-5", { input: 1, output: 5, cacheRead: 0.1 }]
8595
9056
  ]);
8596
- var FAST_PRICED_MODELS = /* @__PURE__ */ new Set(["claude-opus-5-5", "claude-opus-5"]);
8597
9057
  var DATED_SUFFIX = /-\d{8}$/;
8598
9058
  var BRACKET_SUFFIX = /\[[^\]]*\]$/;
8599
9059
  function baseModelId(model) {
8600
9060
  return model.replace(BRACKET_SUFFIX, "").replace(DATED_SUFFIX, "");
8601
9061
  }
8602
- function fastModel(model) {
8603
- return `${model}${FAST_MODEL_MARKER}`;
9062
+ function modelKey({ model, fast, tokens }) {
9063
+ const longPrompt = promptTokens(tokens) > LONG_PROMPT_TOKENS && PRICE_TABLE.get(baseModelId(model))?.longPrompt !== void 0;
9064
+ return `${model}${fast ? FAST_MODEL_MARKER : ""}${longPrompt ? LONG_PROMPT_MARKER : ""}`;
8604
9065
  }
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 };
9066
+ function stripMarker(key, marker) {
9067
+ const marked = key.endsWith(marker);
9068
+ return { rest: marked ? key.slice(0, -marker.length) : key, marked };
8608
9069
  }
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;
9070
+ function parseModelKey(key) {
9071
+ const { rest, marked: longPrompt } = stripMarker(key, LONG_PROMPT_MARKER);
9072
+ const { rest: model, marked: fast } = stripMarker(rest, FAST_MODEL_MARKER);
9073
+ return { model, fast, longPrompt };
9074
+ }
9075
+ function modelRowKey(key) {
9076
+ return stripMarker(key, LONG_PROMPT_MARKER).rest;
9077
+ }
9078
+ function splitFastModel(key) {
9079
+ const { model, fast } = parseModelKey(key);
9080
+ return { model, fast };
9081
+ }
9082
+ function priceOf(key) {
9083
+ const { model, fast, longPrompt } = parseModelKey(key);
9084
+ const pricing = PRICE_TABLE.get(baseModelId(model));
9085
+ if (pricing === void 0) return null;
9086
+ const price = longPrompt ? pricing.longPrompt ?? pricing : pricing;
8614
9087
  if (!fast) return price;
8615
- if (!FAST_PRICED_MODELS.has(baseId)) return null;
9088
+ if (pricing.fastMode !== true) return null;
8616
9089
  return { input: price.input * FAST_PRICE_FACTOR, output: price.output * FAST_PRICE_FACTOR, cacheRead: price.cacheRead * FAST_PRICE_FACTOR };
8617
9090
  }
8618
- function costOf(model, tokens) {
8619
- const price = priceOf(model);
9091
+ function costOf(key, tokens) {
9092
+ const price = priceOf(key);
8620
9093
  if (price === null) return null;
8621
9094
  const { input, cacheWrite5m, cacheWrite1h, cacheRead, output } = tokens;
8622
9095
  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 +9166,7 @@ function costNumbers({ buckets, runs }) {
8693
9166
  };
8694
9167
  }
8695
9168
  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);
9169
+ 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
9170
  }
8698
9171
  function commandsOf(runs) {
8699
9172
  return [...groupBy(runs, (run) => run.command).entries()].map(([command2, commandRuns]) => ({
@@ -8708,9 +9181,74 @@ function average(values) {
8708
9181
  return sum(values) / values.length;
8709
9182
  }
8710
9183
 
9184
+ // src/core/usage/usage-cache.ts
9185
+ import { mkdir as mkdir5 } from "node:fs/promises";
9186
+ import { join as join29 } from "node:path";
9187
+ import { z as z18 } from "zod";
9188
+
9189
+ // src/core/stats/cost/usage-state.ts
9190
+ import { z as z17 } from "zod";
9191
+ var estimatedKindSchema = z17.enum(["cli", "skill"]);
9192
+ var usageBucketSchema = z17.object({
9193
+ slot: z17.string(),
9194
+ cwd: z17.string(),
9195
+ model: z17.string(),
9196
+ kind: z17.enum(["hook", ...estimatedKindSchema.options]),
9197
+ tokens: tokenCountsSchema,
9198
+ hookTurns: z17.number()
9199
+ });
9200
+ var transcriptStateSchema = z17.object({
9201
+ hookOpen: z17.boolean(),
9202
+ lastModel: z17.string().nullable(),
9203
+ lastMessageId: z17.string().nullable(),
9204
+ lastMessageTokens: tokenCountsSchema.nullable().optional(),
9205
+ pending: z17.record(z17.string(), estimatedKindSchema),
9206
+ pendingEstimates: z17.array(z17.object({ kind: estimatedKindSchema, chars: z17.number(), slot: z17.string(), cwd: z17.string() }))
9207
+ });
9208
+
9209
+ // src/core/usage/usage-cache.ts
9210
+ var USAGE_CACHE_FILE = ".usage-cache.json";
9211
+ var USAGE_CACHE_VERSION = 6;
9212
+ var bucketsSchema = z18.array(usageBucketSchema);
9213
+ var usageCacheEntrySchema = z18.object({
9214
+ size: z18.number(),
9215
+ mtimeMs: z18.number().optional(),
9216
+ offset: z18.number(),
9217
+ fingerprint: z18.string(),
9218
+ state: transcriptStateSchema,
9219
+ buckets: bucketsSchema
9220
+ });
9221
+ var usageCacheSchema = z18.object({
9222
+ version: z18.literal(USAGE_CACHE_VERSION),
9223
+ files: z18.record(z18.string(), usageCacheEntrySchema),
9224
+ carried: z18.record(z18.string(), bucketsSchema).default({})
9225
+ });
9226
+ var salvagedEntrySchema = z18.object({ buckets: bucketsSchema }).transform((entry) => entry.buckets);
9227
+ var salvagedCacheSchema = z18.object({
9228
+ files: z18.record(z18.string(), salvagedEntrySchema.nullable().catch(null)).catch({}),
9229
+ carried: z18.record(z18.string(), bucketsSchema.nullable().catch(null)).catch({})
9230
+ }).transform(({ files, carried }) => {
9231
+ const salvaged = [...Object.entries(carried), ...Object.entries(files)].flatMap(([path, buckets]) => buckets === null ? [] : [[path, buckets]]);
9232
+ return { ...emptyUsageCache(), carried: Object.fromEntries(salvaged) };
9233
+ });
9234
+ var storedCacheSchema = z18.union([usageCacheSchema, salvagedCacheSchema]);
9235
+ function emptyUsageCache() {
9236
+ return { version: USAGE_CACHE_VERSION, files: {}, carried: {} };
9237
+ }
9238
+ function usageBucketsOf(cache) {
9239
+ return [...Object.values(cache.files).flatMap((entry) => entry.buckets), ...Object.values(cache.carried).flat()];
9240
+ }
9241
+ async function readUsageCache(root) {
9242
+ return await readJsonFile(join29(root, USAGE_CACHE_FILE), storedCacheSchema) ?? emptyUsageCache();
9243
+ }
9244
+ async function writeUsageCache(root, cache, onErrorAfterPublish) {
9245
+ await mkdir5(root, { recursive: true });
9246
+ await writeFileAtomic(join29(root, USAGE_CACHE_FILE), JSON.stringify(cache), { onErrorAfterPublish });
9247
+ }
9248
+
8711
9249
  // src/server/cost-source.ts
8712
9250
  function createCostSource(root, home2) {
8713
- const runsTail = createJsonlTail(join27(root, RUNS_FILE), cliRunSchema);
9251
+ const runsTail = createJsonlTail(join30(root, RUNS_FILE), cliRunSchema);
8714
9252
  const context = { home: home2, onUnreadable: unreadablePathHasNoProject };
8715
9253
  const lookupRepoRoot = cachedRepoRoots({ onUnreadable: unreadablePathHasNoProject });
8716
9254
  return {
@@ -8735,20 +9273,14 @@ async function computeCostReport({ usage: { cache, scan }, runs, known, projectI
8735
9273
  return costReport({ buckets, runs, projectOf: (cwd) => projectIds.get(cwd) ?? null, projectId, now, scan });
8736
9274
  }
8737
9275
  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
- );
9276
+ const projectIdOf = async (cwd) => {
9277
+ const lookup = await lookupProjectForRecordedDir(known, cwd, lookupRepoRoot, context);
9278
+ return [cwd, "project" in lookup ? lookup.project.id : null];
9279
+ };
9280
+ return new Map(await Promise.all([...new Set(cwds)].map(projectIdOf)));
8746
9281
  }
8747
9282
  function unreadablePathHasNoProject() {
8748
9283
  }
8749
- function usageBucketsOf(cache) {
8750
- return Object.values(cache.files).flatMap((entry) => entry.buckets);
8751
- }
8752
9284
 
8753
9285
  // src/server/stats-api.ts
8754
9286
  var REPORT_TTL_MS = 5 * MINUTE_MS;
@@ -9070,14 +9602,14 @@ function createApp({ root, readLanguage, changes, allowedHosts, home: home2, sta
9070
9602
  });
9071
9603
  if (staticDir !== void 0) {
9072
9604
  app.use("*", serveStatic({ root: staticDir }));
9073
- app.get("*", serveStatic({ path: join28(staticDir, "index.html") }));
9605
+ app.get("*", serveStatic({ path: join31(staticDir, "index.html") }));
9074
9606
  }
9075
9607
  return app;
9076
9608
  }
9077
9609
 
9078
9610
  // src/server/change-feed.ts
9079
9611
  import { setMaxListeners } from "node:events";
9080
- import { join as join29, relative as relative3, sep as sep4 } from "node:path";
9612
+ import { join as join32, relative as relative3, sep as sep4 } from "node:path";
9081
9613
  import { watch } from "chokidar";
9082
9614
  var CHANGE_DEBOUNCE_MS = 100;
9083
9615
  function createDebouncer(delayMs, run) {
@@ -9094,7 +9626,7 @@ function isHiddenPath(root, path) {
9094
9626
  return relative3(root, path).split(sep4).some((segment) => segment.startsWith("."));
9095
9627
  }
9096
9628
  async function watchDirectoriesMissedAtStart(watcher, root) {
9097
- const directories = (await listDir(root)).filter((entry) => entry.isDirectory()).map((entry) => join29(root, entry.name));
9629
+ const directories = (await listDir(root)).filter((entry) => entry.isDirectory()).map((entry) => join32(root, entry.name));
9098
9630
  const watched = watcher.getWatched();
9099
9631
  const missed = directories.filter((path) => !isHiddenPath(root, path) && !(path in watched));
9100
9632
  if (missed.length > 0 && !watcher.closed) watcher.add(missed);
@@ -9194,10 +9726,10 @@ import { isDeepStrictEqual } from "node:util";
9194
9726
 
9195
9727
  // src/core/usage/transcripts.ts
9196
9728
  import { createHash as createHash6 } from "node:crypto";
9197
- import { basename as basename10, join as join31 } from "node:path";
9729
+ import { basename as basename9, join as join33 } from "node:path";
9198
9730
 
9199
9731
  // src/core/stats/cost/attribute.ts
9200
- import { z as z17 } from "zod";
9732
+ import { z as z19 } from "zod";
9201
9733
 
9202
9734
  // src/core/stats/cost/shell-commands.ts
9203
9735
  var ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
@@ -9423,21 +9955,21 @@ var PENDING_TOOL_LIMIT = 64;
9423
9955
  var ZONE_OFFSETS_PER_HOUR = 4;
9424
9956
  var ZONE_OFFSET_STEP_MS = HOUR_MS / ZONE_OFFSETS_PER_HOUR;
9425
9957
  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()
9958
+ var usageSchema = z19.object({
9959
+ input_tokens: z19.number().optional(),
9960
+ output_tokens: z19.number().optional(),
9961
+ cache_read_input_tokens: z19.number().optional(),
9962
+ cache_creation_input_tokens: z19.number().optional(),
9963
+ speed: z19.string().optional(),
9964
+ cache_creation: z19.object({ ephemeral_5m_input_tokens: z19.number().optional(), ephemeral_1h_input_tokens: z19.number().optional() }).passthrough().optional()
9433
9965
  }).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();
9966
+ var assistantMessageSchema = z19.object({ id: z19.string().optional(), model: z19.string().optional(), usage: usageSchema.optional(), content: z19.array(z19.unknown()).optional() }).passthrough();
9967
+ var userMessageSchema = z19.object({ content: z19.unknown().optional() }).passthrough();
9968
+ var toolUseBlockSchema = z19.object({ type: z19.literal("tool_use"), id: z19.string(), name: z19.string(), input: z19.unknown().optional() }).passthrough();
9969
+ var toolResultBlockSchema = z19.object({ type: z19.literal("tool_result"), tool_use_id: z19.string().optional(), content: z19.unknown().optional() }).passthrough();
9970
+ var textBlockSchema = z19.object({ type: z19.literal("text"), text: z19.string() }).passthrough();
9971
+ var bashInputSchema = z19.object({ command: z19.string() }).passthrough();
9972
+ 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
9973
  function newTranscriptState() {
9442
9974
  return { hookOpen: false, lastModel: null, lastMessageId: null, lastMessageTokens: null, pending: {}, pendingEstimates: [] };
9443
9975
  }
@@ -9461,8 +9993,8 @@ function attributeAssistant(rawMessage, state, context) {
9461
9993
  const buckets = [];
9462
9994
  const repeatOfCountedMessage = id !== void 0 && id === state.lastMessageId;
9463
9995
  if (usage !== void 0 && isPricedModel(model)) {
9464
- const pricedModel = usage.speed === FAST_SPEED ? fastModel(model) : model;
9465
9996
  const tokens = tokensFrom(usage);
9997
+ const pricedModel = modelKey({ model, fast: usage.speed === FAST_SPEED, tokens });
9466
9998
  if (repeatOfCountedMessage) {
9467
9999
  const counted = state.lastMessageTokens ?? tokens;
9468
10000
  const growth = tokensGrowth(counted, tokens);
@@ -9560,57 +10092,6 @@ function slotOf(timestamp) {
9560
10092
  return Number.isNaN(moment) ? "" : new Date(moment - moment % ZONE_OFFSET_STEP_MS).toISOString();
9561
10093
  }
9562
10094
 
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
10095
  // src/core/usage/transcripts.ts
9615
10096
  var FINGERPRINT_BYTES = 256;
9616
10097
  var ABANDONED_LINE_MS = 10 * 60 * 1e3;
@@ -9619,16 +10100,16 @@ async function listTranscripts(claudeProjectsDir2) {
9619
10100
  const files = [];
9620
10101
  for (const projectEntry of await listDir(claudeProjectsDir2)) {
9621
10102
  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);
10103
+ const projectDir = join33(claudeProjectsDir2, projectEntry.name);
10104
+ for (const entry of await listDir(projectDir)) {
10105
+ const entryPath = join33(projectDir, entry.name);
9625
10106
  if (entry.isFile() && entry.name.endsWith(".jsonl")) {
9626
10107
  files.push(...await listedFile(entryPath));
9627
10108
  continue;
9628
10109
  }
9629
10110
  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)));
10111
+ for (const subagentEntry of await listDir(join33(entryPath, "subagents"), { recursive: true })) {
10112
+ if (subagentEntry.isFile() && subagentEntry.name.endsWith(".jsonl")) files.push(...await listedFile(join33(subagentEntry.parentPath, subagentEntry.name)));
9632
10113
  }
9633
10114
  }
9634
10115
  }
@@ -9647,14 +10128,19 @@ async function scanTranscripts({ files, cache, byteBudget, now }) {
9647
10128
  remainingBudget -= budgetUsed;
9648
10129
  await yieldToEventLoop();
9649
10130
  }
9650
- const merged = { ...deletedStillReported(cache, listedFiles, now), ...listedFiles };
9651
- const pruned = pruneStaleBuckets(merged, now);
10131
+ const stillReported = deletedStillReported(listedFiles, now);
10132
+ const merged = {
10133
+ version: USAGE_CACHE_VERSION,
10134
+ files: { ...entriesWhere(cache.files, (path, entry) => stillReported(path, entry.buckets)), ...listedFiles },
10135
+ carried: entriesWhere(cache.carried, stillReported)
10136
+ };
10137
+ const pruned = withoutStaleBuckets(merged, now);
9652
10138
  return {
9653
- cache: { version: USAGE_CACHE_VERSION, files: pruned.files },
10139
+ cache: pruned,
9654
10140
  bytesRead: byteBudget - remainingBudget,
9655
10141
  bytesLeft: sum(Object.values(listedFiles).map((entry) => entry.size - entry.offset)),
9656
10142
  filesDone: Object.values(listedFiles).filter((entry) => entry.offset === entry.size).length,
9657
- prunedBuckets: pruned.prunedBuckets
10143
+ prunedBuckets: bucketCount(merged) - bucketCount(pruned)
9658
10144
  };
9659
10145
  }
9660
10146
  async function scanFile(file, previous, budget, limits) {
@@ -9666,21 +10152,28 @@ async function scanFile(file, previous, budget, limits) {
9666
10152
  const fingerprint = unmoved ? previous.fingerprint : await fingerprintOf3(file.path, scanned.offset);
9667
10153
  return { entry: { ...scanned, mtimeMs: file.mtimeMs, fingerprint }, budgetUsed: Math.max(chunkSize, 0) };
9668
10154
  }
9669
- function pruneStaleBuckets(entries, now) {
10155
+ function withoutStaleBuckets(cache, now) {
9670
10156
  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 };
10157
+ const fresh = (buckets) => {
10158
+ const kept = buckets.filter((bucket) => Date.parse(bucket.slot) >= retained);
10159
+ return kept.length === buckets.length ? buckets : kept;
10160
+ };
10161
+ return {
10162
+ ...cache,
10163
+ files: Object.fromEntries(Object.entries(cache.files).map(([path, entry]) => [path, { ...entry, buckets: fresh(entry.buckets) }])),
10164
+ carried: Object.fromEntries(Object.entries(cache.carried).map(([path, buckets]) => [path, fresh(buckets)]))
10165
+ };
9679
10166
  }
9680
- function deletedStillReported(cache, listedFiles, now) {
10167
+ function bucketCount(cache) {
10168
+ return sum([...Object.values(cache.files).map((entry) => entry.buckets.length), ...Object.values(cache.carried).map((buckets) => buckets.length)]);
10169
+ }
10170
+ function deletedStillReported(listedFiles, now) {
9681
10171
  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)));
10172
+ const listedSessions = new Set(Object.keys(listedFiles).map((path) => basename9(path)));
10173
+ return (path, buckets) => !listedSessions.has(basename9(path)) && buckets.some((bucket) => Date.parse(bucket.slot) >= reportStart);
10174
+ }
10175
+ function entriesWhere(records2, keeps) {
10176
+ return Object.fromEntries(Object.entries(records2).filter(([path, value]) => keeps(path, value)));
9684
10177
  }
9685
10178
  async function scanChunk(file, start, chunkSize, { longestReadableLine, now }) {
9686
10179
  if (chunkSize <= 0) return { size: file.size, offset: start.offset, state: start.state, buckets: start.buckets };
@@ -9743,6 +10236,7 @@ function createUsageScanner({ root, claudeProjectsDir: claudeProjectsDir2, byteB
9743
10236
  let revision = 0;
9744
10237
  let inFlight = null;
9745
10238
  let schedule = STOPPED;
10239
+ const onErrorAfterPublish = warnPathErrors((line) => void warn2(() => line));
9746
10240
  const setScan = (next) => {
9747
10241
  if (!scanEquals(scan, next)) revision += 1;
9748
10242
  scan = next;
@@ -9756,7 +10250,7 @@ function createUsageScanner({ root, claudeProjectsDir: claudeProjectsDir2, byteB
9756
10250
  if (cacheChanged(published, result.cache)) revision += 1;
9757
10251
  cache = result.cache;
9758
10252
  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);
10253
+ if (result.bytesRead > 0 || result.prunedBuckets > 0) await writeUsageCache(root, result.cache, onErrorAfterPublish);
9760
10254
  return result.bytesRead >= byteBudget ? "budget-spent" : "settled";
9761
10255
  };
9762
10256
  const scanOnce = () => {
@@ -9794,7 +10288,7 @@ function scanEquals(a, b) {
9794
10288
  }
9795
10289
  function cacheChanged(previous, next) {
9796
10290
  const previousPaths = Object.keys(previous.files);
9797
- if (previousPaths.length !== Object.keys(next.files).length) return true;
10291
+ if (previousPaths.length !== Object.keys(next.files).length || !isDeepStrictEqual(previous.carried, next.carried)) return true;
9798
10292
  return previousPaths.some((path) => entryChanged(previous.files[path], next.files[path]));
9799
10293
  }
9800
10294
  function entryChanged(previous, next) {
@@ -9817,7 +10311,7 @@ function progressBefore(files, cache) {
9817
10311
  // src/server/start.ts
9818
10312
  var SWEEP_INTERVAL_MS = HOUR_MS;
9819
10313
  var STOP_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
9820
- var BUNDLED_WEB_DIR = join32(import.meta.dirname, "web");
10314
+ var BUNDLED_WEB_DIR = join34(import.meta.dirname, "web");
9821
10315
  async function startServer({ root, port, home: home2, env, platform, log, warn: warn2, pidFile, staticDir, settledLanguage, now = () => /* @__PURE__ */ new Date() }) {
9822
10316
  await mkdir6(root, { recursive: true });
9823
10317
  const startupMessages = serverMessages(settledLanguage);
@@ -9928,7 +10422,7 @@ function isFailure(outcome) {
9928
10422
 
9929
10423
  // src/cli/service/launchd.ts
9930
10424
  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";
10425
+ import { dirname as dirname9, join as join35 } from "node:path";
9932
10426
  import { setTimeout as sleep3 } from "node:timers/promises";
9933
10427
 
9934
10428
  // src/cli/service/service.ts
@@ -9936,13 +10430,13 @@ import { readFile as readFile3 } from "node:fs/promises";
9936
10430
  function serviceEnvironment(launch) {
9937
10431
  return { BACKLOG_DIR: launch.backlogRoot, PORT: String(launch.port), PATH: launch.env.PATH ?? "", HOME: launch.home };
9938
10432
  }
9939
- async function numberRecordedIn(file, pattern, encoding = "utf8") {
10433
+ async function numberRecordedIn(file, pattern, parse2, encoding = "utf8") {
9940
10434
  const text = await readFile3(file, encoding).catch((error) => {
9941
10435
  if (hasErrorCode(error, "ENOENT")) return "";
9942
10436
  throw error;
9943
10437
  });
9944
10438
  const recorded = pattern.exec(text)?.[1];
9945
- return recorded === void 0 ? null : portNumber(recorded);
10439
+ return recorded === void 0 ? null : parse2(recorded);
9946
10440
  }
9947
10441
 
9948
10442
  // src/cli/service/launchd.ts
@@ -9992,7 +10486,7 @@ ${entries}
9992
10486
  `;
9993
10487
  }
9994
10488
  function launchdManager(context, delay = sleep3) {
9995
- const file = join33(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
10489
+ const file = join35(context.home, "Library/LaunchAgents", `${LABEL}.plist`);
9996
10490
  const domain = `gui/${context.uid}`;
9997
10491
  const bootout = () => context.exec("launchctl", ["bootout", `${domain}/${LABEL}`]);
9998
10492
  const bootstrap = () => context.exec("launchctl", ["bootstrap", domain, file]);
@@ -10021,30 +10515,32 @@ function launchdManager(context, delay = sleep3) {
10021
10515
  async registered() {
10022
10516
  return await fileExists(file) && (await context.exec("launchctl", ["print", `${domain}/${LABEL}`])).code === 0;
10023
10517
  },
10024
- installedPort: () => numberRecordedIn(file, /<key>PORT<\/key>\s*<string>(\d+)<\/string>/)
10518
+ installedPort: () => numberRecordedIn(file, /<key>PORT<\/key>\s*<string>(\d+)<\/string>/, portNumber)
10025
10519
  };
10026
10520
  }
10027
10521
 
10028
10522
  // src/cli/service/startup-folder.ts
10029
10523
  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";
10524
+ import { dirname as dirname10, join as join36, win32 } from "node:path";
10031
10525
  var SCRIPT_NAME = "p-backlog.vbs";
10032
10526
  var COMMAND_LINE_ARGUMENT = /"[^"]*"|\S+/g;
10033
10527
  var PROCESS_QUERY_TIMEOUT_MS = 15e3;
10528
+ var WINDOWS_MAX_PID = 4294967295;
10529
+ var RECORDED_PID = /^(\d+)\s*$/;
10034
10530
  function vbsString(value) {
10035
10531
  return `"${value.replaceAll('"', '""')}"`;
10036
10532
  }
10037
10533
  function appDataDir(site) {
10038
- return join34(site.env.LOCALAPPDATA ?? join34(site.home, "AppData", "Local"), "p-backlog");
10534
+ return join36(site.env.LOCALAPPDATA ?? join36(site.home, "AppData", "Local"), "p-backlog");
10039
10535
  }
10040
10536
  function startupFolder(site) {
10041
- return join34(site.env.APPDATA ?? join34(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
10537
+ return join36(site.env.APPDATA ?? join36(site.home, "AppData", "Roaming"), "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
10042
10538
  }
10043
10539
  function logPath(site) {
10044
- return join34(appDataDir(site), "p-backlog.log");
10540
+ return join36(appDataDir(site), "p-backlog.log");
10045
10541
  }
10046
10542
  function pidFilePath(site) {
10047
- return join34(appDataDir(site), "server.pid");
10543
+ return join36(appDataDir(site), "server.pid");
10048
10544
  }
10049
10545
  var NODE_PATH_ENV = "P_BACKLOG_NODE";
10050
10546
  var CLI_PATH_ENV = "P_BACKLOG_CLI";
@@ -10085,9 +10581,14 @@ function startupScript(launch) {
10085
10581
  ""
10086
10582
  ].join("\r\n");
10087
10583
  }
10584
+ function pidNumber(recorded) {
10585
+ if (!/^\d+$/.test(recorded)) return null;
10586
+ const pid = Number(recorded);
10587
+ return pid > 0 && pid <= WINDOWS_MAX_PID ? pid : null;
10588
+ }
10088
10589
  async function stopRunningServer(context) {
10089
10590
  const file = pidFilePath(context);
10090
- const pid = await numberRecordedIn(file, /^(\d+)$/);
10591
+ const pid = await numberRecordedIn(file, RECORDED_PID, pidNumber);
10091
10592
  if (pid !== null) {
10092
10593
  const identity = await processIdentity(context, pid);
10093
10594
  if (identity === "unknown") {
@@ -10114,7 +10615,7 @@ function sameWindowsPath(left, right) {
10114
10615
  return win32.normalize(left).toLowerCase() === win32.normalize(right).toLowerCase();
10115
10616
  }
10116
10617
  function startupFolderManager(context) {
10117
- const file = join34(startupFolder(context), SCRIPT_NAME);
10618
+ const file = join36(startupFolder(context), SCRIPT_NAME);
10118
10619
  return {
10119
10620
  file,
10120
10621
  logsHint: logPath(context),
@@ -10135,13 +10636,13 @@ function startupFolderManager(context) {
10135
10636
  async registered() {
10136
10637
  return fileExists(file);
10137
10638
  },
10138
- installedPort: () => numberRecordedIn(file, /env\("PORT"\) = "(\d+)"/, "utf16le")
10639
+ installedPort: () => numberRecordedIn(file, /env\("PORT"\) = "(\d+)"/, portNumber, "utf16le")
10139
10640
  };
10140
10641
  }
10141
10642
 
10142
10643
  // src/cli/service/systemd.ts
10143
10644
  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";
10645
+ import { dirname as dirname11, join as join37 } from "node:path";
10145
10646
  var SERVICE_NAME = "p-backlog";
10146
10647
  var UNIT = `${SERVICE_NAME}.service`;
10147
10648
  function quoted(value) {
@@ -10176,7 +10677,7 @@ async function systemctlSteps(exec, steps) {
10176
10677
  return "done";
10177
10678
  }
10178
10679
  function systemdManager(context) {
10179
- const file = join35(context.home, ".config/systemd/user", UNIT);
10680
+ const file = join37(context.home, ".config/systemd/user", UNIT);
10180
10681
  return {
10181
10682
  file,
10182
10683
  logsHint: `journalctl --user -u ${SERVICE_NAME}`,
@@ -10195,7 +10696,7 @@ function systemdManager(context) {
10195
10696
  async registered() {
10196
10697
  return await fileExists(file) && (await context.exec("systemctl", ["--user", "is-enabled", UNIT])).code === 0;
10197
10698
  },
10198
- installedPort: () => numberRecordedIn(file, /^Environment="PORT=(\d+)"$/m)
10699
+ installedPort: () => numberRecordedIn(file, /^Environment="PORT=(\d+)"$/m, portNumber)
10199
10700
  };
10200
10701
  }
10201
10702
 
@@ -10318,10 +10819,15 @@ async function readJsonConfig(path, schema) {
10318
10819
  return schema.safeParse(value).success ? { config: value } : { failed: "invalid" };
10319
10820
  }
10320
10821
  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 });
10822
+ try {
10823
+ await mkdir10(dirname12(path), { recursive: true });
10824
+ const target = await writeTargetOf(path);
10825
+ const existing = await statOrNull(target);
10826
+ await writeJsonFile(target, config, { mode: existing === null ? void 0 : existing.mode & 511, onErrorAfterPublish: onError });
10827
+ return "written";
10828
+ } catch (error) {
10829
+ return { failed: "unwritable", code: errorCodeOrText(error) };
10830
+ }
10325
10831
  }
10326
10832
  async function readConfigText(path) {
10327
10833
  try {
@@ -10376,15 +10882,16 @@ async function addStopHookIn(file, schema, slotsOf, hook, ourHook) {
10376
10882
  const refreshed = refreshOurHook(slots.lists, hook, ourHook);
10377
10883
  if (refreshed === "exists") return "exists";
10378
10884
  if (refreshed === "missing") slots.append(hook);
10379
- await writeJsonConfig(file, read.config);
10885
+ const written = await writeJsonConfig(file, read.config);
10886
+ if (isFailure(written)) return written;
10380
10887
  return refreshed === "missing" ? "added" : "updated";
10381
10888
  }
10382
10889
  async function removeStopHookIn(file, schema, removeOurs) {
10383
10890
  const read = await readJsonConfig(file.path, schema);
10384
10891
  if (!("config" in read)) return read;
10385
10892
  if (!removeOurs(read.config)) return "absent";
10386
- await writeJsonConfig(file, read.config);
10387
- return "removed";
10893
+ const written = await writeJsonConfig(file, read.config);
10894
+ return isFailure(written) ? written : "removed";
10388
10895
  }
10389
10896
  function addGroupedStopHook(file, hook, ourHook) {
10390
10897
  return addStopHookIn(file, groupedConfigSchema, groupedSlots, hook, ourHook);
@@ -10600,7 +11107,7 @@ function unlinkReportingFailure(skillsDir, io, voice) {
10600
11107
  }
10601
11108
  function reportHook(result, configPath, io, voice) {
10602
11109
  if (isFailure(result)) {
10603
- voice.warn(result.failed === "unreadable" ? io.cli.installHookConfigUnreadable(configPath, result.code) : io.cli.installHookConfigInvalid(configPath));
11110
+ voice.warn(configFailureText(result, configPath, io.cli.installHookConfigFailed));
10604
11111
  return false;
10605
11112
  }
10606
11113
  const report = { added: io.cli.installHookAdded, exists: io.cli.installHookExists, updated: io.cli.installHookUpdated }[result];
@@ -10634,12 +11141,15 @@ async function remainingSkillDirUser(agent, { removing, installed }, io) {
10634
11141
  }
10635
11142
  function reportHookRemoval(result, configPath, io, voice) {
10636
11143
  if (isFailure(result)) {
10637
- voice.warn(result.failed === "unreadable" ? io.cli.removeHookConfigUnreadable(configPath, result.code) : io.cli.removeHookConfigInvalid(configPath));
11144
+ voice.warn(configFailureText(result, configPath, io.cli.removeHookConfigFailed));
10638
11145
  return false;
10639
11146
  }
10640
11147
  voice.print(io.cli.manualHookRemoval[result](configPath));
10641
11148
  return true;
10642
11149
  }
11150
+ function configFailureText(failure, configPath, texts) {
11151
+ return failure.failed === "invalid" ? texts.invalid(configPath) : texts[failure.failed](configPath, failure.code);
11152
+ }
10643
11153
 
10644
11154
  // src/cli/commands/show.ts
10645
11155
  import { readFile as readFile5 } from "node:fs/promises";
@@ -10941,17 +11451,24 @@ async function verifyOne(id, { loaded, source, write, io }) {
10941
11451
  return EXIT.refused;
10942
11452
  }
10943
11453
  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);
11454
+ const choice = project === void 0 ? void 0 : await verifiedRepo(project, task, source, io);
11455
+ if (source !== void 0 && choice !== void 0 && (await sourcePresenceOrWarn(io, choice.path, source)).kind === "missing") return EXIT.invalid;
11456
+ const recordIn = choice?.recordIn;
11457
+ const target = source ?? await relocatedSource(recordIn, task);
10948
11458
  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 });
11459
+ const anchor = anchored === void 0 ? void 0 : anchorChange(await sourceAnchor(recordIn, anchored, repoContext(io).onUnreadable));
11460
+ const headCommit = recordIn === void 0 ? void 0 : await readHeadCommit(recordIn);
11461
+ const written = await write(task, { verified: formatLocalIso(io.now()), source: target, anchor }, { headCommit });
10951
11462
  if (!written.ok) return written.exitCode;
10952
11463
  io.print(target === void 0 ? io.cli.verified(id) : io.cli.verifiedWithSource(id, target));
10953
11464
  return EXIT.ok;
10954
11465
  }
11466
+ async function verifiedRepo(project, task, source, io) {
11467
+ const lookup = repoLookup(io);
11468
+ if (source !== void 0) return explicitSourceRepo(project, lookup, source);
11469
+ 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;
11470
+ return taskRepo(project, lookup, task, marks);
11471
+ }
10955
11472
  function anchorChange(found) {
10956
11473
  switch (found.kind) {
10957
11474
  case "no-file":
@@ -11048,6 +11565,10 @@ var packageRoot = resolve6(dirname13(cliPath), "..");
11048
11565
  var argv = process.argv.slice(2);
11049
11566
  var warn = (line) => void process.stderr.write(`${line}
11050
11567
  `);
11568
+ var CLOSED_READER_CODES = ["EPIPE", "EOF"];
11569
+ process.stdout.on("error", (error) => {
11570
+ if (!hasAnyErrorCode(error, CLOSED_READER_CODES)) throw error;
11571
+ });
11051
11572
  var exitCode = await runCli(argv, {
11052
11573
  cwd: process.cwd(),
11053
11574
  home,
@@ -11081,6 +11602,6 @@ if (command !== SERVE_COMMAND_NAME) {
11081
11602
  exitCode
11082
11603
  };
11083
11604
  const language = await readLanguageOrLocale(backlogRoot, process.env, alreadyReportedByRunCli);
11084
- await appendRun(backlogRoot, run).catch((error) => warn(cliMessages(language).runNotRecorded(errorText(error))));
11605
+ await appendRun(backlogRoot, run, warnPathErrors(warn)).catch((error) => warn(cliMessages(language).runNotRecorded(errorText(error))));
11085
11606
  await tidyAfterCommand({ backlogRoot, command, language, now: /* @__PURE__ */ new Date(), warn });
11086
11607
  }